diff --git a/dist/assets/index-BKho0BkD.css b/dist/assets/index-BKho0BkD.css deleted file mode 100644 index 121e1b5..0000000 --- a/dist/assets/index-BKho0BkD.css +++ /dev/null @@ -1 +0,0 @@ -.canvas-container{position:fixed;top:0;right:0;bottom:0;left:0;overflow:hidden;cursor:default;background:var(--bg);touch-action:none;overscroll-behavior:contain}.canvas-container.pan-mode{cursor:grab}.canvas-container.panning{cursor:grabbing}.canvas-grid{position:absolute;top:0;right:0;bottom:0;left:0;pointer-events:none;background-image:radial-gradient(circle,var(--bg-grid) 1px,transparent 1px);background-repeat:repeat}.canvas-hud{position:fixed;bottom:12px;left:12px;display:flex;gap:12px;padding:6px 10px;background:#00000080;border-radius:6px;font-size:11px;font-family:ui-monospace,Menlo,monospace;color:var(--text);pointer-events:none;z-index:1000}.card{position:absolute;background:var(--card-bg);border:calc(1px * var(--scale, 1)) solid var(--card-border);border-radius:calc(8px * var(--scale, 1));box-shadow:0 calc(4px * var(--scale, 1)) calc(16px * var(--scale, 1)) #0000004d;overflow:hidden;display:flex;flex-direction:column}.card-header{padding:.46em .77em;background:#0003;border-bottom:calc(1px * var(--scale, 1)) solid var(--card-border);font-size:.85em;cursor:move;flex-shrink:0}.card-body{flex:1;overflow:auto}.note-card textarea{width:100%;height:100%;background:transparent;border:none;outline:none;resize:none;color:var(--text);font-family:inherit;font-size:1em;padding:.77em}:root{--bg: #1a1a1f;--bg-grid: #25252c;--card-bg: #2a2a32;--card-border: #3a3a45;--text: #e8e8ec;--accent: #6a8cff;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,sans-serif;color-scheme:dark}*{box-sizing:border-box;margin:0;padding:0}html,body,#root{width:100%;height:100%;overflow:hidden;background:var(--bg);color:var(--text);-webkit-user-select:none;user-select:none} diff --git a/dist/assets/index-BS64ttyv.js b/dist/assets/index-BS64ttyv.js new file mode 100644 index 0000000..d6628f1 --- /dev/null +++ b/dist/assets/index-BS64ttyv.js @@ -0,0 +1,82 @@ +(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))r(s);new MutationObserver(s=>{for(const n of s)if(n.type==="childList")for(const o of n.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function i(s){const n={};return s.integrity&&(n.integrity=s.integrity),s.referrerPolicy&&(n.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?n.credentials="include":s.crossOrigin==="anonymous"?n.credentials="omit":n.credentials="same-origin",n}function r(s){if(s.ep)return;s.ep=!0;const n=i(s);fetch(s.href,n)}})();function dp(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var ld={exports:{}},ho={},ad={exports:{}},K={};/** + * @license React + * react.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var Os=Symbol.for("react.element"),fp=Symbol.for("react.portal"),_p=Symbol.for("react.fragment"),pp=Symbol.for("react.strict_mode"),gp=Symbol.for("react.profiler"),vp=Symbol.for("react.provider"),mp=Symbol.for("react.context"),Sp=Symbol.for("react.forward_ref"),yp=Symbol.for("react.suspense"),wp=Symbol.for("react.memo"),Cp=Symbol.for("react.lazy"),Zh=Symbol.iterator;function kp(e){return e===null||typeof e!="object"?null:(e=Zh&&e[Zh]||e["@@iterator"],typeof e=="function"?e:null)}var hd={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},cd=Object.assign,ud={};function Lr(e,t,i){this.props=e,this.context=t,this.refs=ud,this.updater=i||hd}Lr.prototype.isReactComponent={};Lr.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};Lr.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function dd(){}dd.prototype=Lr.prototype;function Ya(e,t,i){this.props=e,this.context=t,this.refs=ud,this.updater=i||hd}var qa=Ya.prototype=new dd;qa.constructor=Ya;cd(qa,Lr.prototype);qa.isPureReactComponent=!0;var Jh=Array.isArray,fd=Object.prototype.hasOwnProperty,Xa={current:null},_d={key:!0,ref:!0,__self:!0,__source:!0};function pd(e,t,i){var r,s={},n=null,o=null;if(t!=null)for(r in t.ref!==void 0&&(o=t.ref),t.key!==void 0&&(n=""+t.key),t)fd.call(t,r)&&!_d.hasOwnProperty(r)&&(s[r]=t[r]);var l=arguments.length-2;if(l===1)s.children=i;else if(1>>1,Q=y[Y];if(0>>1;Ys(Qe,I))ves(dt,Qe)?(y[Y]=dt,y[ve]=I,Y=ve):(y[Y]=Qe,y[ce]=I,Y=ce);else if(ves(dt,I))y[Y]=dt,y[ve]=I,Y=ve;else break e}}return T}function s(y,T){var I=y.sortIndex-T.sortIndex;return I!==0?I:y.id-T.id}if(typeof performance=="object"&&typeof performance.now=="function"){var n=performance;e.unstable_now=function(){return n.now()}}else{var o=Date,l=o.now();e.unstable_now=function(){return o.now()-l}}var a=[],h=[],u=1,c=null,d=3,g=!1,v=!1,m=!1,k=typeof setTimeout=="function"?setTimeout:null,_=typeof clearTimeout=="function"?clearTimeout:null,f=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function p(y){for(var T=i(h);T!==null;){if(T.callback===null)r(h);else if(T.startTime<=y)r(h),T.sortIndex=T.expirationTime,t(a,T);else break;T=i(h)}}function S(y){if(m=!1,p(y),!v)if(i(a)!==null)v=!0,A(w);else{var T=i(h);T!==null&&z(S,T.startTime-y)}}function w(y,T){v=!1,m&&(m=!1,_(B),B=-1),g=!0;var I=d;try{for(p(T),c=i(a);c!==null&&(!(c.expirationTime>T)||y&&!V());){var Y=c.callback;if(typeof Y=="function"){c.callback=null,d=c.priorityLevel;var Q=Y(c.expirationTime<=T);T=e.unstable_now(),typeof Q=="function"?c.callback=Q:c===i(a)&&r(a),p(T)}else r(a);c=i(a)}if(c!==null)var Te=!0;else{var ce=i(h);ce!==null&&z(S,ce.startTime-T),Te=!1}return Te}finally{c=null,d=I,g=!1}}var b=!1,R=null,B=-1,U=5,$=-1;function V(){return!(e.unstable_now()-$y||125Y?(y.sortIndex=I,t(h,y),i(a)===null&&y===i(h)&&(m?(_(B),B=-1):m=!0,z(S,I-Y))):(y.sortIndex=Q,t(a,y),v||g||(v=!0,A(w))),y},e.unstable_shouldYield=V,e.unstable_wrapCallback=function(y){var T=d;return function(){var I=d;d=T;try{return y.apply(this,arguments)}finally{d=I}}}})(yd);Sd.exports=yd;var Op=Sd.exports;/** + * @license React + * react-dom.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var Ap=oe,ht=Op;function E(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,i=1;i"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),ml=Object.prototype.hasOwnProperty,Ip=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,tc={},ic={};function zp(e){return ml.call(ic,e)?!0:ml.call(tc,e)?!1:Ip.test(e)?ic[e]=!0:(tc[e]=!0,!1)}function Fp(e,t,i,r){if(i!==null&&i.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:i!==null?!i.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function $p(e,t,i,r){if(t===null||typeof t>"u"||Fp(e,t,i,r))return!0;if(r)return!1;if(i!==null)switch(i.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function qe(e,t,i,r,s,n,o){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=s,this.mustUseProperty=i,this.propertyName=e,this.type=t,this.sanitizeURL=n,this.removeEmptyString=o}var ze={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){ze[e]=new qe(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];ze[t]=new qe(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){ze[e]=new qe(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){ze[e]=new qe(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){ze[e]=new qe(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){ze[e]=new qe(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){ze[e]=new qe(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){ze[e]=new qe(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){ze[e]=new qe(e,5,!1,e.toLowerCase(),null,!1,!1)});var Qa=/[\-:]([a-z])/g;function Za(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(Qa,Za);ze[t]=new qe(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(Qa,Za);ze[t]=new qe(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(Qa,Za);ze[t]=new qe(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){ze[e]=new qe(e,1,!1,e.toLowerCase(),null,!1,!1)});ze.xlinkHref=new qe("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){ze[e]=new qe(e,1,!1,e.toLowerCase(),null,!0,!0)});function Ja(e,t,i,r){var s=ze.hasOwnProperty(t)?ze[t]:null;(s!==null?s.type!==0:r||!(2l||s[o]!==n[l]){var a=` +`+s[o].replace(" at new "," at ");return e.displayName&&a.includes("")&&(a=a.replace("",e.displayName)),a}while(1<=o&&0<=l);break}}}finally{No=!1,Error.prepareStackTrace=i}return(e=e?e.displayName||e.name:"")?Gr(e):""}function Hp(e){switch(e.tag){case 5:return Gr(e.type);case 16:return Gr("Lazy");case 13:return Gr("Suspense");case 19:return Gr("SuspenseList");case 0:case 2:case 15:return e=Oo(e.type,!1),e;case 11:return e=Oo(e.type.render,!1),e;case 1:return e=Oo(e.type,!0),e;default:return""}}function Cl(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case rr:return"Fragment";case ir:return"Portal";case Sl:return"Profiler";case eh:return"StrictMode";case yl:return"Suspense";case wl:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case kd:return(e.displayName||"Context")+".Consumer";case Cd:return(e._context.displayName||"Context")+".Provider";case th:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case ih:return t=e.displayName||null,t!==null?t:Cl(e.type)||"Memo";case ai:t=e._payload,e=e._init;try{return Cl(e(t))}catch{}}return null}function Wp(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return Cl(t);case 8:return t===eh?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function bi(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function bd(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function Up(e){var t=bd(e)?"checked":"value",i=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof i<"u"&&typeof i.get=="function"&&typeof i.set=="function"){var s=i.get,n=i.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return s.call(this)},set:function(o){r=""+o,n.call(this,o)}}),Object.defineProperty(e,t,{enumerable:i.enumerable}),{getValue:function(){return r},setValue:function(o){r=""+o},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function Ys(e){e._valueTracker||(e._valueTracker=Up(e))}function Ed(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var i=t.getValue(),r="";return e&&(r=bd(e)?e.checked?"true":"false":e.value),e=r,e!==i?(t.setValue(e),!0):!1}function Tn(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function kl(e,t){var i=t.checked;return he({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:i??e._wrapperState.initialChecked})}function sc(e,t){var i=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;i=bi(t.value!=null?t.value:i),e._wrapperState={initialChecked:r,initialValue:i,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function Dd(e,t){t=t.checked,t!=null&&Ja(e,"checked",t,!1)}function xl(e,t){Dd(e,t);var i=bi(t.value),r=t.type;if(i!=null)r==="number"?(i===0&&e.value===""||e.value!=i)&&(e.value=""+i):e.value!==""+i&&(e.value=""+i);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?bl(e,t.type,i):t.hasOwnProperty("defaultValue")&&bl(e,t.type,bi(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function nc(e,t,i){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,i||t===e.value||(e.value=t),e.defaultValue=t}i=e.name,i!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,i!==""&&(e.name=i)}function bl(e,t,i){(t!=="number"||Tn(e.ownerDocument)!==e)&&(i==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+i&&(e.defaultValue=""+i))}var Qr=Array.isArray;function gr(e,t,i,r){if(e=e.options,t){t={};for(var s=0;s"+t.valueOf().toString()+"",t=qs.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function gs(e,t){if(t){var i=e.firstChild;if(i&&i===e.lastChild&&i.nodeType===3){i.nodeValue=t;return}}e.textContent=t}var ns={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},Kp=["Webkit","ms","Moz","O"];Object.keys(ns).forEach(function(e){Kp.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),ns[t]=ns[e]})});function Bd(e,t,i){return t==null||typeof t=="boolean"||t===""?"":i||typeof t!="number"||t===0||ns.hasOwnProperty(e)&&ns[e]?(""+t).trim():t+"px"}function Md(e,t){e=e.style;for(var i in t)if(t.hasOwnProperty(i)){var r=i.indexOf("--")===0,s=Bd(i,t[i],r);i==="float"&&(i="cssFloat"),r?e.setProperty(i,s):e[i]=s}}var Vp=he({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function Rl(e,t){if(t){if(Vp[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(E(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(E(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(E(61))}if(t.style!=null&&typeof t.style!="object")throw Error(E(62))}}function Pl(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var Ll=null;function rh(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var Bl=null,vr=null,mr=null;function ac(e){if(e=zs(e)){if(typeof Bl!="function")throw Error(E(280));var t=e.stateNode;t&&(t=po(t),Bl(e.stateNode,e.type,t))}}function Td(e){vr?mr?mr.push(e):mr=[e]:vr=e}function Nd(){if(vr){var e=vr,t=mr;if(mr=vr=null,ac(e),t)for(e=0;e>>=0,e===0?32:31-(ig(e)/rg|0)|0}var Xs=64,Gs=4194304;function Zr(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function In(e,t){var i=e.pendingLanes;if(i===0)return 0;var r=0,s=e.suspendedLanes,n=e.pingedLanes,o=i&268435455;if(o!==0){var l=o&~s;l!==0?r=Zr(l):(n&=o,n!==0&&(r=Zr(n)))}else o=i&~s,o!==0?r=Zr(o):n!==0&&(r=Zr(n));if(r===0)return 0;if(t!==0&&t!==r&&!(t&s)&&(s=r&-r,n=t&-t,s>=n||s===16&&(n&4194240)!==0))return t;if(r&4&&(r|=i&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0i;i++)t.push(e);return t}function As(e,t,i){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-Rt(t),e[t]=i}function lg(e,t){var i=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=ls),vc=" ",mc=!1;function ef(e,t){switch(e){case"keyup":return Og.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function tf(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var sr=!1;function Ig(e,t){switch(e){case"compositionend":return tf(t);case"keypress":return t.which!==32?null:(mc=!0,vc);case"textInput":return e=t.data,e===vc&&mc?null:e;default:return null}}function zg(e,t){if(sr)return e==="compositionend"||!uh&&ef(e,t)?(e=Zd(),mn=ah=fi=null,sr=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:i,offset:t-e};e=r}e:{for(;i;){if(i.nextSibling){i=i.nextSibling;break e}i=i.parentNode}i=void 0}i=Cc(i)}}function of(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?of(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function lf(){for(var e=window,t=Tn();t instanceof e.HTMLIFrameElement;){try{var i=typeof t.contentWindow.location.href=="string"}catch{i=!1}if(i)e=t.contentWindow;else break;t=Tn(e.document)}return t}function dh(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function Yg(e){var t=lf(),i=e.focusedElem,r=e.selectionRange;if(t!==i&&i&&i.ownerDocument&&of(i.ownerDocument.documentElement,i)){if(r!==null&&dh(i)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in i)i.selectionStart=t,i.selectionEnd=Math.min(e,i.value.length);else if(e=(t=i.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var s=i.textContent.length,n=Math.min(r.start,s);r=r.end===void 0?n:Math.min(r.end,s),!e.extend&&n>r&&(s=r,r=n,n=s),s=kc(i,n);var o=kc(i,r);s&&o&&(e.rangeCount!==1||e.anchorNode!==s.node||e.anchorOffset!==s.offset||e.focusNode!==o.node||e.focusOffset!==o.offset)&&(t=t.createRange(),t.setStart(s.node,s.offset),e.removeAllRanges(),n>r?(e.addRange(t),e.extend(o.node,o.offset)):(t.setEnd(o.node,o.offset),e.addRange(t)))}}for(t=[],e=i;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof i.focus=="function"&&i.focus(),i=0;i=document.documentMode,nr=null,Il=null,hs=null,zl=!1;function xc(e,t,i){var r=i.window===i?i.document:i.nodeType===9?i:i.ownerDocument;zl||nr==null||nr!==Tn(r)||(r=nr,"selectionStart"in r&&dh(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),hs&&Cs(hs,r)||(hs=r,r=$n(Il,"onSelect"),0ar||(e.current=Kl[ar],Kl[ar]=null,ar--)}function Z(e,t){ar++,Kl[ar]=e.current,e.current=t}var Ei={},Ue=Ri(Ei),tt=Ri(!1),Wi=Ei;function kr(e,t){var i=e.type.contextTypes;if(!i)return Ei;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var s={},n;for(n in i)s[n]=t[n];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=s),s}function it(e){return e=e.childContextTypes,e!=null}function Wn(){te(tt),te(Ue)}function Bc(e,t,i){if(Ue.current!==Ei)throw Error(E(168));Z(Ue,t),Z(tt,i)}function gf(e,t,i){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return i;r=r.getChildContext();for(var s in r)if(!(s in t))throw Error(E(108,Wp(e)||"Unknown",s));return he({},i,r)}function Un(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Ei,Wi=Ue.current,Z(Ue,e),Z(tt,tt.current),!0}function Mc(e,t,i){var r=e.stateNode;if(!r)throw Error(E(169));i?(e=gf(e,t,Wi),r.__reactInternalMemoizedMergedChildContext=e,te(tt),te(Ue),Z(Ue,e)):te(tt),Z(tt,i)}var Kt=null,go=!1,Xo=!1;function vf(e){Kt===null?Kt=[e]:Kt.push(e)}function nv(e){go=!0,vf(e)}function Pi(){if(!Xo&&Kt!==null){Xo=!0;var e=0,t=X;try{var i=Kt;for(X=1;e>=o,s-=o,Vt=1<<32-Rt(t)+s|i<B?(U=R,R=null):U=R.sibling;var $=d(_,R,p[B],S);if($===null){R===null&&(R=U);break}e&&R&&$.alternate===null&&t(_,R),f=n($,f,B),b===null?w=$:b.sibling=$,b=$,R=U}if(B===p.length)return i(_,R),ie&&Bi(_,B),w;if(R===null){for(;BB?(U=R,R=null):U=R.sibling;var V=d(_,R,$.value,S);if(V===null){R===null&&(R=U);break}e&&R&&V.alternate===null&&t(_,R),f=n(V,f,B),b===null?w=V:b.sibling=V,b=V,R=U}if($.done)return i(_,R),ie&&Bi(_,B),w;if(R===null){for(;!$.done;B++,$=p.next())$=c(_,$.value,S),$!==null&&(f=n($,f,B),b===null?w=$:b.sibling=$,b=$);return ie&&Bi(_,B),w}for(R=r(_,R);!$.done;B++,$=p.next())$=g(R,_,B,$.value,S),$!==null&&(e&&$.alternate!==null&&R.delete($.key===null?B:$.key),f=n($,f,B),b===null?w=$:b.sibling=$,b=$);return e&&R.forEach(function(N){return t(_,N)}),ie&&Bi(_,B),w}function k(_,f,p,S){if(typeof p=="object"&&p!==null&&p.type===rr&&p.key===null&&(p=p.props.children),typeof p=="object"&&p!==null){switch(p.$$typeof){case js:e:{for(var w=p.key,b=f;b!==null;){if(b.key===w){if(w=p.type,w===rr){if(b.tag===7){i(_,b.sibling),f=s(b,p.props.children),f.return=_,_=f;break e}}else if(b.elementType===w||typeof w=="object"&&w!==null&&w.$$typeof===ai&&Oc(w)===b.type){i(_,b.sibling),f=s(b,p.props),f.ref=Hr(_,b,p),f.return=_,_=f;break e}i(_,b);break}else t(_,b);b=b.sibling}p.type===rr?(f=$i(p.props.children,_.mode,S,p.key),f.return=_,_=f):(S=En(p.type,p.key,p.props,null,_.mode,S),S.ref=Hr(_,f,p),S.return=_,_=S)}return o(_);case ir:e:{for(b=p.key;f!==null;){if(f.key===b)if(f.tag===4&&f.stateNode.containerInfo===p.containerInfo&&f.stateNode.implementation===p.implementation){i(_,f.sibling),f=s(f,p.children||[]),f.return=_,_=f;break e}else{i(_,f);break}else t(_,f);f=f.sibling}f=rl(p,_.mode,S),f.return=_,_=f}return o(_);case ai:return b=p._init,k(_,f,b(p._payload),S)}if(Qr(p))return v(_,f,p,S);if(Ar(p))return m(_,f,p,S);sn(_,p)}return typeof p=="string"&&p!==""||typeof p=="number"?(p=""+p,f!==null&&f.tag===6?(i(_,f.sibling),f=s(f,p),f.return=_,_=f):(i(_,f),f=il(p,_.mode,S),f.return=_,_=f),o(_)):i(_,f)}return k}var br=wf(!0),Cf=wf(!1),jn=Ri(null),Yn=null,ur=null,gh=null;function vh(){gh=ur=Yn=null}function mh(e){var t=jn.current;te(jn),e._currentValue=t}function Yl(e,t,i){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,r!==null&&(r.childLanes|=t)):r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===i)break;e=e.return}}function yr(e,t){Yn=e,gh=ur=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(et=!0),e.firstContext=null)}function wt(e){var t=e._currentValue;if(gh!==e)if(e={context:e,memoizedValue:t,next:null},ur===null){if(Yn===null)throw Error(E(308));ur=e,Yn.dependencies={lanes:0,firstContext:e}}else ur=ur.next=e;return t}var Ai=null;function Sh(e){Ai===null?Ai=[e]:Ai.push(e)}function kf(e,t,i,r){var s=t.interleaved;return s===null?(i.next=i,Sh(t)):(i.next=s.next,s.next=i),t.interleaved=i,Qt(e,r)}function Qt(e,t){e.lanes|=t;var i=e.alternate;for(i!==null&&(i.lanes|=t),i=e,e=e.return;e!==null;)e.childLanes|=t,i=e.alternate,i!==null&&(i.childLanes|=t),i=e,e=e.return;return i.tag===3?i.stateNode:null}var hi=!1;function yh(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function xf(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function qt(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function yi(e,t,i){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,j&2){var s=r.pending;return s===null?t.next=t:(t.next=s.next,s.next=t),r.pending=t,Qt(e,i)}return s=r.interleaved,s===null?(t.next=t,Sh(r)):(t.next=s.next,s.next=t),r.interleaved=t,Qt(e,i)}function yn(e,t,i){if(t=t.updateQueue,t!==null&&(t=t.shared,(i&4194240)!==0)){var r=t.lanes;r&=e.pendingLanes,i|=r,t.lanes=i,nh(e,i)}}function Ac(e,t){var i=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,i===r)){var s=null,n=null;if(i=i.firstBaseUpdate,i!==null){do{var o={eventTime:i.eventTime,lane:i.lane,tag:i.tag,payload:i.payload,callback:i.callback,next:null};n===null?s=n=o:n=n.next=o,i=i.next}while(i!==null);n===null?s=n=t:n=n.next=t}else s=n=t;i={baseState:r.baseState,firstBaseUpdate:s,lastBaseUpdate:n,shared:r.shared,effects:r.effects},e.updateQueue=i;return}e=i.lastBaseUpdate,e===null?i.firstBaseUpdate=t:e.next=t,i.lastBaseUpdate=t}function qn(e,t,i,r){var s=e.updateQueue;hi=!1;var n=s.firstBaseUpdate,o=s.lastBaseUpdate,l=s.shared.pending;if(l!==null){s.shared.pending=null;var a=l,h=a.next;a.next=null,o===null?n=h:o.next=h,o=a;var u=e.alternate;u!==null&&(u=u.updateQueue,l=u.lastBaseUpdate,l!==o&&(l===null?u.firstBaseUpdate=h:l.next=h,u.lastBaseUpdate=a))}if(n!==null){var c=s.baseState;o=0,u=h=a=null,l=n;do{var d=l.lane,g=l.eventTime;if((r&d)===d){u!==null&&(u=u.next={eventTime:g,lane:0,tag:l.tag,payload:l.payload,callback:l.callback,next:null});e:{var v=e,m=l;switch(d=t,g=i,m.tag){case 1:if(v=m.payload,typeof v=="function"){c=v.call(g,c,d);break e}c=v;break e;case 3:v.flags=v.flags&-65537|128;case 0:if(v=m.payload,d=typeof v=="function"?v.call(g,c,d):v,d==null)break e;c=he({},c,d);break e;case 2:hi=!0}}l.callback!==null&&l.lane!==0&&(e.flags|=64,d=s.effects,d===null?s.effects=[l]:d.push(l))}else g={eventTime:g,lane:d,tag:l.tag,payload:l.payload,callback:l.callback,next:null},u===null?(h=u=g,a=c):u=u.next=g,o|=d;if(l=l.next,l===null){if(l=s.shared.pending,l===null)break;d=l,l=d.next,d.next=null,s.lastBaseUpdate=d,s.shared.pending=null}}while(!0);if(u===null&&(a=c),s.baseState=a,s.firstBaseUpdate=h,s.lastBaseUpdate=u,t=s.shared.interleaved,t!==null){s=t;do o|=s.lane,s=s.next;while(s!==t)}else n===null&&(s.shared.lanes=0);Vi|=o,e.lanes=o,e.memoizedState=c}}function Ic(e,t,i){if(e=t.effects,t.effects=null,e!==null)for(t=0;ti?i:4,e(!0);var r=Qo.transition;Qo.transition={};try{e(!1),t()}finally{X=i,Qo.transition=r}}function Hf(){return Ct().memoizedState}function hv(e,t,i){var r=Ci(e);if(i={lane:r,action:i,hasEagerState:!1,eagerState:null,next:null},Wf(e))Uf(t,i);else if(i=kf(e,t,i,r),i!==null){var s=je();Pt(i,e,r,s),Kf(i,t,r)}}function cv(e,t,i){var r=Ci(e),s={lane:r,action:i,hasEagerState:!1,eagerState:null,next:null};if(Wf(e))Uf(t,s);else{var n=e.alternate;if(e.lanes===0&&(n===null||n.lanes===0)&&(n=t.lastRenderedReducer,n!==null))try{var o=t.lastRenderedState,l=n(o,i);if(s.hasEagerState=!0,s.eagerState=l,Lt(l,o)){var a=t.interleaved;a===null?(s.next=s,Sh(t)):(s.next=a.next,a.next=s),t.interleaved=s;return}}catch{}finally{}i=kf(e,t,s,r),i!==null&&(s=je(),Pt(i,e,r,s),Kf(i,t,r))}}function Wf(e){var t=e.alternate;return e===ae||t!==null&&t===ae}function Uf(e,t){cs=Gn=!0;var i=e.pending;i===null?t.next=t:(t.next=i.next,i.next=t),e.pending=t}function Kf(e,t,i){if(i&4194240){var r=t.lanes;r&=e.pendingLanes,i|=r,t.lanes=i,nh(e,i)}}var Qn={readContext:wt,useCallback:Fe,useContext:Fe,useEffect:Fe,useImperativeHandle:Fe,useInsertionEffect:Fe,useLayoutEffect:Fe,useMemo:Fe,useReducer:Fe,useRef:Fe,useState:Fe,useDebugValue:Fe,useDeferredValue:Fe,useTransition:Fe,useMutableSource:Fe,useSyncExternalStore:Fe,useId:Fe,unstable_isNewReconciler:!1},uv={readContext:wt,useCallback:function(e,t){return Ot().memoizedState=[e,t===void 0?null:t],e},useContext:wt,useEffect:Fc,useImperativeHandle:function(e,t,i){return i=i!=null?i.concat([e]):null,Cn(4194308,4,Af.bind(null,t,e),i)},useLayoutEffect:function(e,t){return Cn(4194308,4,e,t)},useInsertionEffect:function(e,t){return Cn(4,2,e,t)},useMemo:function(e,t){var i=Ot();return t=t===void 0?null:t,e=e(),i.memoizedState=[e,t],e},useReducer:function(e,t,i){var r=Ot();return t=i!==void 0?i(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=hv.bind(null,ae,e),[r.memoizedState,e]},useRef:function(e){var t=Ot();return e={current:e},t.memoizedState=e},useState:zc,useDebugValue:Rh,useDeferredValue:function(e){return Ot().memoizedState=e},useTransition:function(){var e=zc(!1),t=e[0];return e=av.bind(null,e[1]),Ot().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,i){var r=ae,s=Ot();if(ie){if(i===void 0)throw Error(E(407));i=i()}else{if(i=t(),Be===null)throw Error(E(349));Ki&30||Rf(r,t,i)}s.memoizedState=i;var n={value:i,getSnapshot:t};return s.queue=n,Fc(Lf.bind(null,r,n,e),[e]),r.flags|=2048,Ls(9,Pf.bind(null,r,n,i,t),void 0,null),i},useId:function(){var e=Ot(),t=Be.identifierPrefix;if(ie){var i=jt,r=Vt;i=(r&~(1<<32-Rt(r)-1)).toString(32)+i,t=":"+t+"R"+i,i=Rs++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=o.createElement(i,{is:r.is}):(e=o.createElement(i),i==="select"&&(o=e,r.multiple?o.multiple=!0:r.size&&(o.size=r.size))):e=o.createElementNS(e,i),e[At]=t,e[bs]=r,e_(e,t,!1,!1),t.stateNode=e;e:{switch(o=Pl(i,r),i){case"dialog":J("cancel",e),J("close",e),s=r;break;case"iframe":case"object":case"embed":J("load",e),s=r;break;case"video":case"audio":for(s=0;sRr&&(t.flags|=128,r=!0,Wr(n,!1),t.lanes=4194304)}else{if(!r)if(e=Xn(o),e!==null){if(t.flags|=128,r=!0,i=e.updateQueue,i!==null&&(t.updateQueue=i,t.flags|=4),Wr(n,!0),n.tail===null&&n.tailMode==="hidden"&&!o.alternate&&!ie)return $e(t),null}else 2*ge()-n.renderingStartTime>Rr&&i!==1073741824&&(t.flags|=128,r=!0,Wr(n,!1),t.lanes=4194304);n.isBackwards?(o.sibling=t.child,t.child=o):(i=n.last,i!==null?i.sibling=o:t.child=o,n.last=o)}return n.tail!==null?(t=n.tail,n.rendering=t,n.tail=t.sibling,n.renderingStartTime=ge(),t.sibling=null,i=le.current,Z(le,r?i&1|2:i&1),t):($e(t),null);case 22:case 23:return Nh(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?ot&1073741824&&($e(t),t.subtreeFlags&6&&(t.flags|=8192)):$e(t),null;case 24:return null;case 25:return null}throw Error(E(156,t.tag))}function Sv(e,t){switch(_h(t),t.tag){case 1:return it(t.type)&&Wn(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Er(),te(tt),te(Ue),kh(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Ch(t),null;case 13:if(te(le),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(E(340));xr()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return te(le),null;case 4:return Er(),null;case 10:return mh(t.type._context),null;case 22:case 23:return Nh(),null;case 24:return null;default:return null}}var on=!1,We=!1,yv=typeof WeakSet=="function"?WeakSet:Set,O=null;function dr(e,t){var i=e.ref;if(i!==null)if(typeof i=="function")try{i(null)}catch(r){fe(e,t,r)}else i.current=null}function ia(e,t,i){try{i()}catch(r){fe(e,t,r)}}var Gc=!1;function wv(e,t){if(Fl=zn,e=lf(),dh(e)){if("selectionStart"in e)var i={start:e.selectionStart,end:e.selectionEnd};else e:{i=(i=e.ownerDocument)&&i.defaultView||window;var r=i.getSelection&&i.getSelection();if(r&&r.rangeCount!==0){i=r.anchorNode;var s=r.anchorOffset,n=r.focusNode;r=r.focusOffset;try{i.nodeType,n.nodeType}catch{i=null;break e}var o=0,l=-1,a=-1,h=0,u=0,c=e,d=null;t:for(;;){for(var g;c!==i||s!==0&&c.nodeType!==3||(l=o+s),c!==n||r!==0&&c.nodeType!==3||(a=o+r),c.nodeType===3&&(o+=c.nodeValue.length),(g=c.firstChild)!==null;)d=c,c=g;for(;;){if(c===e)break t;if(d===i&&++h===s&&(l=o),d===n&&++u===r&&(a=o),(g=c.nextSibling)!==null)break;c=d,d=c.parentNode}c=g}i=l===-1||a===-1?null:{start:l,end:a}}else i=null}i=i||{start:0,end:0}}else i=null;for($l={focusedElem:e,selectionRange:i},zn=!1,O=t;O!==null;)if(t=O,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,O=e;else for(;O!==null;){t=O;try{var v=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(v!==null){var m=v.memoizedProps,k=v.memoizedState,_=t.stateNode,f=_.getSnapshotBeforeUpdate(t.elementType===t.type?m:bt(t.type,m),k);_.__reactInternalSnapshotBeforeUpdate=f}break;case 3:var p=t.stateNode.containerInfo;p.nodeType===1?p.textContent="":p.nodeType===9&&p.documentElement&&p.removeChild(p.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(E(163))}}catch(S){fe(t,t.return,S)}if(e=t.sibling,e!==null){e.return=t.return,O=e;break}O=t.return}return v=Gc,Gc=!1,v}function us(e,t,i){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var s=r=r.next;do{if((s.tag&e)===e){var n=s.destroy;s.destroy=void 0,n!==void 0&&ia(t,i,n)}s=s.next}while(s!==r)}}function So(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var i=t=t.next;do{if((i.tag&e)===e){var r=i.create;i.destroy=r()}i=i.next}while(i!==t)}}function ra(e){var t=e.ref;if(t!==null){var i=e.stateNode;switch(e.tag){case 5:e=i;break;default:e=i}typeof t=="function"?t(e):t.current=e}}function r_(e){var t=e.alternate;t!==null&&(e.alternate=null,r_(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[At],delete t[bs],delete t[Ul],delete t[rv],delete t[sv])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function s_(e){return e.tag===5||e.tag===3||e.tag===4}function Qc(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||s_(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function sa(e,t,i){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?i.nodeType===8?i.parentNode.insertBefore(e,t):i.insertBefore(e,t):(i.nodeType===8?(t=i.parentNode,t.insertBefore(e,i)):(t=i,t.appendChild(e)),i=i._reactRootContainer,i!=null||t.onclick!==null||(t.onclick=Hn));else if(r!==4&&(e=e.child,e!==null))for(sa(e,t,i),e=e.sibling;e!==null;)sa(e,t,i),e=e.sibling}function na(e,t,i){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?i.insertBefore(e,t):i.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(na(e,t,i),e=e.sibling;e!==null;)na(e,t,i),e=e.sibling}var Ne=null,Et=!1;function si(e,t,i){for(i=i.child;i!==null;)n_(e,t,i),i=i.sibling}function n_(e,t,i){if(zt&&typeof zt.onCommitFiberUnmount=="function")try{zt.onCommitFiberUnmount(co,i)}catch{}switch(i.tag){case 5:We||dr(i,t);case 6:var r=Ne,s=Et;Ne=null,si(e,t,i),Ne=r,Et=s,Ne!==null&&(Et?(e=Ne,i=i.stateNode,e.nodeType===8?e.parentNode.removeChild(i):e.removeChild(i)):Ne.removeChild(i.stateNode));break;case 18:Ne!==null&&(Et?(e=Ne,i=i.stateNode,e.nodeType===8?qo(e.parentNode,i):e.nodeType===1&&qo(e,i),ys(e)):qo(Ne,i.stateNode));break;case 4:r=Ne,s=Et,Ne=i.stateNode.containerInfo,Et=!0,si(e,t,i),Ne=r,Et=s;break;case 0:case 11:case 14:case 15:if(!We&&(r=i.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){s=r=r.next;do{var n=s,o=n.destroy;n=n.tag,o!==void 0&&(n&2||n&4)&&ia(i,t,o),s=s.next}while(s!==r)}si(e,t,i);break;case 1:if(!We&&(dr(i,t),r=i.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=i.memoizedProps,r.state=i.memoizedState,r.componentWillUnmount()}catch(l){fe(i,t,l)}si(e,t,i);break;case 21:si(e,t,i);break;case 22:i.mode&1?(We=(r=We)||i.memoizedState!==null,si(e,t,i),We=r):si(e,t,i);break;default:si(e,t,i)}}function Zc(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var i=e.stateNode;i===null&&(i=e.stateNode=new yv),t.forEach(function(r){var s=Lv.bind(null,e,r);i.has(r)||(i.add(r),r.then(s,s))})}}function kt(e,t){var i=t.deletions;if(i!==null)for(var r=0;rs&&(s=o),r&=~n}if(r=s,r=ge()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*kv(r/1960))-r,10e?16:e,_i===null)var r=!1;else{if(e=_i,_i=null,eo=0,j&6)throw Error(E(331));var s=j;for(j|=4,O=e.current;O!==null;){var n=O,o=n.child;if(O.flags&16){var l=n.deletions;if(l!==null){for(var a=0;age()-Mh?Fi(e,0):Bh|=i),rt(e,t)}function f_(e,t){t===0&&(e.mode&1?(t=Gs,Gs<<=1,!(Gs&130023424)&&(Gs=4194304)):t=1);var i=je();e=Qt(e,t),e!==null&&(As(e,t,i),rt(e,i))}function Pv(e){var t=e.memoizedState,i=0;t!==null&&(i=t.retryLane),f_(e,i)}function Lv(e,t){var i=0;switch(e.tag){case 13:var r=e.stateNode,s=e.memoizedState;s!==null&&(i=s.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(E(314))}r!==null&&r.delete(t),f_(e,i)}var __;__=function(e,t,i){if(e!==null)if(e.memoizedProps!==t.pendingProps||tt.current)et=!0;else{if(!(e.lanes&i)&&!(t.flags&128))return et=!1,vv(e,t,i);et=!!(e.flags&131072)}else et=!1,ie&&t.flags&1048576&&mf(t,Vn,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;kn(e,t),e=t.pendingProps;var s=kr(t,Ue.current);yr(t,i),s=bh(null,t,r,e,s,i);var n=Eh();return t.flags|=1,typeof s=="object"&&s!==null&&typeof s.render=="function"&&s.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,it(r)?(n=!0,Un(t)):n=!1,t.memoizedState=s.state!==null&&s.state!==void 0?s.state:null,yh(t),s.updater=mo,t.stateNode=s,s._reactInternals=t,Xl(t,r,e,i),t=Zl(null,t,r,!0,n,i)):(t.tag=0,ie&&n&&fh(t),Ve(null,t,s,i),t=t.child),t;case 16:r=t.elementType;e:{switch(kn(e,t),e=t.pendingProps,s=r._init,r=s(r._payload),t.type=r,s=t.tag=Mv(r),e=bt(r,e),s){case 0:t=Ql(null,t,r,e,i);break e;case 1:t=Yc(null,t,r,e,i);break e;case 11:t=Vc(null,t,r,e,i);break e;case 14:t=jc(null,t,r,bt(r.type,e),i);break e}throw Error(E(306,r,""))}return t;case 0:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:bt(r,s),Ql(e,t,r,s,i);case 1:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:bt(r,s),Yc(e,t,r,s,i);case 3:e:{if(Qf(t),e===null)throw Error(E(387));r=t.pendingProps,n=t.memoizedState,s=n.element,xf(e,t),qn(t,r,null,i);var o=t.memoizedState;if(r=o.element,n.isDehydrated)if(n={element:r,isDehydrated:!1,cache:o.cache,pendingSuspenseBoundaries:o.pendingSuspenseBoundaries,transitions:o.transitions},t.updateQueue.baseState=n,t.memoizedState=n,t.flags&256){s=Dr(Error(E(423)),t),t=qc(e,t,r,i,s);break e}else if(r!==s){s=Dr(Error(E(424)),t),t=qc(e,t,r,i,s);break e}else for(lt=Si(t.stateNode.containerInfo.firstChild),at=t,ie=!0,Dt=null,i=Cf(t,null,r,i),t.child=i;i;)i.flags=i.flags&-3|4096,i=i.sibling;else{if(xr(),r===s){t=Zt(e,t,i);break e}Ve(e,t,r,i)}t=t.child}return t;case 5:return bf(t),e===null&&jl(t),r=t.type,s=t.pendingProps,n=e!==null?e.memoizedProps:null,o=s.children,Hl(r,s)?o=null:n!==null&&Hl(r,n)&&(t.flags|=32),Gf(e,t),Ve(e,t,o,i),t.child;case 6:return e===null&&jl(t),null;case 13:return Zf(e,t,i);case 4:return wh(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=br(t,null,r,i):Ve(e,t,r,i),t.child;case 11:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:bt(r,s),Vc(e,t,r,s,i);case 7:return Ve(e,t,t.pendingProps,i),t.child;case 8:return Ve(e,t,t.pendingProps.children,i),t.child;case 12:return Ve(e,t,t.pendingProps.children,i),t.child;case 10:e:{if(r=t.type._context,s=t.pendingProps,n=t.memoizedProps,o=s.value,Z(jn,r._currentValue),r._currentValue=o,n!==null)if(Lt(n.value,o)){if(n.children===s.children&&!tt.current){t=Zt(e,t,i);break e}}else for(n=t.child,n!==null&&(n.return=t);n!==null;){var l=n.dependencies;if(l!==null){o=n.child;for(var a=l.firstContext;a!==null;){if(a.context===r){if(n.tag===1){a=qt(-1,i&-i),a.tag=2;var h=n.updateQueue;if(h!==null){h=h.shared;var u=h.pending;u===null?a.next=a:(a.next=u.next,u.next=a),h.pending=a}}n.lanes|=i,a=n.alternate,a!==null&&(a.lanes|=i),Yl(n.return,i,t),l.lanes|=i;break}a=a.next}}else if(n.tag===10)o=n.type===t.type?null:n.child;else if(n.tag===18){if(o=n.return,o===null)throw Error(E(341));o.lanes|=i,l=o.alternate,l!==null&&(l.lanes|=i),Yl(o,i,t),o=n.sibling}else o=n.child;if(o!==null)o.return=n;else for(o=n;o!==null;){if(o===t){o=null;break}if(n=o.sibling,n!==null){n.return=o.return,o=n;break}o=o.return}n=o}Ve(e,t,s.children,i),t=t.child}return t;case 9:return s=t.type,r=t.pendingProps.children,yr(t,i),s=wt(s),r=r(s),t.flags|=1,Ve(e,t,r,i),t.child;case 14:return r=t.type,s=bt(r,t.pendingProps),s=bt(r.type,s),jc(e,t,r,s,i);case 15:return qf(e,t,t.type,t.pendingProps,i);case 17:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:bt(r,s),kn(e,t),t.tag=1,it(r)?(e=!0,Un(t)):e=!1,yr(t,i),Vf(t,r,s),Xl(t,r,s,i),Zl(null,t,r,!0,e,i);case 19:return Jf(e,t,i);case 22:return Xf(e,t,i)}throw Error(E(156,t.tag))};function p_(e,t){return Hd(e,t)}function Bv(e,t,i,r){this.tag=e,this.key=i,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function mt(e,t,i,r){return new Bv(e,t,i,r)}function Ah(e){return e=e.prototype,!(!e||!e.isReactComponent)}function Mv(e){if(typeof e=="function")return Ah(e)?1:0;if(e!=null){if(e=e.$$typeof,e===th)return 11;if(e===ih)return 14}return 2}function ki(e,t){var i=e.alternate;return i===null?(i=mt(e.tag,t,e.key,e.mode),i.elementType=e.elementType,i.type=e.type,i.stateNode=e.stateNode,i.alternate=e,e.alternate=i):(i.pendingProps=t,i.type=e.type,i.flags=0,i.subtreeFlags=0,i.deletions=null),i.flags=e.flags&14680064,i.childLanes=e.childLanes,i.lanes=e.lanes,i.child=e.child,i.memoizedProps=e.memoizedProps,i.memoizedState=e.memoizedState,i.updateQueue=e.updateQueue,t=e.dependencies,i.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},i.sibling=e.sibling,i.index=e.index,i.ref=e.ref,i}function En(e,t,i,r,s,n){var o=2;if(r=e,typeof e=="function")Ah(e)&&(o=1);else if(typeof e=="string")o=5;else e:switch(e){case rr:return $i(i.children,s,n,t);case eh:o=8,s|=8;break;case Sl:return e=mt(12,i,t,s|2),e.elementType=Sl,e.lanes=n,e;case yl:return e=mt(13,i,t,s),e.elementType=yl,e.lanes=n,e;case wl:return e=mt(19,i,t,s),e.elementType=wl,e.lanes=n,e;case xd:return wo(i,s,n,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case Cd:o=10;break e;case kd:o=9;break e;case th:o=11;break e;case ih:o=14;break e;case ai:o=16,r=null;break e}throw Error(E(130,e==null?e:typeof e,""))}return t=mt(o,i,t,s),t.elementType=e,t.type=r,t.lanes=n,t}function $i(e,t,i,r){return e=mt(7,e,r,t),e.lanes=i,e}function wo(e,t,i,r){return e=mt(22,e,r,t),e.elementType=xd,e.lanes=i,e.stateNode={isHidden:!1},e}function il(e,t,i){return e=mt(6,e,null,t),e.lanes=i,e}function rl(e,t,i){return t=mt(4,e.children!==null?e.children:[],e.key,t),t.lanes=i,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function Tv(e,t,i,r,s){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Io(0),this.expirationTimes=Io(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Io(0),this.identifierPrefix=r,this.onRecoverableError=s,this.mutableSourceEagerHydrationData=null}function Ih(e,t,i,r,s,n,o,l,a){return e=new Tv(e,t,i,l,a),t===1?(t=1,n===!0&&(t|=8)):t=0,n=mt(3,null,null,t),e.current=n,n.stateNode=e,n.memoizedState={element:r,isDehydrated:i,cache:null,transitions:null,pendingSuspenseBoundaries:null},yh(n),e}function Nv(e,t,i){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(S_)}catch(e){console.error(e)}}S_(),md.exports=ct;var Fv=md.exports,ou=Fv;vl.createRoot=ou.createRoot,vl.hydrateRoot=ou.hydrateRoot;const y_=oe.createContext({x:0,y:0,scale:1}),Hh=()=>oe.useContext(y_);function w_(e,t){const i=Hh(),r=oe.useRef(null),s=l=>{l.button===0&&(l.stopPropagation(),l.target.setPointerCapture(l.pointerId),r.current={startX:l.clientX,startY:l.clientY,cardX:e.x,cardY:e.y})},n=l=>{const a=r.current;if(!a)return;const h=(l.clientX-a.startX)/i.scale,u=(l.clientY-a.startY)/i.scale;t({x:a.cardX+h,y:a.cardY+u})},o=l=>{if(r.current){try{l.target.releasePointerCapture(l.pointerId)}catch{}r.current=null}};return{onPointerDown:s,onPointerMove:n,onPointerUp:o,onPointerCancel:o}}const $v=13;function Hv({card:e,onUpdate:t}){const i=Hh(),r=w_(e,s=>t(s));return ue.jsxs("div",{className:"card note-card",style:{left:i.x+e.x*i.scale,top:i.y+e.y*i.scale,width:e.width*i.scale,height:e.height*i.scale,zIndex:e.z,fontSize:$v*i.scale,"--scale":i.scale},children:[ue.jsx("div",{className:"card-header",...r,children:"note"}),ue.jsx("div",{className:"card-body",children:ue.jsx("textarea",{value:e.text,onChange:s=>t({text:s.target.value}),onPointerDown:s=>s.stopPropagation()})})]})}/** + * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved. + * @license MIT + * + * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License) + * @license MIT + * + * Originally forked from (with the author's permission): + * Fabrice Bellard's javascript vt100 for jslinux: + * http://bellard.org/jslinux/ + * Copyright (c) 2011 Fabrice Bellard + */var C_=Object.defineProperty,Wv=Object.getOwnPropertyDescriptor,Uv=(e,t)=>{for(var i in t)C_(e,i,{get:t[i],enumerable:!0})},_e=(e,t,i,r)=>{for(var s=r>1?void 0:r?Wv(t,i):t,n=e.length-1,o;n>=0;n--)(o=e[n])&&(s=(r?o(t,i,s):o(s))||s);return r&&s&&C_(t,i,s),s},L=(e,t)=>(i,r)=>t(i,r,e),lu="Terminal input",ca={get:()=>lu,set:e=>lu=e},au="Too much output to announce, navigate to rows manually to read",ua={get:()=>au,set:e=>au=e};function Kv(e){return e.replace(/\r?\n/g,"\r")}function Vv(e,t){return t?"\x1B[200~"+e+"\x1B[201~":e}function jv(e,t){e.clipboardData&&e.clipboardData.setData("text/plain",t.selectionText),e.preventDefault()}function Yv(e,t,i,r){if(e.stopPropagation(),e.clipboardData){let s=e.clipboardData.getData("text/plain");k_(s,t,i,r)}}function k_(e,t,i,r){e=Kv(e),e=Vv(e,i.decPrivateModes.bracketedPasteMode&&r.rawOptions.ignoreBracketedPasteMode!==!0),i.triggerDataEvent(e,!0),t.value=""}function x_(e,t,i){let r=i.getBoundingClientRect(),s=e.clientX-r.left-10,n=e.clientY-r.top-10;t.style.width="20px",t.style.height="20px",t.style.left=`${s}px`,t.style.top=`${n}px`,t.style.zIndex="1000",t.focus()}function hu(e,t,i,r,s){x_(e,t,i),s&&r.rightClickSelect(e),t.value=r.selectionText,t.select()}function ci(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function Eo(e,t=0,i=e.length){let r="";for(let s=t;s65535?(n-=65536,r+=String.fromCharCode((n>>10)+55296)+String.fromCharCode(n%1024+56320)):r+=String.fromCharCode(n)}return r}var qv=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){let i=e.length;if(!i)return 0;let r=0,s=0;if(this._interim){let n=e.charCodeAt(s++);56320<=n&&n<=57343?t[r++]=(this._interim-55296)*1024+n-56320+65536:(t[r++]=this._interim,t[r++]=n),this._interim=0}for(let n=s;n=i)return this._interim=o,r;let l=e.charCodeAt(n);56320<=l&&l<=57343?t[r++]=(o-55296)*1024+l-56320+65536:(t[r++]=o,t[r++]=l);continue}o!==65279&&(t[r++]=o)}return r}},Xv=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let i=e.length;if(!i)return 0;let r=0,s,n,o,l,a=0,h=0;if(this.interim[0]){let d=!1,g=this.interim[0];g&=(g&224)===192?31:(g&240)===224?15:7;let v=0,m;for(;(m=this.interim[++v]&63)&&v<4;)g<<=6,g|=m;let k=(this.interim[0]&224)===192?2:(this.interim[0]&240)===224?3:4,_=k-v;for(;h<_;){if(h>=i)return 0;if(m=e[h++],(m&192)!==128){h--,d=!0;break}else this.interim[v++]=m,g<<=6,g|=m&63}d||(k===2?g<128?h--:t[r++]=g:k===3?g<2048||g>=55296&&g<=57343||g===65279||(t[r++]=g):g<65536||g>1114111||(t[r++]=g)),this.interim.fill(0)}let u=i-4,c=h;for(;c=i)return this.interim[0]=s,r;if(n=e[c++],(n&192)!==128){c--;continue}if(a=(s&31)<<6|n&63,a<128){c--;continue}t[r++]=a}else if((s&240)===224){if(c>=i)return this.interim[0]=s,r;if(n=e[c++],(n&192)!==128){c--;continue}if(c>=i)return this.interim[0]=s,this.interim[1]=n,r;if(o=e[c++],(o&192)!==128){c--;continue}if(a=(s&15)<<12|(n&63)<<6|o&63,a<2048||a>=55296&&a<=57343||a===65279)continue;t[r++]=a}else if((s&248)===240){if(c>=i)return this.interim[0]=s,r;if(n=e[c++],(n&192)!==128){c--;continue}if(c>=i)return this.interim[0]=s,this.interim[1]=n,r;if(o=e[c++],(o&192)!==128){c--;continue}if(c>=i)return this.interim[0]=s,this.interim[1]=n,this.interim[2]=o,r;if(l=e[c++],(l&192)!==128){c--;continue}if(a=(s&7)<<18|(n&63)<<12|(o&63)<<6|l&63,a<65536||a>1114111)continue;t[r++]=a}}return r}},b_="",pi=" ",$s=class E_{constructor(){this.fg=0,this.bg=0,this.extended=new ro}static toColorRGB(t){return[t>>>16&255,t>>>8&255,t&255]}static fromColorRGB(t){return(t[0]&255)<<16|(t[1]&255)<<8|t[2]&255}clone(){let t=new E_;return t.fg=this.fg,t.bg=this.bg,t.extended=this.extended.clone(),t}isInverse(){return this.fg&67108864}isBold(){return this.fg&134217728}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:this.fg&268435456}isBlink(){return this.fg&536870912}isInvisible(){return this.fg&1073741824}isItalic(){return this.bg&67108864}isDim(){return this.bg&134217728}isStrikethrough(){return this.fg&2147483648}isProtected(){return this.bg&536870912}isOverline(){return this.bg&1073741824}getFgColorMode(){return this.fg&50331648}getBgColorMode(){return this.bg&50331648}isFgRGB(){return(this.fg&50331648)===50331648}isBgRGB(){return(this.bg&50331648)===50331648}isFgPalette(){return(this.fg&50331648)===16777216||(this.fg&50331648)===33554432}isBgPalette(){return(this.bg&50331648)===16777216||(this.bg&50331648)===33554432}isFgDefault(){return(this.fg&50331648)===0}isBgDefault(){return(this.bg&50331648)===0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(this.fg&50331648){case 16777216:case 33554432:return this.fg&255;case 50331648:return this.fg&16777215;default:return-1}}getBgColor(){switch(this.bg&50331648){case 16777216:case 33554432:return this.bg&255;case 50331648:return this.bg&16777215;default:return-1}}hasExtendedAttrs(){return this.bg&268435456}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(this.bg&268435456&&~this.extended.underlineColor)switch(this.extended.underlineColor&50331648){case 16777216:case 33554432:return this.extended.underlineColor&255;case 50331648:return this.extended.underlineColor&16777215;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return this.bg&268435456&&~this.extended.underlineColor?this.extended.underlineColor&50331648:this.getFgColorMode()}isUnderlineColorRGB(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===50331648:this.isFgRGB()}isUnderlineColorPalette(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===16777216||(this.extended.underlineColor&50331648)===33554432:this.isFgPalette()}isUnderlineColorDefault(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===0:this.isFgDefault()}getUnderlineStyle(){return this.fg&268435456?this.bg&268435456?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},ro=class D_{constructor(t=0,i=0){this._ext=0,this._urlId=0,this._ext=t,this._urlId=i}get ext(){return this._urlId?this._ext&-469762049|this.underlineStyle<<26:this._ext}set ext(t){this._ext=t}get underlineStyle(){return this._urlId?5:(this._ext&469762048)>>26}set underlineStyle(t){this._ext&=-469762049,this._ext|=t<<26&469762048}get underlineColor(){return this._ext&67108863}set underlineColor(t){this._ext&=-67108864,this._ext|=t&67108863}get urlId(){return this._urlId}set urlId(t){this._urlId=t}get underlineVariantOffset(){let t=(this._ext&3758096384)>>29;return t<0?t^4294967288:t}set underlineVariantOffset(t){this._ext&=536870911,this._ext|=t<<29&3758096384}clone(){return new D_(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},yt=class R_ extends $s{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new ro,this.combinedData=""}static fromCharData(t){let i=new R_;return i.setFromCharData(t),i}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?ci(this.content&2097151):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):this.content&2097151}setFromCharData(t){this.fg=t[0],this.bg=0;let i=!1;if(t[1].length>2)i=!0;else if(t[1].length===2){let r=t[1].charCodeAt(0);if(55296<=r&&r<=56319){let s=t[1].charCodeAt(1);56320<=s&&s<=57343?this.content=(r-55296)*1024+s-56320+65536|t[2]<<22:i=!0}else i=!0}else this.content=t[1].charCodeAt(0)|t[2]<<22;i&&(this.combinedData=t[1],this.content=2097152|t[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},cu="di$target",da="di$dependencies",sl=new Map;function Gv(e){return e[da]||[]}function Me(e){if(sl.has(e))return sl.get(e);let t=function(i,r,s){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");Qv(t,i,s)};return t._id=e,sl.set(e,t),t}function Qv(e,t,i){t[cu]===t?t[da].push({id:e,index:i}):(t[da]=[{id:e,index:i}],t[cu]=t)}var Xe=Me("BufferService"),P_=Me("CoreMouseService"),Qi=Me("CoreService"),Zv=Me("CharsetService"),Wh=Me("InstantiationService"),L_=Me("LogService"),Ge=Me("OptionsService"),B_=Me("OscLinkService"),Jv=Me("UnicodeService"),Hs=Me("DecorationService"),fa=class{constructor(e,t,i){this._bufferService=e,this._optionsService=t,this._oscLinkService=i}provideLinks(e,t){var u;let i=this._bufferService.buffer.lines.get(e-1);if(!i){t(void 0);return}let r=[],s=this._optionsService.rawOptions.linkHandler,n=new yt,o=i.getTrimmedLength(),l=-1,a=-1,h=!1;for(let c=0;cs?s.activate(m,k,g):em(m,k),hover:(m,k)=>{var _;return(_=s==null?void 0:s.hover)==null?void 0:_.call(s,m,k,g)},leave:(m,k)=>{var _;return(_=s==null?void 0:s.leave)==null?void 0:_.call(s,m,k,g)}})}h=!1,n.hasExtendedAttrs()&&n.extended.urlId?(a=c,l=n.extended.urlId):(a=-1,l=-1)}}t(r)}};fa=_e([L(0,Xe),L(1,Ge),L(2,B_)],fa);function em(e,t){if(confirm(`Do you want to navigate to ${t}? + +WARNING: This link could potentially be dangerous`)){let i=window.open();if(i){try{i.opener=null}catch{}i.location.href=t}else console.warn("Opening link blocked as opener could not be cleared")}}var Do=Me("CharSizeService"),ei=Me("CoreBrowserService"),Uh=Me("MouseService"),ti=Me("RenderService"),tm=Me("SelectionService"),M_=Me("CharacterJoinerService"),Tr=Me("ThemeService"),T_=Me("LinkProviderService"),im=class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?uu.isErrorNoTelemetry(e)?new uu(e.message+` + +`+e.stack):new Error(e.message+` + +`+e.stack):e},0)}}addListener(e){return this.listeners.push(e),()=>{this._removeListener(e)}}emit(e){this.listeners.forEach(t=>{t(e)})}_removeListener(e){this.listeners.splice(this.listeners.indexOf(e),1)}setUnexpectedErrorHandler(e){this.unexpectedErrorHandler=e}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(e){this.unexpectedErrorHandler(e),this.emit(e)}onUnexpectedExternalError(e){this.unexpectedErrorHandler(e)}},rm=new im;function Dn(e){sm(e)||rm.onUnexpectedError(e)}var _a="Canceled";function sm(e){return e instanceof nm?!0:e instanceof Error&&e.name===_a&&e.message===_a}var nm=class extends Error{constructor(){super(_a),this.name=this.message}};function om(e){return new Error(`Illegal argument: ${e}`)}var uu=class pa extends Error{constructor(t){super(t),this.name="CodeExpectedError"}static fromError(t){if(t instanceof pa)return t;let i=new pa;return i.message=t.message,i.stack=t.stack,i}static isErrorNoTelemetry(t){return t.name==="CodeExpectedError"}},ga=class N_ extends Error{constructor(t){super(t||"An unexpected bug occurred."),Object.setPrototypeOf(this,N_.prototype)}};function st(e,t=0){return e[e.length-(1+t)]}var lm;(e=>{function t(n){return n<0}e.isLessThan=t;function i(n){return n<=0}e.isLessThanOrEqual=i;function r(n){return n>0}e.isGreaterThan=r;function s(n){return n===0}e.isNeitherLessOrGreaterThan=s,e.greaterThan=1,e.lessThan=-1,e.neitherLessOrGreaterThan=0})(lm||(lm={}));function am(e,t){let i=this,r=!1,s;return function(){return r||(r=!0,t||(s=e.apply(i,arguments))),s}}var O_;(e=>{function t(S){return S&&typeof S=="object"&&typeof S[Symbol.iterator]=="function"}e.is=t;let i=Object.freeze([]);function r(){return i}e.empty=r;function*s(S){yield S}e.single=s;function n(S){return t(S)?S:s(S)}e.wrap=n;function o(S){return S||i}e.from=o;function*l(S){for(let w=S.length-1;w>=0;w--)yield S[w]}e.reverse=l;function a(S){return!S||S[Symbol.iterator]().next().done===!0}e.isEmpty=a;function h(S){return S[Symbol.iterator]().next().value}e.first=h;function u(S,w){let b=0;for(let R of S)if(w(R,b++))return!0;return!1}e.some=u;function c(S,w){for(let b of S)if(w(b))return b}e.find=c;function*d(S,w){for(let b of S)w(b)&&(yield b)}e.filter=d;function*g(S,w){let b=0;for(let R of S)yield w(R,b++)}e.map=g;function*v(S,w){let b=0;for(let R of S)yield*w(R,b++)}e.flatMap=v;function*m(...S){for(let w of S)yield*w}e.concat=m;function k(S,w,b){let R=b;for(let B of S)R=w(R,B);return R}e.reduce=k;function*_(S,w,b=S.length){for(w<0&&(w+=S.length),b<0?b+=S.length:b>S.length&&(b=S.length);w1)throw new AggregateError(t,"Encountered errors while disposing of store");return Array.isArray(e)?[]:e}else if(e)return e.dispose(),e}function hm(...e){return re(()=>Yi(e))}function re(e){return{dispose:am(()=>{e()})}}var A_=class I_{constructor(){this._toDispose=new Set,this._isDisposed=!1}dispose(){this._isDisposed||(this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{Yi(this._toDispose)}finally{this._toDispose.clear()}}add(t){if(!t)return t;if(t===this)throw new Error("Cannot register a disposable on itself!");return this._isDisposed?I_.DISABLE_DISPOSED_WARNING||console.warn(new Error("Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!").stack):this._toDispose.add(t),t}delete(t){if(t){if(t===this)throw new Error("Cannot dispose a disposable on itself!");this._toDispose.delete(t),t.dispose()}}deleteAndLeak(t){t&&this._toDispose.has(t)&&(this._toDispose.delete(t),void 0)}};A_.DISABLE_DISPOSED_WARNING=!1;var xi=A_,W=class{constructor(){this._store=new xi,this._store}dispose(){this._store.dispose()}_register(e){if(e===this)throw new Error("Cannot register a disposable on itself!");return this._store.add(e)}};W.None=Object.freeze({dispose(){}});var Pr=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(e){var t;this._isDisposed||e===this._value||((t=this._value)==null||t.dispose(),this._value=e)}clear(){this.value=void 0}dispose(){var e;this._isDisposed=!0,(e=this._value)==null||e.dispose(),this._value=void 0}clearAndLeak(){let e=this._value;return this._value=void 0,e}},Yt=typeof window=="object"?window:globalThis,va=class ma{constructor(t){this.element=t,this.next=ma.Undefined,this.prev=ma.Undefined}};va.Undefined=new va(void 0);var se=va,du=class{constructor(){this._first=se.Undefined,this._last=se.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===se.Undefined}clear(){let e=this._first;for(;e!==se.Undefined;){let t=e.next;e.prev=se.Undefined,e.next=se.Undefined,e=t}this._first=se.Undefined,this._last=se.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let i=new se(e);if(this._first===se.Undefined)this._first=i,this._last=i;else if(t){let s=this._last;this._last=i,i.prev=s,s.next=i}else{let s=this._first;this._first=i,i.next=s,s.prev=i}this._size+=1;let r=!1;return()=>{r||(r=!0,this._remove(i))}}shift(){if(this._first!==se.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==se.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==se.Undefined&&e.next!==se.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===se.Undefined&&e.next===se.Undefined?(this._first=se.Undefined,this._last=se.Undefined):e.next===se.Undefined?(this._last=this._last.prev,this._last.next=se.Undefined):e.prev===se.Undefined&&(this._first=this._first.next,this._first.prev=se.Undefined);this._size-=1}*[Symbol.iterator](){let e=this._first;for(;e!==se.Undefined;)yield e.element,e=e.next}},cm=globalThis.performance&&typeof globalThis.performance.now=="function",um=class z_{static create(t){return new z_(t)}constructor(t){this._now=cm&&t===!1?Date.now:globalThis.performance.now.bind(globalThis.performance),this._startTime=this._now(),this._stopTime=-1}stop(){this._stopTime=this._now()}reset(){this._startTime=this._now(),this._stopTime=-1}elapsed(){return this._stopTime!==-1?this._stopTime-this._startTime:this._now()-this._startTime}},Ae;(e=>{e.None=()=>W.None;function t(N,x){return c(N,()=>{},0,void 0,!0,void 0,x)}e.defer=t;function i(N){return(x,M=null,P)=>{let A=!1,z;return z=N(y=>{if(!A)return z?z.dispose():A=!0,x.call(M,y)},null,P),A&&z.dispose(),z}}e.once=i;function r(N,x,M){return h((P,A=null,z)=>N(y=>P.call(A,x(y)),null,z),M)}e.map=r;function s(N,x,M){return h((P,A=null,z)=>N(y=>{x(y),P.call(A,y)},null,z),M)}e.forEach=s;function n(N,x,M){return h((P,A=null,z)=>N(y=>x(y)&&P.call(A,y),null,z),M)}e.filter=n;function o(N){return N}e.signal=o;function l(...N){return(x,M=null,P)=>{let A=hm(...N.map(z=>z(y=>x.call(M,y))));return u(A,P)}}e.any=l;function a(N,x,M,P){let A=M;return r(N,z=>(A=x(A,z),A),P)}e.reduce=a;function h(N,x){let M,P={onWillAddFirstListener(){M=N(A.fire,A)},onDidRemoveLastListener(){M==null||M.dispose()}},A=new D(P);return x==null||x.add(A),A.event}function u(N,x){return x instanceof Array?x.push(N):x&&x.add(N),N}function c(N,x,M=100,P=!1,A=!1,z,y){let T,I,Y,Q=0,Te,ce={leakWarningThreshold:z,onWillAddFirstListener(){T=N(ve=>{Q++,I=x(I,ve),P&&!Y&&(Qe.fire(I),I=void 0),Te=()=>{let dt=I;I=void 0,Y=void 0,(!P||Q>1)&&Qe.fire(dt),Q=0},typeof M=="number"?(clearTimeout(Y),Y=setTimeout(Te,M)):Y===void 0&&(Y=0,queueMicrotask(Te))})},onWillRemoveListener(){A&&Q>0&&(Te==null||Te())},onDidRemoveLastListener(){Te=void 0,T.dispose()}},Qe=new D(ce);return y==null||y.add(Qe),Qe.event}e.debounce=c;function d(N,x=0,M){return e.debounce(N,(P,A)=>P?(P.push(A),P):[A],x,void 0,!0,void 0,M)}e.accumulate=d;function g(N,x=(P,A)=>P===A,M){let P=!0,A;return n(N,z=>{let y=P||!x(z,A);return P=!1,A=z,y},M)}e.latch=g;function v(N,x,M){return[e.filter(N,x,M),e.filter(N,P=>!x(P),M)]}e.split=v;function m(N,x=!1,M=[],P){let A=M.slice(),z=N(I=>{A?A.push(I):T.fire(I)});P&&P.add(z);let y=()=>{A==null||A.forEach(I=>T.fire(I)),A=null},T=new D({onWillAddFirstListener(){z||(z=N(I=>T.fire(I)),P&&P.add(z))},onDidAddFirstListener(){A&&(x?setTimeout(y):y())},onDidRemoveLastListener(){z&&z.dispose(),z=null}});return P&&P.add(T),T.event}e.buffer=m;function k(N,x){return(M,P,A)=>{let z=x(new f);return N(function(y){let T=z.evaluate(y);T!==_&&M.call(P,T)},void 0,A)}}e.chain=k;let _=Symbol("HaltChainable");class f{constructor(){this.steps=[]}map(x){return this.steps.push(x),this}forEach(x){return this.steps.push(M=>(x(M),M)),this}filter(x){return this.steps.push(M=>x(M)?M:_),this}reduce(x,M){let P=M;return this.steps.push(A=>(P=x(P,A),P)),this}latch(x=(M,P)=>M===P){let M=!0,P;return this.steps.push(A=>{let z=M||!x(A,P);return M=!1,P=A,z?A:_}),this}evaluate(x){for(let M of this.steps)if(x=M(x),x===_)break;return x}}function p(N,x,M=P=>P){let P=(...T)=>y.fire(M(...T)),A=()=>N.on(x,P),z=()=>N.removeListener(x,P),y=new D({onWillAddFirstListener:A,onDidRemoveLastListener:z});return y.event}e.fromNodeEventEmitter=p;function S(N,x,M=P=>P){let P=(...T)=>y.fire(M(...T)),A=()=>N.addEventListener(x,P),z=()=>N.removeEventListener(x,P),y=new D({onWillAddFirstListener:A,onDidRemoveLastListener:z});return y.event}e.fromDOMEventEmitter=S;function w(N){return new Promise(x=>i(N)(x))}e.toPromise=w;function b(N){let x=new D;return N.then(M=>{x.fire(M)},()=>{x.fire(void 0)}).finally(()=>{x.dispose()}),x.event}e.fromPromise=b;function R(N,x){return N(M=>x.fire(M))}e.forward=R;function B(N,x,M){return x(M),N(P=>x(P))}e.runAndSubscribe=B;class U{constructor(x,M){this._observable=x,this._counter=0,this._hasChanged=!1;let P={onWillAddFirstListener:()=>{x.addObserver(this)},onDidRemoveLastListener:()=>{x.removeObserver(this)}};this.emitter=new D(P),M&&M.add(this.emitter)}beginUpdate(x){this._counter++}handlePossibleChange(x){}handleChange(x,M){this._hasChanged=!0}endUpdate(x){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function $(N,x){return new U(N,x).emitter.event}e.fromObservable=$;function V(N){return(x,M,P)=>{let A=0,z=!1,y={beginUpdate(){A++},endUpdate(){A--,A===0&&(N.reportChanges(),z&&(z=!1,x.call(M)))},handlePossibleChange(){},handleChange(){z=!0}};N.addObserver(y),N.reportChanges();let T={dispose(){N.removeObserver(y)}};return P instanceof xi?P.add(T):Array.isArray(P)&&P.push(T),T}}e.fromObservableLight=V})(Ae||(Ae={}));var Sa=class ya{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${ya._idPool++}`,ya.all.add(this)}start(t){this._stopWatch=new um,this.listenerCount=t}stop(){if(this._stopWatch){let t=this._stopWatch.elapsed();this.durations.push(t),this.elapsedOverall+=t,this.invocationCount+=1,this._stopWatch=void 0}}};Sa.all=new Set,Sa._idPool=0;var dm=Sa,fm=-1,F_=class $_{constructor(t,i,r=($_._idPool++).toString(16).padStart(3,"0")){this._errorHandler=t,this.threshold=i,this.name=r,this._warnCountdown=0}dispose(){var t;(t=this._stacks)==null||t.clear()}check(t,i){let r=this.threshold;if(r<=0||i{let n=this._stacks.get(t.value)||0;this._stacks.set(t.value,n-1)}}getMostFrequentStack(){if(!this._stacks)return;let t,i=0;for(let[r,s]of this._stacks)(!t||i{var o,l,a,h,u;if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let c=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(c);let d=this._leakageMon.getMostFrequentStack()??["UNKNOWN stack",-1],g=new vm(`${c}. HINT: Stack shows most frequent listener (${d[1]}-times)`,d[0]);return(((o=this._options)==null?void 0:o.onListenerError)||Dn)(g),W.None}if(this._disposed)return W.None;t&&(e=e.bind(t));let r=new nl(e),s;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(r.stack=pm.create(),s=this._leakageMon.check(r.stack,this._size+1)),this._listeners?this._listeners instanceof nl?(this._deliveryQueue??(this._deliveryQueue=new wm),this._listeners=[this._listeners,r]):this._listeners.push(r):((a=(l=this._options)==null?void 0:l.onWillAddFirstListener)==null||a.call(l,this),this._listeners=r,(u=(h=this._options)==null?void 0:h.onDidAddFirstListener)==null||u.call(h,this)),this._size++;let n=re(()=>{s==null||s(),this._removeListener(r)});return i instanceof xi?i.add(n):Array.isArray(i)&&i.push(n),n}),this._event}_removeListener(e){var s,n,o,l;if((n=(s=this._options)==null?void 0:s.onWillRemoveListener)==null||n.call(s,this),!this._listeners)return;if(this._size===1){this._listeners=void 0,(l=(o=this._options)==null?void 0:o.onDidRemoveLastListener)==null||l.call(o,this),this._size=0;return}let t=this._listeners,i=t.indexOf(e);if(i===-1)throw console.log("disposed?",this._disposed),console.log("size?",this._size),console.log("arr?",JSON.stringify(this._listeners)),new Error("Attempted to dispose unknown listener");this._size--,t[i]=void 0;let r=this._deliveryQueue.current===this;if(this._size*Sm<=t.length){let a=0;for(let h=0;h0}},wm=class{constructor(){this.i=-1,this.end=0}enqueue(e,t,i){this.i=0,this.end=i,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},wa=class{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new D,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new D,this.onDidChangeFullscreen=this._onDidChangeFullscreen.event,this.mapWindowIdToFullScreen=new Map}getZoomLevel(t){return this.mapWindowIdToZoomLevel.get(this.getWindowId(t))??0}setZoomLevel(t,i){if(this.getZoomLevel(i)===t)return;let r=this.getWindowId(i);this.mapWindowIdToZoomLevel.set(r,t),this._onDidChangeZoomLevel.fire(r)}getZoomFactor(t){return this.mapWindowIdToZoomFactor.get(this.getWindowId(t))??1}setZoomFactor(t,i){this.mapWindowIdToZoomFactor.set(this.getWindowId(i),t)}setFullscreen(t,i){if(this.isFullscreen(i)===t)return;let r=this.getWindowId(i);this.mapWindowIdToFullScreen.set(r,t),this._onDidChangeFullscreen.fire(r)}isFullscreen(t){return!!this.mapWindowIdToFullScreen.get(this.getWindowId(t))}getWindowId(t){return t.vscodeWindowId}};wa.INSTANCE=new wa;var Kh=wa;function Cm(e,t,i){typeof t=="string"&&(t=e.matchMedia(t)),t.addEventListener("change",i)}Kh.INSTANCE.onDidChangeZoomLevel;function km(e){return Kh.INSTANCE.getZoomFactor(e)}Kh.INSTANCE.onDidChangeFullscreen;var Nr=typeof navigator=="object"?navigator.userAgent:"",Ca=Nr.indexOf("Firefox")>=0,xm=Nr.indexOf("AppleWebKit")>=0,Vh=Nr.indexOf("Chrome")>=0,bm=!Vh&&Nr.indexOf("Safari")>=0;Nr.indexOf("Electron/")>=0;Nr.indexOf("Android")>=0;var ol=!1;if(typeof Yt.matchMedia=="function"){let e=Yt.matchMedia("(display-mode: standalone) or (display-mode: window-controls-overlay)"),t=Yt.matchMedia("(display-mode: fullscreen)");ol=e.matches,Cm(Yt,e,({matches:i})=>{ol&&t.matches||(ol=i)})}var _r="en",ka=!1,xa=!1,Rn=!1,W_=!1,hn,Pn=_r,fu=_r,Em,xt,Hi=globalThis,Oe,sd;typeof Hi.vscode<"u"&&typeof Hi.vscode.process<"u"?Oe=Hi.vscode.process:typeof process<"u"&&typeof((sd=process==null?void 0:process.versions)==null?void 0:sd.node)=="string"&&(Oe=process);var nd,Dm=typeof((nd=Oe==null?void 0:Oe.versions)==null?void 0:nd.electron)=="string",Rm=Dm&&(Oe==null?void 0:Oe.type)==="renderer",od;if(typeof Oe=="object"){ka=Oe.platform==="win32",xa=Oe.platform==="darwin",Rn=Oe.platform==="linux",Rn&&Oe.env.SNAP&&Oe.env.SNAP_REVISION,Oe.env.CI||Oe.env.BUILD_ARTIFACTSTAGINGDIRECTORY,hn=_r,Pn=_r;let e=Oe.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);hn=t.userLocale,fu=t.osLocale,Pn=t.resolvedLanguage||_r,Em=(od=t.languagePack)==null?void 0:od.translationsConfigFile}catch{}W_=!0}else typeof navigator=="object"&&!Rm?(xt=navigator.userAgent,ka=xt.indexOf("Windows")>=0,xa=xt.indexOf("Macintosh")>=0,(xt.indexOf("Macintosh")>=0||xt.indexOf("iPad")>=0||xt.indexOf("iPhone")>=0)&&navigator.maxTouchPoints&&navigator.maxTouchPoints>0,Rn=xt.indexOf("Linux")>=0,(xt==null?void 0:xt.indexOf("Mobi"))>=0,Pn=globalThis._VSCODE_NLS_LANGUAGE||_r,hn=navigator.language.toLowerCase(),fu=hn):console.error("Unable to resolve platform.");var U_=ka,$t=xa,Pm=Rn,_u=W_,Ht=xt,ni=Pn,Lm;(e=>{function t(){return ni}e.value=t;function i(){return ni.length===2?ni==="en":ni.length>=3?ni[0]==="e"&&ni[1]==="n"&&ni[2]==="-":!1}e.isDefaultVariant=i;function r(){return ni==="en"}e.isDefault=r})(Lm||(Lm={}));var Bm=typeof Hi.postMessage=="function"&&!Hi.importScripts;(()=>{if(Bm){let e=[];Hi.addEventListener("message",i=>{if(i.data&&i.data.vscodeScheduleAsyncWork)for(let r=0,s=e.length;r{let r=++t;e.push({id:r,callback:i}),Hi.postMessage({vscodeScheduleAsyncWork:r},"*")}}return e=>setTimeout(e)})();var Mm=!!(Ht&&Ht.indexOf("Chrome")>=0);Ht&&Ht.indexOf("Firefox")>=0;!Mm&&Ht&&Ht.indexOf("Safari")>=0;Ht&&Ht.indexOf("Edg/")>=0;Ht&&Ht.indexOf("Android")>=0;var Ji=typeof navigator=="object"?navigator:{};_u||document.queryCommandSupported&&document.queryCommandSupported("copy")||Ji&&Ji.clipboard&&Ji.clipboard.writeText,_u||Ji&&Ji.clipboard&&Ji.clipboard.readText;var jh=class{constructor(){this._keyCodeToStr=[],this._strToKeyCode=Object.create(null)}define(e,t){this._keyCodeToStr[e]=t,this._strToKeyCode[t.toLowerCase()]=e}keyCodeToStr(e){return this._keyCodeToStr[e]}strToKeyCode(e){return this._strToKeyCode[e.toLowerCase()]||0}},ll=new jh,pu=new jh,gu=new jh,Tm=new Array(230),K_;(e=>{function t(l){return ll.keyCodeToStr(l)}e.toString=t;function i(l){return ll.strToKeyCode(l)}e.fromString=i;function r(l){return pu.keyCodeToStr(l)}e.toUserSettingsUS=r;function s(l){return gu.keyCodeToStr(l)}e.toUserSettingsGeneral=s;function n(l){return pu.strToKeyCode(l)||gu.strToKeyCode(l)}e.fromUserSettings=n;function o(l){if(l>=98&&l<=113)return null;switch(l){case 16:return"Up";case 18:return"Down";case 15:return"Left";case 17:return"Right"}return ll.keyCodeToStr(l)}e.toElectronAccelerator=o})(K_||(K_={}));var Nm=class V_{constructor(t,i,r,s,n){this.ctrlKey=t,this.shiftKey=i,this.altKey=r,this.metaKey=s,this.keyCode=n}equals(t){return t instanceof V_&&this.ctrlKey===t.ctrlKey&&this.shiftKey===t.shiftKey&&this.altKey===t.altKey&&this.metaKey===t.metaKey&&this.keyCode===t.keyCode}getHashCode(){let t=this.ctrlKey?"1":"0",i=this.shiftKey?"1":"0",r=this.altKey?"1":"0",s=this.metaKey?"1":"0";return`K${t}${i}${r}${s}${this.keyCode}`}isModifierKey(){return this.keyCode===0||this.keyCode===5||this.keyCode===57||this.keyCode===6||this.keyCode===4}toKeybinding(){return new Om([this])}isDuplicateModifierCase(){return this.ctrlKey&&this.keyCode===5||this.shiftKey&&this.keyCode===4||this.altKey&&this.keyCode===6||this.metaKey&&this.keyCode===57}},Om=class{constructor(e){if(e.length===0)throw om("chords");this.chords=e}getHashCode(){let e="";for(let t=0,i=this.chords.length;t{function t(i){return i===e.None||i===e.Cancelled||i instanceof Km?!0:!i||typeof i!="object"?!1:typeof i.isCancellationRequested=="boolean"&&typeof i.onCancellationRequested=="function"}e.isCancellationToken=t,e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:Ae.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:j_})})(Um||(Um={}));var Km=class{constructor(){this._isCancelled=!1,this._emitter=null}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?j_:(this._emitter||(this._emitter=new D),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=null)}},Yh=class{constructor(e,t){this._isDisposed=!1,this._token=-1,typeof e=="function"&&typeof t=="number"&&this.setIfNotSet(e,t)}dispose(){this.cancel(),this._isDisposed=!0}cancel(){this._token!==-1&&(clearTimeout(this._token),this._token=-1)}cancelAndSet(e,t){if(this._isDisposed)throw new ga("Calling 'cancelAndSet' on a disposed TimeoutTimer");this.cancel(),this._token=setTimeout(()=>{this._token=-1,e()},t)}setIfNotSet(e,t){if(this._isDisposed)throw new ga("Calling 'setIfNotSet' on a disposed TimeoutTimer");this._token===-1&&(this._token=setTimeout(()=>{this._token=-1,e()},t))}},Vm=class{constructor(){this.disposable=void 0,this.isDisposed=!1}cancel(){var e;(e=this.disposable)==null||e.dispose(),this.disposable=void 0}cancelAndSet(e,t,i=globalThis){if(this.isDisposed)throw new ga("Calling 'cancelAndSet' on a disposed IntervalTimer");this.cancel();let r=i.setInterval(()=>{e()},t);this.disposable=re(()=>{i.clearInterval(r),this.disposable=void 0})}dispose(){this.cancel(),this.isDisposed=!0}},jm;(e=>{async function t(r){let s,n=await Promise.all(r.map(o=>o.then(l=>l,l=>{s||(s=l)})));if(typeof s<"u")throw s;return n}e.settled=t;function i(r){return new Promise(async(s,n)=>{try{await r(s,n)}catch(o){n(o)}})}e.withAsyncBody=i})(jm||(jm={}));var yu=class _t{static fromArray(t){return new _t(i=>{i.emitMany(t)})}static fromPromise(t){return new _t(async i=>{i.emitMany(await t)})}static fromPromises(t){return new _t(async i=>{await Promise.all(t.map(async r=>i.emitOne(await r)))})}static merge(t){return new _t(async i=>{await Promise.all(t.map(async r=>{for await(let s of r)i.emitOne(s)}))})}constructor(t,i){this._state=0,this._results=[],this._error=null,this._onReturn=i,this._onStateChanged=new D,queueMicrotask(async()=>{let r={emitOne:s=>this.emitOne(s),emitMany:s=>this.emitMany(s),reject:s=>this.reject(s)};try{await Promise.resolve(t(r)),this.resolve()}catch(s){this.reject(s)}finally{r.emitOne=void 0,r.emitMany=void 0,r.reject=void 0}})}[Symbol.asyncIterator](){let t=0;return{next:async()=>{do{if(this._state===2)throw this._error;if(t{var i;return(i=this._onReturn)==null||i.call(this),{done:!0,value:void 0}}}}static map(t,i){return new _t(async r=>{for await(let s of t)r.emitOne(i(s))})}map(t){return _t.map(this,t)}static filter(t,i){return new _t(async r=>{for await(let s of t)i(s)&&r.emitOne(s)})}filter(t){return _t.filter(this,t)}static coalesce(t){return _t.filter(t,i=>!!i)}coalesce(){return _t.coalesce(this)}static async toPromise(t){let i=[];for await(let r of t)i.push(r);return i}toPromise(){return _t.toPromise(this)}emitOne(t){this._state===0&&(this._results.push(t),this._onStateChanged.fire())}emitMany(t){this._state===0&&(this._results=this._results.concat(t),this._onStateChanged.fire())}resolve(){this._state===0&&(this._state=1,this._onStateChanged.fire())}reject(t){this._state===0&&(this._state=2,this._error=t,this._onStateChanged.fire())}};yu.EMPTY=yu.fromArray([]);var{getWindow:It,getWindowId:Ym,onDidRegisterWindow:qm}=function(){let e=new Map,t={window:Yt,disposables:new xi};e.set(Yt.vscodeWindowId,t);let i=new D,r=new D,s=new D;function n(o,l){return(typeof o=="number"?e.get(o):void 0)??(l?t:void 0)}return{onDidRegisterWindow:i.event,onWillUnregisterWindow:s.event,onDidUnregisterWindow:r.event,registerWindow(o){if(e.has(o.vscodeWindowId))return W.None;let l=new xi,a={window:o,disposables:l.add(new xi)};return e.set(o.vscodeWindowId,a),l.add(re(()=>{e.delete(o.vscodeWindowId),r.fire(o)})),l.add(F(o,Ee.BEFORE_UNLOAD,()=>{s.fire(o)})),i.fire(a),l},getWindows(){return e.values()},getWindowsCount(){return e.size},getWindowId(o){return o.vscodeWindowId},hasWindow(o){return e.has(o)},getWindowById:n,getWindow(o){var h;let l=o;if((h=l==null?void 0:l.ownerDocument)!=null&&h.defaultView)return l.ownerDocument.defaultView.window;let a=o;return a!=null&&a.view?a.view.window:Yt},getDocument(o){return It(o).document}}}(),Xm=class{constructor(e,t,i,r){this._node=e,this._type=t,this._handler=i,this._options=r||!1,this._node.addEventListener(this._type,this._handler,this._options)}dispose(){this._handler&&(this._node.removeEventListener(this._type,this._handler,this._options),this._node=null,this._handler=null)}};function F(e,t,i,r){return new Xm(e,t,i,r)}var wu=function(e,t,i,r){return F(e,t,i,r)},qh,Gm=class extends Vm{constructor(e){super(),this.defaultTarget=e&&It(e)}cancelAndSet(e,t,i){return super.cancelAndSet(e,t,i??this.defaultTarget)}},Cu=class{constructor(e,t=0){this._runner=e,this.priority=t,this._canceled=!1}dispose(){this._canceled=!0}execute(){if(!this._canceled)try{this._runner()}catch(e){Dn(e)}}static sort(e,t){return t.priority-e.priority}};(function(){let e=new Map,t=new Map,i=new Map,r=new Map,s=n=>{i.set(n,!1);let o=e.get(n)??[];for(t.set(n,o),e.set(n,[]),r.set(n,!0);o.length>0;)o.sort(Cu.sort),o.shift().execute();r.set(n,!1)};qh=(n,o,l=0)=>{let a=Ym(n),h=new Cu(o,l),u=e.get(a);return u||(u=[],e.set(a,u)),u.push(h),i.get(a)||(i.set(a,!0),n.requestAnimationFrame(()=>s(a))),h}})();function Qm(e){let t=e.getBoundingClientRect(),i=It(e);return{left:t.left+i.scrollX,top:t.top+i.scrollY,width:t.width,height:t.height}}var Ee={CLICK:"click",MOUSE_DOWN:"mousedown",MOUSE_OVER:"mouseover",MOUSE_LEAVE:"mouseleave",MOUSE_WHEEL:"wheel",POINTER_UP:"pointerup",POINTER_DOWN:"pointerdown",POINTER_MOVE:"pointermove",KEY_DOWN:"keydown",KEY_UP:"keyup",BEFORE_UNLOAD:"beforeunload",CHANGE:"change",FOCUS:"focus",BLUR:"blur",INPUT:"input"},Zm=class{constructor(e){this.domNode=e,this._maxWidth="",this._width="",this._height="",this._top="",this._left="",this._bottom="",this._right="",this._paddingTop="",this._paddingLeft="",this._paddingBottom="",this._paddingRight="",this._fontFamily="",this._fontWeight="",this._fontSize="",this._fontStyle="",this._fontFeatureSettings="",this._fontVariationSettings="",this._textDecoration="",this._lineHeight="",this._letterSpacing="",this._className="",this._display="",this._position="",this._visibility="",this._color="",this._backgroundColor="",this._layerHint=!1,this._contain="none",this._boxShadow=""}setMaxWidth(e){let t=Ze(e);this._maxWidth!==t&&(this._maxWidth=t,this.domNode.style.maxWidth=this._maxWidth)}setWidth(e){let t=Ze(e);this._width!==t&&(this._width=t,this.domNode.style.width=this._width)}setHeight(e){let t=Ze(e);this._height!==t&&(this._height=t,this.domNode.style.height=this._height)}setTop(e){let t=Ze(e);this._top!==t&&(this._top=t,this.domNode.style.top=this._top)}setLeft(e){let t=Ze(e);this._left!==t&&(this._left=t,this.domNode.style.left=this._left)}setBottom(e){let t=Ze(e);this._bottom!==t&&(this._bottom=t,this.domNode.style.bottom=this._bottom)}setRight(e){let t=Ze(e);this._right!==t&&(this._right=t,this.domNode.style.right=this._right)}setPaddingTop(e){let t=Ze(e);this._paddingTop!==t&&(this._paddingTop=t,this.domNode.style.paddingTop=this._paddingTop)}setPaddingLeft(e){let t=Ze(e);this._paddingLeft!==t&&(this._paddingLeft=t,this.domNode.style.paddingLeft=this._paddingLeft)}setPaddingBottom(e){let t=Ze(e);this._paddingBottom!==t&&(this._paddingBottom=t,this.domNode.style.paddingBottom=this._paddingBottom)}setPaddingRight(e){let t=Ze(e);this._paddingRight!==t&&(this._paddingRight=t,this.domNode.style.paddingRight=this._paddingRight)}setFontFamily(e){this._fontFamily!==e&&(this._fontFamily=e,this.domNode.style.fontFamily=this._fontFamily)}setFontWeight(e){this._fontWeight!==e&&(this._fontWeight=e,this.domNode.style.fontWeight=this._fontWeight)}setFontSize(e){let t=Ze(e);this._fontSize!==t&&(this._fontSize=t,this.domNode.style.fontSize=this._fontSize)}setFontStyle(e){this._fontStyle!==e&&(this._fontStyle=e,this.domNode.style.fontStyle=this._fontStyle)}setFontFeatureSettings(e){this._fontFeatureSettings!==e&&(this._fontFeatureSettings=e,this.domNode.style.fontFeatureSettings=this._fontFeatureSettings)}setFontVariationSettings(e){this._fontVariationSettings!==e&&(this._fontVariationSettings=e,this.domNode.style.fontVariationSettings=this._fontVariationSettings)}setTextDecoration(e){this._textDecoration!==e&&(this._textDecoration=e,this.domNode.style.textDecoration=this._textDecoration)}setLineHeight(e){let t=Ze(e);this._lineHeight!==t&&(this._lineHeight=t,this.domNode.style.lineHeight=this._lineHeight)}setLetterSpacing(e){let t=Ze(e);this._letterSpacing!==t&&(this._letterSpacing=t,this.domNode.style.letterSpacing=this._letterSpacing)}setClassName(e){this._className!==e&&(this._className=e,this.domNode.className=this._className)}toggleClassName(e,t){this.domNode.classList.toggle(e,t),this._className=this.domNode.className}setDisplay(e){this._display!==e&&(this._display=e,this.domNode.style.display=this._display)}setPosition(e){this._position!==e&&(this._position=e,this.domNode.style.position=this._position)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this.domNode.style.visibility=this._visibility)}setColor(e){this._color!==e&&(this._color=e,this.domNode.style.color=this._color)}setBackgroundColor(e){this._backgroundColor!==e&&(this._backgroundColor=e,this.domNode.style.backgroundColor=this._backgroundColor)}setLayerHinting(e){this._layerHint!==e&&(this._layerHint=e,this.domNode.style.transform=this._layerHint?"translate3d(0px, 0px, 0px)":"")}setBoxShadow(e){this._boxShadow!==e&&(this._boxShadow=e,this.domNode.style.boxShadow=e)}setContain(e){this._contain!==e&&(this._contain=e,this.domNode.style.contain=this._contain)}setAttribute(e,t){this.domNode.setAttribute(e,t)}removeAttribute(e){this.domNode.removeAttribute(e)}appendChild(e){this.domNode.appendChild(e.domNode)}removeChild(e){this.domNode.removeChild(e.domNode)}};function Ze(e){return typeof e=="number"?`${e}px`:e}function _s(e){return new Zm(e)}var Y_=class{constructor(){this._hooks=new xi,this._pointerMoveCallback=null,this._onStopCallback=null}dispose(){this.stopMonitoring(!1),this._hooks.dispose()}stopMonitoring(e,t){if(!this.isMonitoring())return;this._hooks.clear(),this._pointerMoveCallback=null;let i=this._onStopCallback;this._onStopCallback=null,e&&i&&i(t)}isMonitoring(){return!!this._pointerMoveCallback}startMonitoring(e,t,i,r,s){this.isMonitoring()&&this.stopMonitoring(!1),this._pointerMoveCallback=r,this._onStopCallback=s;let n=e;try{e.setPointerCapture(t),this._hooks.add(re(()=>{try{e.releasePointerCapture(t)}catch{}}))}catch{n=It(e)}this._hooks.add(F(n,Ee.POINTER_MOVE,o=>{if(o.buttons!==i){this.stopMonitoring(!0);return}o.preventDefault(),this._pointerMoveCallback(o)})),this._hooks.add(F(n,Ee.POINTER_UP,o=>this.stopMonitoring(!0)))}};function Jm(e,t,i){let r=null,s=null;if(typeof i.value=="function"?(r="value",s=i.value,s.length!==0&&console.warn("Memoize should only be used in functions with zero parameters")):typeof i.get=="function"&&(r="get",s=i.get),!s)throw new Error("not supported");let n=`$memoize$${t}`;i[r]=function(...o){return this.hasOwnProperty(n)||Object.defineProperty(this,n,{configurable:!1,enumerable:!1,writable:!1,value:s.apply(this,o)}),this[n]}}var Nt;(e=>(e.Tap="-xterm-gesturetap",e.Change="-xterm-gesturechange",e.Start="-xterm-gesturestart",e.End="-xterm-gesturesend",e.Contextmenu="-xterm-gesturecontextmenu"))(Nt||(Nt={}));var es=class He extends W{constructor(){super(),this.dispatched=!1,this.targets=new du,this.ignoreTargets=new du,this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register(Ae.runAndSubscribe(qm,({window:t,disposables:i})=>{i.add(F(t.document,"touchstart",r=>this.onTouchStart(r),{passive:!1})),i.add(F(t.document,"touchend",r=>this.onTouchEnd(t,r))),i.add(F(t.document,"touchmove",r=>this.onTouchMove(r),{passive:!1}))},{window:Yt,disposables:this._store}))}static addTarget(t){if(!He.isTouchDevice())return W.None;He.INSTANCE||(He.INSTANCE=new He);let i=He.INSTANCE.targets.push(t);return re(i)}static ignoreTarget(t){if(!He.isTouchDevice())return W.None;He.INSTANCE||(He.INSTANCE=new He);let i=He.INSTANCE.ignoreTargets.push(t);return re(i)}static isTouchDevice(){return"ontouchstart"in Yt||navigator.maxTouchPoints>0}dispose(){this.handle&&(this.handle.dispose(),this.handle=null),super.dispose()}onTouchStart(t){let i=Date.now();this.handle&&(this.handle.dispose(),this.handle=null);for(let r=0,s=t.targetTouches.length;r=He.HOLD_DELAY&&Math.abs(a.initialPageX-st(a.rollingPageX))<30&&Math.abs(a.initialPageY-st(a.rollingPageY))<30){let u=this.newGestureEvent(Nt.Contextmenu,a.initialTarget);u.pageX=st(a.rollingPageX),u.pageY=st(a.rollingPageY),this.dispatchEvent(u)}else if(s===1){let u=st(a.rollingPageX),c=st(a.rollingPageY),d=st(a.rollingTimestamps)-a.rollingTimestamps[0],g=u-a.rollingPageX[0],v=c-a.rollingPageY[0],m=[...this.targets].filter(k=>a.initialTarget instanceof Node&&k.contains(a.initialTarget));this.inertia(t,m,r,Math.abs(g)/d,g>0?1:-1,u,Math.abs(v)/d,v>0?1:-1,c)}this.dispatchEvent(this.newGestureEvent(Nt.End,a.initialTarget)),delete this.activeTouches[l.identifier]}this.dispatched&&(i.preventDefault(),i.stopPropagation(),this.dispatched=!1)}newGestureEvent(t,i){let r=document.createEvent("CustomEvent");return r.initEvent(t,!1,!0),r.initialTarget=i,r.tapCount=0,r}dispatchEvent(t){if(t.type===Nt.Tap){let i=new Date().getTime(),r=0;i-this._lastSetTapCountTime>He.CLEAR_TAP_COUNT_TIME?r=1:r=2,this._lastSetTapCountTime=i,t.tapCount=r}else(t.type===Nt.Change||t.type===Nt.Contextmenu)&&(this._lastSetTapCountTime=0);if(t.initialTarget instanceof Node){for(let r of this.ignoreTargets)if(r.contains(t.initialTarget))return;let i=[];for(let r of this.targets)if(r.contains(t.initialTarget)){let s=0,n=t.initialTarget;for(;n&&n!==r;)s++,n=n.parentElement;i.push([s,r])}i.sort((r,s)=>r[0]-s[0]);for(let[r,s]of i)s.dispatchEvent(t),this.dispatched=!0}}inertia(t,i,r,s,n,o,l,a,h){this.handle=qh(t,()=>{let u=Date.now(),c=u-r,d=0,g=0,v=!0;s+=He.SCROLL_FRICTION*c,l+=He.SCROLL_FRICTION*c,s>0&&(v=!1,d=n*s*c),l>0&&(v=!1,g=a*l*c);let m=this.newGestureEvent(Nt.Change);m.translationX=d,m.translationY=g,i.forEach(k=>k.dispatchEvent(m)),v||this.inertia(t,i,u,s,n,o+d,l,a,h+g)})}onTouchMove(t){let i=Date.now();for(let r=0,s=t.changedTouches.length;r3&&(o.rollingPageX.shift(),o.rollingPageY.shift(),o.rollingTimestamps.shift()),o.rollingPageX.push(n.pageX),o.rollingPageY.push(n.pageY),o.rollingTimestamps.push(i)}this.dispatched&&(t.preventDefault(),t.stopPropagation(),this.dispatched=!1)}};es.SCROLL_FRICTION=-.005,es.HOLD_DELAY=700,es.CLEAR_TAP_COUNT_TIME=400,_e([Jm],es,"isTouchDevice",1);var eS=es,Xh=class extends W{onclick(e,t){this._register(F(e,Ee.CLICK,i=>t(new cn(It(e),i))))}onmousedown(e,t){this._register(F(e,Ee.MOUSE_DOWN,i=>t(new cn(It(e),i))))}onmouseover(e,t){this._register(F(e,Ee.MOUSE_OVER,i=>t(new cn(It(e),i))))}onmouseleave(e,t){this._register(F(e,Ee.MOUSE_LEAVE,i=>t(new cn(It(e),i))))}onkeydown(e,t){this._register(F(e,Ee.KEY_DOWN,i=>t(new vu(i))))}onkeyup(e,t){this._register(F(e,Ee.KEY_UP,i=>t(new vu(i))))}oninput(e,t){this._register(F(e,Ee.INPUT,t))}onblur(e,t){this._register(F(e,Ee.BLUR,t))}onfocus(e,t){this._register(F(e,Ee.FOCUS,t))}onchange(e,t){this._register(F(e,Ee.CHANGE,t))}ignoreGesture(e){return eS.ignoreTarget(e)}},ku=11,tS=class extends Xh{constructor(e){super(),this._onActivate=e.onActivate,this.bgDomNode=document.createElement("div"),this.bgDomNode.className="arrow-background",this.bgDomNode.style.position="absolute",this.bgDomNode.style.width=e.bgWidth+"px",this.bgDomNode.style.height=e.bgHeight+"px",typeof e.top<"u"&&(this.bgDomNode.style.top="0px"),typeof e.left<"u"&&(this.bgDomNode.style.left="0px"),typeof e.bottom<"u"&&(this.bgDomNode.style.bottom="0px"),typeof e.right<"u"&&(this.bgDomNode.style.right="0px"),this.domNode=document.createElement("div"),this.domNode.className=e.className,this.domNode.style.position="absolute",this.domNode.style.width=ku+"px",this.domNode.style.height=ku+"px",typeof e.top<"u"&&(this.domNode.style.top=e.top+"px"),typeof e.left<"u"&&(this.domNode.style.left=e.left+"px"),typeof e.bottom<"u"&&(this.domNode.style.bottom=e.bottom+"px"),typeof e.right<"u"&&(this.domNode.style.right=e.right+"px"),this._pointerMoveMonitor=this._register(new Y_),this._register(wu(this.bgDomNode,Ee.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._register(wu(this.domNode,Ee.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._pointerdownRepeatTimer=this._register(new Gm),this._pointerdownScheduleRepeatTimer=this._register(new Yh)}_arrowPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=()=>{this._pointerdownRepeatTimer.cancelAndSet(()=>this._onActivate(),1e3/24,It(e))};this._onActivate(),this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancelAndSet(t,200),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,i=>{},()=>{this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancel()}),e.preventDefault()}},iS=class ba{constructor(t,i,r,s,n,o,l){this._forceIntegerValues=t,this._scrollStateBrand=void 0,this._forceIntegerValues&&(i=i|0,r=r|0,s=s|0,n=n|0,o=o|0,l=l|0),this.rawScrollLeft=s,this.rawScrollTop=l,i<0&&(i=0),s+i>r&&(s=r-i),s<0&&(s=0),n<0&&(n=0),l+n>o&&(l=o-n),l<0&&(l=0),this.width=i,this.scrollWidth=r,this.scrollLeft=s,this.height=n,this.scrollHeight=o,this.scrollTop=l}equals(t){return this.rawScrollLeft===t.rawScrollLeft&&this.rawScrollTop===t.rawScrollTop&&this.width===t.width&&this.scrollWidth===t.scrollWidth&&this.scrollLeft===t.scrollLeft&&this.height===t.height&&this.scrollHeight===t.scrollHeight&&this.scrollTop===t.scrollTop}withScrollDimensions(t,i){return new ba(this._forceIntegerValues,typeof t.width<"u"?t.width:this.width,typeof t.scrollWidth<"u"?t.scrollWidth:this.scrollWidth,i?this.rawScrollLeft:this.scrollLeft,typeof t.height<"u"?t.height:this.height,typeof t.scrollHeight<"u"?t.scrollHeight:this.scrollHeight,i?this.rawScrollTop:this.scrollTop)}withScrollPosition(t){return new ba(this._forceIntegerValues,this.width,this.scrollWidth,typeof t.scrollLeft<"u"?t.scrollLeft:this.rawScrollLeft,this.height,this.scrollHeight,typeof t.scrollTop<"u"?t.scrollTop:this.rawScrollTop)}createScrollEvent(t,i){let r=this.width!==t.width,s=this.scrollWidth!==t.scrollWidth,n=this.scrollLeft!==t.scrollLeft,o=this.height!==t.height,l=this.scrollHeight!==t.scrollHeight,a=this.scrollTop!==t.scrollTop;return{inSmoothScrolling:i,oldWidth:t.width,oldScrollWidth:t.scrollWidth,oldScrollLeft:t.scrollLeft,width:this.width,scrollWidth:this.scrollWidth,scrollLeft:this.scrollLeft,oldHeight:t.height,oldScrollHeight:t.scrollHeight,oldScrollTop:t.scrollTop,height:this.height,scrollHeight:this.scrollHeight,scrollTop:this.scrollTop,widthChanged:r,scrollWidthChanged:s,scrollLeftChanged:n,heightChanged:o,scrollHeightChanged:l,scrollTopChanged:a}}},rS=class extends W{constructor(e){super(),this._scrollableBrand=void 0,this._onScroll=this._register(new D),this.onScroll=this._onScroll.event,this._smoothScrollDuration=e.smoothScrollDuration,this._scheduleAtNextAnimationFrame=e.scheduleAtNextAnimationFrame,this._state=new iS(e.forceIntegerValues,0,0,0,0,0,0),this._smoothScrolling=null}dispose(){this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),super.dispose()}setSmoothScrollDuration(e){this._smoothScrollDuration=e}validateScrollPosition(e){return this._state.withScrollPosition(e)}getScrollDimensions(){return this._state}setScrollDimensions(e,t){var r;let i=this._state.withScrollDimensions(e,t);this._setState(i,!!this._smoothScrolling),(r=this._smoothScrolling)==null||r.acceptScrollDimensions(this._state)}getFutureScrollPosition(){return this._smoothScrolling?this._smoothScrolling.to:this._state}getCurrentScrollPosition(){return this._state}setScrollPositionNow(e){let t=this._state.withScrollPosition(e);this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),this._setState(t,!1)}setScrollPositionSmooth(e,t){if(this._smoothScrollDuration===0)return this.setScrollPositionNow(e);if(this._smoothScrolling){e={scrollLeft:typeof e.scrollLeft>"u"?this._smoothScrolling.to.scrollLeft:e.scrollLeft,scrollTop:typeof e.scrollTop>"u"?this._smoothScrolling.to.scrollTop:e.scrollTop};let i=this._state.withScrollPosition(e);if(this._smoothScrolling.to.scrollLeft===i.scrollLeft&&this._smoothScrolling.to.scrollTop===i.scrollTop)return;let r;t?r=new bu(this._smoothScrolling.from,i,this._smoothScrolling.startTime,this._smoothScrolling.duration):r=this._smoothScrolling.combine(this._state,i,this._smoothScrollDuration),this._smoothScrolling.dispose(),this._smoothScrolling=r}else{let i=this._state.withScrollPosition(e);this._smoothScrolling=bu.start(this._state,i,this._smoothScrollDuration)}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}hasPendingScrollAnimation(){return!!this._smoothScrolling}_performSmoothScrolling(){if(!this._smoothScrolling)return;let e=this._smoothScrolling.tick(),t=this._state.withScrollPosition(e);if(this._setState(t,!0),!!this._smoothScrolling){if(e.isDone){this._smoothScrolling.dispose(),this._smoothScrolling=null;return}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}}_setState(e,t){let i=this._state;i.equals(e)||(this._state=e,this._onScroll.fire(this._state.createScrollEvent(i,t)))}},xu=class{constructor(e,t,i){this.scrollLeft=e,this.scrollTop=t,this.isDone=i}};function al(e,t){let i=t-e;return function(r){return e+i*oS(r)}}function sS(e,t,i){return function(r){return r2.5*r){let s,n;return t{var e;(e=this._domNode)==null||e.setClassName(this._visibleClassName)},0))}_hide(e){var t;this._revealTimer.cancel(),this._isVisible&&(this._isVisible=!1,(t=this._domNode)==null||t.setClassName(this._invisibleClassName+(e?" fade":"")))}},aS=140,q_=class extends Xh{constructor(e){super(),this._lazyRender=e.lazyRender,this._host=e.host,this._scrollable=e.scrollable,this._scrollByPage=e.scrollByPage,this._scrollbarState=e.scrollbarState,this._visibilityController=this._register(new lS(e.visibility,"visible scrollbar "+e.extraScrollbarClassName,"invisible scrollbar "+e.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new Y_),this._shouldRender=!0,this.domNode=_s(document.createElement("div")),this.domNode.setAttribute("role","presentation"),this.domNode.setAttribute("aria-hidden","true"),this._visibilityController.setDomNode(this.domNode),this.domNode.setPosition("absolute"),this._register(F(this.domNode.domNode,Ee.POINTER_DOWN,t=>this._domNodePointerDown(t)))}_createArrow(e){let t=this._register(new tS(e));this.domNode.domNode.appendChild(t.bgDomNode),this.domNode.domNode.appendChild(t.domNode)}_createSlider(e,t,i,r){this.slider=_s(document.createElement("div")),this.slider.setClassName("slider"),this.slider.setPosition("absolute"),this.slider.setTop(e),this.slider.setLeft(t),typeof i=="number"&&this.slider.setWidth(i),typeof r=="number"&&this.slider.setHeight(r),this.slider.setLayerHinting(!0),this.slider.setContain("strict"),this.domNode.domNode.appendChild(this.slider.domNode),this._register(F(this.slider.domNode,Ee.POINTER_DOWN,s=>{s.button===0&&(s.preventDefault(),this._sliderPointerDown(s))})),this.onclick(this.slider.domNode,s=>{s.leftButton&&s.stopPropagation()})}_onElementSize(e){return this._scrollbarState.setVisibleSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollSize(e){return this._scrollbarState.setScrollSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollPosition(e){return this._scrollbarState.setScrollPosition(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}beginReveal(){this._visibilityController.setShouldBeVisible(!0)}beginHide(){this._visibilityController.setShouldBeVisible(!1)}render(){this._shouldRender&&(this._shouldRender=!1,this._renderDomNode(this._scrollbarState.getRectangleLargeSize(),this._scrollbarState.getRectangleSmallSize()),this._updateSlider(this._scrollbarState.getSliderSize(),this._scrollbarState.getArrowSize()+this._scrollbarState.getSliderPosition()))}_domNodePointerDown(e){e.target===this.domNode.domNode&&this._onPointerDown(e)}delegatePointerDown(e){let t=this.domNode.domNode.getClientRects()[0].top,i=t+this._scrollbarState.getSliderPosition(),r=t+this._scrollbarState.getSliderPosition()+this._scrollbarState.getSliderSize(),s=this._sliderPointerPosition(e);i<=s&&s<=r?e.button===0&&(e.preventDefault(),this._sliderPointerDown(e)):this._onPointerDown(e)}_onPointerDown(e){let t,i;if(e.target===this.domNode.domNode&&typeof e.offsetX=="number"&&typeof e.offsetY=="number")t=e.offsetX,i=e.offsetY;else{let s=Qm(this.domNode.domNode);t=e.pageX-s.left,i=e.pageY-s.top}let r=this._pointerDownRelativePosition(t,i);this._setDesiredScrollPositionNow(this._scrollByPage?this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(r):this._scrollbarState.getDesiredScrollPositionFromOffset(r)),e.button===0&&(e.preventDefault(),this._sliderPointerDown(e))}_sliderPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=this._sliderPointerPosition(e),i=this._sliderOrthogonalPointerPosition(e),r=this._scrollbarState.clone();this.slider.toggleClassName("active",!0),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,s=>{let n=this._sliderOrthogonalPointerPosition(s),o=Math.abs(n-i);if(U_&&o>aS){this._setDesiredScrollPositionNow(r.getScrollPosition());return}let l=this._sliderPointerPosition(s)-t;this._setDesiredScrollPositionNow(r.getDesiredScrollPositionFromDelta(l))},()=>{this.slider.toggleClassName("active",!1),this._host.onDragEnd()}),this._host.onDragStart()}_setDesiredScrollPositionNow(e){let t={};this.writeScrollPosition(t,e),this._scrollable.setScrollPositionNow(t)}updateScrollbarSize(e){this._updateScrollbarSize(e),this._scrollbarState.setScrollbarSize(e),this._shouldRender=!0,this._lazyRender||this.render()}isNeeded(){return this._scrollbarState.isNeeded()}},X_=class Da{constructor(t,i,r,s,n,o){this._scrollbarSize=Math.round(i),this._oppositeScrollbarSize=Math.round(r),this._arrowSize=Math.round(t),this._visibleSize=s,this._scrollSize=n,this._scrollPosition=o,this._computedAvailableSize=0,this._computedIsNeeded=!1,this._computedSliderSize=0,this._computedSliderRatio=0,this._computedSliderPosition=0,this._refreshComputedValues()}clone(){return new Da(this._arrowSize,this._scrollbarSize,this._oppositeScrollbarSize,this._visibleSize,this._scrollSize,this._scrollPosition)}setVisibleSize(t){let i=Math.round(t);return this._visibleSize!==i?(this._visibleSize=i,this._refreshComputedValues(),!0):!1}setScrollSize(t){let i=Math.round(t);return this._scrollSize!==i?(this._scrollSize=i,this._refreshComputedValues(),!0):!1}setScrollPosition(t){let i=Math.round(t);return this._scrollPosition!==i?(this._scrollPosition=i,this._refreshComputedValues(),!0):!1}setScrollbarSize(t){this._scrollbarSize=Math.round(t)}setOppositeScrollbarSize(t){this._oppositeScrollbarSize=Math.round(t)}static _computeValues(t,i,r,s,n){let o=Math.max(0,r-t),l=Math.max(0,o-2*i),a=s>0&&s>r;if(!a)return{computedAvailableSize:Math.round(o),computedIsNeeded:a,computedSliderSize:Math.round(l),computedSliderRatio:0,computedSliderPosition:0};let h=Math.round(Math.max(20,Math.floor(r*l/s))),u=(l-h)/(s-r),c=n*u;return{computedAvailableSize:Math.round(o),computedIsNeeded:a,computedSliderSize:Math.round(h),computedSliderRatio:u,computedSliderPosition:Math.round(c)}}_refreshComputedValues(){let t=Da._computeValues(this._oppositeScrollbarSize,this._arrowSize,this._visibleSize,this._scrollSize,this._scrollPosition);this._computedAvailableSize=t.computedAvailableSize,this._computedIsNeeded=t.computedIsNeeded,this._computedSliderSize=t.computedSliderSize,this._computedSliderRatio=t.computedSliderRatio,this._computedSliderPosition=t.computedSliderPosition}getArrowSize(){return this._arrowSize}getScrollPosition(){return this._scrollPosition}getRectangleLargeSize(){return this._computedAvailableSize}getRectangleSmallSize(){return this._scrollbarSize}isNeeded(){return this._computedIsNeeded}getSliderSize(){return this._computedSliderSize}getSliderPosition(){return this._computedSliderPosition}getDesiredScrollPositionFromOffset(t){if(!this._computedIsNeeded)return 0;let i=t-this._arrowSize-this._computedSliderSize/2;return Math.round(i/this._computedSliderRatio)}getDesiredScrollPositionFromOffsetPaged(t){if(!this._computedIsNeeded)return 0;let i=t-this._arrowSize,r=this._scrollPosition;return i0&&Math.abs(t.deltaY)>0)return 1;let r=.5;if((!this._isAlmostInt(t.deltaX)||!this._isAlmostInt(t.deltaY))&&(r+=.25),i){let s=Math.abs(t.deltaX),n=Math.abs(t.deltaY),o=Math.abs(i.deltaX),l=Math.abs(i.deltaY),a=Math.max(Math.min(s,o),1),h=Math.max(Math.min(n,l),1),u=Math.max(s,o),c=Math.max(n,l);u%a===0&&c%h===0&&(r-=.5)}return Math.min(Math.max(r,0),1)}_isAlmostInt(t){return Math.abs(Math.round(t)-t)<.01}};Ra.INSTANCE=new Ra;var fS=Ra,_S=class extends Xh{constructor(e,t,i){super(),this._onScroll=this._register(new D),this.onScroll=this._onScroll.event,this._onWillScroll=this._register(new D),this.onWillScroll=this._onWillScroll.event,this._options=gS(t),this._scrollable=i,this._register(this._scrollable.onScroll(s=>{this._onWillScroll.fire(s),this._onDidScroll(s),this._onScroll.fire(s)}));let r={onMouseWheel:s=>this._onMouseWheel(s),onDragStart:()=>this._onDragStart(),onDragEnd:()=>this._onDragEnd()};this._verticalScrollbar=this._register(new cS(this._scrollable,this._options,r)),this._horizontalScrollbar=this._register(new hS(this._scrollable,this._options,r)),this._domNode=document.createElement("div"),this._domNode.className="xterm-scrollable-element "+this._options.className,this._domNode.setAttribute("role","presentation"),this._domNode.style.position="relative",this._domNode.appendChild(e),this._domNode.appendChild(this._horizontalScrollbar.domNode.domNode),this._domNode.appendChild(this._verticalScrollbar.domNode.domNode),this._options.useShadows?(this._leftShadowDomNode=_s(document.createElement("div")),this._leftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=_s(document.createElement("div")),this._topShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=_s(document.createElement("div")),this._topLeftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topLeftShadowDomNode.domNode)):(this._leftShadowDomNode=null,this._topShadowDomNode=null,this._topLeftShadowDomNode=null),this._listenOnDomNode=this._options.listenOnDomNode||this._domNode,this._mouseWheelToDispose=[],this._setListeningToMouseWheel(this._options.handleMouseWheel),this.onmouseover(this._listenOnDomNode,s=>this._onMouseOver(s)),this.onmouseleave(this._listenOnDomNode,s=>this._onMouseLeave(s)),this._hideTimeout=this._register(new Yh),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}get options(){return this._options}dispose(){this._mouseWheelToDispose=Yi(this._mouseWheelToDispose),super.dispose()}getDomNode(){return this._domNode}getOverviewRulerLayoutInfo(){return{parent:this._domNode,insertBefore:this._verticalScrollbar.domNode.domNode}}delegateVerticalScrollbarPointerDown(e){this._verticalScrollbar.delegatePointerDown(e)}getScrollDimensions(){return this._scrollable.getScrollDimensions()}setScrollDimensions(e){this._scrollable.setScrollDimensions(e,!1)}updateClassName(e){this._options.className=e,$t&&(this._options.className+=" mac"),this._domNode.className="xterm-scrollable-element "+this._options.className}updateOptions(e){typeof e.handleMouseWheel<"u"&&(this._options.handleMouseWheel=e.handleMouseWheel,this._setListeningToMouseWheel(this._options.handleMouseWheel)),typeof e.mouseWheelScrollSensitivity<"u"&&(this._options.mouseWheelScrollSensitivity=e.mouseWheelScrollSensitivity),typeof e.fastScrollSensitivity<"u"&&(this._options.fastScrollSensitivity=e.fastScrollSensitivity),typeof e.scrollPredominantAxis<"u"&&(this._options.scrollPredominantAxis=e.scrollPredominantAxis),typeof e.horizontal<"u"&&(this._options.horizontal=e.horizontal),typeof e.vertical<"u"&&(this._options.vertical=e.vertical),typeof e.horizontalScrollbarSize<"u"&&(this._options.horizontalScrollbarSize=e.horizontalScrollbarSize),typeof e.verticalScrollbarSize<"u"&&(this._options.verticalScrollbarSize=e.verticalScrollbarSize),typeof e.scrollByPage<"u"&&(this._options.scrollByPage=e.scrollByPage),this._horizontalScrollbar.updateOptions(this._options),this._verticalScrollbar.updateOptions(this._options),this._options.lazyRender||this._render()}setRevealOnScroll(e){this._revealOnScroll=e}delegateScrollFromMouseWheelEvent(e){this._onMouseWheel(new Su(e))}_setListeningToMouseWheel(e){if(this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=Yi(this._mouseWheelToDispose),e)){let t=i=>{this._onMouseWheel(new Su(i))};this._mouseWheelToDispose.push(F(this._listenOnDomNode,Ee.MOUSE_WHEEL,t,{passive:!1}))}}_onMouseWheel(e){var s;if((s=e.browserEvent)!=null&&s.defaultPrevented)return;let t=fS.INSTANCE;t.acceptStandardWheelEvent(e);let i=!1;if(e.deltaY||e.deltaX){let n=e.deltaY*this._options.mouseWheelScrollSensitivity,o=e.deltaX*this._options.mouseWheelScrollSensitivity;this._options.scrollPredominantAxis&&(this._options.scrollYToX&&o+n===0?o=n=0:Math.abs(n)>=Math.abs(o)?o=0:n=0),this._options.flipAxes&&([n,o]=[o,n]);let l=!$t&&e.browserEvent&&e.browserEvent.shiftKey;(this._options.scrollYToX||l)&&!o&&(o=n,n=0),e.browserEvent&&e.browserEvent.altKey&&(o=o*this._options.fastScrollSensitivity,n=n*this._options.fastScrollSensitivity);let a=this._scrollable.getFutureScrollPosition(),h={};if(n){let u=Eu*n,c=a.scrollTop-(u<0?Math.floor(u):Math.ceil(u));this._verticalScrollbar.writeScrollPosition(h,c)}if(o){let u=Eu*o,c=a.scrollLeft-(u<0?Math.floor(u):Math.ceil(u));this._horizontalScrollbar.writeScrollPosition(h,c)}h=this._scrollable.validateScrollPosition(h),(a.scrollLeft!==h.scrollLeft||a.scrollTop!==h.scrollTop)&&(this._options.mouseWheelSmoothScroll&&t.isPhysicalMouseWheel()?this._scrollable.setScrollPositionSmooth(h):this._scrollable.setScrollPositionNow(h),i=!0)}let r=i;!r&&this._options.alwaysConsumeMouseWheel&&(r=!0),!r&&this._options.consumeMouseWheelIfScrollbarIsNeeded&&(this._verticalScrollbar.isNeeded()||this._horizontalScrollbar.isNeeded())&&(r=!0),r&&(e.preventDefault(),e.stopPropagation())}_onDidScroll(e){this._shouldRender=this._horizontalScrollbar.onDidScroll(e)||this._shouldRender,this._shouldRender=this._verticalScrollbar.onDidScroll(e)||this._shouldRender,this._options.useShadows&&(this._shouldRender=!0),this._revealOnScroll&&this._reveal(),this._options.lazyRender||this._render()}renderNow(){if(!this._options.lazyRender)throw new Error("Please use `lazyRender` together with `renderNow`!");this._render()}_render(){if(this._shouldRender&&(this._shouldRender=!1,this._horizontalScrollbar.render(),this._verticalScrollbar.render(),this._options.useShadows)){let e=this._scrollable.getCurrentScrollPosition(),t=e.scrollTop>0,i=e.scrollLeft>0,r=i?" left":"",s=t?" top":"",n=i||t?" top-left-corner":"";this._leftShadowDomNode.setClassName(`shadow${r}`),this._topShadowDomNode.setClassName(`shadow${s}`),this._topLeftShadowDomNode.setClassName(`shadow${n}${s}${r}`)}}_onDragStart(){this._isDragging=!0,this._reveal()}_onDragEnd(){this._isDragging=!1,this._hide()}_onMouseLeave(e){this._mouseIsOver=!1,this._hide()}_onMouseOver(e){this._mouseIsOver=!0,this._reveal()}_reveal(){this._verticalScrollbar.beginReveal(),this._horizontalScrollbar.beginReveal(),this._scheduleHide()}_hide(){!this._mouseIsOver&&!this._isDragging&&(this._verticalScrollbar.beginHide(),this._horizontalScrollbar.beginHide())}_scheduleHide(){!this._mouseIsOver&&!this._isDragging&&this._hideTimeout.cancelAndSet(()=>this._hide(),uS)}},pS=class extends _S{constructor(e,t,i){super(e,t,i)}setScrollPosition(e){e.reuseAnimation?this._scrollable.setScrollPositionSmooth(e,e.reuseAnimation):this._scrollable.setScrollPositionNow(e)}getScrollPosition(){return this._scrollable.getCurrentScrollPosition()}};function gS(e){let t={lazyRender:typeof e.lazyRender<"u"?e.lazyRender:!1,className:typeof e.className<"u"?e.className:"",useShadows:typeof e.useShadows<"u"?e.useShadows:!0,handleMouseWheel:typeof e.handleMouseWheel<"u"?e.handleMouseWheel:!0,flipAxes:typeof e.flipAxes<"u"?e.flipAxes:!1,consumeMouseWheelIfScrollbarIsNeeded:typeof e.consumeMouseWheelIfScrollbarIsNeeded<"u"?e.consumeMouseWheelIfScrollbarIsNeeded:!1,alwaysConsumeMouseWheel:typeof e.alwaysConsumeMouseWheel<"u"?e.alwaysConsumeMouseWheel:!1,scrollYToX:typeof e.scrollYToX<"u"?e.scrollYToX:!1,mouseWheelScrollSensitivity:typeof e.mouseWheelScrollSensitivity<"u"?e.mouseWheelScrollSensitivity:1,fastScrollSensitivity:typeof e.fastScrollSensitivity<"u"?e.fastScrollSensitivity:5,scrollPredominantAxis:typeof e.scrollPredominantAxis<"u"?e.scrollPredominantAxis:!0,mouseWheelSmoothScroll:typeof e.mouseWheelSmoothScroll<"u"?e.mouseWheelSmoothScroll:!0,arrowSize:typeof e.arrowSize<"u"?e.arrowSize:11,listenOnDomNode:typeof e.listenOnDomNode<"u"?e.listenOnDomNode:null,horizontal:typeof e.horizontal<"u"?e.horizontal:1,horizontalScrollbarSize:typeof e.horizontalScrollbarSize<"u"?e.horizontalScrollbarSize:10,horizontalSliderSize:typeof e.horizontalSliderSize<"u"?e.horizontalSliderSize:0,horizontalHasArrows:typeof e.horizontalHasArrows<"u"?e.horizontalHasArrows:!1,vertical:typeof e.vertical<"u"?e.vertical:1,verticalScrollbarSize:typeof e.verticalScrollbarSize<"u"?e.verticalScrollbarSize:10,verticalHasArrows:typeof e.verticalHasArrows<"u"?e.verticalHasArrows:!1,verticalSliderSize:typeof e.verticalSliderSize<"u"?e.verticalSliderSize:0,scrollByPage:typeof e.scrollByPage<"u"?e.scrollByPage:!1};return t.horizontalSliderSize=typeof e.horizontalSliderSize<"u"?e.horizontalSliderSize:t.horizontalScrollbarSize,t.verticalSliderSize=typeof e.verticalSliderSize<"u"?e.verticalSliderSize:t.verticalScrollbarSize,$t&&(t.className+=" mac"),t}var Pa=class extends W{constructor(e,t,i,r,s,n,o,l){super(),this._bufferService=i,this._optionsService=o,this._renderService=l,this._onRequestScrollLines=this._register(new D),this.onRequestScrollLines=this._onRequestScrollLines.event,this._isSyncing=!1,this._isHandlingScroll=!1,this._suppressOnScrollHandler=!1;let a=this._register(new rS({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:h=>qh(r.window,h)}));this._register(this._optionsService.onSpecificOptionChange("smoothScrollDuration",()=>{a.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)})),this._scrollableElement=this._register(new pS(t,{vertical:1,horizontal:2,useShadows:!1,mouseWheelSmoothScroll:!0,...this._getChangeOptions()},a)),this._register(this._optionsService.onMultipleOptionChange(["scrollSensitivity","fastScrollSensitivity","overviewRuler"],()=>this._scrollableElement.updateOptions(this._getChangeOptions()))),this._register(s.onProtocolChange(h=>{this._scrollableElement.updateOptions({handleMouseWheel:!(h&16)})})),this._scrollableElement.setScrollDimensions({height:0,scrollHeight:0}),this._register(Ae.runAndSubscribe(n.onChangeColors,()=>{this._scrollableElement.getDomNode().style.backgroundColor=n.colors.background.css})),e.appendChild(this._scrollableElement.getDomNode()),this._register(re(()=>this._scrollableElement.getDomNode().remove())),this._styleElement=r.mainDocument.createElement("style"),t.appendChild(this._styleElement),this._register(re(()=>this._styleElement.remove())),this._register(Ae.runAndSubscribe(n.onChangeColors,()=>{this._styleElement.textContent=[".xterm .xterm-scrollable-element > .scrollbar > .slider {",` background: ${n.colors.scrollbarSliderBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider:hover {",` background: ${n.colors.scrollbarSliderHoverBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider.active {",` background: ${n.colors.scrollbarSliderActiveBackground.css};`,"}"].join(` +`)})),this._register(this._bufferService.onResize(()=>this.queueSync())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._latestYDisp=void 0,this.queueSync()})),this._register(this._bufferService.onScroll(()=>this._sync())),this._register(this._scrollableElement.onScroll(h=>this._handleScroll(h)))}scrollLines(e){let t=this._scrollableElement.getScrollPosition();this._scrollableElement.setScrollPosition({reuseAnimation:!0,scrollTop:t.scrollTop+e*this._renderService.dimensions.css.cell.height})}scrollToLine(e,t){t&&(this._latestYDisp=e),this._scrollableElement.setScrollPosition({reuseAnimation:!t,scrollTop:e*this._renderService.dimensions.css.cell.height})}_getChangeOptions(){var e;return{mouseWheelScrollSensitivity:this._optionsService.rawOptions.scrollSensitivity,fastScrollSensitivity:this._optionsService.rawOptions.fastScrollSensitivity,verticalScrollbarSize:((e=this._optionsService.rawOptions.overviewRuler)==null?void 0:e.width)||14}}queueSync(e){e!==void 0&&(this._latestYDisp=e),this._queuedAnimationFrame===void 0&&(this._queuedAnimationFrame=this._renderService.addRefreshCallback(()=>{this._queuedAnimationFrame=void 0,this._sync(this._latestYDisp)}))}_sync(e=this._bufferService.buffer.ydisp){!this._renderService||this._isSyncing||(this._isSyncing=!0,this._suppressOnScrollHandler=!0,this._scrollableElement.setScrollDimensions({height:this._renderService.dimensions.css.canvas.height,scrollHeight:this._renderService.dimensions.css.cell.height*this._bufferService.buffer.lines.length}),this._suppressOnScrollHandler=!1,e!==this._latestYDisp&&this._scrollableElement.setScrollPosition({scrollTop:e*this._renderService.dimensions.css.cell.height}),this._isSyncing=!1)}_handleScroll(e){if(!this._renderService||this._isHandlingScroll||this._suppressOnScrollHandler)return;this._isHandlingScroll=!0;let t=Math.round(e.scrollTop/this._renderService.dimensions.css.cell.height),i=t-this._bufferService.buffer.ydisp;i!==0&&(this._latestYDisp=t,this._onRequestScrollLines.fire(i)),this._isHandlingScroll=!1}};Pa=_e([L(2,Xe),L(3,ei),L(4,P_),L(5,Tr),L(6,Ge),L(7,ti)],Pa);var La=class extends W{constructor(e,t,i,r,s){super(),this._screenElement=e,this._bufferService=t,this._coreBrowserService=i,this._decorationService=r,this._renderService=s,this._decorationElements=new Map,this._altBufferIsActive=!1,this._dimensionsChanged=!1,this._container=document.createElement("div"),this._container.classList.add("xterm-decoration-container"),this._screenElement.appendChild(this._container),this._register(this._renderService.onRenderedViewportChange(()=>this._doRefreshDecorations())),this._register(this._renderService.onDimensionsChange(()=>{this._dimensionsChanged=!0,this._queueRefresh()})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt})),this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh())),this._register(this._decorationService.onDecorationRemoved(n=>this._removeDecoration(n))),this._register(re(()=>{this._container.remove(),this._decorationElements.clear()}))}_queueRefresh(){this._animationFrame===void 0&&(this._animationFrame=this._renderService.addRefreshCallback(()=>{this._doRefreshDecorations(),this._animationFrame=void 0}))}_doRefreshDecorations(){for(let e of this._decorationService.decorations)this._renderDecoration(e);this._dimensionsChanged=!1}_renderDecoration(e){this._refreshStyle(e),this._dimensionsChanged&&this._refreshXPosition(e)}_createElement(e){var r;let t=this._coreBrowserService.mainDocument.createElement("div");t.classList.add("xterm-decoration"),t.classList.toggle("xterm-decoration-top-layer",((r=e==null?void 0:e.options)==null?void 0:r.layer)==="top"),t.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,t.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,t.style.top=`${(e.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height}px`,t.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;let i=e.options.x??0;return i&&i>this._bufferService.cols&&(t.style.display="none"),this._refreshXPosition(e,t),t}_refreshStyle(e){let t=e.marker.line-this._bufferService.buffers.active.ydisp;if(t<0||t>=this._bufferService.rows)e.element&&(e.element.style.display="none",e.onRenderEmitter.fire(e.element));else{let i=this._decorationElements.get(e);i||(i=this._createElement(e),e.element=i,this._decorationElements.set(e,i),this._container.appendChild(i),e.onDispose(()=>{this._decorationElements.delete(e),i.remove()})),i.style.display=this._altBufferIsActive?"none":"block",this._altBufferIsActive||(i.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,i.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,i.style.top=`${t*this._renderService.dimensions.css.cell.height}px`,i.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`),e.onRenderEmitter.fire(i)}}_refreshXPosition(e,t=e.element){if(!t)return;let i=e.options.x??0;(e.options.anchor||"left")==="right"?t.style.right=i?`${i*this._renderService.dimensions.css.cell.width}px`:"":t.style.left=i?`${i*this._renderService.dimensions.css.cell.width}px`:""}_removeDecoration(e){var t;(t=this._decorationElements.get(e))==null||t.remove(),this._decorationElements.delete(e),e.dispose()}};La=_e([L(1,Xe),L(2,ei),L(3,Hs),L(4,ti)],La);var vS=class{constructor(){this._zones=[],this._zonePool=[],this._zonePoolIndex=0,this._linePadding={full:0,left:0,center:0,right:0}}get zones(){return this._zonePool.length=Math.min(this._zonePool.length,this._zones.length),this._zones}clear(){this._zones.length=0,this._zonePoolIndex=0}addDecoration(e){if(e.options.overviewRulerOptions){for(let t of this._zones)if(t.color===e.options.overviewRulerOptions.color&&t.position===e.options.overviewRulerOptions.position){if(this._lineIntersectsZone(t,e.marker.line))return;if(this._lineAdjacentToZone(t,e.marker.line,e.options.overviewRulerOptions.position)){this._addLineToZone(t,e.marker.line);return}}if(this._zonePoolIndex=e.startBufferLine&&t<=e.endBufferLine}_lineAdjacentToZone(e,t,i){return t>=e.startBufferLine-this._linePadding[i||"full"]&&t<=e.endBufferLine+this._linePadding[i||"full"]}_addLineToZone(e,t){e.startBufferLine=Math.min(e.startBufferLine,t),e.endBufferLine=Math.max(e.endBufferLine,t)}},Mt={full:0,left:0,center:0,right:0},oi={full:0,left:0,center:0,right:0},Kr={full:0,left:0,center:0,right:0},so=class extends W{constructor(e,t,i,r,s,n,o,l){var h;super(),this._viewportElement=e,this._screenElement=t,this._bufferService=i,this._decorationService=r,this._renderService=s,this._optionsService=n,this._themeService=o,this._coreBrowserService=l,this._colorZoneStore=new vS,this._shouldUpdateDimensions=!0,this._shouldUpdateAnchor=!0,this._lastKnownBufferLength=0,this._canvas=this._coreBrowserService.mainDocument.createElement("canvas"),this._canvas.classList.add("xterm-decoration-overview-ruler"),this._refreshCanvasDimensions(),(h=this._viewportElement.parentElement)==null||h.insertBefore(this._canvas,this._viewportElement),this._register(re(()=>{var u;return(u=this._canvas)==null?void 0:u.remove()}));let a=this._canvas.getContext("2d");if(a)this._ctx=a;else throw new Error("Ctx cannot be null");this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh(void 0,!0))),this._register(this._decorationService.onDecorationRemoved(()=>this._queueRefresh(void 0,!0))),this._register(this._renderService.onRenderedViewportChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._canvas.style.display=this._bufferService.buffer===this._bufferService.buffers.alt?"none":"block"})),this._register(this._bufferService.onScroll(()=>{this._lastKnownBufferLength!==this._bufferService.buffers.normal.lines.length&&(this._refreshDrawHeightConstants(),this._refreshColorZonePadding())})),this._register(this._renderService.onRender(()=>{(!this._containerHeight||this._containerHeight!==this._screenElement.clientHeight)&&(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh(!0))),this._register(this._optionsService.onSpecificOptionChange("overviewRuler",()=>this._queueRefresh(!0))),this._register(this._themeService.onChangeColors(()=>this._queueRefresh())),this._queueRefresh(!0)}get _width(){var e;return((e=this._optionsService.options.overviewRuler)==null?void 0:e.width)||0}_refreshDrawConstants(){let e=Math.floor((this._canvas.width-1)/3),t=Math.ceil((this._canvas.width-1)/3);oi.full=this._canvas.width,oi.left=e,oi.center=t,oi.right=e,this._refreshDrawHeightConstants(),Kr.full=1,Kr.left=1,Kr.center=1+oi.left,Kr.right=1+oi.left+oi.center}_refreshDrawHeightConstants(){Mt.full=Math.round(2*this._coreBrowserService.dpr);let e=this._canvas.height/this._bufferService.buffer.lines.length,t=Math.round(Math.max(Math.min(e,12),6)*this._coreBrowserService.dpr);Mt.left=t,Mt.center=t,Mt.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*Mt.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*Mt.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*Mt.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*Mt.right)}),this._lastKnownBufferLength=this._bufferService.buffers.normal.lines.length}_refreshCanvasDimensions(){this._canvas.style.width=`${this._width}px`,this._canvas.width=Math.round(this._width*this._coreBrowserService.dpr),this._canvas.style.height=`${this._screenElement.clientHeight}px`,this._canvas.height=Math.round(this._screenElement.clientHeight*this._coreBrowserService.dpr),this._refreshDrawConstants(),this._refreshColorZonePadding()}_refreshDecorations(){this._shouldUpdateDimensions&&this._refreshCanvasDimensions(),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._colorZoneStore.clear();for(let t of this._decorationService.decorations)this._colorZoneStore.addDecoration(t);this._ctx.lineWidth=1,this._renderRulerOutline();let e=this._colorZoneStore.zones;for(let t of e)t.position!=="full"&&this._renderColorZone(t);for(let t of e)t.position==="full"&&this._renderColorZone(t);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderRulerOutline(){this._ctx.fillStyle=this._themeService.colors.overviewRulerBorder.css,this._ctx.fillRect(0,0,1,this._canvas.height),this._optionsService.rawOptions.overviewRuler.showTopBorder&&this._ctx.fillRect(1,0,this._canvas.width-1,1),this._optionsService.rawOptions.overviewRuler.showBottomBorder&&this._ctx.fillRect(1,this._canvas.height-1,this._canvas.width-1,this._canvas.height)}_renderColorZone(e){this._ctx.fillStyle=e.color,this._ctx.fillRect(Kr[e.position||"full"],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-Mt[e.position||"full"]/2),oi[e.position||"full"],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+Mt[e.position||"full"]))}_queueRefresh(e,t){this._shouldUpdateDimensions=e||this._shouldUpdateDimensions,this._shouldUpdateAnchor=t||this._shouldUpdateAnchor,this._animationFrame===void 0&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._refreshDecorations(),this._animationFrame=void 0}))}};so=_e([L(2,Xe),L(3,Hs),L(4,ti),L(5,Ge),L(6,Tr),L(7,ei)],so);var C;(e=>(e.NUL="\0",e.SOH="",e.STX="",e.ETX="",e.EOT="",e.ENQ="",e.ACK="",e.BEL="\x07",e.BS="\b",e.HT=" ",e.LF=` +`,e.VT="\v",e.FF="\f",e.CR="\r",e.SO="",e.SI="",e.DLE="",e.DC1="",e.DC2="",e.DC3="",e.DC4="",e.NAK="",e.SYN="",e.ETB="",e.CAN="",e.EM="",e.SUB="",e.ESC="\x1B",e.FS="",e.GS="",e.RS="",e.US="",e.SP=" ",e.DEL=""))(C||(C={}));var Ln;(e=>(e.PAD="€",e.HOP="",e.BPH="‚",e.NBH="ƒ",e.IND="„",e.NEL="…",e.SSA="†",e.ESA="‡",e.HTS="ˆ",e.HTJ="‰",e.VTS="Š",e.PLD="‹",e.PLU="Œ",e.RI="",e.SS2="Ž",e.SS3="",e.DCS="",e.PU1="‘",e.PU2="’",e.STS="“",e.CCH="”",e.MW="•",e.SPA="–",e.EPA="—",e.SOS="˜",e.SGCI="™",e.SCI="š",e.CSI="›",e.ST="œ",e.OSC="",e.PM="ž",e.APC="Ÿ"))(Ln||(Ln={}));var G_;(e=>e.ST=`${C.ESC}\\`)(G_||(G_={}));var Ba=class{constructor(e,t,i,r,s,n){this._textarea=e,this._compositionView=t,this._bufferService=i,this._optionsService=r,this._coreService=s,this._renderService=n,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=""}get isComposing(){return this._isComposing}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent="",this._dataAlreadySent="",this._compositionView.classList.add("active")}compositionupdate(e){this._compositionView.textContent=e.data,this.updateCompositionElements(),setTimeout(()=>{this._compositionPosition.end=this._textarea.value.length},0)}compositionend(){this._finalizeComposition(!0)}keydown(e){if(this._isComposing||this._isSendingComposition){if(e.keyCode===20||e.keyCode===229||e.keyCode===16||e.keyCode===17||e.keyCode===18)return!1;this._finalizeComposition(!1)}return e.keyCode===229?(this._handleAnyTextareaChanges(),!1):!0}_finalizeComposition(e){if(this._compositionView.classList.remove("active"),this._isComposing=!1,e){let t={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(()=>{if(this._isSendingComposition){this._isSendingComposition=!1;let i;t.start+=this._dataAlreadySent.length,this._isComposing?i=this._textarea.value.substring(t.start,this._compositionPosition.start):i=this._textarea.value.substring(t.start),i.length>0&&this._coreService.triggerDataEvent(i,!0)}},0)}else{this._isSendingComposition=!1;let t=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(t,!0)}}_handleAnyTextareaChanges(){let e=this._textarea.value;setTimeout(()=>{if(!this._isComposing){let t=this._textarea.value,i=t.replace(e,"");this._dataAlreadySent=i,t.length>e.length?this._coreService.triggerDataEvent(i,!0):t.lengththis.updateCompositionElements(!0),0)}}};Ba=_e([L(2,Xe),L(3,Ge),L(4,Qi),L(5,ti)],Ba);var Re=0,Pe=0,Le=0,de=0,Du={css:"#00000000",rgba:0},Se;(e=>{function t(s,n,o,l){return l!==void 0?`#${Li(s)}${Li(n)}${Li(o)}${Li(l)}`:`#${Li(s)}${Li(n)}${Li(o)}`}e.toCss=t;function i(s,n,o,l=255){return(s<<24|n<<16|o<<8|l)>>>0}e.toRgba=i;function r(s,n,o,l){return{css:e.toCss(s,n,o,l),rgba:e.toRgba(s,n,o,l)}}e.toColor=r})(Se||(Se={}));var ee;(e=>{function t(a,h){if(de=(h.rgba&255)/255,de===1)return{css:h.css,rgba:h.rgba};let u=h.rgba>>24&255,c=h.rgba>>16&255,d=h.rgba>>8&255,g=a.rgba>>24&255,v=a.rgba>>16&255,m=a.rgba>>8&255;Re=g+Math.round((u-g)*de),Pe=v+Math.round((c-v)*de),Le=m+Math.round((d-m)*de);let k=Se.toCss(Re,Pe,Le),_=Se.toRgba(Re,Pe,Le);return{css:k,rgba:_}}e.blend=t;function i(a){return(a.rgba&255)===255}e.isOpaque=i;function r(a,h,u){let c=Bn.ensureContrastRatio(a.rgba,h.rgba,u);if(c)return Se.toColor(c>>24&255,c>>16&255,c>>8&255)}e.ensureContrastRatio=r;function s(a){let h=(a.rgba|255)>>>0;return[Re,Pe,Le]=Bn.toChannels(h),{css:Se.toCss(Re,Pe,Le),rgba:h}}e.opaque=s;function n(a,h){return de=Math.round(h*255),[Re,Pe,Le]=Bn.toChannels(a.rgba),{css:Se.toCss(Re,Pe,Le,de),rgba:Se.toRgba(Re,Pe,Le,de)}}e.opacity=n;function o(a,h){return de=a.rgba&255,n(a,de*h/255)}e.multiplyOpacity=o;function l(a){return[a.rgba>>24&255,a.rgba>>16&255,a.rgba>>8&255]}e.toColorRGB=l})(ee||(ee={}));var ne;(e=>{let t,i;try{let s=document.createElement("canvas");s.width=1,s.height=1;let n=s.getContext("2d",{willReadFrequently:!0});n&&(t=n,t.globalCompositeOperation="copy",i=t.createLinearGradient(0,0,1,1))}catch{}function r(s){if(s.match(/#[\da-f]{3,8}/i))switch(s.length){case 4:return Re=parseInt(s.slice(1,2).repeat(2),16),Pe=parseInt(s.slice(2,3).repeat(2),16),Le=parseInt(s.slice(3,4).repeat(2),16),Se.toColor(Re,Pe,Le);case 5:return Re=parseInt(s.slice(1,2).repeat(2),16),Pe=parseInt(s.slice(2,3).repeat(2),16),Le=parseInt(s.slice(3,4).repeat(2),16),de=parseInt(s.slice(4,5).repeat(2),16),Se.toColor(Re,Pe,Le,de);case 7:return{css:s,rgba:(parseInt(s.slice(1),16)<<8|255)>>>0};case 9:return{css:s,rgba:parseInt(s.slice(1),16)>>>0}}let n=s.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(n)return Re=parseInt(n[1]),Pe=parseInt(n[2]),Le=parseInt(n[3]),de=Math.round((n[5]===void 0?1:parseFloat(n[5]))*255),Se.toColor(Re,Pe,Le,de);if(!t||!i)throw new Error("css.toColor: Unsupported css format");if(t.fillStyle=i,t.fillStyle=s,typeof t.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(t.fillRect(0,0,1,1),[Re,Pe,Le,de]=t.getImageData(0,0,1,1).data,de!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:Se.toRgba(Re,Pe,Le,de),css:s}}e.toColor=r})(ne||(ne={}));var Ke;(e=>{function t(r){return i(r>>16&255,r>>8&255,r&255)}e.relativeLuminance=t;function i(r,s,n){let o=r/255,l=s/255,a=n/255,h=o<=.03928?o/12.92:Math.pow((o+.055)/1.055,2.4),u=l<=.03928?l/12.92:Math.pow((l+.055)/1.055,2.4),c=a<=.03928?a/12.92:Math.pow((a+.055)/1.055,2.4);return h*.2126+u*.7152+c*.0722}e.relativeLuminance2=i})(Ke||(Ke={}));var Bn;(e=>{function t(o,l){if(de=(l&255)/255,de===1)return l;let a=l>>24&255,h=l>>16&255,u=l>>8&255,c=o>>24&255,d=o>>16&255,g=o>>8&255;return Re=c+Math.round((a-c)*de),Pe=d+Math.round((h-d)*de),Le=g+Math.round((u-g)*de),Se.toRgba(Re,Pe,Le)}e.blend=t;function i(o,l,a){let h=Ke.relativeLuminance(o>>8),u=Ke.relativeLuminance(l>>8);if(Wt(h,u)>8));if(v>8));return v>k?g:m}return g}let c=s(o,l,a),d=Wt(h,Ke.relativeLuminance(c>>8));if(d>8));return d>v?c:g}return c}}e.ensureContrastRatio=i;function r(o,l,a){let h=o>>24&255,u=o>>16&255,c=o>>8&255,d=l>>24&255,g=l>>16&255,v=l>>8&255,m=Wt(Ke.relativeLuminance2(d,g,v),Ke.relativeLuminance2(h,u,c));for(;m0||g>0||v>0);)d-=Math.max(0,Math.ceil(d*.1)),g-=Math.max(0,Math.ceil(g*.1)),v-=Math.max(0,Math.ceil(v*.1)),m=Wt(Ke.relativeLuminance2(d,g,v),Ke.relativeLuminance2(h,u,c));return(d<<24|g<<16|v<<8|255)>>>0}e.reduceLuminance=r;function s(o,l,a){let h=o>>24&255,u=o>>16&255,c=o>>8&255,d=l>>24&255,g=l>>16&255,v=l>>8&255,m=Wt(Ke.relativeLuminance2(d,g,v),Ke.relativeLuminance2(h,u,c));for(;m>>0}e.increaseLuminance=s;function n(o){return[o>>24&255,o>>16&255,o>>8&255,o&255]}e.toChannels=n})(Bn||(Bn={}));function Li(e){let t=e.toString(16);return t.length<2?"0"+t:t}function Wt(e,t){return e1){let u=this._getJoinedRanges(r,o,n,t,s);for(let c=0;c1){let h=this._getJoinedRanges(r,o,n,t,s);for(let u=0;u=$,z=x,y=this._workCell;if(d.length>0&&x===d[0][0]&&A){let q=d.shift(),Bo=this._isCellInSelection(q[0],t);for(f=q[0]+1;f=q[1]),A?(P=!0,y=new mS(this._workCell,e.translateToString(!0,q[0],q[1]),q[1]-q[0]),z=q[1]-1,M=y.getWidth()):$=q[1]}let T=this._isCellInSelection(x,t),I=i&&x===n,Y=N&&x>=h&&x<=u,Q=!1;this._decorationService.forEachDecorationAtCell(x,t,void 0,q=>{Q=!0});let Te=y.getChars()||pi;if(Te===" "&&(y.isUnderline()||y.isOverline())&&(Te=" "),U=M*l-a.get(Te,y.isBold(),y.isItalic()),!m)m=this._document.createElement("span");else if(k&&(T&&B||!T&&!B&&y.bg===p)&&(T&&B&&g.selectionForeground||y.fg===S)&&y.extended.ext===w&&Y===b&&U===R&&!I&&!P&&!Q&&A){y.isInvisible()?_+=pi:_+=Te,k++;continue}else k&&(m.textContent=_),m=this._document.createElement("span"),k=0,_="";if(p=y.bg,S=y.fg,w=y.extended.ext,b=Y,R=U,B=T,P&&n>=x&&n<=z&&(n=x),!this._coreService.isCursorHidden&&I&&this._coreService.isCursorInitialized){if(V.push("xterm-cursor"),this._coreBrowserService.isFocused)o&&V.push("xterm-cursor-blink"),V.push(r==="bar"?"xterm-cursor-bar":r==="underline"?"xterm-cursor-underline":"xterm-cursor-block");else if(s)switch(s){case"outline":V.push("xterm-cursor-outline");break;case"block":V.push("xterm-cursor-block");break;case"bar":V.push("xterm-cursor-bar");break;case"underline":V.push("xterm-cursor-underline");break}}if(y.isBold()&&V.push("xterm-bold"),y.isItalic()&&V.push("xterm-italic"),y.isDim()&&V.push("xterm-dim"),y.isInvisible()?_=pi:_=y.getChars()||pi,y.isUnderline()&&(V.push(`xterm-underline-${y.extended.underlineStyle}`),_===" "&&(_=" "),!y.isUnderlineColorDefault()))if(y.isUnderlineColorRGB())m.style.textDecorationColor=`rgb(${$s.toColorRGB(y.getUnderlineColor()).join(",")})`;else{let q=y.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&y.isBold()&&q<8&&(q+=8),m.style.textDecorationColor=g.ansi[q].css}y.isOverline()&&(V.push("xterm-overline"),_===" "&&(_=" ")),y.isStrikethrough()&&V.push("xterm-strikethrough"),Y&&(m.style.textDecoration="underline");let ce=y.getFgColor(),Qe=y.getFgColorMode(),ve=y.getBgColor(),dt=y.getBgColorMode(),Lo=!!y.isInverse();if(Lo){let q=ce;ce=ve,ve=q;let Bo=Qe;Qe=dt,dt=Bo}let ii,Ks,Or=!1;this._decorationService.forEachDecorationAtCell(x,t,void 0,q=>{q.options.layer!=="top"&&Or||(q.backgroundColorRGB&&(dt=50331648,ve=q.backgroundColorRGB.rgba>>8&16777215,ii=q.backgroundColorRGB),q.foregroundColorRGB&&(Qe=50331648,ce=q.foregroundColorRGB.rgba>>8&16777215,Ks=q.foregroundColorRGB),Or=q.options.layer==="top")}),!Or&&T&&(ii=this._coreBrowserService.isFocused?g.selectionBackgroundOpaque:g.selectionInactiveBackgroundOpaque,ve=ii.rgba>>8&16777215,dt=50331648,Or=!0,g.selectionForeground&&(Qe=50331648,ce=g.selectionForeground.rgba>>8&16777215,Ks=g.selectionForeground)),Or&&V.push("xterm-decoration-top");let ri;switch(dt){case 16777216:case 33554432:ri=g.ansi[ve],V.push(`xterm-bg-${ve}`);break;case 50331648:ri=Se.toColor(ve>>16,ve>>8&255,ve&255),this._addStyle(m,`background-color:#${Ru((ve>>>0).toString(16),"0",6)}`);break;case 0:default:Lo?(ri=g.foreground,V.push("xterm-bg-257")):ri=g.background}switch(ii||y.isDim()&&(ii=ee.multiplyOpacity(ri,.5)),Qe){case 16777216:case 33554432:y.isBold()&&ce<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(ce+=8),this._applyMinimumContrast(m,ri,g.ansi[ce],y,ii,void 0)||V.push(`xterm-fg-${ce}`);break;case 50331648:let q=Se.toColor(ce>>16&255,ce>>8&255,ce&255);this._applyMinimumContrast(m,ri,q,y,ii,Ks)||this._addStyle(m,`color:#${Ru(ce.toString(16),"0",6)}`);break;case 0:default:this._applyMinimumContrast(m,ri,g.foreground,y,ii,Ks)||Lo&&V.push("xterm-fg-257")}V.length&&(m.className=V.join(" "),V.length=0),!I&&!P&&!Q&&A?k++:m.textContent=_,U!==this.defaultSpacing&&(m.style.letterSpacing=`${U}px`),c.push(m),x=z}return m&&k&&(m.textContent=_),c}_applyMinimumContrast(e,t,i,r,s,n){if(this._optionsService.rawOptions.minimumContrastRatio===1||wS(r.getCode()))return!1;let o=this._getContrastCache(r),l;if(!s&&!n&&(l=o.getColor(t.rgba,i.rgba)),l===void 0){let a=this._optionsService.rawOptions.minimumContrastRatio/(r.isDim()?2:1);l=ee.ensureContrastRatio(s||t,n||i,a),o.setColor((s||t).rgba,(n||i).rgba,l??null)}return l?(this._addStyle(e,`color:${l.css}`),!0):!1}_getContrastCache(e){return e.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(e,t){e.setAttribute("style",`${e.getAttribute("style")||""}${t};`)}_isCellInSelection(e,t){let i=this._selectionStart,r=this._selectionEnd;return!i||!r?!1:this._columnSelectMode?i[0]<=r[0]?e>=i[0]&&t>=i[1]&&e=i[1]&&e>=r[0]&&t<=r[1]:t>i[1]&&t=i[0]&&e=i[0]}};Ma=_e([L(1,M_),L(2,Ge),L(3,ei),L(4,Qi),L(5,Hs),L(6,Tr)],Ma);function Ru(e,t,i){for(;e.length0&&(this._flat[r]=o),o}let s=e;t&&(s+="B"),i&&(s+="I");let n=this._holey.get(s);if(n===void 0){let o=0;t&&(o|=1),i&&(o|=2),n=this._measure(e,o),n>0&&this._holey.set(s,n)}return n}_measure(e,t){let i=this._measureElements[t];return i.textContent=e.repeat(32),i.offsetWidth/32}},xS=class{constructor(){this.clear()}clear(){this.hasSelection=!1,this.columnSelectMode=!1,this.viewportStartRow=0,this.viewportEndRow=0,this.viewportCappedStartRow=0,this.viewportCappedEndRow=0,this.startCol=0,this.endCol=0,this.selectionStart=void 0,this.selectionEnd=void 0}update(e,t,i,r=!1){if(this.selectionStart=t,this.selectionEnd=i,!t||!i||t[0]===i[0]&&t[1]===i[1]){this.clear();return}let s=e.buffers.active.ydisp,n=t[1]-s,o=i[1]-s,l=Math.max(n,0),a=Math.min(o,e.rows-1);if(l>=e.rows||a<0){this.clear();return}this.hasSelection=!0,this.columnSelectMode=r,this.viewportStartRow=n,this.viewportEndRow=o,this.viewportCappedStartRow=l,this.viewportCappedEndRow=a,this.startCol=t[0],this.endCol=i[0]}isCellSelected(e,t,i){return this.hasSelection?(i-=e.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?t>=this.startCol&&i>=this.viewportCappedStartRow&&t=this.viewportCappedStartRow&&t>=this.endCol&&i<=this.viewportCappedEndRow:i>this.viewportStartRow&&i=this.startCol&&t=this.startCol):!1}};function bS(){return new xS}var hl="xterm-dom-renderer-owner-",ft="xterm-rows",dn="xterm-fg-",Pu="xterm-bg-",Vr="xterm-focus",fn="xterm-selection",ES=1,Ta=class extends W{constructor(e,t,i,r,s,n,o,l,a,h,u,c,d,g){super(),this._terminal=e,this._document=t,this._element=i,this._screenElement=r,this._viewportElement=s,this._helperContainer=n,this._linkifier2=o,this._charSizeService=a,this._optionsService=h,this._bufferService=u,this._coreService=c,this._coreBrowserService=d,this._themeService=g,this._terminalClass=ES++,this._rowElements=[],this._selectionRenderModel=bS(),this.onRequestRedraw=this._register(new D).event,this._rowContainer=this._document.createElement("div"),this._rowContainer.classList.add(ft),this._rowContainer.style.lineHeight="normal",this._rowContainer.setAttribute("aria-hidden","true"),this._refreshRowElements(this._bufferService.cols,this._bufferService.rows),this._selectionContainer=this._document.createElement("div"),this._selectionContainer.classList.add(fn),this._selectionContainer.setAttribute("aria-hidden","true"),this.dimensions=CS(),this._updateDimensions(),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._themeService.onChangeColors(v=>this._injectCss(v))),this._injectCss(this._themeService.colors),this._rowFactory=l.createInstance(Ma,document),this._element.classList.add(hl+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline(v=>this._handleLinkHover(v))),this._register(this._linkifier2.onHideLinkUnderline(v=>this._handleLinkLeave(v))),this._register(re(()=>{this._element.classList.remove(hl+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new kS(this._document,this._helperContainer),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}_updateDimensions(){let e=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*e,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*e),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.left=0,this.dimensions.device.char.top=0,this.dimensions.device.canvas.width=this.dimensions.device.cell.width*this._bufferService.cols,this.dimensions.device.canvas.height=this.dimensions.device.cell.height*this._bufferService.rows,this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/e),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/e),this.dimensions.css.cell.width=this.dimensions.css.canvas.width/this._bufferService.cols,this.dimensions.css.cell.height=this.dimensions.css.canvas.height/this._bufferService.rows;for(let i of this._rowElements)i.style.width=`${this.dimensions.css.canvas.width}px`,i.style.height=`${this.dimensions.css.cell.height}px`,i.style.lineHeight=`${this.dimensions.css.cell.height}px`,i.style.overflow="hidden";this._dimensionsStyleElement||(this._dimensionsStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._dimensionsStyleElement));let t=`${this._terminalSelector} .${ft} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=t,this._selectionContainer.style.height=this._viewportElement.style.height,this._screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._screenElement.style.height=`${this.dimensions.css.canvas.height}px`}_injectCss(e){this._themeStyleElement||(this._themeStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._themeStyleElement));let t=`${this._terminalSelector} .${ft} { pointer-events: none; color: ${e.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;t+=`${this._terminalSelector} .${ft} .xterm-dim { color: ${ee.multiplyOpacity(e.foreground,.5).css};}`,t+=`${this._terminalSelector} span:not(.xterm-bold) { font-weight: ${this._optionsService.rawOptions.fontWeight};}${this._terminalSelector} span.xterm-bold { font-weight: ${this._optionsService.rawOptions.fontWeightBold};}${this._terminalSelector} span.xterm-italic { font-style: italic;}`;let i=`blink_underline_${this._terminalClass}`,r=`blink_bar_${this._terminalClass}`,s=`blink_block_${this._terminalClass}`;t+=`@keyframes ${i} { 50% { border-bottom-style: hidden; }}`,t+=`@keyframes ${r} { 50% { box-shadow: none; }}`,t+=`@keyframes ${s} { 0% { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css}; } 50% { background-color: inherit; color: ${e.cursor.css}; }}`,t+=`${this._terminalSelector} .${ft}.${Vr} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${i} 1s step-end infinite;}${this._terminalSelector} .${ft}.${Vr} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${r} 1s step-end infinite;}${this._terminalSelector} .${ft}.${Vr} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${s} 1s step-end infinite;}${this._terminalSelector} .${ft} .xterm-cursor.xterm-cursor-block { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css};}${this._terminalSelector} .${ft} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e.cursor.css} !important; color: ${e.cursorAccent.css} !important;}${this._terminalSelector} .${ft} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${ft} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}${this._terminalSelector} .${ft} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,t+=`${this._terminalSelector} .${fn} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${fn} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${fn} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(let[n,o]of e.ansi.entries())t+=`${this._terminalSelector} .${dn}${n} { color: ${o.css}; }${this._terminalSelector} .${dn}${n}.xterm-dim { color: ${ee.multiplyOpacity(o,.5).css}; }${this._terminalSelector} .${Pu}${n} { background-color: ${o.css}; }`;t+=`${this._terminalSelector} .${dn}257 { color: ${ee.opaque(e.background).css}; }${this._terminalSelector} .${dn}257.xterm-dim { color: ${ee.multiplyOpacity(ee.opaque(e.background),.5).css}; }${this._terminalSelector} .${Pu}257 { background-color: ${e.foreground.css}; }`,this._themeStyleElement.textContent=t}_setDefaultSpacing(){let e=this.dimensions.css.cell.width-this._widthCache.get("W",!1,!1);this._rowContainer.style.letterSpacing=`${e}px`,this._rowFactory.defaultSpacing=e}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(e,t){for(let i=this._rowElements.length;i<=t;i++){let r=this._document.createElement("div");this._rowContainer.appendChild(r),this._rowElements.push(r)}for(;this._rowElements.length>t;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(e,t){this._refreshRowElements(e,t),this._updateDimensions(),this.handleSelectionChanged(this._selectionRenderModel.selectionStart,this._selectionRenderModel.selectionEnd,this._selectionRenderModel.columnSelectMode)}handleCharSizeChanged(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}handleBlur(){this._rowContainer.classList.remove(Vr),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(Vr),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(e,t,i){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(e,t,i),this.renderRows(0,this._bufferService.rows-1),!e||!t||(this._selectionRenderModel.update(this._terminal,e,t,i),!this._selectionRenderModel.hasSelection))return;let r=this._selectionRenderModel.viewportStartRow,s=this._selectionRenderModel.viewportEndRow,n=this._selectionRenderModel.viewportCappedStartRow,o=this._selectionRenderModel.viewportCappedEndRow,l=this._document.createDocumentFragment();if(i){let a=e[0]>t[0];l.appendChild(this._createSelectionElement(n,a?t[0]:e[0],a?e[0]:t[0],o-n+1))}else{let a=r===n?e[0]:0,h=n===s?t[0]:this._bufferService.cols;l.appendChild(this._createSelectionElement(n,a,h));let u=o-n-1;if(l.appendChild(this._createSelectionElement(n+1,0,this._bufferService.cols,u)),n!==o){let c=s===o?t[0]:this._bufferService.cols;l.appendChild(this._createSelectionElement(o,0,c))}}this._selectionContainer.appendChild(l)}_createSelectionElement(e,t,i,r=1){let s=this._document.createElement("div"),n=t*this.dimensions.css.cell.width,o=this.dimensions.css.cell.width*(i-t);return n+o>this.dimensions.css.canvas.width&&(o=this.dimensions.css.canvas.width-n),s.style.height=`${r*this.dimensions.css.cell.height}px`,s.style.top=`${e*this.dimensions.css.cell.height}px`,s.style.left=`${n}px`,s.style.width=`${o}px`,s}handleCursorMove(){}_handleOptionsChanged(){this._updateDimensions(),this._injectCss(this._themeService.colors),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}clear(){for(let e of this._rowElements)e.replaceChildren()}renderRows(e,t){let i=this._bufferService.buffer,r=i.ybase+i.y,s=Math.min(i.x,this._bufferService.cols-1),n=this._coreService.decPrivateModes.cursorBlink??this._optionsService.rawOptions.cursorBlink,o=this._coreService.decPrivateModes.cursorStyle??this._optionsService.rawOptions.cursorStyle,l=this._optionsService.rawOptions.cursorInactiveStyle;for(let a=e;a<=t;a++){let h=a+i.ydisp,u=this._rowElements[a],c=i.lines.get(h);if(!u||!c)break;u.replaceChildren(...this._rowFactory.createRow(c,h,h===r,o,l,s,n,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${hl}${this._terminalClass}`}_handleLinkHover(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!0)}_handleLinkLeave(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!1)}_setCellUnderline(e,t,i,r,s,n){i<0&&(e=0),r<0&&(t=0);let o=this._bufferService.rows-1;i=Math.max(Math.min(i,o),0),r=Math.max(Math.min(r,o),0),s=Math.min(s,this._bufferService.cols);let l=this._bufferService.buffer,a=l.ybase+l.y,h=Math.min(l.x,s-1),u=this._optionsService.rawOptions.cursorBlink,c=this._optionsService.rawOptions.cursorStyle,d=this._optionsService.rawOptions.cursorInactiveStyle;for(let g=i;g<=r;++g){let v=g+l.ydisp,m=this._rowElements[g],k=l.lines.get(v);if(!m||!k)break;m.replaceChildren(...this._rowFactory.createRow(k,v,v===a,c,d,h,u,this.dimensions.css.cell.width,this._widthCache,n?g===i?e:0:-1,n?(g===r?t:s)-1:-1))}}};Ta=_e([L(7,Wh),L(8,Do),L(9,Ge),L(10,Xe),L(11,Qi),L(12,ei),L(13,Tr)],Ta);var Na=class extends W{constructor(e,t,i){super(),this._optionsService=i,this.width=0,this.height=0,this._onCharSizeChange=this._register(new D),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this._register(new RS(this._optionsService))}catch{this._measureStrategy=this._register(new DS(e,t,this._optionsService))}this._register(this._optionsService.onMultipleOptionChange(["fontFamily","fontSize"],()=>this.measure()))}get hasValidSize(){return this.width>0&&this.height>0}measure(){let e=this._measureStrategy.measure();(e.width!==this.width||e.height!==this.height)&&(this.width=e.width,this.height=e.height,this._onCharSizeChange.fire())}};Na=_e([L(2,Ge)],Na);var Q_=class extends W{constructor(){super(...arguments),this._result={width:0,height:0}}_validateAndSet(e,t){e!==void 0&&e>0&&t!==void 0&&t>0&&(this._result.width=e,this._result.height=t)}},DS=class extends Q_{constructor(e,t,i){super(),this._document=e,this._parentElement=t,this._optionsService=i,this._measureElement=this._document.createElement("span"),this._measureElement.classList.add("xterm-char-measure-element"),this._measureElement.textContent="W".repeat(32),this._measureElement.setAttribute("aria-hidden","true"),this._measureElement.style.whiteSpace="pre",this._measureElement.style.fontKerning="none",this._parentElement.appendChild(this._measureElement)}measure(){return this._measureElement.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._measureElement.style.fontSize=`${this._optionsService.rawOptions.fontSize}px`,this._validateAndSet(Number(this._measureElement.offsetWidth)/32,Number(this._measureElement.offsetHeight)),this._result}},RS=class extends Q_{constructor(e){super(),this._optionsService=e,this._canvas=new OffscreenCanvas(100,100),this._ctx=this._canvas.getContext("2d");let t=this._ctx.measureText("W");if(!("width"in t&&"fontBoundingBoxAscent"in t&&"fontBoundingBoxDescent"in t))throw new Error("Required font metrics not supported")}measure(){this._ctx.font=`${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`;let e=this._ctx.measureText("W");return this._validateAndSet(e.width,e.fontBoundingBoxAscent+e.fontBoundingBoxDescent),this._result}},PS=class extends W{constructor(e,t,i){super(),this._textarea=e,this._window=t,this.mainDocument=i,this._isFocused=!1,this._cachedIsFocused=void 0,this._screenDprMonitor=this._register(new LS(this._window)),this._onDprChange=this._register(new D),this.onDprChange=this._onDprChange.event,this._onWindowChange=this._register(new D),this.onWindowChange=this._onWindowChange.event,this._register(this.onWindowChange(r=>this._screenDprMonitor.setWindow(r))),this._register(Ae.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register(F(this._textarea,"focus",()=>this._isFocused=!0)),this._register(F(this._textarea,"blur",()=>this._isFocused=!1))}get window(){return this._window}set window(e){this._window!==e&&(this._window=e,this._onWindowChange.fire(this._window))}get dpr(){return this.window.devicePixelRatio}get isFocused(){return this._cachedIsFocused===void 0&&(this._cachedIsFocused=this._isFocused&&this._textarea.ownerDocument.hasFocus(),queueMicrotask(()=>this._cachedIsFocused=void 0)),this._cachedIsFocused}},LS=class extends W{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this._register(new Pr),this._onDprChange=this._register(new D),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this._register(re(()=>this.clearListener()))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=F(this._parentWindow,"resize",()=>this._setDprAndFireIfDiffers())}_setDprAndFireIfDiffers(){this._parentWindow.devicePixelRatio!==this._currentDevicePixelRatio&&this._onDprChange.fire(this._parentWindow.devicePixelRatio),this._updateDpr()}_updateDpr(){var e;this._outerListener&&((e=this._resolutionMediaMatchList)==null||e.removeListener(this._outerListener),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._resolutionMediaMatchList=this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`),this._resolutionMediaMatchList.addListener(this._outerListener))}clearListener(){!this._resolutionMediaMatchList||!this._outerListener||(this._resolutionMediaMatchList.removeListener(this._outerListener),this._resolutionMediaMatchList=void 0,this._outerListener=void 0)}},BS=class extends W{constructor(){super(),this.linkProviders=[],this._register(re(()=>this.linkProviders.length=0))}registerLinkProvider(e){return this.linkProviders.push(e),{dispose:()=>{let t=this.linkProviders.indexOf(e);t!==-1&&this.linkProviders.splice(t,1)}}}};function Gh(e,t,i){let r=i.getBoundingClientRect(),s=e.getComputedStyle(i),n=parseInt(s.getPropertyValue("padding-left")),o=parseInt(s.getPropertyValue("padding-top"));return[t.clientX-r.left-n,t.clientY-r.top-o]}function MS(e,t,i,r,s,n,o,l,a){if(!n)return;let h=Gh(e,t,i);if(h)return h[0]=Math.ceil((h[0]+(a?o/2:0))/o),h[1]=Math.ceil(h[1]/l),h[0]=Math.min(Math.max(h[0],1),r+(a?1:0)),h[1]=Math.min(Math.max(h[1],1),s),h}var Oa=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,i,r,s){return MS(window,e,t,i,r,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,s)}getMouseReportCoords(e,t){let i=Gh(window,e,t);if(this._charSizeService.hasValidSize)return i[0]=Math.min(Math.max(i[0],0),this._renderService.dimensions.css.canvas.width-1),i[1]=Math.min(Math.max(i[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(i[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(i[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(i[0]),y:Math.floor(i[1])}}};Oa=_e([L(0,ti),L(1,Do)],Oa);var TS=class{constructor(e,t){this._renderCallback=e,this._coreBrowserService=t,this._refreshCallbacks=[]}dispose(){this._animationFrame&&(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0)}addRefreshCallback(e){return this._refreshCallbacks.push(e),this._animationFrame||(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh())),this._animationFrame}refresh(e,t,i){this._rowCount=i,e=e!==void 0?e:0,t=t!==void 0?t:this._rowCount-1,this._rowStart=this._rowStart!==void 0?Math.min(this._rowStart,e):e,this._rowEnd=this._rowEnd!==void 0?Math.max(this._rowEnd,t):t,!this._animationFrame&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()))}_innerRefresh(){if(this._animationFrame=void 0,this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0){this._runRefreshCallbacks();return}let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(let e of this._refreshCallbacks)e(0);this._refreshCallbacks=[]}},Z_={};Uv(Z_,{getSafariVersion:()=>OS,isChromeOS:()=>ip,isFirefox:()=>J_,isIpad:()=>AS,isIphone:()=>IS,isLegacyEdge:()=>NS,isLinux:()=>Qh,isMac:()=>oo,isNode:()=>Ro,isSafari:()=>ep,isWindows:()=>tp});var Ro=typeof process<"u"&&"title"in process,Ws=Ro?"node":navigator.userAgent,Us=Ro?"node":navigator.platform,J_=Ws.includes("Firefox"),NS=Ws.includes("Edge"),ep=/^((?!chrome|android).)*safari/i.test(Ws);function OS(){if(!ep)return 0;let e=Ws.match(/Version\/(\d+)/);return e===null||e.length<2?0:parseInt(e[1])}var oo=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(Us),AS=Us==="iPad",IS=Us==="iPhone",tp=["Windows","Win16","Win32","WinCE"].includes(Us),Qh=Us.indexOf("Linux")>=0,ip=/\bCrOS\b/.test(Ws),rp=class{constructor(){this._tasks=[],this._i=0}enqueue(e){this._tasks.push(e),this._start()}flush(){for(;this._is){r-t<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(r-t))}ms`),this._start();return}r=s}this.clear()}},zS=class extends rp{_requestCallback(e){return setTimeout(()=>e(this._createDeadline(16)))}_cancelCallback(e){clearTimeout(e)}_createDeadline(e){let t=performance.now()+e;return{timeRemaining:()=>Math.max(0,t-performance.now())}}},FS=class extends rp{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}},lo=!Ro&&"requestIdleCallback"in window?FS:zS,$S=class{constructor(){this._queue=new lo}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}},Aa=class extends W{constructor(e,t,i,r,s,n,o,l,a){super(),this._rowCount=e,this._optionsService=i,this._charSizeService=r,this._coreService=s,this._coreBrowserService=l,this._renderer=this._register(new Pr),this._pausedResizeTask=new $S,this._observerDisposable=this._register(new Pr),this._isPaused=!1,this._needsFullRefresh=!1,this._isNextRenderRedrawOnly=!0,this._needsSelectionRefresh=!1,this._canvasWidth=0,this._canvasHeight=0,this._selectionState={start:void 0,end:void 0,columnSelectMode:!1},this._onDimensionsChange=this._register(new D),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this._register(new D),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this._register(new D),this.onRender=this._onRender.event,this._onRefreshRequest=this._register(new D),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new TS((h,u)=>this._renderRows(h,u),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new HS(this._coreBrowserService,this._coreService,()=>this._fullRefresh()),this._register(re(()=>this._syncOutputHandler.dispose())),this._register(this._coreBrowserService.onDprChange(()=>this.handleDevicePixelRatioChange())),this._register(o.onResize(()=>this._fullRefresh())),this._register(o.buffers.onBufferActivate(()=>{var h;return(h=this._renderer.value)==null?void 0:h.clear()})),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._charSizeService.onCharSizeChange(()=>this.handleCharSizeChanged())),this._register(n.onDecorationRegistered(()=>this._fullRefresh())),this._register(n.onDecorationRemoved(()=>this._fullRefresh())),this._register(this._optionsService.onMultipleOptionChange(["customGlyphs","drawBoldTextInBrightColors","letterSpacing","lineHeight","fontFamily","fontSize","fontWeight","fontWeightBold","minimumContrastRatio","rescaleOverlappingGlyphs"],()=>{this.clear(),this.handleResize(o.cols,o.rows),this._fullRefresh()})),this._register(this._optionsService.onMultipleOptionChange(["cursorBlink","cursorStyle"],()=>this.refreshRows(o.buffer.y,o.buffer.y,!0))),this._register(a.onChangeColors(()=>this._fullRefresh())),this._registerIntersectionObserver(this._coreBrowserService.window,t),this._register(this._coreBrowserService.onWindowChange(h=>this._registerIntersectionObserver(h,t)))}get dimensions(){return this._renderer.value.dimensions}_registerIntersectionObserver(e,t){if("IntersectionObserver"in e){let i=new e.IntersectionObserver(r=>this._handleIntersectionChange(r[r.length-1]),{threshold:0});i.observe(t),this._observerDisposable.value=re(()=>i.disconnect())}}_handleIntersectionChange(e){this._isPaused=e.isIntersecting===void 0?e.intersectionRatio===0:!e.isIntersecting,!this._isPaused&&!this._charSizeService.hasValidSize&&this._charSizeService.measure(),!this._isPaused&&this._needsFullRefresh&&(this._pausedResizeTask.flush(),this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)}refreshRows(e,t,i=!1){if(this._isPaused){this._needsFullRefresh=!0;return}if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}let r=this._syncOutputHandler.flush();r&&(e=Math.min(e,r.start),t=Math.max(t,r.end)),i||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(e,t,this._rowCount)}_renderRows(e,t){if(this._renderer.value){if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}e=Math.min(e,this._rowCount-1),t=Math.min(t,this._rowCount-1),this._renderer.value.renderRows(e,t),this._needsSelectionRefresh&&(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),this._needsSelectionRefresh=!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:e,end:t}),this._onRender.fire({start:e,end:t}),this._isNextRenderRedrawOnly=!0}}resize(e,t){this._rowCount=t,this._fireOnCanvasResize()}_handleOptionsChanged(){this._renderer.value&&(this.refreshRows(0,this._rowCount-1),this._fireOnCanvasResize())}_fireOnCanvasResize(){this._renderer.value&&(this._renderer.value.dimensions.css.canvas.width===this._canvasWidth&&this._renderer.value.dimensions.css.canvas.height===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.value.dimensions))}hasRenderer(){return!!this._renderer.value}setRenderer(e){this._renderer.value=e,this._renderer.value&&(this._renderer.value.onRequestRedraw(t=>this.refreshRows(t.start,t.end,!0)),this._needsSelectionRefresh=!0,this._fullRefresh())}addRefreshCallback(e){return this._renderDebouncer.addRefreshCallback(e)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){var e,t;this._renderer.value&&((t=(e=this._renderer.value).clearTextureAtlas)==null||t.call(e),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(e,t){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set(()=>{var i;return(i=this._renderer.value)==null?void 0:i.handleResize(e,t)}):this._renderer.value.handleResize(e,t),this._fullRefresh())}handleCharSizeChanged(){var e;(e=this._renderer.value)==null||e.handleCharSizeChanged()}handleBlur(){var e;(e=this._renderer.value)==null||e.handleBlur()}handleFocus(){var e;(e=this._renderer.value)==null||e.handleFocus()}handleSelectionChanged(e,t,i){var r;this._selectionState.start=e,this._selectionState.end=t,this._selectionState.columnSelectMode=i,(r=this._renderer.value)==null||r.handleSelectionChanged(e,t,i)}handleCursorMove(){var e;(e=this._renderer.value)==null||e.handleCursorMove()}clear(){var e;(e=this._renderer.value)==null||e.clear()}};Aa=_e([L(2,Ge),L(3,Do),L(4,Qi),L(5,Hs),L(6,Xe),L(7,ei),L(8,Tr)],Aa);var HS=class{constructor(e,t,i){this._coreBrowserService=e,this._coreService=t,this._onTimeout=i,this._start=0,this._end=0,this._isBuffering=!1}bufferRows(e,t){this._isBuffering?(this._start=Math.min(this._start,e),this._end=Math.max(this._end,t)):(this._start=e,this._end=t,this._isBuffering=!0),this._timeout===void 0&&(this._timeout=this._coreBrowserService.window.setTimeout(()=>{this._timeout=void 0,this._coreService.decPrivateModes.synchronizedOutput=!1,this._onTimeout()},1e3))}flush(){if(this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0),!this._isBuffering)return;let e={start:this._start,end:this._end};return this._isBuffering=!1,e}dispose(){this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0)}};function WS(e,t,i,r){let s=i.buffer.x,n=i.buffer.y;if(!i.buffer.hasScrollback)return VS(s,n,e,t,i,r)+Po(n,t,i,r)+jS(s,n,e,t,i,r);let o;if(n===t)return o=s>e?"D":"C",Ts(Math.abs(s-e),Ms(o,r));o=n>t?"D":"C";let l=Math.abs(n-t),a=KS(n>t?e:s,i)+(l-1)*i.cols+1+US(n>t?s:e);return Ts(a,Ms(o,r))}function US(e,t){return e-1}function KS(e,t){return t.cols-e}function VS(e,t,i,r,s,n){return Po(t,r,s,n).length===0?"":Ts(np(e,t,e,t-qi(t,s),!1,s).length,Ms("D",n))}function Po(e,t,i,r){let s=e-qi(e,i),n=t-qi(t,i),o=Math.abs(s-n)-YS(e,t,i);return Ts(o,Ms(sp(e,t),r))}function jS(e,t,i,r,s,n){let o;Po(t,r,s,n).length>0?o=r-qi(r,s):o=t;let l=r,a=qS(e,t,i,r,s,n);return Ts(np(e,o,i,l,a==="C",s).length,Ms(a,n))}function YS(e,t,i){var o;let r=0,s=e-qi(e,i),n=t-qi(t,i);for(let l=0;l=0&&e0?o=r-qi(r,s):o=t,e=i&&ot?"A":"B"}function np(e,t,i,r,s,n){let o=e,l=t,a="";for(;(o!==i||l!==r)&&l>=0&&ln.cols-1?(a+=n.buffer.translateBufferLineToString(l,!1,e,o),o=0,e=0,l++):!s&&o<0&&(a+=n.buffer.translateBufferLineToString(l,!1,0,e+1),o=n.cols-1,e=o,l--);return a+n.buffer.translateBufferLineToString(l,!1,e,o)}function Ms(e,t){let i=t?"O":"[";return C.ESC+i+e}function Ts(e,t){e=Math.floor(e);let i="";for(let r=0;rthis._bufferService.cols?e%this._bufferService.cols===0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)-1]:[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[e,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[Math.max(e,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){let e=this.selectionStart,t=this.selectionEnd;return!e||!t?!1:e[1]>t[1]||e[1]===t[1]&&e[0]>t[0]}handleTrim(e){return this.selectionStart&&(this.selectionStart[1]-=e),this.selectionEnd&&(this.selectionEnd[1]-=e),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}};function Lu(e,t){if(e.start.y>e.end.y)throw new Error(`Buffer range end (${e.end.x}, ${e.end.y}) cannot be before start (${e.start.x}, ${e.start.y})`);return t*(e.end.y-e.start.y)+(e.end.x-e.start.x+1)}var cl=50,GS=15,QS=50,ZS=500,JS=" ",e0=new RegExp(JS,"g"),Ia=class extends W{constructor(e,t,i,r,s,n,o,l,a){super(),this._element=e,this._screenElement=t,this._linkifier=i,this._bufferService=r,this._coreService=s,this._mouseService=n,this._optionsService=o,this._renderService=l,this._coreBrowserService=a,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new yt,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this._register(new D),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this._register(new D),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this._register(new D),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this._register(new D),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=h=>this._handleMouseMove(h),this._mouseUpListener=h=>this._handleMouseUp(h),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(h=>this._handleTrim(h)),this._register(this._bufferService.buffers.onBufferActivate(h=>this._handleBufferActivate(h))),this.enable(),this._model=new XS(this._bufferService),this._activeSelectionMode=0,this._register(re(()=>{this._removeMouseDownListeners()})),this._register(this._bufferService.onResize(h=>{h.rowsChanged&&this.clearSelection()}))}reset(){this.clearSelection()}disable(){this.clearSelection(),this._enabled=!1}enable(){this._enabled=!0}get selectionStart(){return this._model.finalSelectionStart}get selectionEnd(){return this._model.finalSelectionEnd}get hasSelection(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;return!e||!t?!1:e[0]!==t[0]||e[1]!==t[1]}get selectionText(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;if(!e||!t)return"";let i=this._bufferService.buffer,r=[];if(this._activeSelectionMode===3){if(e[0]===t[0])return"";let s=e[0]s.replace(e0," ")).join(tp?`\r +`:` +`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh())),Qh&&e&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(e){let t=this._getMouseBufferCoords(e),i=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!i||!r||!t?!1:this._areCoordsInSelection(t,i,r)}isCellInSelection(e,t){let i=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!i||!r?!1:this._areCoordsInSelection([e,t],i,r)}_areCoordsInSelection(e,t,i){return e[1]>t[1]&&e[1]=t[0]&&e[0]=t[0]}_selectWordAtCursor(e,t){var s,n;let i=(n=(s=this._linkifier.currentLink)==null?void 0:s.link)==null?void 0:n.range;if(i)return this._model.selectionStart=[i.start.x-1,i.start.y-1],this._model.selectionStartLength=Lu(i,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let r=this._getMouseBufferCoords(e);return r?(this._selectWordAt(r,t),this._model.selectionEnd=void 0,!0):!1}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,t){this._model.clearSelection(),e=Math.max(e,0),t=Math.min(t,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,t],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){let t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t}_getMouseEventScrollAmount(e){let t=Gh(this._coreBrowserService.window,e,this._screenElement)[1],i=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=i?0:(t>i&&(t-=i),t=Math.min(Math.max(t,-cl),cl),t/=cl,t/Math.abs(t)+Math.round(t*(GS-1)))}shouldForceSelection(e){return oo?e.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:e.shiftKey}handleMouseDown(e){if(this._mouseDownTimeStamp=e.timeStamp,!(e.button===2&&this.hasSelection)&&e.button===0){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._handleIncrementalClick(e):e.detail===1?this._handleSingleClick(e):e.detail===2?this._handleDoubleClick(e):e.detail===3&&this._handleTripleClick(e),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener("mouseup",this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval(()=>this._dragScroll(),QS)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener("mouseup",this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))}_handleSingleClick(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(e)?3:0,this._model.selectionStart=this._getMouseBufferCoords(e),!this._model.selectionStart)return;this._model.selectionEnd=void 0;let t=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);t&&t.length!==this._model.selectionStart[0]&&t.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(e){this._selectWordAtCursor(e,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(e){let t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))}shouldColumnSelect(e){return e.altKey&&!(oo&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;let t=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!this._model.selectionEnd){this.refresh(!0);return}this._activeSelectionMode===2?this._model.selectionEnd[1]0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));let i=this._bufferService.buffer;if(this._model.selectionEnd[1]0?(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(e.ydisp+this._bufferService.rows,e.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=e.ydisp),this.refresh()}}_handleMouseUp(e){let t=e.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&tthis._handleTrim(t))}_convertViewportColToCharacterIndex(e,t){let i=t;for(let r=0;t>=r;r++){let s=e.loadCell(r,this._workCell).getChars().length;this._workCell.getWidth()===0?i--:s>1&&t!==r&&(i+=s-1)}return i}setSelection(e,t,i){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,t],this._model.selectionStartLength=i,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(e){this._isClickInSelection(e)||(this._selectWordAtCursor(e,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(e,t,i=!0,r=!0){if(e[0]>=this._bufferService.cols)return;let s=this._bufferService.buffer,n=s.lines.get(e[1]);if(!n)return;let o=s.translateBufferLineToString(e[1],!1),l=this._convertViewportColToCharacterIndex(n,e[0]),a=l,h=e[0]-l,u=0,c=0,d=0,g=0;if(o.charAt(l)===" "){for(;l>0&&o.charAt(l-1)===" ";)l--;for(;a1&&(g+=f-1,a+=f-1);k>0&&l>0&&!this._isCharWordSeparator(n.loadCell(k-1,this._workCell));){n.loadCell(k-1,this._workCell);let p=this._workCell.getChars().length;this._workCell.getWidth()===0?(u++,k--):p>1&&(d+=p-1,l-=p-1),l--,k--}for(;_1&&(g+=p-1,a+=p-1),a++,_++}}a++;let v=l+h-u+d,m=Math.min(this._bufferService.cols,a-l+u+c-d-g);if(!(!t&&o.slice(l,a).trim()==="")){if(i&&v===0&&n.getCodePoint(0)!==32){let k=s.lines.get(e[1]-1);if(k&&n.isWrapped&&k.getCodePoint(this._bufferService.cols-1)!==32){let _=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(_){let f=this._bufferService.cols-_.start;v-=f,m+=f}}}if(r&&v+m===this._bufferService.cols&&n.getCodePoint(this._bufferService.cols-1)!==32){let k=s.lines.get(e[1]+1);if(k!=null&&k.isWrapped&&k.getCodePoint(0)!==32){let _=this._getWordAt([0,e[1]+1],!1,!1,!0);_&&(m+=_.length)}}return{start:v,length:m}}}_selectWordAt(e,t){let i=this._getWordAt(e,t);if(i){for(;i.start<0;)i.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[i.start,e[1]],this._model.selectionStartLength=i.length}}_selectToWordAt(e){let t=this._getWordAt(e,!0);if(t){let i=e[1];for(;t.start<0;)t.start+=this._bufferService.cols,i--;if(!this._model.areSelectionValuesReversed())for(;t.start+t.length>this._bufferService.cols;)t.length-=this._bufferService.cols,i++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?t.start:t.start+t.length,i]}}_isCharWordSeparator(e){return e.getWidth()===0?!1:this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars())>=0}_selectLineAt(e){let t=this._bufferService.buffer.getWrappedRangeForLine(e),i={start:{x:0,y:t.first},end:{x:this._bufferService.cols-1,y:t.last}};this._model.selectionStart=[0,t.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=Lu(i,this._bufferService.cols)}};Ia=_e([L(3,Xe),L(4,Qi),L(5,Uh),L(6,Ge),L(7,ti),L(8,ei)],Ia);var Bu=class{constructor(){this._data={}}set(e,t,i){this._data[e]||(this._data[e]={}),this._data[e][t]=i}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}},Mu=class{constructor(){this._color=new Bu,this._css=new Bu}setCss(e,t,i){this._css.set(e,t,i)}getCss(e,t){return this._css.get(e,t)}setColor(e,t,i){this._color.set(e,t,i)}getColor(e,t){return this._color.get(e,t)}clear(){this._color.clear(),this._css.clear()}},we=Object.freeze((()=>{let e=[ne.toColor("#2e3436"),ne.toColor("#cc0000"),ne.toColor("#4e9a06"),ne.toColor("#c4a000"),ne.toColor("#3465a4"),ne.toColor("#75507b"),ne.toColor("#06989a"),ne.toColor("#d3d7cf"),ne.toColor("#555753"),ne.toColor("#ef2929"),ne.toColor("#8ae234"),ne.toColor("#fce94f"),ne.toColor("#729fcf"),ne.toColor("#ad7fa8"),ne.toColor("#34e2e2"),ne.toColor("#eeeeec")],t=[0,95,135,175,215,255];for(let i=0;i<216;i++){let r=t[i/36%6|0],s=t[i/6%6|0],n=t[i%6];e.push({css:Se.toCss(r,s,n),rgba:Se.toRgba(r,s,n)})}for(let i=0;i<24;i++){let r=8+i*10;e.push({css:Se.toCss(r,r,r),rgba:Se.toRgba(r,r,r)})}return e})()),Ti=ne.toColor("#ffffff"),ts=ne.toColor("#000000"),Tu=ne.toColor("#ffffff"),Nu=ts,jr={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117},t0=Ti,za=class extends W{constructor(e){super(),this._optionsService=e,this._contrastCache=new Mu,this._halfContrastCache=new Mu,this._onChangeColors=this._register(new D),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:Ti,background:ts,cursor:Tu,cursorAccent:Nu,selectionForeground:void 0,selectionBackgroundTransparent:jr,selectionBackgroundOpaque:ee.blend(ts,jr),selectionInactiveBackgroundTransparent:jr,selectionInactiveBackgroundOpaque:ee.blend(ts,jr),scrollbarSliderBackground:ee.opacity(Ti,.2),scrollbarSliderHoverBackground:ee.opacity(Ti,.4),scrollbarSliderActiveBackground:ee.opacity(Ti,.5),overviewRulerBorder:Ti,ansi:we.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this._register(this._optionsService.onSpecificOptionChange("minimumContrastRatio",()=>this._contrastCache.clear())),this._register(this._optionsService.onSpecificOptionChange("theme",()=>this._setTheme(this._optionsService.rawOptions.theme)))}get colors(){return this._colors}_setTheme(e={}){let t=this._colors;if(t.foreground=G(e.foreground,Ti),t.background=G(e.background,ts),t.cursor=ee.blend(t.background,G(e.cursor,Tu)),t.cursorAccent=ee.blend(t.background,G(e.cursorAccent,Nu)),t.selectionBackgroundTransparent=G(e.selectionBackground,jr),t.selectionBackgroundOpaque=ee.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=G(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=ee.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?G(e.selectionForeground,Du):void 0,t.selectionForeground===Du&&(t.selectionForeground=void 0),ee.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=ee.opacity(t.selectionBackgroundTransparent,.3)),ee.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=ee.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=G(e.scrollbarSliderBackground,ee.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=G(e.scrollbarSliderHoverBackground,ee.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=G(e.scrollbarSliderActiveBackground,ee.opacity(t.foreground,.5)),t.overviewRulerBorder=G(e.overviewRulerBorder,t0),t.ansi=we.slice(),t.ansi[0]=G(e.black,we[0]),t.ansi[1]=G(e.red,we[1]),t.ansi[2]=G(e.green,we[2]),t.ansi[3]=G(e.yellow,we[3]),t.ansi[4]=G(e.blue,we[4]),t.ansi[5]=G(e.magenta,we[5]),t.ansi[6]=G(e.cyan,we[6]),t.ansi[7]=G(e.white,we[7]),t.ansi[8]=G(e.brightBlack,we[8]),t.ansi[9]=G(e.brightRed,we[9]),t.ansi[10]=G(e.brightGreen,we[10]),t.ansi[11]=G(e.brightYellow,we[11]),t.ansi[12]=G(e.brightBlue,we[12]),t.ansi[13]=G(e.brightMagenta,we[13]),t.ansi[14]=G(e.brightCyan,we[14]),t.ansi[15]=G(e.brightWhite,we[15]),e.extendedAnsi){let i=Math.min(t.ansi.length-16,e.extendedAnsi.length);for(let r=0;rn.index-o.index),r=[];for(let n of i){let o=this._services.get(n.id);if(!o)throw new Error(`[createInstance] ${e.name} depends on UNKNOWN service ${n.id._id}.`);r.push(o)}let s=i.length>0?i[0].index:t.length;if(t.length!==s)throw new Error(`[createInstance] First service dependency of ${e.name} at position ${s+1} conflicts with ${t.length} static arguments`);return new e(...t,...r)}},s0={trace:0,debug:1,info:2,warn:3,error:4,off:5},n0="xterm.js: ",Fa=class extends W{constructor(e){super(),this._optionsService=e,this._logLevel=5,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange("logLevel",()=>this._updateLogLevel()))}get logLevel(){return this._logLevel}_updateLogLevel(){this._logLevel=s0[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e){for(let t=0;tthis._length)for(let t=this._length;t=e;r--)this._array[this._getCyclicIndex(r+i.length)]=this._array[this._getCyclicIndex(r)];for(let r=0;rthis._maxLength){let r=this._length+i.length-this._maxLength;this._startIndex+=r,this._length=this._maxLength,this.onTrimEmitter.fire(r)}else this._length+=i.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,t,i){if(!(t<=0)){if(e<0||e>=this._length)throw new Error("start argument out of range");if(e+i<0)throw new Error("Cannot shift elements in list beyond index 0");if(i>0){for(let s=t-1;s>=0;s--)this.set(e+s+i,this.get(e+s));let r=e+t+i-this._length;if(r>0)for(this._length+=r;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let r=0;r>22,i&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):r]}set(t,i){this._data[t*H+1]=i[0],i[1].length>1?(this._combined[t]=i[1],this._data[t*H+0]=t|2097152|i[2]<<22):this._data[t*H+0]=i[1].charCodeAt(0)|i[2]<<22}getWidth(t){return this._data[t*H+0]>>22}hasWidth(t){return this._data[t*H+0]&12582912}getFg(t){return this._data[t*H+1]}getBg(t){return this._data[t*H+2]}hasContent(t){return this._data[t*H+0]&4194303}getCodePoint(t){let i=this._data[t*H+0];return i&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):i&2097151}isCombined(t){return this._data[t*H+0]&2097152}getString(t){let i=this._data[t*H+0];return i&2097152?this._combined[t]:i&2097151?ci(i&2097151):""}isProtected(t){return this._data[t*H+2]&536870912}loadCell(t,i){return _n=t*H,i.content=this._data[_n+0],i.fg=this._data[_n+1],i.bg=this._data[_n+2],i.content&2097152&&(i.combinedData=this._combined[t]),i.bg&268435456&&(i.extended=this._extendedAttrs[t]),i}setCell(t,i){i.content&2097152&&(this._combined[t]=i.combinedData),i.bg&268435456&&(this._extendedAttrs[t]=i.extended),this._data[t*H+0]=i.content,this._data[t*H+1]=i.fg,this._data[t*H+2]=i.bg}setCellFromCodepoint(t,i,r,s){s.bg&268435456&&(this._extendedAttrs[t]=s.extended),this._data[t*H+0]=i|r<<22,this._data[t*H+1]=s.fg,this._data[t*H+2]=s.bg}addCodepointToCell(t,i,r){let s=this._data[t*H+0];s&2097152?this._combined[t]+=ci(i):s&2097151?(this._combined[t]=ci(s&2097151)+ci(i),s&=-2097152,s|=2097152):s=i|1<<22,r&&(s&=-12582913,s|=r<<22),this._data[t*H+0]=s}insertCells(t,i,r){if(t%=this.length,t&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t-1,0,1,r),i=0;--n)this.setCell(t+i+n,this.loadCell(t+n,s));for(let n=0;nthis.length){if(this._data.buffer.byteLength>=r*4)this._data=new Uint32Array(this._data.buffer,0,r);else{let s=new Uint32Array(r);s.set(this._data),this._data=s}for(let s=this.length;s=t&&delete this._combined[l]}let n=Object.keys(this._extendedAttrs);for(let o=0;o=t&&delete this._extendedAttrs[l]}}return this.length=t,r*4*ul=0;--t)if(this._data[t*H+0]&4194303)return t+(this._data[t*H+0]>>22);return 0}getNoBgTrimmedLength(){for(let t=this.length-1;t>=0;--t)if(this._data[t*H+0]&4194303||this._data[t*H+2]&50331648)return t+(this._data[t*H+0]>>22);return 0}copyCellsFrom(t,i,r,s,n){let o=t._data;if(n)for(let a=s-1;a>=0;a--){for(let h=0;h=i&&(this._combined[h-i+r]=t._combined[h])}}translateToString(t,i,r,s){i=i??0,r=r??this.length,t&&(r=Math.min(r,this.getTrimmedLength())),s&&(s.length=0);let n="";for(;i>22||1}return s&&s.push(i),n}};function o0(e,t,i,r,s,n){let o=[];for(let l=0;l=l&&r0&&(k>c||u[k].getTrimmedLength()===0);k--)m++;m>0&&(o.push(l+u.length-m),o.push(m)),l+=u.length-1}return o}function l0(e,t){let i=[],r=0,s=t[r],n=0;for(let o=0;oNs(e,h,t)).reduce((a,h)=>a+h),n=0,o=0,l=0;for(;la&&(n-=a,o++);let h=e[o].getWidth(n-1)===2;h&&n--;let u=h?i-1:i;r.push(u),l+=u}return r}function Ns(e,t,i){if(t===e.length-1)return e[t].getTrimmedLength();let r=!e[t].hasContent(i-1)&&e[t].getWidth(i-1)===1,s=e[t+1].getWidth(0)===2;return r&&s?i-1:i}var lp=class ap{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=ap._nextId++,this._onDispose=this.register(new D),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),Yi(this._disposables),this._disposables.length=0)}register(t){return this._disposables.push(t),t}};lp._nextId=1;var c0=lp,be={},Ni=be.B;be[0]={"`":"◆",a:"▒",b:"␉",c:"␌",d:"␍",e:"␊",f:"°",g:"±",h:"␤",i:"␋",j:"┘",k:"┐",l:"┌",m:"└",n:"┼",o:"⎺",p:"⎻",q:"─",r:"⎼",s:"⎽",t:"├",u:"┤",v:"┴",w:"┬",x:"│",y:"≤",z:"≥","{":"π","|":"≠","}":"£","~":"·"};be.A={"#":"£"};be.B=void 0;be[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"};be.C=be[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};be.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"};be.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"};be.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"};be.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"};be.E=be[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"};be.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"};be.H=be[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};be["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"};var Au=4294967295,Iu=class{constructor(e,t,i){this._hasScrollback=e,this._optionsService=t,this._bufferService=i,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=me.clone(),this.savedCharset=Ni,this.markers=[],this._nullCell=yt.fromCharData([0,b_,1,0]),this._whitespaceCell=yt.fromCharData([0,pi,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new lo,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new Ou(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(e){return e?(this._nullCell.fg=e.fg,this._nullCell.bg=e.bg,this._nullCell.extended=e.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new ro),this._nullCell}getWhitespaceCell(e){return e?(this._whitespaceCell.fg=e.fg,this._whitespaceCell.bg=e.bg,this._whitespaceCell.extended=e.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new ro),this._whitespaceCell}getBlankLine(e,t){return new is(this._bufferService.cols,this.getNullCell(e),t)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let e=this.ybase+this.y-this.ydisp;return e>=0&&eAu?Au:t}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=me);let t=this._rows;for(;t--;)this.lines.push(this.getBlankLine(e))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new Ou(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let i=this.getNullCell(me),r=0,s=this._getCorrectBufferLength(t);if(s>this.lines.maxLength&&(this.lines.maxLength=s),this.lines.length>0){if(this._cols0&&this.lines.length<=this.ybase+this.y+n+1?(this.ybase--,n++,this.ydisp>0&&this.ydisp--):this.lines.push(new is(e,i)));else for(let o=this._rows;o>t;o--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(s0&&(this.lines.trimStart(o),this.ybase=Math.max(this.ybase-o,0),this.ydisp=Math.max(this.ydisp-o,0),this.savedY=Math.max(this.savedY-o,0)),this.lines.maxLength=s}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),n&&(this.y+=n),this.savedX=Math.min(this.savedX,e-1),this.scrollTop=0}if(this.scrollBottom=t-1,this._isReflowEnabled&&(this._reflow(e,t),this._cols>e))for(let n=0;n.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let e=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,e=!1);let t=0;for(;this._memoryCleanupPosition100)return!0;return e}get _isReflowEnabled(){let e=this._optionsService.rawOptions.windowsPty;return e&&e.buildNumber?this._hasScrollback&&e.backend==="conpty"&&e.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(e,t){this._cols!==e&&(e>this._cols?this._reflowLarger(e,t):this._reflowSmaller(e,t))}_reflowLarger(e,t){let i=this._optionsService.rawOptions.reflowCursorLine,r=o0(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(me),i);if(r.length>0){let s=l0(this.lines,r);a0(this.lines,s.layout),this._reflowLargerAdjustViewport(e,t,s.countRemoved)}}_reflowLargerAdjustViewport(e,t,i){let r=this.getNullCell(me),s=i;for(;s-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length=0;o--){let l=this.lines.get(o);if(!l||!l.isWrapped&&l.getTrimmedLength()<=e)continue;let a=[l];for(;l.isWrapped&&o>0;)l=this.lines.get(--o),a.unshift(l);if(!i){let p=this.ybase+this.y;if(p>=o&&p0&&(s.push({start:o+a.length+n,newLines:g}),n+=g.length),a.push(...g);let v=u.length-1,m=u[v];m===0&&(v--,m=u[v]);let k=a.length-c-1,_=h;for(;k>=0;){let p=Math.min(_,m);if(a[v]===void 0)break;if(a[v].copyCellsFrom(a[k],_-p,m-p,p,!0),m-=p,m===0&&(v--,m=u[v]),_-=p,_===0){k--;let S=Math.max(k,0);_=Ns(a,S,this._cols)}}for(let p=0;p0;)this.ybase===0?this.y0){let o=[],l=[];for(let m=0;m=0;m--)if(c&&c.start>h+d){for(let k=c.newLines.length-1;k>=0;k--)this.lines.set(m--,c.newLines[k]);m++,o.push({index:h+1,amount:c.newLines.length}),d+=c.newLines.length,c=s[++u]}else this.lines.set(m,l[h--]);let g=0;for(let m=o.length-1;m>=0;m--)o[m].index+=g,this.lines.onInsertEmitter.fire(o[m]),g+=o[m].amount;let v=Math.max(0,a+n-this.lines.maxLength);v>0&&this.lines.onTrimEmitter.fire(v)}}translateBufferLineToString(e,t,i=0,r){let s=this.lines.get(e);return s?s.translateToString(t,i,r):""}getWrappedRangeForLine(e){let t=e,i=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;i+10;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(e==null&&(e=this.x);!this.tabs[++e]&&e=this._cols?this._cols-1:e<0?0:e}clearMarkers(e){this._isClearing=!0;for(let t=0;t{t.line-=i,t.line<0&&t.dispose()})),t.register(this.lines.onInsert(i=>{t.line>=i.index&&(t.line+=i.amount)})),t.register(this.lines.onDelete(i=>{t.line>=i.index&&t.linei.index&&(t.line-=i.amount)})),t.register(t.onDispose(()=>this._removeMarker(t))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}},u0=class extends W{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this._register(new D),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this._register(this._optionsService.onSpecificOptionChange("scrollback",()=>this.resize(this._bufferService.cols,this._bufferService.rows))),this._register(this._optionsService.onSpecificOptionChange("tabStopWidth",()=>this.setupTabStops()))}reset(){this._normal=new Iu(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new Iu(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(e){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(e,t){this._normal.resize(e,t),this._alt.resize(e,t),this.setupTabStops(e)}setupTabStops(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)}},hp=2,cp=1,$a=class extends W{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new D),this.onResize=this._onResize.event,this._onScroll=this._register(new D),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,hp),this.rows=Math.max(e.rawOptions.rows||0,cp),this.buffers=this._register(new u0(e,this)),this._register(this.buffers.onBufferActivate(t=>{this._onScroll.fire(t.activeBuffer.ydisp)}))}get buffer(){return this.buffers.active}resize(e,t){let i=this.cols!==e,r=this.rows!==t;this.cols=e,this.rows=t,this.buffers.resize(e,t),this._onResize.fire({cols:e,rows:t,colsChanged:i,rowsChanged:r})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,t=!1){let i=this.buffer,r;r=this._cachedBlankLine,(!r||r.length!==this.cols||r.getFg(0)!==e.fg||r.getBg(0)!==e.bg)&&(r=i.getBlankLine(e,t),this._cachedBlankLine=r),r.isWrapped=t;let s=i.ybase+i.scrollTop,n=i.ybase+i.scrollBottom;if(i.scrollTop===0){let o=i.lines.isFull;n===i.lines.length-1?o?i.lines.recycle().copyFrom(r):i.lines.push(r.clone()):i.lines.splice(n+1,0,r.clone()),o?this.isUserScrolling&&(i.ydisp=Math.max(i.ydisp-1,0)):(i.ybase++,this.isUserScrolling||i.ydisp++)}else{let o=n-s+1;i.lines.shiftElements(s+1,o-1,-1),i.lines.set(n,r.clone())}this.isUserScrolling||(i.ydisp=i.ybase),this._onScroll.fire(i.ydisp)}scrollLines(e,t){let i=this.buffer;if(e<0){if(i.ydisp===0)return;this.isUserScrolling=!0}else e+i.ydisp>=i.ybase&&(this.isUserScrolling=!1);let r=i.ydisp;i.ydisp=Math.max(Math.min(i.ydisp+e,i.ybase),0),r!==i.ydisp&&(t||this._onScroll.fire(i.ydisp))}};$a=_e([L(0,Ge)],$a);var er={cols:80,rows:24,cursorBlink:!1,cursorStyle:"block",cursorWidth:1,cursorInactiveStyle:"outline",customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:"alt",fastScrollSensitivity:5,fontFamily:"monospace",fontSize:15,fontWeight:"normal",fontWeightBold:"bold",ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:"info",logger:null,scrollback:1e3,scrollOnEraseInDisplay:!1,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},reflowCursorLine:!1,rescaleOverlappingGlyphs:!1,rightClickSelectsWord:oo,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRuler:{}},d0=["normal","bold","100","200","300","400","500","600","700","800","900"],f0=class extends W{constructor(e){super(),this._onOptionChange=this._register(new D),this.onOptionChange=this._onOptionChange.event;let t={...er};for(let i in e)if(i in t)try{let r=e[i];t[i]=this._sanitizeAndValidateOption(i,r)}catch(r){console.error(r)}this.rawOptions=t,this.options={...t},this._setupOptions(),this._register(re(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(e,t){return this.onOptionChange(i=>{i===e&&t(this.rawOptions[e])})}onMultipleOptionChange(e,t){return this.onOptionChange(i=>{e.indexOf(i)!==-1&&t()})}_setupOptions(){let e=i=>{if(!(i in er))throw new Error(`No option with key "${i}"`);return this.rawOptions[i]},t=(i,r)=>{if(!(i in er))throw new Error(`No option with key "${i}"`);r=this._sanitizeAndValidateOption(i,r),this.rawOptions[i]!==r&&(this.rawOptions[i]=r,this._onOptionChange.fire(i))};for(let i in this.rawOptions){let r={get:e.bind(this,i),set:t.bind(this,i)};Object.defineProperty(this.options,i,r)}}_sanitizeAndValidateOption(e,t){switch(e){case"cursorStyle":if(t||(t=er[e]),!_0(t))throw new Error(`"${t}" is not a valid value for ${e}`);break;case"wordSeparator":t||(t=er[e]);break;case"fontWeight":case"fontWeightBold":if(typeof t=="number"&&1<=t&&t<=1e3)break;t=d0.includes(t)?t:er[e];break;case"cursorWidth":t=Math.floor(t);case"lineHeight":case"tabStopWidth":if(t<1)throw new Error(`${e} cannot be less than 1, value: ${t}`);break;case"minimumContrastRatio":t=Math.max(1,Math.min(21,Math.round(t*10)/10));break;case"scrollback":if(t=Math.min(t,4294967295),t<0)throw new Error(`${e} cannot be less than 0, value: ${t}`);break;case"fastScrollSensitivity":case"scrollSensitivity":if(t<=0)throw new Error(`${e} cannot be less than or equal to 0, value: ${t}`);break;case"rows":case"cols":if(!t&&t!==0)throw new Error(`${e} must be numeric, value: ${t}`);break;case"windowsPty":t=t??{};break}return t}};function _0(e){return e==="block"||e==="underline"||e==="bar"}function rs(e,t=5){if(typeof e!="object")return e;let i=Array.isArray(e)?[]:{};for(let r in e)i[r]=t<=1?e[r]:e[r]&&rs(e[r],t-1);return i}var zu=Object.freeze({insertMode:!1}),Fu=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),Ha=class extends W{constructor(e,t,i){super(),this._bufferService=e,this._logService=t,this._optionsService=i,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new D),this.onData=this._onData.event,this._onUserInput=this._register(new D),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new D),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new D),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=rs(zu),this.decPrivateModes=rs(Fu)}reset(){this.modes=rs(zu),this.decPrivateModes=rs(Fu)}triggerDataEvent(e,t=!1){if(this._optionsService.rawOptions.disableStdin)return;let i=this._bufferService.buffer;t&&this._optionsService.rawOptions.scrollOnUserInput&&i.ybase!==i.ydisp&&this._onRequestScrollToBottom.fire(),t&&this._onUserInput.fire(),this._logService.debug(`sending data "${e}"`),this._logService.trace("sending data (codes)",()=>e.split("").map(r=>r.charCodeAt(0))),this._onData.fire(e)}triggerBinaryEvent(e){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${e}"`),this._logService.trace("sending binary (codes)",()=>e.split("").map(t=>t.charCodeAt(0))),this._onBinary.fire(e))}};Ha=_e([L(0,Xe),L(1,L_),L(2,Ge)],Ha);var $u={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:e=>e.button===4||e.action!==1?!1:(e.ctrl=!1,e.alt=!1,e.shift=!1,!0)},VT200:{events:19,restrict:e=>e.action!==32},DRAG:{events:23,restrict:e=>!(e.action===32&&e.button===3)},ANY:{events:31,restrict:e=>!0}};function dl(e,t){let i=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return e.button===4?(i|=64,i|=e.action):(i|=e.button&3,e.button&4&&(i|=64),e.button&8&&(i|=128),e.action===32?i|=32:e.action===0&&!t&&(i|=3)),i}var fl=String.fromCharCode,Hu={DEFAULT:e=>{let t=[dl(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?"":`\x1B[M${fl(t[0])}${fl(t[1])}${fl(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${dl(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${dl(e,!0)};${e.x};${e.y}${t}`}},Wa=class extends W{constructor(e,t,i){super(),this._bufferService=e,this._coreService=t,this._optionsService=i,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new D),this.onProtocolChange=this._onProtocolChange.event;for(let r of Object.keys($u))this.addProtocol(r,$u[r]);for(let r of Object.keys(Hu))this.addEncoding(r,Hu[r]);this.reset()}addProtocol(e,t){this._protocols[e]=t}addEncoding(e,t){this._encodings[e]=t}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(e){if(!this._protocols[e])throw new Error(`unknown protocol "${e}"`);this._activeProtocol=e,this._onProtocolChange.fire(this._protocols[e].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(e){if(!this._encodings[e])throw new Error(`unknown encoding "${e}"`);this._activeEncoding=e}reset(){this.activeProtocol="NONE",this.activeEncoding="DEFAULT",this._lastEvent=null,this._wheelPartialScroll=0}consumeWheelEvent(e,t,i){if(e.deltaY===0||e.shiftKey||t===void 0||i===void 0)return 0;let r=t/i,s=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(s/=r+0,Math.abs(e.deltaY)<50&&(s*=.3),this._wheelPartialScroll+=s,s=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(s*=this._bufferService.rows),s}_applyScrollModifier(e,t){return t.altKey||t.ctrlKey||t.shiftKey?e*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:e*this._optionsService.rawOptions.scrollSensitivity}triggerMouseEvent(e){if(e.col<0||e.col>=this._bufferService.cols||e.row<0||e.row>=this._bufferService.rows||e.button===4&&e.action===32||e.button===3&&e.action!==32||e.button!==4&&(e.action===2||e.action===3)||(e.col++,e.row++,e.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,e,this._activeEncoding==="SGR_PIXELS"))||!this._protocols[this._activeProtocol].restrict(e))return!1;let t=this._encodings[this._activeEncoding](e);return t&&(this._activeEncoding==="DEFAULT"?this._coreService.triggerBinaryEvent(t):this._coreService.triggerDataEvent(t,!0)),this._lastEvent=e,!0}explainEvents(e){return{down:!!(e&1),up:!!(e&2),drag:!!(e&4),move:!!(e&8),wheel:!!(e&16)}}_equalEvents(e,t,i){if(i){if(e.x!==t.x||e.y!==t.y)return!1}else if(e.col!==t.col||e.row!==t.row)return!1;return!(e.button!==t.button||e.action!==t.action||e.ctrl!==t.ctrl||e.alt!==t.alt||e.shift!==t.shift)}};Wa=_e([L(0,Xe),L(1,Qi),L(2,Ge)],Wa);var _l=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],p0=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]],Ce;function g0(e,t){let i=0,r=t.length-1,s;if(et[r][1])return!1;for(;r>=i;)if(s=i+r>>1,e>t[s][1])i=s+1;else if(e=131072&&e<=196605||e>=196608&&e<=262141?2:1}charProperties(e,t){let i=this.wcwidth(e),r=i===0&&t!==0;if(r){let s=zi.extractWidth(t);s===0?r=!1:s>i&&(i=s)}return zi.createPropertyValue(0,i,r)}},zi=class Mn{constructor(){this._providers=Object.create(null),this._active="",this._onChange=new D,this.onChange=this._onChange.event;let t=new v0;this.register(t),this._active=t.version,this._activeProvider=t}static extractShouldJoin(t){return(t&1)!==0}static extractWidth(t){return t>>1&3}static extractCharKind(t){return t>>3}static createPropertyValue(t,i,r=!1){return(t&16777215)<<3|(i&3)<<1|(r?1:0)}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(t){if(!this._providers[t])throw new Error(`unknown Unicode version "${t}"`);this._active=t,this._activeProvider=this._providers[t],this._onChange.fire(t)}register(t){this._providers[t.version]=t}wcwidth(t){return this._activeProvider.wcwidth(t)}getStringCellWidth(t){let i=0,r=0,s=t.length;for(let n=0;n=s)return i+this.wcwidth(o);let h=t.charCodeAt(n);56320<=h&&h<=57343?o=(o-55296)*1024+h-56320+65536:i+=this.wcwidth(h)}let l=this.charProperties(o,r),a=Mn.extractWidth(l);Mn.extractShouldJoin(l)&&(a-=Mn.extractWidth(r)),i+=a,r=l}return i}charProperties(t,i){return this._activeProvider.charProperties(t,i)}},m0=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(e){this.glevel=e,this.charset=this._charsets[e]}setgCharset(e,t){this._charsets[e]=t,this.glevel===e&&(this.charset=t)}};function Wu(e){var r;let t=(r=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1))==null?void 0:r.get(e.cols-1),i=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);i&&t&&(i.isWrapped=t[3]!==0&&t[3]!==32)}var Yr=2147483647,S0=256,up=class Ua{constructor(t=32,i=32){if(this.maxLength=t,this.maxSubParamsLength=i,i>S0)throw new Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(t),this.length=0,this._subParams=new Int32Array(i),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(t),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}static fromArray(t){let i=new Ua;if(!t.length)return i;for(let r=Array.isArray(t[0])?1:0;r>8,s=this._subParamsIdx[i]&255;s-r>0&&t.push(Array.prototype.slice.call(this._subParams,r,s))}return t}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(t){if(this._digitIsSub=!1,this.length>=this.maxLength){this._rejectDigits=!0;return}if(t<-1)throw new Error("values lesser than -1 are not allowed");this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=t>Yr?Yr:t}addSubParam(t){if(this._digitIsSub=!0,!!this.length){if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength){this._rejectSubDigits=!0;return}if(t<-1)throw new Error("values lesser than -1 are not allowed");this._subParams[this._subParamsLength++]=t>Yr?Yr:t,this._subParamsIdx[this.length-1]++}}hasSubParams(t){return(this._subParamsIdx[t]&255)-(this._subParamsIdx[t]>>8)>0}getSubParams(t){let i=this._subParamsIdx[t]>>8,r=this._subParamsIdx[t]&255;return r-i>0?this._subParams.subarray(i,r):null}getSubParamsAll(){let t={};for(let i=0;i>8,s=this._subParamsIdx[i]&255;s-r>0&&(t[i]=this._subParams.slice(r,s))}return t}addDigit(t){let i;if(this._rejectDigits||!(i=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let r=this._digitIsSub?this._subParams:this.params,s=r[i-1];r[i-1]=~s?Math.min(s*10+t,Yr):t}},qr=[],y0=class{constructor(){this._state=0,this._active=qr,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let i=this._handlers[e];return i.push(t),{dispose:()=>{let r=i.indexOf(t);r!==-1&&i.splice(r,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=qr}reset(){if(this._state===2)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].end(!1);this._stack.paused=!1,this._active=qr,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||qr,!this._active.length)this._handlerFb(this._id,"START");else for(let e=this._active.length-1;e>=0;e--)this._active[e].start()}_put(e,t,i){if(!this._active.length)this._handlerFb(this._id,"PUT",Eo(e,t,i));else for(let r=this._active.length-1;r>=0;r--)this._active[r].put(e,t,i)}start(){this.reset(),this._state=1}put(e,t,i){if(this._state!==3){if(this._state===1)for(;t0&&this._put(e,t,i)}}end(e,t=!0){if(this._state!==0){if(this._state!==3)if(this._state===1&&this._start(),!this._active.length)this._handlerFb(this._id,"END",e);else{let i=!1,r=this._active.length-1,s=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,i=t,s=this._stack.fallThrough,this._stack.paused=!1),!s&&i===!1){for(;r>=0&&(i=this._active[r].end(e),i!==!0);r--)if(i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,i;r--}for(;r>=0;r--)if(i=this._active[r].end(!1),i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,i}this._active=qr,this._id=-1,this._state=0}}},nt=class{constructor(e){this._handler=e,this._data="",this._hitLimit=!1}start(){this._data="",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=Eo(e,t,i),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}end(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data),t instanceof Promise))return t.then(i=>(this._data="",this._hitLimit=!1,i));return this._data="",this._hitLimit=!1,t}},Xr=[],w0=class{constructor(){this._handlers=Object.create(null),this._active=Xr,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=Xr}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let i=this._handlers[e];return i.push(t),{dispose:()=>{let r=i.indexOf(t);r!==-1&&i.splice(r,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}reset(){if(this._active.length)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].unhook(!1);this._stack.paused=!1,this._active=Xr,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||Xr,!this._active.length)this._handlerFb(this._ident,"HOOK",t);else for(let i=this._active.length-1;i>=0;i--)this._active[i].hook(t)}put(e,t,i){if(!this._active.length)this._handlerFb(this._ident,"PUT",Eo(e,t,i));else for(let r=this._active.length-1;r>=0;r--)this._active[r].put(e,t,i)}unhook(e,t=!0){if(!this._active.length)this._handlerFb(this._ident,"UNHOOK",e);else{let i=!1,r=this._active.length-1,s=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,i=t,s=this._stack.fallThrough,this._stack.paused=!1),!s&&i===!1){for(;r>=0&&(i=this._active[r].unhook(e),i!==!0);r--)if(i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,i;r--}for(;r>=0;r--)if(i=this._active[r].unhook(!1),i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,i}this._active=Xr,this._ident=0}},ss=new up;ss.addParam(0);var Uu=class{constructor(e){this._handler=e,this._data="",this._params=ss,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():ss,this._data="",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=Eo(e,t,i),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}unhook(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data,this._params),t instanceof Promise))return t.then(i=>(this._params=ss,this._data="",this._hitLimit=!1,i));return this._params=ss,this._data="",this._hitLimit=!1,t}},C0=class{constructor(e){this.table=new Uint8Array(e)}setDefault(e,t){this.table.fill(e<<4|t)}add(e,t,i,r){this.table[t<<8|e]=i<<4|r}addMany(e,t,i,r){for(let s=0;sa),i=(l,a)=>t.slice(l,a),r=i(32,127),s=i(0,24);s.push(25),s.push.apply(s,i(28,32));let n=i(0,14),o;e.setDefault(1,0),e.addMany(r,0,2,0);for(o in n)e.addMany([24,26,153,154],o,3,0),e.addMany(i(128,144),o,3,0),e.addMany(i(144,152),o,3,0),e.add(156,o,0,0),e.add(27,o,11,1),e.add(157,o,4,8),e.addMany([152,158,159],o,0,7),e.add(155,o,11,3),e.add(144,o,11,9);return e.addMany(s,0,3,0),e.addMany(s,1,3,1),e.add(127,1,0,1),e.addMany(s,8,0,8),e.addMany(s,3,3,3),e.add(127,3,0,3),e.addMany(s,4,3,4),e.add(127,4,0,4),e.addMany(s,6,3,6),e.addMany(s,5,3,5),e.add(127,5,0,5),e.addMany(s,2,3,2),e.add(127,2,0,2),e.add(93,1,4,8),e.addMany(r,8,5,8),e.add(127,8,5,8),e.addMany([156,27,24,26,7],8,6,0),e.addMany(i(28,32),8,0,8),e.addMany([88,94,95],1,0,7),e.addMany(r,7,0,7),e.addMany(s,7,0,7),e.add(156,7,0,0),e.add(127,7,0,7),e.add(91,1,11,3),e.addMany(i(64,127),3,7,0),e.addMany(i(48,60),3,8,4),e.addMany([60,61,62,63],3,9,4),e.addMany(i(48,60),4,8,4),e.addMany(i(64,127),4,7,0),e.addMany([60,61,62,63],4,0,6),e.addMany(i(32,64),6,0,6),e.add(127,6,0,6),e.addMany(i(64,127),6,0,0),e.addMany(i(32,48),3,9,5),e.addMany(i(32,48),5,9,5),e.addMany(i(48,64),5,0,6),e.addMany(i(64,127),5,7,0),e.addMany(i(32,48),4,9,5),e.addMany(i(32,48),1,9,2),e.addMany(i(32,48),2,9,2),e.addMany(i(48,127),2,10,0),e.addMany(i(48,80),1,10,0),e.addMany(i(81,88),1,10,0),e.addMany([89,90,92],1,10,0),e.addMany(i(96,127),1,10,0),e.add(80,1,11,9),e.addMany(s,9,0,9),e.add(127,9,0,9),e.addMany(i(28,32),9,0,9),e.addMany(i(32,48),9,9,12),e.addMany(i(48,60),9,8,10),e.addMany([60,61,62,63],9,9,10),e.addMany(s,11,0,11),e.addMany(i(32,128),11,0,11),e.addMany(i(28,32),11,0,11),e.addMany(s,10,0,10),e.add(127,10,0,10),e.addMany(i(28,32),10,0,10),e.addMany(i(48,60),10,8,10),e.addMany([60,61,62,63],10,0,11),e.addMany(i(32,48),10,9,12),e.addMany(s,12,0,12),e.add(127,12,0,12),e.addMany(i(28,32),12,0,12),e.addMany(i(32,48),12,9,12),e.addMany(i(48,64),12,0,11),e.addMany(i(64,127),12,12,13),e.addMany(i(64,127),10,12,13),e.addMany(i(64,127),9,12,13),e.addMany(s,13,13,13),e.addMany(r,13,13,13),e.add(127,13,0,13),e.addMany([27,156,24,26],13,14,0),e.add(pt,0,2,0),e.add(pt,8,5,8),e.add(pt,6,0,6),e.add(pt,11,0,11),e.add(pt,13,13,13),e}(),x0=class extends W{constructor(e=k0){super(),this._transitions=e,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new up,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(t,i,r)=>{},this._executeHandlerFb=t=>{},this._csiHandlerFb=(t,i)=>{},this._escHandlerFb=t=>{},this._errorHandlerFb=t=>t,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this._register(re(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new y0),this._dcsParser=this._register(new w0),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:"\\"},()=>!0)}_identifier(e,t=[64,126]){let i=0;if(e.prefix){if(e.prefix.length>1)throw new Error("only one byte as prefix supported");if(i=e.prefix.charCodeAt(0),i&&60>i||i>63)throw new Error("prefix must be in range 0x3c .. 0x3f")}if(e.intermediates){if(e.intermediates.length>2)throw new Error("only two bytes as intermediates are supported");for(let s=0;sn||n>47)throw new Error("intermediate must be in range 0x20 .. 0x2f");i<<=8,i|=n}}if(e.final.length!==1)throw new Error("final must be a single byte");let r=e.final.charCodeAt(0);if(t[0]>r||r>t[1])throw new Error(`final must be in range ${t[0]} .. ${t[1]}`);return i<<=8,i|=r,i}identToString(e){let t=[];for(;e;)t.push(String.fromCharCode(e&255)),e>>=8;return t.reverse().join("")}setPrintHandler(e){this._printHandler=e}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(e,t){let i=this._identifier(e,[48,126]);this._escHandlers[i]===void 0&&(this._escHandlers[i]=[]);let r=this._escHandlers[i];return r.push(t),{dispose:()=>{let s=r.indexOf(t);s!==-1&&r.splice(s,1)}}}clearEscHandler(e){this._escHandlers[this._identifier(e,[48,126])]&&delete this._escHandlers[this._identifier(e,[48,126])]}setEscHandlerFallback(e){this._escHandlerFb=e}setExecuteHandler(e,t){this._executeHandlers[e.charCodeAt(0)]=t}clearExecuteHandler(e){this._executeHandlers[e.charCodeAt(0)]&&delete this._executeHandlers[e.charCodeAt(0)]}setExecuteHandlerFallback(e){this._executeHandlerFb=e}registerCsiHandler(e,t){let i=this._identifier(e);this._csiHandlers[i]===void 0&&(this._csiHandlers[i]=[]);let r=this._csiHandlers[i];return r.push(t),{dispose:()=>{let s=r.indexOf(t);s!==-1&&r.splice(s,1)}}}clearCsiHandler(e){this._csiHandlers[this._identifier(e)]&&delete this._csiHandlers[this._identifier(e)]}setCsiHandlerFallback(e){this._csiHandlerFb=e}registerDcsHandler(e,t){return this._dcsParser.registerHandler(this._identifier(e),t)}clearDcsHandler(e){this._dcsParser.clearHandler(this._identifier(e))}setDcsHandlerFallback(e){this._dcsParser.setHandlerFallback(e)}registerOscHandler(e,t){return this._oscParser.registerHandler(e,t)}clearOscHandler(e){this._oscParser.clearHandler(e)}setOscHandlerFallback(e){this._oscParser.setHandlerFallback(e)}setErrorHandler(e){this._errorHandler=e}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(e,t,i,r,s){this._parseStack.state=e,this._parseStack.handlers=t,this._parseStack.handlerPos=i,this._parseStack.transition=r,this._parseStack.chunkPos=s}parse(e,t,i){let r=0,s=0,n=0,o;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,n=this._parseStack.chunkPos+1;else{if(i===void 0||this._parseStack.state===1)throw this._parseStack.state=1,new Error("improper continuation due to previous async handler, giving up parsing");let l=this._parseStack.handlers,a=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(i===!1&&a>-1){for(;a>=0&&(o=l[a](this._params),o!==!0);a--)if(o instanceof Promise)return this._parseStack.handlerPos=a,o}this._parseStack.handlers=[];break;case 4:if(i===!1&&a>-1){for(;a>=0&&(o=l[a](),o!==!0);a--)if(o instanceof Promise)return this._parseStack.handlerPos=a,o}this._parseStack.handlers=[];break;case 6:if(r=e[this._parseStack.chunkPos],o=this._dcsParser.unhook(r!==24&&r!==26,i),o)return o;r===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(r=e[this._parseStack.chunkPos],o=this._oscParser.end(r!==24&&r!==26,i),o)return o;r===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break}this._parseStack.state=0,n=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=this._parseStack.transition&15}for(let l=n;l>4){case 2:for(let d=l+1;;++d){if(d>=t||(r=e[d])<32||r>126&&r=t||(r=e[d])<32||r>126&&r=t||(r=e[d])<32||r>126&&r=t||(r=e[d])<32||r>126&&r=0&&(o=a[h](this._params),o!==!0);h--)if(o instanceof Promise)return this._preserveStack(3,a,h,s,l),o;h<0&&this._csiHandlerFb(this._collect<<8|r,this._params),this.precedingJoinState=0;break;case 8:do switch(r){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(r-48)}while(++l47&&r<60);l--;break;case 9:this._collect<<=8,this._collect|=r;break;case 10:let u=this._escHandlers[this._collect<<8|r],c=u?u.length-1:-1;for(;c>=0&&(o=u[c](),o!==!0);c--)if(o instanceof Promise)return this._preserveStack(4,u,c,s,l),o;c<0&&this._escHandlerFb(this._collect<<8|r),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|r,this._params);break;case 13:for(let d=l+1;;++d)if(d>=t||(r=e[d])===24||r===26||r===27||r>127&&r=t||(r=e[d])<32||r>127&&r>4:n>>8}return r}}function pl(e,t){let i=e.toString(16),r=i.length<2?"0"+i:i;switch(t){case 4:return i[0];case 8:return r;case 12:return(r+r).slice(0,3);default:return r+r}}function D0(e,t=16){let[i,r,s]=e;return`rgb:${pl(i,t)}/${pl(r,t)}/${pl(s,t)}`}var R0={"(":0,")":1,"*":2,"+":3,"-":1,".":2},li=131072,Vu=10;function ju(e,t){if(e>24)return t.setWinLines||!1;switch(e){case 1:return!!t.restoreWin;case 2:return!!t.minimizeWin;case 3:return!!t.setWinPosition;case 4:return!!t.setWinSizePixels;case 5:return!!t.raiseWin;case 6:return!!t.lowerWin;case 7:return!!t.refreshWin;case 8:return!!t.setWinSizeChars;case 9:return!!t.maximizeWin;case 10:return!!t.fullscreenWin;case 11:return!!t.getWinState;case 13:return!!t.getWinPosition;case 14:return!!t.getWinSizePixels;case 15:return!!t.getScreenSizePixels;case 16:return!!t.getCellSizePixels;case 18:return!!t.getWinSizeChars;case 19:return!!t.getScreenSizeChars;case 20:return!!t.getIconTitle;case 21:return!!t.getWinTitle;case 22:return!!t.pushTitle;case 23:return!!t.popTitle;case 24:return!!t.setWinLines}return!1}var Yu=5e3,qu=0,P0=class extends W{constructor(e,t,i,r,s,n,o,l,a=new x0){super(),this._bufferService=e,this._charsetService=t,this._coreService=i,this._logService=r,this._optionsService=s,this._oscLinkService=n,this._coreMouseService=o,this._unicodeService=l,this._parser=a,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new qv,this._utf8Decoder=new Xv,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=me.clone(),this._eraseAttrDataInternal=me.clone(),this._onRequestBell=this._register(new D),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new D),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new D),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new D),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new D),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new D),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new D),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new D),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new D),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new D),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new D),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new D),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new D),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this._register(this._parser),this._dirtyRowTracker=new Ka(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(h=>this._activeBuffer=h.activeBuffer)),this._parser.setCsiHandlerFallback((h,u)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(h),params:u.toArray()})}),this._parser.setEscHandlerFallback(h=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(h)})}),this._parser.setExecuteHandlerFallback(h=>{this._logService.debug("Unknown EXECUTE code: ",{code:h})}),this._parser.setOscHandlerFallback((h,u,c)=>{this._logService.debug("Unknown OSC code: ",{identifier:h,action:u,data:c})}),this._parser.setDcsHandlerFallback((h,u,c)=>{u==="HOOK"&&(c=c.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(h),action:u,payload:c})}),this._parser.setPrintHandler((h,u,c)=>this.print(h,u,c)),this._parser.registerCsiHandler({final:"@"},h=>this.insertChars(h)),this._parser.registerCsiHandler({intermediates:" ",final:"@"},h=>this.scrollLeft(h)),this._parser.registerCsiHandler({final:"A"},h=>this.cursorUp(h)),this._parser.registerCsiHandler({intermediates:" ",final:"A"},h=>this.scrollRight(h)),this._parser.registerCsiHandler({final:"B"},h=>this.cursorDown(h)),this._parser.registerCsiHandler({final:"C"},h=>this.cursorForward(h)),this._parser.registerCsiHandler({final:"D"},h=>this.cursorBackward(h)),this._parser.registerCsiHandler({final:"E"},h=>this.cursorNextLine(h)),this._parser.registerCsiHandler({final:"F"},h=>this.cursorPrecedingLine(h)),this._parser.registerCsiHandler({final:"G"},h=>this.cursorCharAbsolute(h)),this._parser.registerCsiHandler({final:"H"},h=>this.cursorPosition(h)),this._parser.registerCsiHandler({final:"I"},h=>this.cursorForwardTab(h)),this._parser.registerCsiHandler({final:"J"},h=>this.eraseInDisplay(h,!1)),this._parser.registerCsiHandler({prefix:"?",final:"J"},h=>this.eraseInDisplay(h,!0)),this._parser.registerCsiHandler({final:"K"},h=>this.eraseInLine(h,!1)),this._parser.registerCsiHandler({prefix:"?",final:"K"},h=>this.eraseInLine(h,!0)),this._parser.registerCsiHandler({final:"L"},h=>this.insertLines(h)),this._parser.registerCsiHandler({final:"M"},h=>this.deleteLines(h)),this._parser.registerCsiHandler({final:"P"},h=>this.deleteChars(h)),this._parser.registerCsiHandler({final:"S"},h=>this.scrollUp(h)),this._parser.registerCsiHandler({final:"T"},h=>this.scrollDown(h)),this._parser.registerCsiHandler({final:"X"},h=>this.eraseChars(h)),this._parser.registerCsiHandler({final:"Z"},h=>this.cursorBackwardTab(h)),this._parser.registerCsiHandler({final:"`"},h=>this.charPosAbsolute(h)),this._parser.registerCsiHandler({final:"a"},h=>this.hPositionRelative(h)),this._parser.registerCsiHandler({final:"b"},h=>this.repeatPrecedingCharacter(h)),this._parser.registerCsiHandler({final:"c"},h=>this.sendDeviceAttributesPrimary(h)),this._parser.registerCsiHandler({prefix:">",final:"c"},h=>this.sendDeviceAttributesSecondary(h)),this._parser.registerCsiHandler({final:"d"},h=>this.linePosAbsolute(h)),this._parser.registerCsiHandler({final:"e"},h=>this.vPositionRelative(h)),this._parser.registerCsiHandler({final:"f"},h=>this.hVPosition(h)),this._parser.registerCsiHandler({final:"g"},h=>this.tabClear(h)),this._parser.registerCsiHandler({final:"h"},h=>this.setMode(h)),this._parser.registerCsiHandler({prefix:"?",final:"h"},h=>this.setModePrivate(h)),this._parser.registerCsiHandler({final:"l"},h=>this.resetMode(h)),this._parser.registerCsiHandler({prefix:"?",final:"l"},h=>this.resetModePrivate(h)),this._parser.registerCsiHandler({final:"m"},h=>this.charAttributes(h)),this._parser.registerCsiHandler({final:"n"},h=>this.deviceStatus(h)),this._parser.registerCsiHandler({prefix:"?",final:"n"},h=>this.deviceStatusPrivate(h)),this._parser.registerCsiHandler({intermediates:"!",final:"p"},h=>this.softReset(h)),this._parser.registerCsiHandler({intermediates:" ",final:"q"},h=>this.setCursorStyle(h)),this._parser.registerCsiHandler({final:"r"},h=>this.setScrollRegion(h)),this._parser.registerCsiHandler({final:"s"},h=>this.saveCursor(h)),this._parser.registerCsiHandler({final:"t"},h=>this.windowOptions(h)),this._parser.registerCsiHandler({final:"u"},h=>this.restoreCursor(h)),this._parser.registerCsiHandler({intermediates:"'",final:"}"},h=>this.insertColumns(h)),this._parser.registerCsiHandler({intermediates:"'",final:"~"},h=>this.deleteColumns(h)),this._parser.registerCsiHandler({intermediates:'"',final:"q"},h=>this.selectProtected(h)),this._parser.registerCsiHandler({intermediates:"$",final:"p"},h=>this.requestMode(h,!0)),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},h=>this.requestMode(h,!1)),this._parser.setExecuteHandler(C.BEL,()=>this.bell()),this._parser.setExecuteHandler(C.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(C.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(C.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(C.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(C.BS,()=>this.backspace()),this._parser.setExecuteHandler(C.HT,()=>this.tab()),this._parser.setExecuteHandler(C.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(C.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(Ln.IND,()=>this.index()),this._parser.setExecuteHandler(Ln.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(Ln.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new nt(h=>(this.setTitle(h),this.setIconName(h),!0))),this._parser.registerOscHandler(1,new nt(h=>this.setIconName(h))),this._parser.registerOscHandler(2,new nt(h=>this.setTitle(h))),this._parser.registerOscHandler(4,new nt(h=>this.setOrReportIndexedColor(h))),this._parser.registerOscHandler(8,new nt(h=>this.setHyperlink(h))),this._parser.registerOscHandler(10,new nt(h=>this.setOrReportFgColor(h))),this._parser.registerOscHandler(11,new nt(h=>this.setOrReportBgColor(h))),this._parser.registerOscHandler(12,new nt(h=>this.setOrReportCursorColor(h))),this._parser.registerOscHandler(104,new nt(h=>this.restoreIndexedColor(h))),this._parser.registerOscHandler(110,new nt(h=>this.restoreFgColor(h))),this._parser.registerOscHandler(111,new nt(h=>this.restoreBgColor(h))),this._parser.registerOscHandler(112,new nt(h=>this.restoreCursorColor(h))),this._parser.registerEscHandler({final:"7"},()=>this.saveCursor()),this._parser.registerEscHandler({final:"8"},()=>this.restoreCursor()),this._parser.registerEscHandler({final:"D"},()=>this.index()),this._parser.registerEscHandler({final:"E"},()=>this.nextLine()),this._parser.registerEscHandler({final:"H"},()=>this.tabSet()),this._parser.registerEscHandler({final:"M"},()=>this.reverseIndex()),this._parser.registerEscHandler({final:"="},()=>this.keypadApplicationMode()),this._parser.registerEscHandler({final:">"},()=>this.keypadNumericMode()),this._parser.registerEscHandler({final:"c"},()=>this.fullReset()),this._parser.registerEscHandler({final:"n"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"o"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"|"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"}"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"~"},()=>this.setgLevel(1)),this._parser.registerEscHandler({intermediates:"%",final:"@"},()=>this.selectDefaultCharset()),this._parser.registerEscHandler({intermediates:"%",final:"G"},()=>this.selectDefaultCharset());for(let h in be)this._parser.registerEscHandler({intermediates:"(",final:h},()=>this.selectCharset("("+h)),this._parser.registerEscHandler({intermediates:")",final:h},()=>this.selectCharset(")"+h)),this._parser.registerEscHandler({intermediates:"*",final:h},()=>this.selectCharset("*"+h)),this._parser.registerEscHandler({intermediates:"+",final:h},()=>this.selectCharset("+"+h)),this._parser.registerEscHandler({intermediates:"-",final:h},()=>this.selectCharset("-"+h)),this._parser.registerEscHandler({intermediates:".",final:h},()=>this.selectCharset("."+h)),this._parser.registerEscHandler({intermediates:"/",final:h},()=>this.selectCharset("/"+h));this._parser.registerEscHandler({intermediates:"#",final:"8"},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(h=>(this._logService.error("Parsing error: ",h),h)),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new Uu((h,u)=>this.requestStatusString(h,u)))}getAttrData(){return this._curAttrData}_preserveStack(e,t,i,r){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=t,this._parseStack.decodedLength=i,this._parseStack.position=r}_logSlowResolvingAsync(e){this._logService.logLevel<=3&&Promise.race([e,new Promise((t,i)=>setTimeout(()=>i("#SLOW_TIMEOUT"),Yu))]).catch(t=>{if(t!=="#SLOW_TIMEOUT")throw t;console.warn(`async parser handler taking longer than ${Yu} ms`)})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let i,r=this._activeBuffer.x,s=this._activeBuffer.y,n=0,o=this._parseStack.paused;if(o){if(i=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(i),i;r=this._parseStack.cursorStartX,s=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>li&&(n=this._parseStack.position+li)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e=="string"?` "${e}"`:` "${Array.prototype.map.call(e,h=>String.fromCharCode(h)).join("")}"`}`),this._logService.logLevel===0&&this._logService.trace("parsing data (codes)",typeof e=="string"?e.split("").map(h=>h.charCodeAt(0)):e),this._parseBuffer.lengthli)for(let h=n;h0&&c.getWidth(this._activeBuffer.x-1)===2&&c.setCellFromCodepoint(this._activeBuffer.x-1,0,1,u);let d=this._parser.precedingJoinState;for(let g=t;gl){if(a){let _=c,f=this._activeBuffer.x-k;for(this._activeBuffer.x=k,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),c=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),k>0&&c instanceof is&&c.copyCellsFrom(_,f,0,k,!1);f=0;)c.setCellFromCodepoint(this._activeBuffer.x++,0,0,u);continue}if(h&&(c.insertCells(this._activeBuffer.x,s-k,this._activeBuffer.getNullCell(u)),c.getWidth(l-1)===2&&c.setCellFromCodepoint(l-1,0,1,u)),c.setCellFromCodepoint(this._activeBuffer.x++,r,s,u),s>0)for(;--s;)c.setCellFromCodepoint(this._activeBuffer.x++,0,0,u)}this._parser.precedingJoinState=d,this._activeBuffer.x0&&c.getWidth(this._activeBuffer.x)===0&&!c.hasContent(this._activeBuffer.x)&&c.setCellFromCodepoint(this._activeBuffer.x,0,1,u),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return e.final==="t"&&!e.prefix&&!e.intermediates?this._parser.registerCsiHandler(e,i=>ju(i.params[0],this._optionsService.rawOptions.windowOptions)?t(i):!0):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new Uu(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new nt(t))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){var e;if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&((e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y))!=null&&e.isWrapped)){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);t.hasWidth(this._activeBuffer.x)&&!t.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let e=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(e,t){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e,this._activeBuffer.y=this._activeBuffer.scrollTop+t):(this._activeBuffer.x=e,this._activeBuffer.y=t),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e,t){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e,this._activeBuffer.y+t)}cursorUp(e){let t=this._activeBuffer.y-this._activeBuffer.scrollTop;return t>=0?this._moveCursor(0,-Math.min(t,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1)),!0}cursorDown(e){let t=this._activeBuffer.scrollBottom-this._activeBuffer.y;return t>=0?this._moveCursor(0,Math.min(t,e.params[0]||1)):this._moveCursor(0,e.params[0]||1),!0}cursorForward(e){return this._moveCursor(e.params[0]||1,0),!0}cursorBackward(e){return this._moveCursor(-(e.params[0]||1),0),!0}cursorNextLine(e){return this.cursorDown(e),this._activeBuffer.x=0,!0}cursorPrecedingLine(e){return this.cursorUp(e),this._activeBuffer.x=0,!0}cursorCharAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e){return this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1),!0}charPosAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e){return this._moveCursor(e.params[0]||1,0),!0}linePosAbsolute(e){return this._setCursor(this._activeBuffer.x,(e.params[0]||1)-1),!0}vPositionRelative(e){return this._moveCursor(0,e.params[0]||1),!0}hVPosition(e){return this.cursorPosition(e),!0}tabClear(e){let t=e.params[0];return t===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:t===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e){let t=e.params[0];return t===1&&(this._curAttrData.bg|=536870912),(t===2||t===0)&&(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(e,t,i,r=!1,s=!1){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.replaceCells(t,i,this._activeBuffer.getNullCell(this._eraseAttrData()),s),r&&(n.isWrapped=!1)}_resetBufferLine(e,t=!1){let i=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);i&&(i.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),i.isWrapped=!1)}eraseInDisplay(e,t=!1){var r;this._restrictCursor(this._bufferService.cols);let i;switch(e.params[0]){case 0:for(i=this._activeBuffer.y,this._dirtyRowTracker.markDirty(i),this._eraseInBufferLine(i++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);i=this._bufferService.cols&&(this._activeBuffer.lines.get(i+1).isWrapped=!1);i--;)this._resetBufferLine(i,t);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(i=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,i-1);i--&&!((r=this._activeBuffer.lines.get(this._activeBuffer.ybase+i))!=null&&r.getTrimmedLength()););for(;i>=0;i--)this._bufferService.scroll(this._eraseAttrData())}else{for(i=this._bufferService.rows,this._dirtyRowTracker.markDirty(i-1);i--;)this._resetBufferLine(i,t);this._dirtyRowTracker.markDirty(0)}break;case 3:let s=this._activeBuffer.lines.length-this._bufferService.rows;s>0&&(this._activeBuffer.lines.trimStart(s),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-s,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-s,0),this._onScroll.fire(0));break}return!0}eraseInLine(e,t=!1){switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,t);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,t);break}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.y65535?2:1}let a=l;for(let h=1;h0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(C.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(C.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(C.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(C.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(e.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(C.ESC+"[>83;40003;0c")),!0}_is(e){return(this._optionsService.rawOptions.termName+"").indexOf(e)===0}setMode(e){for(let t=0;t(m[m.NOT_RECOGNIZED=0]="NOT_RECOGNIZED",m[m.SET=1]="SET",m[m.RESET=2]="RESET",m[m.PERMANENTLY_SET=3]="PERMANENTLY_SET",m[m.PERMANENTLY_RESET=4]="PERMANENTLY_RESET"))(void 0||(i={}));let r=this._coreService.decPrivateModes,{activeProtocol:s,activeEncoding:n}=this._coreMouseService,o=this._coreService,{buffers:l,cols:a}=this._bufferService,{active:h,alt:u}=l,c=this._optionsService.rawOptions,d=(m,k)=>(o.triggerDataEvent(`${C.ESC}[${t?"":"?"}${m};${k}$y`),!0),g=m=>m?1:2,v=e.params[0];return t?v===2?d(v,4):v===4?d(v,g(o.modes.insertMode)):v===12?d(v,3):v===20?d(v,g(c.convertEol)):d(v,0):v===1?d(v,g(r.applicationCursorKeys)):v===3?d(v,c.windowOptions.setWinLines?a===80?2:a===132?1:0:0):v===6?d(v,g(r.origin)):v===7?d(v,g(r.wraparound)):v===8?d(v,3):v===9?d(v,g(s==="X10")):v===12?d(v,g(c.cursorBlink)):v===25?d(v,g(!o.isCursorHidden)):v===45?d(v,g(r.reverseWraparound)):v===66?d(v,g(r.applicationKeypad)):v===67?d(v,4):v===1e3?d(v,g(s==="VT200")):v===1002?d(v,g(s==="DRAG")):v===1003?d(v,g(s==="ANY")):v===1004?d(v,g(r.sendFocus)):v===1005?d(v,4):v===1006?d(v,g(n==="SGR")):v===1015?d(v,4):v===1016?d(v,g(n==="SGR_PIXELS")):v===1048?d(v,1):v===47||v===1047||v===1049?d(v,g(h===u)):v===2004?d(v,g(r.bracketedPasteMode)):v===2026?d(v,g(r.synchronizedOutput)):d(v,0)}_updateAttrColor(e,t,i,r,s){return t===2?(e|=50331648,e&=-16777216,e|=$s.fromColorRGB([i,r,s])):t===5&&(e&=-50331904,e|=33554432|i&255),e}_extractColor(e,t,i){let r=[0,0,-1,0,0,0],s=0,n=0;do{if(r[n+s]=e.params[t+n],e.hasSubParams(t+n)){let o=e.getSubParams(t+n),l=0;do r[1]===5&&(s=1),r[n+l+1+s]=o[l];while(++l=2||r[1]===2&&n+s>=5)break;r[1]&&(s=1)}while(++n+t5)&&(e=1),t.extended.underlineStyle=e,t.fg|=268435456,e===0&&(t.fg&=-268435457),t.updateExtended()}_processSGR0(e){e.fg=me.fg,e.bg=me.bg,e.extended=e.extended.clone(),e.extended.underlineStyle=0,e.extended.underlineColor&=-67108864,e.updateExtended()}charAttributes(e){if(e.length===1&&e.params[0]===0)return this._processSGR0(this._curAttrData),!0;let t=e.length,i,r=this._curAttrData;for(let s=0;s=30&&i<=37?(r.fg&=-50331904,r.fg|=16777216|i-30):i>=40&&i<=47?(r.bg&=-50331904,r.bg|=16777216|i-40):i>=90&&i<=97?(r.fg&=-50331904,r.fg|=16777216|i-90|8):i>=100&&i<=107?(r.bg&=-50331904,r.bg|=16777216|i-100|8):i===0?this._processSGR0(r):i===1?r.fg|=134217728:i===3?r.bg|=67108864:i===4?(r.fg|=268435456,this._processUnderline(e.hasSubParams(s)?e.getSubParams(s)[0]:1,r)):i===5?r.fg|=536870912:i===7?r.fg|=67108864:i===8?r.fg|=1073741824:i===9?r.fg|=2147483648:i===2?r.bg|=134217728:i===21?this._processUnderline(2,r):i===22?(r.fg&=-134217729,r.bg&=-134217729):i===23?r.bg&=-67108865:i===24?(r.fg&=-268435457,this._processUnderline(0,r)):i===25?r.fg&=-536870913:i===27?r.fg&=-67108865:i===28?r.fg&=-1073741825:i===29?r.fg&=2147483647:i===39?(r.fg&=-67108864,r.fg|=me.fg&16777215):i===49?(r.bg&=-67108864,r.bg|=me.bg&16777215):i===38||i===48||i===58?s+=this._extractColor(e,s,r):i===53?r.bg|=1073741824:i===55?r.bg&=-1073741825:i===59?(r.extended=r.extended.clone(),r.extended.underlineColor=-1,r.updateExtended()):i===100?(r.fg&=-67108864,r.fg|=me.fg&16777215,r.bg&=-67108864,r.bg|=me.bg&16777215):this._logService.debug("Unknown SGR attribute: %d.",i);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${C.ESC}[0n`);break;case 6:let t=this._activeBuffer.y+1,i=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${C.ESC}[${t};${i}R`);break}return!0}deviceStatusPrivate(e){switch(e.params[0]){case 6:let t=this._activeBuffer.y+1,i=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${C.ESC}[?${t};${i}R`);break}return!0}softReset(e){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=me.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(e){let t=e.length===0?1:e.params[0];if(t===0)this._coreService.decPrivateModes.cursorStyle=void 0,this._coreService.decPrivateModes.cursorBlink=void 0;else{switch(t){case 1:case 2:this._coreService.decPrivateModes.cursorStyle="block";break;case 3:case 4:this._coreService.decPrivateModes.cursorStyle="underline";break;case 5:case 6:this._coreService.decPrivateModes.cursorStyle="bar";break}let i=t%2===1;this._coreService.decPrivateModes.cursorBlink=i}return!0}setScrollRegion(e){let t=e.params[0]||1,i;return(e.length<2||(i=e.params[1])>this._bufferService.rows||i===0)&&(i=this._bufferService.rows),i>t&&(this._activeBuffer.scrollTop=t-1,this._activeBuffer.scrollBottom=i-1,this._setCursor(0,0)),!0}windowOptions(e){if(!ju(e.params[0],this._optionsService.rawOptions.windowOptions))return!0;let t=e.length>1?e.params[1]:0;switch(e.params[0]){case 14:t!==2&&this._onRequestWindowsOptionsReport.fire(0);break;case 16:this._onRequestWindowsOptionsReport.fire(1);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${C.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(t===0||t===2)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>Vu&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>Vu&&this._iconNameStack.shift());break;case 23:(t===0||t===2)&&this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),(t===0||t===1)&&this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop());break}return!0}saveCursor(e){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(e){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(e){return this._windowTitle=e,this._onTitleChange.fire(e),!0}setIconName(e){return this._iconName=e,!0}setOrReportIndexedColor(e){let t=[],i=e.split(";");for(;i.length>1;){let r=i.shift(),s=i.shift();if(/^\d+$/.exec(r)){let n=parseInt(r);if(Xu(n))if(s==="?")t.push({type:0,index:n});else{let o=Ku(s);o&&t.push({type:1,index:n,color:o})}}}return t.length&&this._onColor.fire(t),!0}setHyperlink(e){let t=e.indexOf(";");if(t===-1)return!0;let i=e.slice(0,t).trim(),r=e.slice(t+1);return r?this._createHyperlink(i,r):i.trim()?!1:this._finishHyperlink()}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();let i=e.split(":"),r,s=i.findIndex(n=>n.startsWith("id="));return s!==-1&&(r=i[s].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:r,uri:t}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e,t){let i=e.split(";");for(let r=0;r=this._specialColors.length);++r,++t)if(i[r]==="?")this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{let s=Ku(i[r]);s&&this._onColor.fire([{type:1,index:this._specialColors[t],color:s}])}return!0}setOrReportFgColor(e){return this._setOrReportSpecialColor(e,0)}setOrReportBgColor(e){return this._setOrReportSpecialColor(e,1)}setOrReportCursorColor(e){return this._setOrReportSpecialColor(e,2)}restoreIndexedColor(e){if(!e)return this._onColor.fire([{type:2}]),!0;let t=[],i=e.split(";");for(let r=0;r=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){let e=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,e,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=me.clone(),this._eraseAttrDataInternal=me.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=this._curAttrData.bg&67108863,this._eraseAttrDataInternal}setgLevel(e){return this._charsetService.setgLevel(e),!0}screenAlignmentPattern(){let e=new yt;e.content=1<<22|69,e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let t=0;t(this._coreService.triggerDataEvent(`${C.ESC}${o}${C.ESC}\\`),!0),r=this._bufferService.buffer,s=this._optionsService.rawOptions;return i(e==='"q'?`P1$r${this._curAttrData.isProtected()?1:0}"q`:e==='"p'?'P1$r61;1"p':e==="r"?`P1$r${r.scrollTop+1};${r.scrollBottom+1}r`:e==="m"?"P1$r0m":e===" q"?`P1$r${{block:2,underline:4,bar:6}[s.cursorStyle]-(s.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}},Ka=class{constructor(e){this._bufferService=e,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e){ethis.end&&(this.end=e)}markRangeDirty(e,t){e>t&&(qu=e,e=t,t=qu),ethis.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};Ka=_e([L(0,Xe)],Ka);function Xu(e){return 0<=e&&e<256}var L0=5e7,Gu=12,B0=50,M0=class extends W{constructor(e){super(),this._action=e,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this._register(new D),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(e,t){if(t!==void 0&&this._syncCalls>t){this._syncCalls=0;return}if(this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;this._isSyncWriting=!0;let i;for(;i=this._writeBuffer.shift();){this._action(i);let r=this._callbacks.shift();r&&r()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(e,t){if(this._pendingData>L0)throw new Error("write data discarded, use flow control to avoid losing data");if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput){this._didUserInput=!1,this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t),this._innerWrite();return}setTimeout(()=>this._innerWrite())}this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t)}_innerWrite(e=0,t=!0){let i=e||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){let r=this._writeBuffer[this._bufferOffset],s=this._action(r,t);if(s){let o=l=>performance.now()-i>=Gu?setTimeout(()=>this._innerWrite(0,l)):this._innerWrite(i,l);s.catch(l=>(queueMicrotask(()=>{throw l}),Promise.resolve(!1))).then(o);return}let n=this._callbacks[this._bufferOffset];if(n&&n(),this._bufferOffset++,this._pendingData-=r.length,performance.now()-i>=Gu)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>B0&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout(()=>this._innerWrite())):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}},Va=class{constructor(e){this._bufferService=e,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(e){let t=this._bufferService.buffer;if(e.id===void 0){let l=t.addMarker(t.ybase+t.y),a={data:e,id:this._nextId++,lines:[l]};return l.onDispose(()=>this._removeMarkerFromLink(a,l)),this._dataByLinkId.set(a.id,a),a.id}let i=e,r=this._getEntryIdKey(i),s=this._entriesWithId.get(r);if(s)return this.addLineToLink(s.id,t.ybase+t.y),s.id;let n=t.addMarker(t.ybase+t.y),o={id:this._nextId++,key:this._getEntryIdKey(i),data:i,lines:[n]};return n.onDispose(()=>this._removeMarkerFromLink(o,n)),this._entriesWithId.set(o.key,o),this._dataByLinkId.set(o.id,o),o.id}addLineToLink(e,t){let i=this._dataByLinkId.get(e);if(i&&i.lines.every(r=>r.line!==t)){let r=this._bufferService.buffer.addMarker(t);i.lines.push(r),r.onDispose(()=>this._removeMarkerFromLink(i,r))}}getLinkData(e){var t;return(t=this._dataByLinkId.get(e))==null?void 0:t.data}_getEntryIdKey(e){return`${e.id};;${e.uri}`}_removeMarkerFromLink(e,t){let i=e.lines.indexOf(t);i!==-1&&(e.lines.splice(i,1),e.lines.length===0&&(e.data.id!==void 0&&this._entriesWithId.delete(e.key),this._dataByLinkId.delete(e.id)))}};Va=_e([L(0,Xe)],Va);var Qu=!1,T0=class extends W{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new Pr),this._onBinary=this._register(new D),this.onBinary=this._onBinary.event,this._onData=this._register(new D),this.onData=this._onData.event,this._onLineFeed=this._register(new D),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new D),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new D),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new D),this._instantiationService=new r0,this.optionsService=this._register(new f0(e)),this._instantiationService.setService(Ge,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance($a)),this._instantiationService.setService(Xe,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(Fa)),this._instantiationService.setService(L_,this._logService),this.coreService=this._register(this._instantiationService.createInstance(Ha)),this._instantiationService.setService(Qi,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(Wa)),this._instantiationService.setService(P_,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(zi)),this._instantiationService.setService(Jv,this.unicodeService),this._charsetService=this._instantiationService.createInstance(m0),this._instantiationService.setService(Zv,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(Va),this._instantiationService.setService(B_,this._oscLinkService),this._inputHandler=this._register(new P0(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(Ae.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(Ae.forward(this._bufferService.onResize,this._onResize)),this._register(Ae.forward(this.coreService.onData,this._onData)),this._register(Ae.forward(this.coreService.onBinary,this._onBinary)),this._register(this.coreService.onRequestScrollToBottom(()=>this.scrollToBottom(!0))),this._register(this.coreService.onUserInput(()=>this._writeBuffer.handleUserInput())),this._register(this.optionsService.onMultipleOptionChange(["windowsMode","windowsPty"],()=>this._handleWindowsPtyOptionChange())),this._register(this._bufferService.onScroll(()=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this._writeBuffer=this._register(new M0((t,i)=>this._inputHandler.parse(t,i))),this._register(Ae.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new D),this._onScroll.event(e=>{var t;(t=this._onScrollApi)==null||t.fire(e.position)})),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(e){for(let t in e)this.optionsService.options[t]=e[t]}write(e,t){this._writeBuffer.write(e,t)}writeSync(e,t){this._logService.logLevel<=3&&!Qu&&(this._logService.warn("writeSync is unreliable and will be removed soon."),Qu=!0),this._writeBuffer.writeSync(e,t)}input(e,t=!0){this.coreService.triggerDataEvent(e,t)}resize(e,t){isNaN(e)||isNaN(t)||(e=Math.max(e,hp),t=Math.max(t,cp),this._bufferService.resize(e,t))}scroll(e,t=!1){this._bufferService.scroll(e,t)}scrollLines(e,t){this._bufferService.scrollLines(e,t)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}registerEscHandler(e,t){return this._inputHandler.registerEscHandler(e,t)}registerDcsHandler(e,t){return this._inputHandler.registerDcsHandler(e,t)}registerCsiHandler(e,t){return this._inputHandler.registerCsiHandler(e,t)}registerOscHandler(e,t){return this._inputHandler.registerOscHandler(e,t)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let e=!1,t=this.optionsService.rawOptions.windowsPty;t&&t.buildNumber!==void 0&&t.buildNumber!==void 0?e=t.backend==="conpty"&&t.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(e=!0),e?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let e=[];e.push(this.onLineFeed(Wu.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:"H"},()=>(Wu(this._bufferService),!1))),this._windowsWrappingHeuristics.value=re(()=>{for(let t of e)t.dispose()})}}},N0={48:["0",")"],49:["1","!"],50:["2","@"],51:["3","#"],52:["4","$"],53:["5","%"],54:["6","^"],55:["7","&"],56:["8","*"],57:["9","("],186:[";",":"],187:["=","+"],188:[",","<"],189:["-","_"],190:[".",">"],191:["/","?"],192:["`","~"],219:["[","{"],220:["\\","|"],221:["]","}"],222:["'",'"']};function O0(e,t,i,r){var o;let s={type:0,cancel:!1,key:void 0},n=(e.shiftKey?1:0)|(e.altKey?2:0)|(e.ctrlKey?4:0)|(e.metaKey?8:0);switch(e.keyCode){case 0:e.key==="UIKeyInputUpArrow"?t?s.key=C.ESC+"OA":s.key=C.ESC+"[A":e.key==="UIKeyInputLeftArrow"?t?s.key=C.ESC+"OD":s.key=C.ESC+"[D":e.key==="UIKeyInputRightArrow"?t?s.key=C.ESC+"OC":s.key=C.ESC+"[C":e.key==="UIKeyInputDownArrow"&&(t?s.key=C.ESC+"OB":s.key=C.ESC+"[B");break;case 8:s.key=e.ctrlKey?"\b":C.DEL,e.altKey&&(s.key=C.ESC+s.key);break;case 9:if(e.shiftKey){s.key=C.ESC+"[Z";break}s.key=C.HT,s.cancel=!0;break;case 13:s.key=e.altKey?C.ESC+C.CR:C.CR,s.cancel=!0;break;case 27:s.key=C.ESC,e.altKey&&(s.key=C.ESC+C.ESC),s.cancel=!0;break;case 37:if(e.metaKey)break;n?s.key=C.ESC+"[1;"+(n+1)+"D":t?s.key=C.ESC+"OD":s.key=C.ESC+"[D";break;case 39:if(e.metaKey)break;n?s.key=C.ESC+"[1;"+(n+1)+"C":t?s.key=C.ESC+"OC":s.key=C.ESC+"[C";break;case 38:if(e.metaKey)break;n?s.key=C.ESC+"[1;"+(n+1)+"A":t?s.key=C.ESC+"OA":s.key=C.ESC+"[A";break;case 40:if(e.metaKey)break;n?s.key=C.ESC+"[1;"+(n+1)+"B":t?s.key=C.ESC+"OB":s.key=C.ESC+"[B";break;case 45:!e.shiftKey&&!e.ctrlKey&&(s.key=C.ESC+"[2~");break;case 46:n?s.key=C.ESC+"[3;"+(n+1)+"~":s.key=C.ESC+"[3~";break;case 36:n?s.key=C.ESC+"[1;"+(n+1)+"H":t?s.key=C.ESC+"OH":s.key=C.ESC+"[H";break;case 35:n?s.key=C.ESC+"[1;"+(n+1)+"F":t?s.key=C.ESC+"OF":s.key=C.ESC+"[F";break;case 33:e.shiftKey?s.type=2:e.ctrlKey?s.key=C.ESC+"[5;"+(n+1)+"~":s.key=C.ESC+"[5~";break;case 34:e.shiftKey?s.type=3:e.ctrlKey?s.key=C.ESC+"[6;"+(n+1)+"~":s.key=C.ESC+"[6~";break;case 112:n?s.key=C.ESC+"[1;"+(n+1)+"P":s.key=C.ESC+"OP";break;case 113:n?s.key=C.ESC+"[1;"+(n+1)+"Q":s.key=C.ESC+"OQ";break;case 114:n?s.key=C.ESC+"[1;"+(n+1)+"R":s.key=C.ESC+"OR";break;case 115:n?s.key=C.ESC+"[1;"+(n+1)+"S":s.key=C.ESC+"OS";break;case 116:n?s.key=C.ESC+"[15;"+(n+1)+"~":s.key=C.ESC+"[15~";break;case 117:n?s.key=C.ESC+"[17;"+(n+1)+"~":s.key=C.ESC+"[17~";break;case 118:n?s.key=C.ESC+"[18;"+(n+1)+"~":s.key=C.ESC+"[18~";break;case 119:n?s.key=C.ESC+"[19;"+(n+1)+"~":s.key=C.ESC+"[19~";break;case 120:n?s.key=C.ESC+"[20;"+(n+1)+"~":s.key=C.ESC+"[20~";break;case 121:n?s.key=C.ESC+"[21;"+(n+1)+"~":s.key=C.ESC+"[21~";break;case 122:n?s.key=C.ESC+"[23;"+(n+1)+"~":s.key=C.ESC+"[23~";break;case 123:n?s.key=C.ESC+"[24;"+(n+1)+"~":s.key=C.ESC+"[24~";break;default:if(e.ctrlKey&&!e.shiftKey&&!e.altKey&&!e.metaKey)e.keyCode>=65&&e.keyCode<=90?s.key=String.fromCharCode(e.keyCode-64):e.keyCode===32?s.key=C.NUL:e.keyCode>=51&&e.keyCode<=55?s.key=String.fromCharCode(e.keyCode-51+27):e.keyCode===56?s.key=C.DEL:e.keyCode===219?s.key=C.ESC:e.keyCode===220?s.key=C.FS:e.keyCode===221&&(s.key=C.GS);else if((!i||r)&&e.altKey&&!e.metaKey){let l=(o=N0[e.keyCode])==null?void 0:o[e.shiftKey?1:0];if(l)s.key=C.ESC+l;else if(e.keyCode>=65&&e.keyCode<=90){let a=e.ctrlKey?e.keyCode-64:e.keyCode+32,h=String.fromCharCode(a);e.shiftKey&&(h=h.toUpperCase()),s.key=C.ESC+h}else if(e.keyCode===32)s.key=C.ESC+(e.ctrlKey?C.NUL:" ");else if(e.key==="Dead"&&e.code.startsWith("Key")){let a=e.code.slice(3,4);e.shiftKey||(a=a.toLowerCase()),s.key=C.ESC+a,s.cancel=!0}}else i&&!e.altKey&&!e.ctrlKey&&!e.shiftKey&&e.metaKey?e.keyCode===65&&(s.type=1):e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.keyCode>=48&&e.key.length===1?s.key=e.key:e.key&&e.ctrlKey&&(e.key==="_"&&(s.key=C.US),e.key==="@"&&(s.key=C.NUL));break}return s}var pe=0,A0=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new lo,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new lo,this._isFlushingDeleted=!1}clear(){this._array.length=0,this._insertedValues.length=0,this._flushInsertedTask.clear(),this._isFlushingInserted=!1,this._deletedIndices.length=0,this._flushDeletedTask.clear(),this._isFlushingDeleted=!1}insert(e){this._flushCleanupDeleted(),this._insertedValues.length===0&&this._flushInsertedTask.enqueue(()=>this._flushInserted()),this._insertedValues.push(e)}_flushInserted(){let e=this._insertedValues.sort((s,n)=>this._getKey(s)-this._getKey(n)),t=0,i=0,r=new Array(this._array.length+this._insertedValues.length);for(let s=0;s=this._array.length||this._getKey(e[t])<=this._getKey(this._array[i])?(r[s]=e[t],t++):r[s]=this._array[i++];this._array=r,this._insertedValues.length=0}_flushCleanupInserted(){!this._isFlushingInserted&&this._insertedValues.length>0&&this._flushInsertedTask.flush()}delete(e){if(this._flushCleanupInserted(),this._array.length===0)return!1;let t=this._getKey(e);if(t===void 0||(pe=this._search(t),pe===-1)||this._getKey(this._array[pe])!==t)return!1;do if(this._array[pe]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(pe),!0;while(++pes-n),t=0,i=new Array(this._array.length-e.length),r=0;for(let s=0;s0&&this._flushDeletedTask.flush()}*getKeyIterator(e){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(pe=this._search(e),!(pe<0||pe>=this._array.length)&&this._getKey(this._array[pe])===e))do yield this._array[pe];while(++pe=this._array.length)&&this._getKey(this._array[pe])===e))do t(this._array[pe]);while(++pe=t;){let r=t+i>>1,s=this._getKey(this._array[r]);if(s>e)i=r-1;else if(s0&&this._getKey(this._array[r-1])===e;)r--;return r}}return t}},gl=0,Zu=0,I0=class extends W{constructor(){super(),this._decorations=new A0(e=>e==null?void 0:e.marker.line),this._onDecorationRegistered=this._register(new D),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new D),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register(re(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new z0(e);if(t){let i=t.marker.onDispose(()=>t.dispose()),r=t.onDispose(()=>{r.dispose(),t&&(this._decorations.delete(t)&&this._onDecorationRemoved.fire(t),i.dispose())});this._decorations.insert(t),this._onDecorationRegistered.fire(t)}return t}reset(){for(let e of this._decorations.values())e.dispose();this._decorations.clear()}*getDecorationsAtCell(e,t,i){let r=0,s=0;for(let n of this._decorations.getKeyIterator(t))r=n.options.x??0,s=r+(n.options.width??1),e>=r&&e{gl=s.options.x??0,Zu=gl+(s.options.width??1),e>=gl&&e=this._debounceThresholdMS)this._lastRefreshMs=r,this._innerRefresh();else if(!this._additionalRefreshRequested){let s=r-this._lastRefreshMs,n=this._debounceThresholdMS-s;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=performance.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},n)}}_innerRefresh(){if(this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return;let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t)}},Ju=20,ao=class extends W{constructor(e,t,i,r){super(),this._terminal=e,this._coreBrowserService=i,this._renderService=r,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="";let s=this._coreBrowserService.mainDocument;this._accessibilityContainer=s.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=s.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let n=0;nthis._handleBoundaryFocus(n,0),this._bottomBoundaryFocusListener=n=>this._handleBoundaryFocus(n,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=s.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this._register(new $0(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this._register(this._terminal.onResize(n=>this._handleResize(n.rows))),this._register(this._terminal.onRender(n=>this._refreshRows(n.start,n.end))),this._register(this._terminal.onScroll(()=>this._refreshRows())),this._register(this._terminal.onA11yChar(n=>this._handleChar(n))),this._register(this._terminal.onLineFeed(()=>this._handleChar(` +`))),this._register(this._terminal.onA11yTab(n=>this._handleTab(n))),this._register(this._terminal.onKey(n=>this._handleKey(n.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register(F(s,"selectionchange",()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(re(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let t=0;t0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===` +`&&(this._liveRegionLineCount++,this._liveRegionLineCount===Ju+1&&(this._liveRegion.textContent+=ua.get())))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),new RegExp("\\p{Control}","u").test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){let i=this._terminal.buffer,r=i.lines.length.toString();for(let s=e;s<=t;s++){let n=i.lines.get(i.ydisp+s),o=[],l=(n==null?void 0:n.translateToString(!0,void 0,void 0,o))||"",a=(i.ydisp+s+1).toString(),h=this._rowElements[s];h&&(l.length===0?(h.textContent=" ",this._rowColumns.set(h,[0,1])):(h.textContent=l,this._rowColumns.set(h,o)),h.setAttribute("aria-posinset",a),h.setAttribute("aria-setsize",r),this._alignRowWidth(h))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(e,t){let i=e.target,r=this._rowElements[t===0?1:this._rowElements.length-2],s=i.getAttribute("aria-posinset"),n=t===0?"1":`${this._terminal.buffer.lines.length}`;if(s===n||e.relatedTarget!==r)return;let o,l;if(t===0?(o=i,l=this._rowElements.pop(),this._rowContainer.removeChild(l)):(o=this._rowElements.shift(),l=i,this._rowContainer.removeChild(o)),o.removeEventListener("focus",this._topBoundaryFocusListener),l.removeEventListener("focus",this._bottomBoundaryFocusListener),t===0){let a=this._createAccessibilityTreeNode();this._rowElements.unshift(a),this._rowContainer.insertAdjacentElement("afterbegin",a)}else{let a=this._createAccessibilityTreeNode();this._rowElements.push(a),this._rowContainer.appendChild(a)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(t===0?-1:1),this._rowElements[t===0?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}_handleSelectionChange(){var l;if(this._rowElements.length===0)return;let e=this._coreBrowserService.mainDocument.getSelection();if(!e)return;if(e.isCollapsed){this._rowContainer.contains(e.anchorNode)&&this._terminal.clearSelection();return}if(!e.anchorNode||!e.focusNode){console.error("anchorNode and/or focusNode are null");return}let t={node:e.anchorNode,offset:e.anchorOffset},i={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(i.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===i.node&&t.offset>i.offset)&&([t,i]=[i,t]),t.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(t={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(t.node))return;let r=this._rowElements.slice(-1)[0];if(i.node.compareDocumentPosition(r)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(i={node:r,offset:((l=r.textContent)==null?void 0:l.length)??0}),!this._rowContainer.contains(i.node))return;let s=({node:a,offset:h})=>{let u=a instanceof Text?a.parentNode:a,c=parseInt(u==null?void 0:u.getAttribute("aria-posinset"),10)-1;if(isNaN(c))return console.warn("row is invalid. Race condition?"),null;let d=this._rowColumns.get(u);if(!d)return console.warn("columns is null. Race condition?"),null;let g=h=this._terminal.cols&&(++c,g=0),{row:c,column:g}},n=s(t),o=s(i);if(!(!n||!o)){if(n.row>o.row||n.row===o.row&&n.column>=o.column)throw new Error("invalid range");this._terminal.select(n.column,n.row,(o.row-n.row)*this._terminal.cols-n.column+o.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let t=this._rowContainer.children.length;te;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){let e=this._coreBrowserService.mainDocument.createElement("div");return e.setAttribute("role","listitem"),e.tabIndex=-1,this._refreshRowDimensions(e),e}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){Object.assign(this._accessibilityContainer.style,{width:`${this._renderService.dimensions.css.canvas.width}px`,fontSize:`${this._terminal.options.fontSize}px`}),this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let e=0;e{var n;Yi(this._linkCacheDisposables),this._linkCacheDisposables.length=0,this._lastMouseEvent=void 0,(n=this._activeProviderReplies)==null||n.clear()})),this._register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0})),this._register(F(this._element,"mouseleave",()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(F(this._element,"mousemove",this._handleMouseMove.bind(this))),this._register(F(this._element,"mousedown",this._handleMouseDown.bind(this))),this._register(F(this._element,"mouseup",this._handleMouseUp.bind(this)))}get currentLink(){return this._currentLink}_handleMouseMove(e){this._lastMouseEvent=e;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);if(!t)return;this._isMouseOut=!1;let i=e.composedPath();for(let r=0;r{n==null||n.forEach(o=>{o.link.dispose&&o.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=e.y);let i=!1;for(let[n,o]of this._linkProviderService.linkProviders.entries())t?(s=this._activeProviderReplies)!=null&&s.get(n)&&(i=this._checkLinkProviderResult(n,e,i)):o.provideLinks(e.y,l=>{var h,u;if(this._isMouseOut)return;let a=l==null?void 0:l.map(c=>({link:c}));(h=this._activeProviderReplies)==null||h.set(n,a),i=this._checkLinkProviderResult(n,e,i),((u=this._activeProviderReplies)==null?void 0:u.size)===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)})}_removeIntersectingLinks(e,t){let i=new Set;for(let r=0;re?this._bufferService.cols:o.link.range.end.x;for(let h=l;h<=a;h++){if(i.has(h)){s.splice(n--,1);break}i.add(h)}}}}_checkLinkProviderResult(e,t,i){var n;if(!this._activeProviderReplies)return i;let r=this._activeProviderReplies.get(e),s=!1;for(let o=0;othis._linkAtPosition(l.link,t));o&&(i=!0,this._handleNewLink(o))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!i)for(let o=0;othis._linkAtPosition(a.link,t));if(l){i=!0,this._handleNewLink(l);break}}return i}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){if(!this._currentLink)return;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);t&&this._mouseDownLink&&H0(this._mouseDownLink.link,this._currentLink.link)&&this._linkAtPosition(this._currentLink.link,t)&&this._currentLink.link.activate(e,this._currentLink.link.text)}_clearCurrentLink(e,t){!this._currentLink||!this._lastMouseEvent||(!e||!t||this._currentLink.link.range.start.y>=e&&this._currentLink.link.range.end.y<=t)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,Yi(this._linkCacheDisposables),this._linkCacheDisposables.length=0)}_handleNewLink(e){if(!this._lastMouseEvent)return;let t=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);t&&this._linkAtPosition(e.link,t)&&(this._currentLink=e,this._currentLink.state={decorations:{underline:e.link.decorations===void 0?!0:e.link.decorations.underline,pointerCursor:e.link.decorations===void 0?!0:e.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,e.link,this._lastMouseEvent),e.link.decorations={},Object.defineProperties(e.link.decorations,{pointerCursor:{get:()=>{var i,r;return(r=(i=this._currentLink)==null?void 0:i.state)==null?void 0:r.decorations.pointerCursor},set:i=>{var r;(r=this._currentLink)!=null&&r.state&&this._currentLink.state.decorations.pointerCursor!==i&&(this._currentLink.state.decorations.pointerCursor=i,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",i))}},underline:{get:()=>{var i,r;return(r=(i=this._currentLink)==null?void 0:i.state)==null?void 0:r.decorations.underline},set:i=>{var r,s,n;(r=this._currentLink)!=null&&r.state&&((n=(s=this._currentLink)==null?void 0:s.state)==null?void 0:n.decorations.underline)!==i&&(this._currentLink.state.decorations.underline=i,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,i))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(i=>{if(!this._currentLink)return;let r=i.start===0?0:i.start+1+this._bufferService.buffer.ydisp,s=this._bufferService.buffer.ydisp+1+i.end;if(this._currentLink.link.range.start.y>=r&&this._currentLink.link.range.end.y<=s&&(this._clearCurrentLink(r,s),this._lastMouseEvent)){let n=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);n&&this._askForLink(n,!1)}})))}_linkHover(e,t,i){var r;(r=this._currentLink)!=null&&r.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!0),this._currentLink.state.decorations.pointerCursor&&e.classList.add("xterm-cursor-pointer")),t.hover&&t.hover(i,t.text)}_fireUnderlineEvent(e,t){let i=e.range,r=this._bufferService.buffer.ydisp,s=this._createLinkUnderlineEvent(i.start.x-1,i.start.y-r-1,i.end.x,i.end.y-r-1,void 0);(t?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(s)}_linkLeave(e,t,i){var r;(r=this._currentLink)!=null&&r.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!1),this._currentLink.state.decorations.pointerCursor&&e.classList.remove("xterm-cursor-pointer")),t.leave&&t.leave(i,t.text)}_linkAtPosition(e,t){let i=e.range.start.y*this._bufferService.cols+e.range.start.x,r=e.range.end.y*this._bufferService.cols+e.range.end.x,s=t.y*this._bufferService.cols+t.x;return i<=s&&s<=r}_positionFromMouseEvent(e,t,i){let r=i.getCoords(e,t,this._bufferService.cols,this._bufferService.rows);if(r)return{x:r[0],y:r[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,t,i,r,s){return{x1:e,y1:t,x2:i,y2:r,cols:this._bufferService.cols,fg:s}}};ja=_e([L(1,Uh),L(2,ti),L(3,Xe),L(4,T_)],ja);function H0(e,t){return e.text===t.text&&e.range.start.x===t.range.start.x&&e.range.start.y===t.range.start.y&&e.range.end.x===t.range.end.x&&e.range.end.y===t.range.end.y}var W0=class extends T0{constructor(e={}){super(e),this._linkifier=this._register(new Pr),this.browser=Z_,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new Pr),this._onCursorMove=this._register(new D),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new D),this.onKey=this._onKey.event,this._onRender=this._register(new D),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new D),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new D),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new D),this.onBell=this._onBell.event,this._onFocus=this._register(new D),this._onBlur=this._register(new D),this._onA11yCharEmitter=this._register(new D),this._onA11yTabEmitter=this._register(new D),this._onWillOpen=this._register(new D),this._setup(),this._decorationService=this._instantiationService.createInstance(I0),this._instantiationService.setService(Hs,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(BS),this._instantiationService.setService(T_,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(fa)),this._register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this._register(this._inputHandler.onRequestRefreshRows(t=>this.refresh((t==null?void 0:t.start)??0,(t==null?void 0:t.end)??this.rows-1))),this._register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this._register(this._inputHandler.onRequestReset(()=>this.reset())),this._register(this._inputHandler.onRequestWindowsOptionsReport(t=>this._reportWindowsOptions(t))),this._register(this._inputHandler.onColor(t=>this._handleColorEvent(t))),this._register(Ae.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(Ae.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(Ae.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(Ae.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(t=>this._afterResize(t.cols,t.rows))),this._register(re(()=>{var t,i;this._customKeyEventHandler=void 0,(i=(t=this.element)==null?void 0:t.parentNode)==null||i.removeChild(this.element)}))}get linkifier(){return this._linkifier.value}get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}_handleColorEvent(e){if(this._themeService)for(let t of e){let i,r="";switch(t.index){case 256:i="foreground",r="10";break;case 257:i="background",r="11";break;case 258:i="cursor",r="12";break;default:i="ansi",r="4;"+t.index}switch(t.type){case 0:let s=ee.toColorRGB(i==="ansi"?this._themeService.colors.ansi[t.index]:this._themeService.colors[i]);this.coreService.triggerDataEvent(`${C.ESC}]${r};${D0(s)}${G_.ST}`);break;case 1:if(i==="ansi")this._themeService.modifyColors(n=>n.ansi[t.index]=Se.toColor(...t.color));else{let n=i;this._themeService.modifyColors(o=>o[n]=Se.toColor(...t.color))}break;case 2:this._themeService.restoreColor(t.index);break}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(e){e?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(ao,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(C.ESC+"[I"),this.element.classList.add("focus"),this._showCursor(),this._onFocus.fire()}blur(){var e;return(e=this.textarea)==null?void 0:e.blur()}_handleTextAreaBlur(){this.textarea.value="",this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(C.ESC+"[O"),this.element.classList.remove("focus"),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;let e=this.buffer.ybase+this.buffer.y,t=this.buffer.lines.get(e);if(!t)return;let i=Math.min(this.buffer.x,this.cols-1),r=this._renderService.dimensions.css.cell.height,s=t.getWidth(i),n=this._renderService.dimensions.css.cell.width*s,o=this.buffer.y*this._renderService.dimensions.css.cell.height,l=i*this._renderService.dimensions.css.cell.width;this.textarea.style.left=l+"px",this.textarea.style.top=o+"px",this.textarea.style.width=n+"px",this.textarea.style.height=r+"px",this.textarea.style.lineHeight=r+"px",this.textarea.style.zIndex="-5"}_initGlobal(){this._bindKeys(),this._register(F(this.element,"copy",t=>{this.hasSelection()&&jv(t,this._selectionService)}));let e=t=>Yv(t,this.textarea,this.coreService,this.optionsService);this._register(F(this.textarea,"paste",e)),this._register(F(this.element,"paste",e)),J_?this._register(F(this.element,"mousedown",t=>{t.button===2&&hu(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(F(this.element,"contextmenu",t=>{hu(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),Qh&&this._register(F(this.element,"auxclick",t=>{t.button===1&&x_(t,this.textarea,this.screenElement)}))}_bindKeys(){this._register(F(this.textarea,"keyup",e=>this._keyUp(e),!0)),this._register(F(this.textarea,"keydown",e=>this._keyDown(e),!0)),this._register(F(this.textarea,"keypress",e=>this._keyPress(e),!0)),this._register(F(this.textarea,"compositionstart",()=>this._compositionHelper.compositionstart())),this._register(F(this.textarea,"compositionupdate",e=>this._compositionHelper.compositionupdate(e))),this._register(F(this.textarea,"compositionend",()=>this._compositionHelper.compositionend())),this._register(F(this.textarea,"input",e=>this._inputEvent(e),!0)),this._register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(e){var s;if(!e)throw new Error("Terminal requires a parent element.");if(e.isConnected||this._logService.debug("Terminal.open was called on an element that was not attached to the DOM"),((s=this.element)==null?void 0:s.ownerDocument.defaultView)&&this._coreBrowserService){this.element.ownerDocument.defaultView!==this._coreBrowserService.window&&(this._coreBrowserService.window=this.element.ownerDocument.defaultView);return}this._document=e.ownerDocument,this.options.documentOverride&&this.options.documentOverride instanceof Document&&(this._document=this.optionsService.rawOptions.documentOverride),this.element=this._document.createElement("div"),this.element.dir="ltr",this.element.classList.add("terminal"),this.element.classList.add("xterm"),e.appendChild(this.element);let t=this._document.createDocumentFragment();this._viewportElement=this._document.createElement("div"),this._viewportElement.classList.add("xterm-viewport"),t.appendChild(this._viewportElement),this.screenElement=this._document.createElement("div"),this.screenElement.classList.add("xterm-screen"),this._register(F(this.screenElement,"mousemove",n=>this.updateCursorStyle(n))),this._helperContainer=this._document.createElement("div"),this._helperContainer.classList.add("xterm-helpers"),this.screenElement.appendChild(this._helperContainer),t.appendChild(this.screenElement);let i=this.textarea=this._document.createElement("textarea");this.textarea.classList.add("xterm-helper-textarea"),this.textarea.setAttribute("aria-label",ca.get()),ip||this.textarea.setAttribute("aria-multiline","false"),this.textarea.setAttribute("autocorrect","off"),this.textarea.setAttribute("autocapitalize","off"),this.textarea.setAttribute("spellcheck","false"),this.textarea.tabIndex=0,this._register(this.optionsService.onSpecificOptionChange("disableStdin",()=>i.readOnly=this.optionsService.rawOptions.disableStdin)),this.textarea.readOnly=this.optionsService.rawOptions.disableStdin,this._coreBrowserService=this._register(this._instantiationService.createInstance(PS,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<"u"?window.document:null)),this._instantiationService.setService(ei,this._coreBrowserService),this._register(F(this.textarea,"focus",n=>this._handleTextAreaFocus(n))),this._register(F(this.textarea,"blur",()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(Na,this._document,this._helperContainer),this._instantiationService.setService(Do,this._charSizeService),this._themeService=this._instantiationService.createInstance(za),this._instantiationService.setService(Tr,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(no),this._instantiationService.setService(M_,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(Aa,this.rows,this.screenElement)),this._instantiationService.setService(ti,this._renderService),this._register(this._renderService.onRenderedViewportChange(n=>this._onRender.fire(n))),this.onResize(n=>this._renderService.resize(n.cols,n.rows)),this._compositionView=this._document.createElement("div"),this._compositionView.classList.add("composition-view"),this._compositionHelper=this._instantiationService.createInstance(Ba,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(Oa),this._instantiationService.setService(Uh,this._mouseService);let r=this._linkifier.value=this._register(this._instantiationService.createInstance(ja,this.screenElement));this.element.appendChild(t);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this._register(this.onCursorMove(()=>{this._renderService.handleCursorMove(),this._syncTextArea()})),this._register(this.onResize(()=>this._renderService.handleResize(this.cols,this.rows))),this._register(this.onBlur(()=>this._renderService.handleBlur())),this._register(this.onFocus(()=>this._renderService.handleFocus())),this._viewport=this._register(this._instantiationService.createInstance(Pa,this.element,this.screenElement)),this._register(this._viewport.onRequestScrollLines(n=>{super.scrollLines(n,!1),this.refresh(0,this.rows-1)})),this._selectionService=this._register(this._instantiationService.createInstance(Ia,this.element,this.screenElement,r)),this._instantiationService.setService(tm,this._selectionService),this._register(this._selectionService.onRequestScrollLines(n=>this.scrollLines(n.amount,n.suppressScrollEvent))),this._register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this._register(this._selectionService.onRequestRedraw(n=>this._renderService.handleSelectionChanged(n.start,n.end,n.columnSelectMode))),this._register(this._selectionService.onLinuxMouseSelection(n=>{this.textarea.value=n,this.textarea.focus(),this.textarea.select()})),this._register(Ae.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{var n;this._selectionService.refresh(),(n=this._viewport)==null||n.queueSync()})),this._register(this._instantiationService.createInstance(La,this.screenElement)),this._register(F(this.element,"mousedown",n=>this._selectionService.handleMouseDown(n))),this.coreMouseService.areMouseEventsActive?(this._selectionService.disable(),this.element.classList.add("enable-mouse-events")):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager.value=this._instantiationService.createInstance(ao,this)),this._register(this.optionsService.onSpecificOptionChange("screenReaderMode",n=>this._handleScreenReaderModeOptionChange(n))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(so,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRuler",n=>{!this._overviewRulerRenderer&&n&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(so,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(Ta,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function i(n){var h,u,c,d,g;let o=e._mouseService.getMouseReportCoords(n,e.screenElement);if(!o)return!1;let l,a;switch(n.overrideType||n.type){case"mousemove":a=32,n.buttons===void 0?(l=3,n.button!==void 0&&(l=n.button<3?n.button:3)):l=n.buttons&1?0:n.buttons&4?1:n.buttons&2?2:3;break;case"mouseup":a=0,l=n.button<3?n.button:3;break;case"mousedown":a=1,l=n.button<3?n.button:3;break;case"wheel":if(e._customWheelEventHandler&&e._customWheelEventHandler(n)===!1)return!1;let v=n.deltaY;if(v===0||e.coreMouseService.consumeWheelEvent(n,(d=(c=(u=(h=e._renderService)==null?void 0:h.dimensions)==null?void 0:u.device)==null?void 0:c.cell)==null?void 0:d.height,(g=e._coreBrowserService)==null?void 0:g.dpr)===0)return!1;a=v<0?0:1,l=4;break;default:return!1}return a===void 0||l===void 0||l>4?!1:e.coreMouseService.triggerMouseEvent({col:o.col,row:o.row,x:o.x,y:o.y,button:l,action:a,ctrl:n.ctrlKey,alt:n.altKey,shift:n.shiftKey})}let r={mouseup:null,wheel:null,mousedrag:null,mousemove:null},s={mouseup:n=>(i(n),n.buttons||(this._document.removeEventListener("mouseup",r.mouseup),r.mousedrag&&this._document.removeEventListener("mousemove",r.mousedrag)),this.cancel(n)),wheel:n=>(i(n),this.cancel(n,!0)),mousedrag:n=>{n.buttons&&i(n)},mousemove:n=>{n.buttons||i(n)}};this._register(this.coreMouseService.onProtocolChange(n=>{n?(this.optionsService.rawOptions.logLevel==="debug"&&this._logService.debug("Binding to mouse events:",this.coreMouseService.explainEvents(n)),this.element.classList.add("enable-mouse-events"),this._selectionService.disable()):(this._logService.debug("Unbinding from mouse events."),this.element.classList.remove("enable-mouse-events"),this._selectionService.enable()),n&8?r.mousemove||(t.addEventListener("mousemove",s.mousemove),r.mousemove=s.mousemove):(t.removeEventListener("mousemove",r.mousemove),r.mousemove=null),n&16?r.wheel||(t.addEventListener("wheel",s.wheel,{passive:!1}),r.wheel=s.wheel):(t.removeEventListener("wheel",r.wheel),r.wheel=null),n&2?r.mouseup||(r.mouseup=s.mouseup):(this._document.removeEventListener("mouseup",r.mouseup),r.mouseup=null),n&4?r.mousedrag||(r.mousedrag=s.mousedrag):(this._document.removeEventListener("mousemove",r.mousedrag),r.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register(F(t,"mousedown",n=>{if(n.preventDefault(),this.focus(),!(!this.coreMouseService.areMouseEventsActive||this._selectionService.shouldForceSelection(n)))return i(n),r.mouseup&&this._document.addEventListener("mouseup",r.mouseup),r.mousedrag&&this._document.addEventListener("mousemove",r.mousedrag),this.cancel(n)})),this._register(F(t,"wheel",n=>{var o,l,a,h,u;if(!r.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(n)===!1)return!1;if(!this.buffer.hasScrollback){if(n.deltaY===0)return!1;if(e.coreMouseService.consumeWheelEvent(n,(h=(a=(l=(o=e._renderService)==null?void 0:o.dimensions)==null?void 0:l.device)==null?void 0:a.cell)==null?void 0:h.height,(u=e._coreBrowserService)==null?void 0:u.dpr)===0)return this.cancel(n,!0);let c=C.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?"O":"[")+(n.deltaY<0?"A":"B");return this.coreService.triggerDataEvent(c,!0),this.cancel(n,!0)}}},{passive:!1}))}refresh(e,t){var i;(i=this._renderService)==null||i.refreshRows(e,t)}updateCursorStyle(e){var t;(t=this._selectionService)!=null&&t.shouldColumnSelect(e)?this.element.classList.add("column-select"):this.element.classList.remove("column-select")}_showCursor(){this.coreService.isCursorInitialized||(this.coreService.isCursorInitialized=!0,this.refresh(this.buffer.y,this.buffer.y))}scrollLines(e,t){this._viewport?this._viewport.scrollLines(e):super.scrollLines(e,t),this.refresh(0,this.rows-1)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){e&&this._viewport?this._viewport.scrollToLine(this.buffer.ybase,!0):this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}paste(e){k_(e,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(e){this._customKeyEventHandler=e}attachCustomWheelEventHandler(e){this._customWheelEventHandler=e}registerLinkProvider(e){return this._linkProviderService.registerLinkProvider(e)}registerCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");let t=this._characterJoinerService.register(e);return this.refresh(0,this.rows-1),t}deregisterCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");this._characterJoinerService.deregister(e)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(e){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+e)}registerDecoration(e){return this._decorationService.registerDecoration(e)}hasSelection(){return this._selectionService?this._selectionService.hasSelection:!1}select(e,t,i){this._selectionService.setSelection(e,t,i)}getSelection(){return this._selectionService?this._selectionService.selectionText:""}getSelectionPosition(){if(!(!this._selectionService||!this._selectionService.hasSelection))return{start:{x:this._selectionService.selectionStart[0],y:this._selectionService.selectionStart[1]},end:{x:this._selectionService.selectionEnd[0],y:this._selectionService.selectionEnd[1]}}}clearSelection(){var e;(e=this._selectionService)==null||e.clearSelection()}selectAll(){var e;(e=this._selectionService)==null||e.selectAll()}selectLines(e,t){var i;(i=this._selectionService)==null||i.selectLines(e,t)}_keyDown(e){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;let t=this.browser.isMac&&this.options.macOptionIsMeta&&e.altKey;if(!t&&!this._compositionHelper.keydown(e))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(!0),!1;!t&&(e.key==="Dead"||e.key==="AltGraph")&&(this._unprocessedDeadKey=!0);let i=O0(e,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),i.type===3||i.type===2){let r=this.rows-1;return this.scrollLines(i.type===2?-r:r),this.cancel(e,!0)}if(i.type===1&&this.selectAll(),this._isThirdLevelShift(this.browser,e)||(i.cancel&&this.cancel(e,!0),!i.key)||e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.key.length===1&&e.key.charCodeAt(0)>=65&&e.key.charCodeAt(0)<=90)return!0;if(this._unprocessedDeadKey)return this._unprocessedDeadKey=!1,!0;if((i.key===C.ETX||i.key===C.CR)&&(this.textarea.value=""),this._onKey.fire({key:i.key,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(i.key,!0),!this.optionsService.rawOptions.screenReaderMode||e.altKey||e.ctrlKey)return this.cancel(e,!0);this._keyDownHandled=!0}_isThirdLevelShift(e,t){let i=e.isMac&&!this.options.macOptionIsMeta&&t.altKey&&!t.ctrlKey&&!t.metaKey||e.isWindows&&t.altKey&&t.ctrlKey&&!t.metaKey||e.isWindows&&t.getModifierState("AltGraph");return t.type==="keypress"?i:i&&(!t.keyCode||t.keyCode>47)}_keyUp(e){this._keyDownSeen=!1,!(this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)&&(U0(e)||this.focus(),this.updateCursorStyle(e),this._keyPressHandled=!1)}_keyPress(e){let t;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;if(this.cancel(e),e.charCode)t=e.charCode;else if(e.which===null||e.which===void 0)t=e.keyCode;else if(e.which!==0&&e.charCode!==0)t=e.which;else return!1;return!t||(e.altKey||e.ctrlKey||e.metaKey)&&!this._isThirdLevelShift(this.browser,e)?!1:(t=String.fromCharCode(t),this._onKey.fire({key:t,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(t,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,!0)}_inputEvent(e){if(e.data&&e.inputType==="insertText"&&(!e.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;let t=e.data;return this.coreService.triggerDataEvent(t,!0),this.cancel(e),!0}return!1}resize(e,t){if(e===this.cols&&t===this.rows){this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure();return}super.resize(e,t)}_afterResize(e,t){var i;(i=this._charSizeService)==null||i.measure()}clear(){if(!(this.buffer.ybase===0&&this.buffer.y===0)){this.buffer.clearAllMarkers(),this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let e=1;e=0;e--)this._addons[e].instance.dispose()}loadAddon(e,t){let i={instance:t,dispose:t.dispose,isDisposed:!1};this._addons.push(i),t.dispose=()=>this._wrappedAddonDispose(i),t.activate(e)}_wrappedAddonDispose(e){if(e.isDisposed)return;let t=-1;for(let i=0;i=this._line.length))return t?(this._line.loadCell(e,t),t):this._line.loadCell(e,new yt)}translateToString(e,t,i){return this._line.translateToString(e,t,i)}},ed=class{constructor(e,t){this._buffer=e,this.type=t}init(e){return this._buffer=e,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(e){let t=this._buffer.lines.get(e);if(t)return new V0(t)}getNullCell(){return new yt}},j0=class extends W{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new D),this.onBufferChange=this._onBufferChange.event,this._normal=new ed(this._core.buffers.normal,"normal"),this._alternate=new ed(this._core.buffers.alt,"alternate"),this._core.buffers.onBufferActivate(()=>this._onBufferChange.fire(this.active))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw new Error("Active buffer is neither normal nor alternate")}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}},Y0=class{constructor(e){this._core=e}registerCsiHandler(e,t){return this._core.registerCsiHandler(e,i=>t(i.toArray()))}addCsiHandler(e,t){return this.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._core.registerDcsHandler(e,(i,r)=>t(i,r.toArray()))}addDcsHandler(e,t){return this.registerDcsHandler(e,t)}registerEscHandler(e,t){return this._core.registerEscHandler(e,t)}addEscHandler(e,t){return this.registerEscHandler(e,t)}registerOscHandler(e,t){return this._core.registerOscHandler(e,t)}addOscHandler(e,t){return this.registerOscHandler(e,t)}},q0=class{constructor(e){this._core=e}register(e){this._core.unicodeService.register(e)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(e){this._core.unicodeService.activeVersion=e}},X0=["cols","rows"],Tt=0,G0=class extends W{constructor(e){super(),this._core=this._register(new W0(e)),this._addonManager=this._register(new K0),this._publicOptions={...this._core.options};let t=r=>this._core.options[r],i=(r,s)=>{this._checkReadonlyOptions(r),this._core.options[r]=s};for(let r in this._core.options){let s={get:t.bind(this,r),set:i.bind(this,r)};Object.defineProperty(this._publicOptions,r,s)}}_checkReadonlyOptions(e){if(X0.includes(e))throw new Error(`Option "${e}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw new Error("You must set the allowProposedApi option to true to use proposed API")}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onKey(){return this._core.onKey}get onLineFeed(){return this._core.onLineFeed}get onRender(){return this._core.onRender}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onSelectionChange(){return this._core.onSelectionChange}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get element(){return this._core.element}get parser(){return this._parser||(this._parser=new Y0(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new q0(this._core)}get textarea(){return this._core.textarea}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._buffer||(this._buffer=this._register(new j0(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let e=this._core.coreService.decPrivateModes,t="none";switch(this._core.coreMouseService.activeProtocol){case"X10":t="x10";break;case"VT200":t="vt200";break;case"DRAG":t="drag";break;case"ANY":t="any";break}return{applicationCursorKeysMode:e.applicationCursorKeys,applicationKeypadMode:e.applicationKeypad,bracketedPasteMode:e.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:t,originMode:e.origin,reverseWraparoundMode:e.reverseWraparound,sendFocusMode:e.sendFocus,synchronizedOutputMode:e.synchronizedOutput,wraparoundMode:e.wraparound}}get options(){return this._publicOptions}set options(e){for(let t in e)this._publicOptions[t]=e[t]}blur(){this._core.blur()}focus(){this._core.focus()}input(e,t=!0){this._core.input(e,t)}resize(e,t){this._verifyIntegers(e,t),this._core.resize(e,t)}open(e){this._core.open(e)}attachCustomKeyEventHandler(e){this._core.attachCustomKeyEventHandler(e)}attachCustomWheelEventHandler(e){this._core.attachCustomWheelEventHandler(e)}registerLinkProvider(e){return this._core.registerLinkProvider(e)}registerCharacterJoiner(e){return this._checkProposedApi(),this._core.registerCharacterJoiner(e)}deregisterCharacterJoiner(e){this._checkProposedApi(),this._core.deregisterCharacterJoiner(e)}registerMarker(e=0){return this._verifyIntegers(e),this._core.registerMarker(e)}registerDecoration(e){return this._checkProposedApi(),this._verifyPositiveIntegers(e.x??0,e.width??0,e.height??0),this._core.registerDecoration(e)}hasSelection(){return this._core.hasSelection()}select(e,t,i){this._verifyIntegers(e,t,i),this._core.select(e,t,i)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(e,t){this._verifyIntegers(e,t),this._core.selectLines(e,t)}dispose(){super.dispose()}scrollLines(e){this._verifyIntegers(e),this._core.scrollLines(e)}scrollPages(e){this._verifyIntegers(e),this._core.scrollPages(e)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(e){this._verifyIntegers(e),this._core.scrollToLine(e)}clear(){this._core.clear()}write(e,t){this._core.write(e,t)}writeln(e,t){this._core.write(e),this._core.write(`\r +`,t)}paste(e){this._core.paste(e)}refresh(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return ca.get()},set promptLabel(e){ca.set(e)},get tooMuchOutput(){return ua.get()},set tooMuchOutput(e){ua.set(e)}}}_verifyIntegers(...e){for(Tt of e)if(Tt===1/0||isNaN(Tt)||Tt%1!==0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...e){for(Tt of e)if(Tt&&(Tt===1/0||isNaN(Tt)||Tt%1!==0||Tt<0))throw new Error("This API only accepts positive integers")}};/** + * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved. + * @license MIT + * + * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License) + * @license MIT + * + * Originally forked from (with the author's permission): + * Fabrice Bellard's javascript vt100 for jslinux: + * http://bellard.org/jslinux/ + * Copyright (c) 2011 Fabrice Bellard + */var Q0=2,Z0=1,J0=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let t=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){var c;if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let e=this._terminal._core._renderService.dimensions;if(e.css.cell.width===0||e.css.cell.height===0)return;let t=this._terminal.options.scrollback===0?0:((c=this._terminal.options.overviewRuler)==null?void 0:c.width)||14,i=window.getComputedStyle(this._terminal.element.parentElement),r=parseInt(i.getPropertyValue("height")),s=Math.max(0,parseInt(i.getPropertyValue("width"))),n=window.getComputedStyle(this._terminal.element),o={top:parseInt(n.getPropertyValue("padding-top")),bottom:parseInt(n.getPropertyValue("padding-bottom")),right:parseInt(n.getPropertyValue("padding-right")),left:parseInt(n.getPropertyValue("padding-left"))},l=o.top+o.bottom,a=o.right+o.left,h=r-l,u=s-a-t;return{cols:Math.max(Q0,Math.floor(u/e.css.cell.width)),rows:Math.max(Z0,Math.floor(h/e.css.cell.height))}}};function ey(e,t=!1){return window.__TAURI_INTERNALS__.transformCallback(e,t)}async function pr(e,t={},i){return window.__TAURI_INTERNALS__.invoke(e,t,i)}var td;(function(e){e.WINDOW_RESIZED="tauri://resize",e.WINDOW_MOVED="tauri://move",e.WINDOW_CLOSE_REQUESTED="tauri://close-requested",e.WINDOW_DESTROYED="tauri://destroyed",e.WINDOW_FOCUS="tauri://focus",e.WINDOW_BLUR="tauri://blur",e.WINDOW_SCALE_FACTOR_CHANGED="tauri://scale-change",e.WINDOW_THEME_CHANGED="tauri://theme-changed",e.WINDOW_CREATED="tauri://window-created",e.WINDOW_SUSPENDED="tauri://suspended",e.WINDOW_RESUMED="tauri://resumed",e.WEBVIEW_CREATED="tauri://webview-created",e.DRAG_ENTER="tauri://drag-enter",e.DRAG_OVER="tauri://drag-over",e.DRAG_DROP="tauri://drag-drop",e.DRAG_LEAVE="tauri://drag-leave"})(td||(td={}));async function ty(e,t){window.__TAURI_EVENT_PLUGIN_INTERNALS__.unregisterListener(e,t),await pr("plugin:event|unlisten",{event:e,eventId:t})}async function id(e,t,i){var r;const s=(r=void 0)!==null&&r!==void 0?r:{kind:"Any"};return pr("plugin:event|listen",{event:e,target:s,handler:ey(t)}).then(n=>async()=>ty(e,n))}const tr={spawn:e=>pr("pty_spawn",{opts:e}),write:(e,t)=>pr("pty_write",{id:e,data:t}),resize:(e,t,i)=>pr("pty_resize",{id:e,cols:t,rows:i}),kill:e=>pr("pty_kill",{id:e}),onData:e=>id("pty:data",t=>e(t.payload)),onExit:e=>id("pty:exit",t=>e(t.payload))};function iy(e){let t="";for(let i=0;it(u)),s=oe.useRef(null),n=oe.useRef(null),o=oe.useRef(null),l=oe.useRef(e.ptyId),[a,h]=oe.useState(!1);return oe.useEffect(()=>{let u,c,d=!1;const g=new G0({fontSize:rd*i.scale,fontFamily:'Menlo, "Cascadia Code", Consolas, monospace',theme:{background:"#1d1d23",foreground:"#e8e8ec",cursor:"#e8e8ec"},cursorBlink:!0,allowProposedApi:!0}),v=new J0;return g.loadAddon(v),g.open(s.current),v.fit(),n.current=g,o.current=v,(async()=>{let m=l.current;if(!m){if(m=await tr.spawn({cols:g.cols,rows:g.rows}),d){await tr.kill(m);return}l.current=m,t({ptyId:m})}u=await tr.onData(k=>{k.id===m&&g.write(ry(k.data))}),c=await tr.onExit(k=>{k.id===m&&g.write(`\r +\x1B[2m[process exited]\x1B[0m\r +`)}),g.onData(k=>{tr.write(m,sy(k)).catch(_=>console.error("pty_write",_))}),g.onResize(({cols:k,rows:_})=>{tr.resize(m,k,_).catch(()=>{})}),h(!0)})(),()=>{d=!0,u==null||u(),c==null||c(),g.dispose()}},[]),oe.useEffect(()=>{if(!a)return;const u=n.current,c=o.current;!u||!c||(u.options.fontSize=rd*i.scale,c.fit())},[i.scale,a]),oe.useEffect(()=>{var u;a&&((u=o.current)==null||u.fit())},[e.width,e.height,a]),ue.jsxs("div",{className:"card terminal-card",style:{left:i.x+e.x*i.scale,top:i.y+e.y*i.scale,width:e.width*i.scale,height:e.height*i.scale,zIndex:e.z,"--scale":i.scale},children:[ue.jsx("div",{className:"card-header",...r,children:"terminal"}),ue.jsx("div",{className:"card-body terminal-body",ref:s,onPointerDown:u=>u.stopPropagation(),onWheel:u=>u.stopPropagation()})]})}const oy=.1,ly=4,ay=.0015;function hy({initialCards:e}){const[t,i]=oe.useState(e),[r,s]=oe.useState({x:0,y:0,scale:1}),[n,o]=oe.useState(!1),l=oe.useRef(null),a=oe.useRef(null),h=oe.useRef(e.reduce((f,p)=>Math.max(f,p.z),0));oe.useEffect(()=>{const f=S=>{S.code==="Space"&&!S.repeat&&o(!0)},p=S=>{S.code==="Space"&&o(!1)};return window.addEventListener("keydown",f),window.addEventListener("keyup",p),()=>{window.removeEventListener("keydown",f),window.removeEventListener("keyup",p)}},[]),oe.useEffect(()=>{const f=l.current;if(!f)return;const p=S=>{S.button===1&&S.preventDefault()};return f.addEventListener("mousedown",p),f.addEventListener("auxclick",p),()=>{f.removeEventListener("mousedown",p),f.removeEventListener("auxclick",p)}},[]);const u=oe.useCallback(f=>{if(!f.ctrlKey&&!f.metaKey)return;f.preventDefault();const p=l.current.getBoundingClientRect(),S=f.clientX-p.left,w=f.clientY-p.top;s(b=>{const R=Math.exp(-f.deltaY*ay),B=Math.max(oy,Math.min(ly,b.scale*R)),U=B/b.scale;return{x:S-(S-b.x)*U,y:w-(w-b.y)*U,scale:B}})},[]),c=f=>{var S;(f.button===1||f.button===0&&n)&&(f.preventDefault(),(S=l.current)==null||S.setPointerCapture(f.pointerId),a.current={startX:f.clientX,startY:f.clientY,vpX:r.x,vpY:r.y})},d=f=>{const p=a.current;if(!p)return;const S=p.vpX+(f.clientX-p.startX),w=p.vpY+(f.clientY-p.startY);s(b=>({...b,x:S,y:w}))},g=f=>{var p;if(a.current){try{(p=l.current)==null||p.releasePointerCapture(f.pointerId)}catch{}a.current=null}},v=(f,p)=>{i(S=>S.map(w=>w.id===f?{...w,...p}:w))},m=f=>{const p=window.innerWidth/2,S=window.innerHeight/2,w=(p-r.x)/r.scale,b=(S-r.y)/r.scale,R=crypto.randomUUID();h.current+=1;const B=f(R,w,b,h.current);i(U=>[...U,B])},k=()=>m((f,p,S,w)=>({id:f,kind:"note",x:p-160,y:S-90,width:320,height:180,z:w,text:""})),_=()=>m((f,p,S,w)=>({id:f,kind:"terminal",x:p-280,y:S-180,width:560,height:360,z:w,ptyId:""}));return ue.jsxs("div",{ref:l,className:`canvas-container ${n?"pan-mode":""} ${a.current?"panning":""}`,onWheel:u,onPointerDown:c,onPointerMove:d,onPointerUp:g,onPointerCancel:g,children:[ue.jsx("div",{className:"canvas-grid",style:{backgroundPosition:`${r.x}px ${r.y}px`,backgroundSize:`${40*r.scale}px ${40*r.scale}px`}}),ue.jsx(y_.Provider,{value:r,children:t.map(f=>f.kind==="note"?ue.jsx(Hv,{card:f,onUpdate:p=>v(f.id,p)},f.id):f.kind==="terminal"?ue.jsx(ny,{card:f,onUpdate:p=>v(f.id,p)},f.id):null)}),ue.jsxs("div",{className:"toolbar",children:[ue.jsx("button",{onClick:k,children:"+ Note"}),ue.jsx("button",{onClick:_,children:"+ Terminal"})]}),ue.jsxs("div",{className:"canvas-hud",children:[ue.jsxs("span",{children:["x ",r.x.toFixed(0)]}),ue.jsxs("span",{children:["y ",r.y.toFixed(0)]}),ue.jsxs("span",{children:[(r.scale*100).toFixed(0),"%"]})]})]})}const cy=[{id:"welcome",kind:"note",x:200,y:200,width:320,height:180,z:0,text:`Welcome to Infinite. + +Pan: middle-drag or space+drag. +Zoom: Ctrl+wheel.`},{id:"todo",kind:"note",x:600,y:320,width:260,height:140,z:0,text:"Next: terminal cards, then X11 embedding."}];function uy(){return ue.jsx(hy,{initialCards:cy})}vl.createRoot(document.getElementById("root")).render(ue.jsx(Rp.StrictMode,{children:ue.jsx(uy,{})})); diff --git a/dist/assets/index-BuGxqy5-.css b/dist/assets/index-BuGxqy5-.css new file mode 100644 index 0000000..94a5a05 --- /dev/null +++ b/dist/assets/index-BuGxqy5-.css @@ -0,0 +1,32 @@ +/** + * Copyright (c) 2014 The xterm.js authors. All rights reserved. + * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License) + * https://github.com/chjj/term.js + * @license MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * Originally forked from (with the author's permission): + * Fabrice Bellard's javascript vt100 for jslinux: + * http://bellard.org/jslinux/ + * Copyright (c) 2011 Fabrice Bellard + * The original design remains. The terminal itself + * has been extended to include xterm CSI codes, among + * other features. + */.xterm{cursor:text;position:relative;user-select:none;-ms-user-select:none;-webkit-user-select:none}.xterm.focus,.xterm:focus{outline:none}.xterm .xterm-helpers{position:absolute;top:0;z-index:5}.xterm .xterm-helper-textarea{padding:0;border:0;margin:0;position:absolute;opacity:0;left:-9999em;top:0;width:0;height:0;z-index:-5;white-space:nowrap;overflow:hidden;resize:none}.xterm .composition-view{background:#000;color:#fff;display:none;position:absolute;white-space:nowrap;z-index:1}.xterm .composition-view.active{display:block}.xterm .xterm-viewport{background-color:#000;overflow-y:scroll;cursor:default;position:absolute;right:0;left:0;top:0;bottom:0}.xterm .xterm-screen{position:relative}.xterm .xterm-screen canvas{position:absolute;left:0;top:0}.xterm-char-measure-element{display:inline-block;visibility:hidden;position:absolute;top:0;left:-9999em;line-height:normal}.xterm.enable-mouse-events{cursor:default}.xterm.xterm-cursor-pointer,.xterm .xterm-cursor-pointer{cursor:pointer}.xterm.column-select.focus{cursor:crosshair}.xterm .xterm-accessibility:not(.debug),.xterm .xterm-message{position:absolute;left:0;top:0;bottom:0;right:0;z-index:10;color:transparent;pointer-events:none}.xterm .xterm-accessibility-tree:not(.debug) *::selection{color:transparent}.xterm .xterm-accessibility-tree{font-family:monospace;-webkit-user-select:text;user-select:text;white-space:pre}.xterm .xterm-accessibility-tree>div{transform-origin:left;width:fit-content}.xterm .live-region{position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden}.xterm-dim{opacity:1!important}.xterm-underline-1{text-decoration:underline}.xterm-underline-2{text-decoration:double underline}.xterm-underline-3{text-decoration:wavy underline}.xterm-underline-4{text-decoration:dotted underline}.xterm-underline-5{text-decoration:dashed underline}.xterm-overline{text-decoration:overline}.xterm-overline.xterm-underline-1{text-decoration:overline underline}.xterm-overline.xterm-underline-2{text-decoration:overline double underline}.xterm-overline.xterm-underline-3{text-decoration:overline wavy underline}.xterm-overline.xterm-underline-4{text-decoration:overline dotted underline}.xterm-overline.xterm-underline-5{text-decoration:overline dashed underline}.xterm-strikethrough{text-decoration:line-through}.xterm-screen .xterm-decoration-container .xterm-decoration{z-index:6;position:absolute}.xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer{z-index:7}.xterm-decoration-overview-ruler{z-index:8;position:absolute;top:0;right:0;pointer-events:none}.xterm-decoration-top{z-index:2;position:relative}.xterm .xterm-scrollable-element>.scrollbar{cursor:default}.xterm .xterm-scrollable-element>.scrollbar>.scra{cursor:pointer;font-size:11px!important}.xterm .xterm-scrollable-element>.visible{opacity:1;background:#0000;transition:opacity .1s linear;z-index:11}.xterm .xterm-scrollable-element>.invisible{opacity:0;pointer-events:none}.xterm .xterm-scrollable-element>.invisible.fade{transition:opacity .8s linear}.xterm .xterm-scrollable-element>.shadow{position:absolute;display:none}.xterm .xterm-scrollable-element>.shadow.top{display:block;top:0;left:3px;height:3px;width:100%;box-shadow:var(--vscode-scrollbar-shadow, #000) 0 6px 6px -6px inset}.xterm .xterm-scrollable-element>.shadow.left{display:block;top:3px;left:0;height:100%;width:3px;box-shadow:var(--vscode-scrollbar-shadow, #000) 6px 0 6px -6px inset}.xterm .xterm-scrollable-element>.shadow.top-left-corner{display:block;top:0;left:0;height:3px;width:3px}.xterm .xterm-scrollable-element>.shadow.top.left{box-shadow:var(--vscode-scrollbar-shadow, #000) 6px 0 6px -6px inset}.canvas-container{position:fixed;top:0;right:0;bottom:0;left:0;overflow:hidden;cursor:default;background:var(--bg);touch-action:none;overscroll-behavior:contain}.canvas-container.pan-mode{cursor:grab}.canvas-container.panning{cursor:grabbing}.canvas-grid{position:absolute;top:0;right:0;bottom:0;left:0;pointer-events:none;background-image:radial-gradient(circle,var(--bg-grid) 1px,transparent 1px);background-repeat:repeat}.canvas-hud{position:fixed;bottom:12px;left:12px;display:flex;gap:12px;padding:6px 10px;background:#00000080;border-radius:6px;font-size:11px;font-family:ui-monospace,Menlo,monospace;color:var(--text);pointer-events:none;z-index:1000}.card{position:absolute;background:var(--card-bg);border:calc(1px * var(--scale, 1)) solid var(--card-border);border-radius:calc(8px * var(--scale, 1));box-shadow:0 calc(4px * var(--scale, 1)) calc(16px * var(--scale, 1)) #0000004d;overflow:hidden;display:flex;flex-direction:column}.card-header{padding:.46em .77em;background:#0003;border-bottom:calc(1px * var(--scale, 1)) solid var(--card-border);font-size:.85em;cursor:move;flex-shrink:0}.card-body{flex:1;overflow:auto}.note-card textarea{width:100%;height:100%;background:transparent;border:none;outline:none;resize:none;color:var(--text);font-family:inherit;font-size:1em;padding:.77em}.terminal-body{background:#1d1d23;padding:calc(4px * var(--scale, 1));height:100%}.terminal-body .xterm,.terminal-body .xterm-viewport,.terminal-body .xterm-screen{height:100%!important;width:100%!important}.toolbar{position:fixed;top:12px;left:12px;display:flex;gap:6px;padding:6px;background:#00000080;border-radius:8px;z-index:1000}.toolbar button{background:var(--card-bg);color:var(--text);border:1px solid var(--card-border);border-radius:5px;padding:6px 10px;font-size:12px;cursor:pointer;font-family:inherit}.toolbar button:hover{border-color:var(--accent)}:root{--bg: #1a1a1f;--bg-grid: #25252c;--card-bg: #2a2a32;--card-border: #3a3a45;--text: #e8e8ec;--accent: #6a8cff;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,sans-serif;color-scheme:dark}*{box-sizing:border-box;margin:0;padding:0}html,body,#root{width:100%;height:100%;overflow:hidden;background:var(--bg);color:var(--text);-webkit-user-select:none;user-select:none} diff --git a/dist/assets/index-CdDqLPP_.js b/dist/assets/index-CdDqLPP_.js deleted file mode 100644 index 7f468ac..0000000 --- a/dist/assets/index-CdDqLPP_.js +++ /dev/null @@ -1,43 +0,0 @@ -(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const l of document.querySelectorAll('link[rel="modulepreload"]'))r(l);new MutationObserver(l=>{for(const u of l)if(u.type==="childList")for(const o of u.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function n(l){const u={};return l.integrity&&(u.integrity=l.integrity),l.referrerPolicy&&(u.referrerPolicy=l.referrerPolicy),l.crossOrigin==="use-credentials"?u.credentials="include":l.crossOrigin==="anonymous"?u.credentials="omit":u.credentials="same-origin",u}function r(l){if(l.ep)return;l.ep=!0;const u=n(l);fetch(l.href,u)}})();function rc(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Hi={exports:{}},el={},Wi={exports:{}},T={};/** - * @license React - * react.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var Xn=Symbol.for("react.element"),lc=Symbol.for("react.portal"),uc=Symbol.for("react.fragment"),oc=Symbol.for("react.strict_mode"),ic=Symbol.for("react.profiler"),sc=Symbol.for("react.provider"),ac=Symbol.for("react.context"),cc=Symbol.for("react.forward_ref"),fc=Symbol.for("react.suspense"),dc=Symbol.for("react.memo"),pc=Symbol.for("react.lazy"),Do=Symbol.iterator;function mc(e){return e===null||typeof e!="object"?null:(e=Do&&e[Do]||e["@@iterator"],typeof e=="function"?e:null)}var Qi={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Yi=Object.assign,Ki={};function ln(e,t,n){this.props=e,this.context=t,this.refs=Ki,this.updater=n||Qi}ln.prototype.isReactComponent={};ln.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};ln.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function Xi(){}Xi.prototype=ln.prototype;function Uu(e,t,n){this.props=e,this.context=t,this.refs=Ki,this.updater=n||Qi}var $u=Uu.prototype=new Xi;$u.constructor=Uu;Yi($u,ln.prototype);$u.isPureReactComponent=!0;var Io=Array.isArray,Gi=Object.prototype.hasOwnProperty,Au={current:null},Zi={key:!0,ref:!0,__self:!0,__source:!0};function Ji(e,t,n){var r,l={},u=null,o=null;if(t!=null)for(r in t.ref!==void 0&&(o=t.ref),t.key!==void 0&&(u=""+t.key),t)Gi.call(t,r)&&!Zi.hasOwnProperty(r)&&(l[r]=t[r]);var i=arguments.length-2;if(i===1)l.children=n;else if(1>>1,X=x[H];if(0>>1;Hl(gl,L))ytl(er,gl)?(x[H]=er,x[yt]=L,H=yt):(x[H]=gl,x[ht]=L,H=ht);else if(ytl(er,L))x[H]=er,x[yt]=L,H=yt;else break e}}return z}function l(x,z){var L=x.sortIndex-z.sortIndex;return L!==0?L:x.id-z.id}if(typeof performance=="object"&&typeof performance.now=="function"){var u=performance;e.unstable_now=function(){return u.now()}}else{var o=Date,i=o.now();e.unstable_now=function(){return o.now()-i}}var s=[],f=[],h=1,m=null,p=3,S=!1,v=!1,w=!1,N=typeof setTimeout=="function"?setTimeout:null,c=typeof clearTimeout=="function"?clearTimeout:null,a=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function d(x){for(var z=n(f);z!==null;){if(z.callback===null)r(f);else if(z.startTime<=x)r(f),z.sortIndex=z.expirationTime,t(s,z);else break;z=n(f)}}function y(x){if(w=!1,d(x),!v)if(n(s)!==null)v=!0,hl(k);else{var z=n(f);z!==null&&yl(y,z.startTime-x)}}function k(x,z){v=!1,w&&(w=!1,c(P),P=-1),S=!0;var L=p;try{for(d(z),m=n(s);m!==null&&(!(m.expirationTime>z)||x&&!Ne());){var H=m.callback;if(typeof H=="function"){m.callback=null,p=m.priorityLevel;var X=H(m.expirationTime<=z);z=e.unstable_now(),typeof X=="function"?m.callback=X:m===n(s)&&r(s),d(z)}else r(s);m=n(s)}if(m!==null)var bn=!0;else{var ht=n(f);ht!==null&&yl(y,ht.startTime-z),bn=!1}return bn}finally{m=null,p=L,S=!1}}var C=!1,_=null,P=-1,B=5,R=-1;function Ne(){return!(e.unstable_now()-Rx||125H?(x.sortIndex=L,t(f,x),n(s)===null&&x===n(f)&&(w?(c(P),P=-1):w=!0,yl(y,L-H))):(x.sortIndex=X,t(s,x),v||S||(v=!0,hl(k))),x},e.unstable_shouldYield=Ne,e.unstable_wrapCallback=function(x){var z=p;return function(){var L=p;p=z;try{return x.apply(this,arguments)}finally{p=L}}}})(ns);ts.exports=ns;var Pc=ts.exports;/** - * @license React - * react-dom.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var Nc=ae,ge=Pc;function g(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Yl=Object.prototype.hasOwnProperty,zc=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,jo={},Uo={};function Lc(e){return Yl.call(Uo,e)?!0:Yl.call(jo,e)?!1:zc.test(e)?Uo[e]=!0:(jo[e]=!0,!1)}function Tc(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function Rc(e,t,n,r){if(t===null||typeof t>"u"||Tc(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function se(e,t,n,r,l,u,o){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=l,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=u,this.removeEmptyString=o}var b={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){b[e]=new se(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];b[t]=new se(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){b[e]=new se(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){b[e]=new se(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){b[e]=new se(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){b[e]=new se(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){b[e]=new se(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){b[e]=new se(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){b[e]=new se(e,5,!1,e.toLowerCase(),null,!1,!1)});var Bu=/[\-:]([a-z])/g;function Hu(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(Bu,Hu);b[t]=new se(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(Bu,Hu);b[t]=new se(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(Bu,Hu);b[t]=new se(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){b[e]=new se(e,1,!1,e.toLowerCase(),null,!1,!1)});b.xlinkHref=new se("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){b[e]=new se(e,1,!1,e.toLowerCase(),null,!0,!0)});function Wu(e,t,n,r){var l=b.hasOwnProperty(t)?b[t]:null;(l!==null?l.type!==0:r||!(2i||l[o]!==u[i]){var s=` -`+l[o].replace(" at new "," at ");return e.displayName&&s.includes("")&&(s=s.replace("",e.displayName)),s}while(1<=o&&0<=i);break}}}finally{kl=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?gn(e):""}function Oc(e){switch(e.tag){case 5:return gn(e.type);case 16:return gn("Lazy");case 13:return gn("Suspense");case 19:return gn("SuspenseList");case 0:case 2:case 15:return e=El(e.type,!1),e;case 11:return e=El(e.type.render,!1),e;case 1:return e=El(e.type,!0),e;default:return""}}function Zl(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case Dt:return"Fragment";case Mt:return"Portal";case Kl:return"Profiler";case Qu:return"StrictMode";case Xl:return"Suspense";case Gl:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case us:return(e.displayName||"Context")+".Consumer";case ls:return(e._context.displayName||"Context")+".Provider";case Yu:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case Ku:return t=e.displayName||null,t!==null?t:Zl(e.type)||"Memo";case Je:t=e._payload,e=e._init;try{return Zl(e(t))}catch{}}return null}function Mc(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return Zl(t);case 8:return t===Qu?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function ft(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function is(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function Dc(e){var t=is(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var l=n.get,u=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return l.call(this)},set:function(o){r=""+o,u.call(this,o)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(o){r=""+o},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function rr(e){e._valueTracker||(e._valueTracker=Dc(e))}function ss(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=is(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function Tr(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function Jl(e,t){var n=t.checked;return A({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function Ao(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=ft(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function as(e,t){t=t.checked,t!=null&&Wu(e,"checked",t,!1)}function ql(e,t){as(e,t);var n=ft(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?bl(e,t.type,n):t.hasOwnProperty("defaultValue")&&bl(e,t.type,ft(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function Vo(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function bl(e,t,n){(t!=="number"||Tr(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var wn=Array.isArray;function Qt(e,t,n,r){if(e=e.options,t){t={};for(var l=0;l"+t.valueOf().toString()+"",t=lr.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function On(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var En={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},Ic=["Webkit","ms","Moz","O"];Object.keys(En).forEach(function(e){Ic.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),En[t]=En[e]})});function ps(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||En.hasOwnProperty(e)&&En[e]?(""+t).trim():t+"px"}function ms(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,l=ps(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,l):e[n]=l}}var Fc=A({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function nu(e,t){if(t){if(Fc[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(g(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(g(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(g(61))}if(t.style!=null&&typeof t.style!="object")throw Error(g(62))}}function ru(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var lu=null;function Xu(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var uu=null,Yt=null,Kt=null;function Wo(e){if(e=Jn(e)){if(typeof uu!="function")throw Error(g(280));var t=e.stateNode;t&&(t=ul(t),uu(e.stateNode,e.type,t))}}function vs(e){Yt?Kt?Kt.push(e):Kt=[e]:Yt=e}function hs(){if(Yt){var e=Yt,t=Kt;if(Kt=Yt=null,Wo(e),t)for(e=0;e>>=0,e===0?32:31-(Kc(e)/Xc|0)|0}var ur=64,or=4194304;function Sn(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function Dr(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,l=e.suspendedLanes,u=e.pingedLanes,o=n&268435455;if(o!==0){var i=o&~l;i!==0?r=Sn(i):(u&=o,u!==0&&(r=Sn(u)))}else o=n&~l,o!==0?r=Sn(o):u!==0&&(r=Sn(u));if(r===0)return 0;if(t!==0&&t!==r&&!(t&l)&&(l=r&-r,u=t&-t,l>=u||l===16&&(u&4194240)!==0))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function Gn(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-Oe(t),e[t]=n}function qc(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=Cn),bo=" ",ei=!1;function Fs(e,t){switch(e){case"keyup":return Nf.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function js(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var It=!1;function Lf(e,t){switch(e){case"compositionend":return js(t);case"keypress":return t.which!==32?null:(ei=!0,bo);case"textInput":return e=t.data,e===bo&&ei?null:e;default:return null}}function Tf(e,t){if(It)return e==="compositionend"||!no&&Fs(e,t)?(e=Ds(),kr=bu=tt=null,It=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=li(n)}}function Vs(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Vs(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Bs(){for(var e=window,t=Tr();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=Tr(e.document)}return t}function ro(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function $f(e){var t=Bs(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&Vs(n.ownerDocument.documentElement,n)){if(r!==null&&ro(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var l=n.textContent.length,u=Math.min(r.start,l);r=r.end===void 0?u:Math.min(r.end,l),!e.extend&&u>r&&(l=r,r=u,u=l),l=ui(n,u);var o=ui(n,r);l&&o&&(e.rangeCount!==1||e.anchorNode!==l.node||e.anchorOffset!==l.offset||e.focusNode!==o.node||e.focusOffset!==o.offset)&&(t=t.createRange(),t.setStart(l.node,l.offset),e.removeAllRanges(),u>r?(e.addRange(t),e.extend(o.node,o.offset)):(t.setEnd(o.node,o.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,Ft=null,fu=null,Pn=null,du=!1;function oi(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;du||Ft==null||Ft!==Tr(r)||(r=Ft,"selectionStart"in r&&ro(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),Pn&&Un(Pn,r)||(Pn=r,r=jr(fu,"onSelect"),0$t||(e.current=gu[$t],gu[$t]=null,$t--)}function D(e,t){$t++,gu[$t]=e.current,e.current=t}var dt={},re=mt(dt),de=mt(!1),_t=dt;function qt(e,t){var n=e.type.contextTypes;if(!n)return dt;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var l={},u;for(u in n)l[u]=t[u];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=l),l}function pe(e){return e=e.childContextTypes,e!=null}function $r(){F(de),F(re)}function pi(e,t,n){if(re.current!==dt)throw Error(g(168));D(re,t),D(de,n)}function Js(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var l in r)if(!(l in t))throw Error(g(108,Mc(e)||"Unknown",l));return A({},n,r)}function Ar(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||dt,_t=re.current,D(re,e),D(de,de.current),!0}function mi(e,t,n){var r=e.stateNode;if(!r)throw Error(g(169));n?(e=Js(e,t,_t),r.__reactInternalMemoizedMergedChildContext=e,F(de),F(re),D(re,e)):F(de),D(de,n)}var Ve=null,ol=!1,Fl=!1;function qs(e){Ve===null?Ve=[e]:Ve.push(e)}function Jf(e){ol=!0,qs(e)}function vt(){if(!Fl&&Ve!==null){Fl=!0;var e=0,t=M;try{var n=Ve;for(M=1;e>=o,l-=o,Be=1<<32-Oe(t)+l|n<P?(B=_,_=null):B=_.sibling;var R=p(c,_,d[P],y);if(R===null){_===null&&(_=B);break}e&&_&&R.alternate===null&&t(c,_),a=u(R,a,P),C===null?k=R:C.sibling=R,C=R,_=B}if(P===d.length)return n(c,_),j&>(c,P),k;if(_===null){for(;PP?(B=_,_=null):B=_.sibling;var Ne=p(c,_,R.value,y);if(Ne===null){_===null&&(_=B);break}e&&_&&Ne.alternate===null&&t(c,_),a=u(Ne,a,P),C===null?k=Ne:C.sibling=Ne,C=Ne,_=B}if(R.done)return n(c,_),j&>(c,P),k;if(_===null){for(;!R.done;P++,R=d.next())R=m(c,R.value,y),R!==null&&(a=u(R,a,P),C===null?k=R:C.sibling=R,C=R);return j&>(c,P),k}for(_=r(c,_);!R.done;P++,R=d.next())R=S(_,c,P,R.value,y),R!==null&&(e&&R.alternate!==null&&_.delete(R.key===null?P:R.key),a=u(R,a,P),C===null?k=R:C.sibling=R,C=R);return e&&_.forEach(function(sn){return t(c,sn)}),j&>(c,P),k}function N(c,a,d,y){if(typeof d=="object"&&d!==null&&d.type===Dt&&d.key===null&&(d=d.props.children),typeof d=="object"&&d!==null){switch(d.$$typeof){case nr:e:{for(var k=d.key,C=a;C!==null;){if(C.key===k){if(k=d.type,k===Dt){if(C.tag===7){n(c,C.sibling),a=l(C,d.props.children),a.return=c,c=a;break e}}else if(C.elementType===k||typeof k=="object"&&k!==null&&k.$$typeof===Je&&yi(k)===C.type){n(c,C.sibling),a=l(C,d.props),a.ref=vn(c,C,d),a.return=c,c=a;break e}n(c,C);break}else t(c,C);C=C.sibling}d.type===Dt?(a=Ct(d.props.children,c.mode,y,d.key),a.return=c,c=a):(y=Lr(d.type,d.key,d.props,null,c.mode,y),y.ref=vn(c,a,d),y.return=c,c=y)}return o(c);case Mt:e:{for(C=d.key;a!==null;){if(a.key===C)if(a.tag===4&&a.stateNode.containerInfo===d.containerInfo&&a.stateNode.implementation===d.implementation){n(c,a.sibling),a=l(a,d.children||[]),a.return=c,c=a;break e}else{n(c,a);break}else t(c,a);a=a.sibling}a=Wl(d,c.mode,y),a.return=c,c=a}return o(c);case Je:return C=d._init,N(c,a,C(d._payload),y)}if(wn(d))return v(c,a,d,y);if(cn(d))return w(c,a,d,y);pr(c,d)}return typeof d=="string"&&d!==""||typeof d=="number"?(d=""+d,a!==null&&a.tag===6?(n(c,a.sibling),a=l(a,d),a.return=c,c=a):(n(c,a),a=Hl(d,c.mode,y),a.return=c,c=a),o(c)):n(c,a)}return N}var en=na(!0),ra=na(!1),Hr=mt(null),Wr=null,Bt=null,io=null;function so(){io=Bt=Wr=null}function ao(e){var t=Hr.current;F(Hr),e._currentValue=t}function ku(e,t,n){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,r!==null&&(r.childLanes|=t)):r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===n)break;e=e.return}}function Gt(e,t){Wr=e,io=Bt=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(fe=!0),e.firstContext=null)}function _e(e){var t=e._currentValue;if(io!==e)if(e={context:e,memoizedValue:t,next:null},Bt===null){if(Wr===null)throw Error(g(308));Bt=e,Wr.dependencies={lanes:0,firstContext:e}}else Bt=Bt.next=e;return t}var kt=null;function co(e){kt===null?kt=[e]:kt.push(e)}function la(e,t,n,r){var l=t.interleaved;return l===null?(n.next=n,co(t)):(n.next=l.next,l.next=n),t.interleaved=n,Ke(e,r)}function Ke(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var qe=!1;function fo(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function ua(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function We(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function it(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,O&2){var l=r.pending;return l===null?t.next=t:(t.next=l.next,l.next=t),r.pending=t,Ke(e,n)}return l=r.interleaved,l===null?(t.next=t,co(r)):(t.next=l.next,l.next=t),r.interleaved=t,Ke(e,n)}function xr(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Zu(e,n)}}function gi(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var l=null,u=null;if(n=n.firstBaseUpdate,n!==null){do{var o={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};u===null?l=u=o:u=u.next=o,n=n.next}while(n!==null);u===null?l=u=t:u=u.next=t}else l=u=t;n={baseState:r.baseState,firstBaseUpdate:l,lastBaseUpdate:u,shared:r.shared,effects:r.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function Qr(e,t,n,r){var l=e.updateQueue;qe=!1;var u=l.firstBaseUpdate,o=l.lastBaseUpdate,i=l.shared.pending;if(i!==null){l.shared.pending=null;var s=i,f=s.next;s.next=null,o===null?u=f:o.next=f,o=s;var h=e.alternate;h!==null&&(h=h.updateQueue,i=h.lastBaseUpdate,i!==o&&(i===null?h.firstBaseUpdate=f:i.next=f,h.lastBaseUpdate=s))}if(u!==null){var m=l.baseState;o=0,h=f=s=null,i=u;do{var p=i.lane,S=i.eventTime;if((r&p)===p){h!==null&&(h=h.next={eventTime:S,lane:0,tag:i.tag,payload:i.payload,callback:i.callback,next:null});e:{var v=e,w=i;switch(p=t,S=n,w.tag){case 1:if(v=w.payload,typeof v=="function"){m=v.call(S,m,p);break e}m=v;break e;case 3:v.flags=v.flags&-65537|128;case 0:if(v=w.payload,p=typeof v=="function"?v.call(S,m,p):v,p==null)break e;m=A({},m,p);break e;case 2:qe=!0}}i.callback!==null&&i.lane!==0&&(e.flags|=64,p=l.effects,p===null?l.effects=[i]:p.push(i))}else S={eventTime:S,lane:p,tag:i.tag,payload:i.payload,callback:i.callback,next:null},h===null?(f=h=S,s=m):h=h.next=S,o|=p;if(i=i.next,i===null){if(i=l.shared.pending,i===null)break;p=i,i=p.next,p.next=null,l.lastBaseUpdate=p,l.shared.pending=null}}while(!0);if(h===null&&(s=m),l.baseState=s,l.firstBaseUpdate=f,l.lastBaseUpdate=h,t=l.shared.interleaved,t!==null){l=t;do o|=l.lane,l=l.next;while(l!==t)}else u===null&&(l.shared.lanes=0);zt|=o,e.lanes=o,e.memoizedState=m}}function wi(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=Ul.transition;Ul.transition={};try{e(!1),t()}finally{M=n,Ul.transition=r}}function Ea(){return Pe().memoizedState}function td(e,t,n){var r=at(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},xa(e))Ca(t,n);else if(n=la(e,t,n,r),n!==null){var l=oe();Me(n,e,r,l),_a(n,t,r)}}function nd(e,t,n){var r=at(e),l={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(xa(e))Ca(t,l);else{var u=e.alternate;if(e.lanes===0&&(u===null||u.lanes===0)&&(u=t.lastRenderedReducer,u!==null))try{var o=t.lastRenderedState,i=u(o,n);if(l.hasEagerState=!0,l.eagerState=i,De(i,o)){var s=t.interleaved;s===null?(l.next=l,co(t)):(l.next=s.next,s.next=l),t.interleaved=l;return}}catch{}finally{}n=la(e,t,l,r),n!==null&&(l=oe(),Me(n,e,r,l),_a(n,t,r))}}function xa(e){var t=e.alternate;return e===$||t!==null&&t===$}function Ca(e,t){Nn=Kr=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function _a(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Zu(e,n)}}var Xr={readContext:_e,useCallback:ee,useContext:ee,useEffect:ee,useImperativeHandle:ee,useInsertionEffect:ee,useLayoutEffect:ee,useMemo:ee,useReducer:ee,useRef:ee,useState:ee,useDebugValue:ee,useDeferredValue:ee,useTransition:ee,useMutableSource:ee,useSyncExternalStore:ee,useId:ee,unstable_isNewReconciler:!1},rd={readContext:_e,useCallback:function(e,t){return Fe().memoizedState=[e,t===void 0?null:t],e},useContext:_e,useEffect:ki,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,_r(4194308,4,ya.bind(null,t,e),n)},useLayoutEffect:function(e,t){return _r(4194308,4,e,t)},useInsertionEffect:function(e,t){return _r(4,2,e,t)},useMemo:function(e,t){var n=Fe();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=Fe();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=td.bind(null,$,e),[r.memoizedState,e]},useRef:function(e){var t=Fe();return e={current:e},t.memoizedState=e},useState:Si,useDebugValue:So,useDeferredValue:function(e){return Fe().memoizedState=e},useTransition:function(){var e=Si(!1),t=e[0];return e=ed.bind(null,e[1]),Fe().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=$,l=Fe();if(j){if(n===void 0)throw Error(g(407));n=n()}else{if(n=t(),Z===null)throw Error(g(349));Nt&30||aa(r,t,n)}l.memoizedState=n;var u={value:n,getSnapshot:t};return l.queue=u,ki(fa.bind(null,r,u,e),[e]),r.flags|=2048,Yn(9,ca.bind(null,r,u,n,t),void 0,null),n},useId:function(){var e=Fe(),t=Z.identifierPrefix;if(j){var n=He,r=Be;n=(r&~(1<<32-Oe(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=Wn++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=o.createElement(n,{is:r.is}):(e=o.createElement(n),n==="select"&&(o=e,r.multiple?o.multiple=!0:r.size&&(o.size=r.size))):e=o.createElementNS(e,n),e[je]=t,e[Vn]=r,Ia(e,t,!1,!1),t.stateNode=e;e:{switch(o=ru(n,r),n){case"dialog":I("cancel",e),I("close",e),l=r;break;case"iframe":case"object":case"embed":I("load",e),l=r;break;case"video":case"audio":for(l=0;lrn&&(t.flags|=128,r=!0,hn(u,!1),t.lanes=4194304)}else{if(!r)if(e=Yr(o),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),hn(u,!0),u.tail===null&&u.tailMode==="hidden"&&!o.alternate&&!j)return te(t),null}else 2*W()-u.renderingStartTime>rn&&n!==1073741824&&(t.flags|=128,r=!0,hn(u,!1),t.lanes=4194304);u.isBackwards?(o.sibling=t.child,t.child=o):(n=u.last,n!==null?n.sibling=o:t.child=o,u.last=o)}return u.tail!==null?(t=u.tail,u.rendering=t,u.tail=t.sibling,u.renderingStartTime=W(),t.sibling=null,n=U.current,D(U,r?n&1|2:n&1),t):(te(t),null);case 22:case 23:return Po(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?ve&1073741824&&(te(t),t.subtreeFlags&6&&(t.flags|=8192)):te(t),null;case 24:return null;case 25:return null}throw Error(g(156,t.tag))}function fd(e,t){switch(uo(t),t.tag){case 1:return pe(t.type)&&$r(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return tn(),F(de),F(re),vo(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return mo(t),null;case 13:if(F(U),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(g(340));bt()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return F(U),null;case 4:return tn(),null;case 10:return ao(t.type._context),null;case 22:case 23:return Po(),null;case 24:return null;default:return null}}var vr=!1,ne=!1,dd=typeof WeakSet=="function"?WeakSet:Set,E=null;function Ht(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){V(e,t,r)}else n.current=null}function Tu(e,t,n){try{n()}catch(r){V(e,t,r)}}var Oi=!1;function pd(e,t){if(pu=Ir,e=Bs(),ro(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var l=r.anchorOffset,u=r.focusNode;r=r.focusOffset;try{n.nodeType,u.nodeType}catch{n=null;break e}var o=0,i=-1,s=-1,f=0,h=0,m=e,p=null;t:for(;;){for(var S;m!==n||l!==0&&m.nodeType!==3||(i=o+l),m!==u||r!==0&&m.nodeType!==3||(s=o+r),m.nodeType===3&&(o+=m.nodeValue.length),(S=m.firstChild)!==null;)p=m,m=S;for(;;){if(m===e)break t;if(p===n&&++f===l&&(i=o),p===u&&++h===r&&(s=o),(S=m.nextSibling)!==null)break;m=p,p=m.parentNode}m=S}n=i===-1||s===-1?null:{start:i,end:s}}else n=null}n=n||{start:0,end:0}}else n=null;for(mu={focusedElem:e,selectionRange:n},Ir=!1,E=t;E!==null;)if(t=E,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,E=e;else for(;E!==null;){t=E;try{var v=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(v!==null){var w=v.memoizedProps,N=v.memoizedState,c=t.stateNode,a=c.getSnapshotBeforeUpdate(t.elementType===t.type?w:Le(t.type,w),N);c.__reactInternalSnapshotBeforeUpdate=a}break;case 3:var d=t.stateNode.containerInfo;d.nodeType===1?d.textContent="":d.nodeType===9&&d.documentElement&&d.removeChild(d.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(g(163))}}catch(y){V(t,t.return,y)}if(e=t.sibling,e!==null){e.return=t.return,E=e;break}E=t.return}return v=Oi,Oi=!1,v}function zn(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var l=r=r.next;do{if((l.tag&e)===e){var u=l.destroy;l.destroy=void 0,u!==void 0&&Tu(t,n,u)}l=l.next}while(l!==r)}}function al(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function Ru(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function Ua(e){var t=e.alternate;t!==null&&(e.alternate=null,Ua(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[je],delete t[Vn],delete t[yu],delete t[Gf],delete t[Zf])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function $a(e){return e.tag===5||e.tag===3||e.tag===4}function Mi(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||$a(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Ou(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=Ur));else if(r!==4&&(e=e.child,e!==null))for(Ou(e,t,n),e=e.sibling;e!==null;)Ou(e,t,n),e=e.sibling}function Mu(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(Mu(e,t,n),e=e.sibling;e!==null;)Mu(e,t,n),e=e.sibling}var J=null,Te=!1;function Ze(e,t,n){for(n=n.child;n!==null;)Aa(e,t,n),n=n.sibling}function Aa(e,t,n){if(Ue&&typeof Ue.onCommitFiberUnmount=="function")try{Ue.onCommitFiberUnmount(tl,n)}catch{}switch(n.tag){case 5:ne||Ht(n,t);case 6:var r=J,l=Te;J=null,Ze(e,t,n),J=r,Te=l,J!==null&&(Te?(e=J,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):J.removeChild(n.stateNode));break;case 18:J!==null&&(Te?(e=J,n=n.stateNode,e.nodeType===8?Il(e.parentNode,n):e.nodeType===1&&Il(e,n),Fn(e)):Il(J,n.stateNode));break;case 4:r=J,l=Te,J=n.stateNode.containerInfo,Te=!0,Ze(e,t,n),J=r,Te=l;break;case 0:case 11:case 14:case 15:if(!ne&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){l=r=r.next;do{var u=l,o=u.destroy;u=u.tag,o!==void 0&&(u&2||u&4)&&Tu(n,t,o),l=l.next}while(l!==r)}Ze(e,t,n);break;case 1:if(!ne&&(Ht(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(i){V(n,t,i)}Ze(e,t,n);break;case 21:Ze(e,t,n);break;case 22:n.mode&1?(ne=(r=ne)||n.memoizedState!==null,Ze(e,t,n),ne=r):Ze(e,t,n);break;default:Ze(e,t,n)}}function Di(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new dd),t.forEach(function(r){var l=Ed.bind(null,e,r);n.has(r)||(n.add(r),r.then(l,l))})}}function ze(e,t){var n=t.deletions;if(n!==null)for(var r=0;rl&&(l=o),r&=~u}if(r=l,r=W()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*vd(r/1960))-r,10e?16:e,nt===null)var r=!1;else{if(e=nt,nt=null,Jr=0,O&6)throw Error(g(331));var l=O;for(O|=4,E=e.current;E!==null;){var u=E,o=u.child;if(E.flags&16){var i=u.deletions;if(i!==null){for(var s=0;sW()-Co?xt(e,0):xo|=n),me(e,t)}function Xa(e,t){t===0&&(e.mode&1?(t=or,or<<=1,!(or&130023424)&&(or=4194304)):t=1);var n=oe();e=Ke(e,t),e!==null&&(Gn(e,t,n),me(e,n))}function kd(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),Xa(e,n)}function Ed(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,l=e.memoizedState;l!==null&&(n=l.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(g(314))}r!==null&&r.delete(t),Xa(e,n)}var Ga;Ga=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||de.current)fe=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return fe=!1,ad(e,t,n);fe=!!(e.flags&131072)}else fe=!1,j&&t.flags&1048576&&bs(t,Br,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Pr(e,t),e=t.pendingProps;var l=qt(t,re.current);Gt(t,n),l=yo(null,t,r,e,l,n);var u=go();return t.flags|=1,typeof l=="object"&&l!==null&&typeof l.render=="function"&&l.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,pe(r)?(u=!0,Ar(t)):u=!1,t.memoizedState=l.state!==null&&l.state!==void 0?l.state:null,fo(t),l.updater=sl,t.stateNode=l,l._reactInternals=t,xu(t,r,e,n),t=Pu(null,t,r,!0,u,n)):(t.tag=0,j&&u&&lo(t),le(null,t,l,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Pr(e,t),e=t.pendingProps,l=r._init,r=l(r._payload),t.type=r,l=t.tag=Cd(r),e=Le(r,e),l){case 0:t=_u(null,t,r,e,n);break e;case 1:t=Li(null,t,r,e,n);break e;case 11:t=Ni(null,t,r,e,n);break e;case 14:t=zi(null,t,r,Le(r.type,e),n);break e}throw Error(g(306,r,""))}return t;case 0:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Le(r,l),_u(e,t,r,l,n);case 1:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Le(r,l),Li(e,t,r,l,n);case 3:e:{if(Oa(t),e===null)throw Error(g(387));r=t.pendingProps,u=t.memoizedState,l=u.element,ua(e,t),Qr(t,r,null,n);var o=t.memoizedState;if(r=o.element,u.isDehydrated)if(u={element:r,isDehydrated:!1,cache:o.cache,pendingSuspenseBoundaries:o.pendingSuspenseBoundaries,transitions:o.transitions},t.updateQueue.baseState=u,t.memoizedState=u,t.flags&256){l=nn(Error(g(423)),t),t=Ti(e,t,r,n,l);break e}else if(r!==l){l=nn(Error(g(424)),t),t=Ti(e,t,r,n,l);break e}else for(he=ot(t.stateNode.containerInfo.firstChild),ye=t,j=!0,Re=null,n=ra(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(bt(),r===l){t=Xe(e,t,n);break e}le(e,t,r,n)}t=t.child}return t;case 5:return oa(t),e===null&&Su(t),r=t.type,l=t.pendingProps,u=e!==null?e.memoizedProps:null,o=l.children,vu(r,l)?o=null:u!==null&&vu(r,u)&&(t.flags|=32),Ra(e,t),le(e,t,o,n),t.child;case 6:return e===null&&Su(t),null;case 13:return Ma(e,t,n);case 4:return po(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=en(t,null,r,n):le(e,t,r,n),t.child;case 11:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Le(r,l),Ni(e,t,r,l,n);case 7:return le(e,t,t.pendingProps,n),t.child;case 8:return le(e,t,t.pendingProps.children,n),t.child;case 12:return le(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,l=t.pendingProps,u=t.memoizedProps,o=l.value,D(Hr,r._currentValue),r._currentValue=o,u!==null)if(De(u.value,o)){if(u.children===l.children&&!de.current){t=Xe(e,t,n);break e}}else for(u=t.child,u!==null&&(u.return=t);u!==null;){var i=u.dependencies;if(i!==null){o=u.child;for(var s=i.firstContext;s!==null;){if(s.context===r){if(u.tag===1){s=We(-1,n&-n),s.tag=2;var f=u.updateQueue;if(f!==null){f=f.shared;var h=f.pending;h===null?s.next=s:(s.next=h.next,h.next=s),f.pending=s}}u.lanes|=n,s=u.alternate,s!==null&&(s.lanes|=n),ku(u.return,n,t),i.lanes|=n;break}s=s.next}}else if(u.tag===10)o=u.type===t.type?null:u.child;else if(u.tag===18){if(o=u.return,o===null)throw Error(g(341));o.lanes|=n,i=o.alternate,i!==null&&(i.lanes|=n),ku(o,n,t),o=u.sibling}else o=u.child;if(o!==null)o.return=u;else for(o=u;o!==null;){if(o===t){o=null;break}if(u=o.sibling,u!==null){u.return=o.return,o=u;break}o=o.return}u=o}le(e,t,l.children,n),t=t.child}return t;case 9:return l=t.type,r=t.pendingProps.children,Gt(t,n),l=_e(l),r=r(l),t.flags|=1,le(e,t,r,n),t.child;case 14:return r=t.type,l=Le(r,t.pendingProps),l=Le(r.type,l),zi(e,t,r,l,n);case 15:return La(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Le(r,l),Pr(e,t),t.tag=1,pe(r)?(e=!0,Ar(t)):e=!1,Gt(t,n),Pa(t,r,l),xu(t,r,l,n),Pu(null,t,r,!0,e,n);case 19:return Da(e,t,n);case 22:return Ta(e,t,n)}throw Error(g(156,t.tag))};function Za(e,t){return xs(e,t)}function xd(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function xe(e,t,n,r){return new xd(e,t,n,r)}function zo(e){return e=e.prototype,!(!e||!e.isReactComponent)}function Cd(e){if(typeof e=="function")return zo(e)?1:0;if(e!=null){if(e=e.$$typeof,e===Yu)return 11;if(e===Ku)return 14}return 2}function ct(e,t){var n=e.alternate;return n===null?(n=xe(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function Lr(e,t,n,r,l,u){var o=2;if(r=e,typeof e=="function")zo(e)&&(o=1);else if(typeof e=="string")o=5;else e:switch(e){case Dt:return Ct(n.children,l,u,t);case Qu:o=8,l|=8;break;case Kl:return e=xe(12,n,t,l|2),e.elementType=Kl,e.lanes=u,e;case Xl:return e=xe(13,n,t,l),e.elementType=Xl,e.lanes=u,e;case Gl:return e=xe(19,n,t,l),e.elementType=Gl,e.lanes=u,e;case os:return fl(n,l,u,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case ls:o=10;break e;case us:o=9;break e;case Yu:o=11;break e;case Ku:o=14;break e;case Je:o=16,r=null;break e}throw Error(g(130,e==null?e:typeof e,""))}return t=xe(o,n,t,l),t.elementType=e,t.type=r,t.lanes=u,t}function Ct(e,t,n,r){return e=xe(7,e,r,t),e.lanes=n,e}function fl(e,t,n,r){return e=xe(22,e,r,t),e.elementType=os,e.lanes=n,e.stateNode={isHidden:!1},e}function Hl(e,t,n){return e=xe(6,e,null,t),e.lanes=n,e}function Wl(e,t,n){return t=xe(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function _d(e,t,n,r,l){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Cl(0),this.expirationTimes=Cl(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Cl(0),this.identifierPrefix=r,this.onRecoverableError=l,this.mutableSourceEagerHydrationData=null}function Lo(e,t,n,r,l,u,o,i,s){return e=new _d(e,t,n,i,s),t===1?(t=1,u===!0&&(t|=8)):t=0,u=xe(3,null,null,t),e.current=u,u.stateNode=e,u.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},fo(u),e}function Pd(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(ec)}catch(e){console.error(e)}}ec(),es.exports=we;var Rd=es.exports,Bi=Rd;Ql.createRoot=Bi.createRoot,Ql.hydrateRoot=Bi.hydrateRoot;const tc=ae.createContext({x:0,y:0,scale:1}),Od=()=>ae.useContext(tc),Md=13;function Dd({card:e,onUpdate:t}){const n=Od(),r=ae.useRef(null),l=m=>{m.button===0&&(m.stopPropagation(),m.target.setPointerCapture(m.pointerId),r.current={startX:m.clientX,startY:m.clientY,cardX:e.x,cardY:e.y})},u=m=>{const p=r.current;if(!p)return;const S=(m.clientX-p.startX)/n.scale,v=(m.clientY-p.startY)/n.scale;t({x:p.cardX+S,y:p.cardY+v})},o=m=>{if(r.current){try{m.target.releasePointerCapture(m.pointerId)}catch{}r.current=null}},i=n.x+e.x*n.scale,s=n.y+e.y*n.scale,f=e.width*n.scale,h=e.height*n.scale;return ue.jsxs("div",{className:"card note-card",style:{left:i,top:s,width:f,height:h,zIndex:e.z,fontSize:Md*n.scale,"--scale":n.scale},children:[ue.jsx("div",{className:"card-header",onPointerDown:l,onPointerMove:u,onPointerUp:o,onPointerCancel:o,children:"note"}),ue.jsx("div",{className:"card-body",children:ue.jsx("textarea",{value:e.text,onChange:m=>t({text:m.target.value}),onPointerDown:m=>m.stopPropagation()})})]})}const Id=.1,Fd=4,jd=.0015;function Ud({initialCards:e}){const[t,n]=ae.useState(e),[r,l]=ae.useState({x:0,y:0,scale:1}),[u,o]=ae.useState(!1),i=ae.useRef(null),s=ae.useRef(null);ae.useEffect(()=>{const v=N=>{N.code==="Space"&&!N.repeat&&o(!0)},w=N=>{N.code==="Space"&&o(!1)};return window.addEventListener("keydown",v),window.addEventListener("keyup",w),()=>{window.removeEventListener("keydown",v),window.removeEventListener("keyup",w)}},[]),ae.useEffect(()=>{const v=i.current;if(!v)return;const w=c=>{c.button===1&&c.preventDefault()},N=c=>{c.button===1&&c.preventDefault()};return v.addEventListener("mousedown",w),v.addEventListener("auxclick",N),()=>{v.removeEventListener("mousedown",w),v.removeEventListener("auxclick",N)}},[]);const f=ae.useCallback(v=>{if(!v.ctrlKey&&!v.metaKey)return;v.preventDefault();const w=i.current.getBoundingClientRect(),N=v.clientX-w.left,c=v.clientY-w.top;l(a=>{const d=Math.exp(-v.deltaY*jd),y=Math.max(Id,Math.min(Fd,a.scale*d)),k=y/a.scale;return{x:N-(N-a.x)*k,y:c-(c-a.y)*k,scale:y}})},[]),h=v=>{var N;(v.button===1||v.button===0&&u)&&(v.preventDefault(),(N=i.current)==null||N.setPointerCapture(v.pointerId),s.current={startX:v.clientX,startY:v.clientY,vpX:r.x,vpY:r.y})},m=v=>{const w=s.current;if(!w)return;const N=w.vpX+(v.clientX-w.startX),c=w.vpY+(v.clientY-w.startY);l(a=>({...a,x:N,y:c}))},p=v=>{var w;if(s.current){try{(w=i.current)==null||w.releasePointerCapture(v.pointerId)}catch{}s.current=null}},S=(v,w)=>{n(N=>N.map(c=>c.id===v?{...c,...w}:c))};return ue.jsxs("div",{ref:i,className:`canvas-container ${u?"pan-mode":""} ${s.current?"panning":""}`,onWheel:f,onPointerDown:h,onPointerMove:m,onPointerUp:p,onPointerCancel:p,children:[ue.jsx("div",{className:"canvas-grid",style:{backgroundPosition:`${r.x}px ${r.y}px`,backgroundSize:`${40*r.scale}px ${40*r.scale}px`}}),ue.jsx(tc.Provider,{value:r,children:t.map(v=>v.kind==="note"?ue.jsx(Dd,{card:v,onUpdate:w=>S(v.id,w)},v.id):null)}),ue.jsxs("div",{className:"canvas-hud",children:[ue.jsxs("span",{children:["x ",r.x.toFixed(0)]}),ue.jsxs("span",{children:["y ",r.y.toFixed(0)]}),ue.jsxs("span",{children:[(r.scale*100).toFixed(0),"%"]})]})]})}const $d=[{id:"welcome",kind:"note",x:200,y:200,width:320,height:180,z:0,text:`Welcome to Infinite. - -Pan: middle-drag or space+drag. -Zoom: Ctrl+wheel.`},{id:"todo",kind:"note",x:600,y:320,width:260,height:140,z:0,text:"Next: terminal cards, then X11 embedding."}];function Ad(){return ue.jsx(Ud,{initialCards:$d})}Ql.createRoot(document.getElementById("root")).render(ue.jsx(wc.StrictMode,{children:ue.jsx(Ad,{})})); diff --git a/dist/index.html b/dist/index.html index 75360b3..2541c2c 100644 --- a/dist/index.html +++ b/dist/index.html @@ -4,8 +4,8 @@ Infinite - - + +
diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json index 87fd615..3c2ebec 100644 --- a/node_modules/.package-lock.json +++ b/node_modules/.package-lock.json @@ -404,6 +404,20 @@ "linux" ] }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.60.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.60.4.tgz", + "integrity": "sha512-+qfSY27qIrFfI/Hom04KYFw3GKZSGU4lXus51wsb5EuySfFlWRwjkKWoE9emgRw/ukoT4Udsj4W/+xxG8VbPKg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, "node_modules/@tauri-apps/api": { "version": "2.11.0", "resolved": "https://registry.npmjs.org/@tauri-apps/api/-/api-2.11.0.tgz", @@ -591,6 +605,21 @@ "vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0" } }, + "node_modules/@xterm/addon-fit": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/@xterm/addon-fit/-/addon-fit-0.11.0.tgz", + "integrity": "sha512-jYcgT6xtVYhnhgxh3QgYDnnNMYTcf8ElbxxFzX0IZo+vabQqSPAjC3c1wJrKB5E19VwQei89QCiZZP86DCPF7g==", + "license": "MIT" + }, + "node_modules/@xterm/xterm": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/@xterm/xterm/-/xterm-6.0.0.tgz", + "integrity": "sha512-TQwDdQGtwwDt+2cgKDLn0IRaSxYu1tSUjgKarSDkUM0ZNiSRXFpjxEsvc/Zgc5kq5omJ+V0a8/kIM2WD3sMOYg==", + "license": "MIT", + "workspaces": [ + "addons/*" + ] + }, "node_modules/baseline-browser-mapping": { "version": "2.10.29", "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.10.29.tgz", diff --git a/node_modules/@rollup/rollup-linux-x64-musl/README.md b/node_modules/@rollup/rollup-linux-x64-musl/README.md new file mode 100644 index 0000000..5848a6c --- /dev/null +++ b/node_modules/@rollup/rollup-linux-x64-musl/README.md @@ -0,0 +1,3 @@ +# `@rollup/rollup-linux-x64-musl` + +This is the **x86_64-unknown-linux-musl** binary for `rollup` diff --git a/node_modules/@rollup/rollup-linux-x64-musl/package.json b/node_modules/@rollup/rollup-linux-x64-musl/package.json new file mode 100644 index 0000000..2ffc024 --- /dev/null +++ b/node_modules/@rollup/rollup-linux-x64-musl/package.json @@ -0,0 +1,25 @@ +{ + "name": "@rollup/rollup-linux-x64-musl", + "version": "4.60.4", + "os": [ + "linux" + ], + "cpu": [ + "x64" + ], + "files": [ + "rollup.linux-x64-musl.node" + ], + "description": "Native bindings for Rollup", + "author": "Lukas Taegert-Atkinson", + "homepage": "https://rollupjs.org/", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/rollup/rollup.git" + }, + "libc": [ + "musl" + ], + "main": "./rollup.linux-x64-musl.node" +} \ No newline at end of file diff --git a/node_modules/@rollup/rollup-linux-x64-musl/rollup.linux-x64-musl.node b/node_modules/@rollup/rollup-linux-x64-musl/rollup.linux-x64-musl.node new file mode 100644 index 0000000..947c65c Binary files /dev/null and b/node_modules/@rollup/rollup-linux-x64-musl/rollup.linux-x64-musl.node differ diff --git a/node_modules/@xterm/addon-fit/LICENSE b/node_modules/@xterm/addon-fit/LICENSE new file mode 100644 index 0000000..8f17892 --- /dev/null +++ b/node_modules/@xterm/addon-fit/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2019, The xterm.js authors (https://github.com/xtermjs/xterm.js) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/@xterm/addon-fit/README.md b/node_modules/@xterm/addon-fit/README.md new file mode 100644 index 0000000..076e512 --- /dev/null +++ b/node_modules/@xterm/addon-fit/README.md @@ -0,0 +1,24 @@ +## @xterm/addon-fit + +An addon for [xterm.js](https://github.com/xtermjs/xterm.js) that enables fitting the terminal's dimensions to a containing element. This addon requires xterm.js v4+. + +### Install + +```bash +npm install --save @xterm/addon-fit +``` + +### Usage + +```ts +import { Terminal } from '@xterm/xterm'; +import { FitAddon } from '@xterm/addon-fit'; + +const terminal = new Terminal(); +const fitAddon = new FitAddon(); +terminal.loadAddon(fitAddon); +terminal.open(containerElement); +fitAddon.fit(); +``` + +See the full [API](https://github.com/xtermjs/xterm.js/blob/master/addons/addon-fit/typings/addon-fit.d.ts) for more advanced usage. diff --git a/node_modules/@xterm/addon-fit/lib/addon-fit.js b/node_modules/@xterm/addon-fit/lib/addon-fit.js new file mode 100644 index 0000000..9b25be3 --- /dev/null +++ b/node_modules/@xterm/addon-fit/lib/addon-fit.js @@ -0,0 +1,2 @@ +!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.FitAddon=t():e.FitAddon=t()}(globalThis,(()=>(()=>{"use strict";var e={};return(()=>{var t=e;Object.defineProperty(t,"__esModule",{value:!0}),t.FitAddon=void 0,t.FitAddon=class{activate(e){this._terminal=e}dispose(){}fit(){const e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;const t=this._terminal._core;this._terminal.rows===e.rows&&this._terminal.cols===e.cols||(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){if(!this._terminal)return;if(!this._terminal.element||!this._terminal.element.parentElement)return;const e=this._terminal._core._renderService.dimensions;if(0===e.css.cell.width||0===e.css.cell.height)return;const t=0===this._terminal.options.scrollback?0:this._terminal.options.overviewRuler?.width||14,r=window.getComputedStyle(this._terminal.element.parentElement),i=parseInt(r.getPropertyValue("height")),o=Math.max(0,parseInt(r.getPropertyValue("width"))),s=window.getComputedStyle(this._terminal.element),n=i-(parseInt(s.getPropertyValue("padding-top"))+parseInt(s.getPropertyValue("padding-bottom"))),l=o-(parseInt(s.getPropertyValue("padding-right"))+parseInt(s.getPropertyValue("padding-left")))-t;return{cols:Math.max(2,Math.floor(l/e.css.cell.width)),rows:Math.max(1,Math.floor(n/e.css.cell.height))}}}})(),e})())); +//# sourceMappingURL=addon-fit.js.map \ No newline at end of file diff --git a/node_modules/@xterm/addon-fit/lib/addon-fit.js.map b/node_modules/@xterm/addon-fit/lib/addon-fit.js.map new file mode 100644 index 0000000..15f7b97 --- /dev/null +++ b/node_modules/@xterm/addon-fit/lib/addon-fit.js.map @@ -0,0 +1 @@ +{"version":3,"file":"addon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oBAO3CM,EAAiBL,GANdF,SAASK,EAAaJ,iBAAiB,kBACxCD,SAASK,EAAaJ,iBAAiB,kBAKiBT,EAKhE,MAJiB,CACfd,KAAMyB,KAAKC,IAhEI,EAgEcD,KAAKK,MAAMD,EAAiBhC,EAAKa,IAAIC,KAAKC,QACvEX,KAAMwB,KAAKC,IAhEI,EAgEcD,KAAKK,MAAMF,EAAkB/B,EAAKa,IAAIC,KAAKE,SAG5E,E","sources":["webpack://FitAddon/webpack/universalModuleDefinition","webpack://FitAddon/./src/FitAddon.ts"],"sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"FitAddon\"] = factory();\n\telse\n\t\troot[\"FitAddon\"] = factory();\n})(globalThis, () => {\nreturn ","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport type { Terminal, ITerminalAddon } from '@xterm/xterm';\nimport type { FitAddon as IFitApi } from '@xterm/addon-fit';\nimport { IRenderDimensions } from 'browser/renderer/shared/Types';\nimport { ViewportConstants } from 'browser/shared/Constants';\n\ninterface ITerminalDimensions {\n /**\n * The number of rows in the terminal.\n */\n rows: number;\n\n /**\n * The number of columns in the terminal.\n */\n cols: number;\n}\n\nconst MINIMUM_COLS = 2;\nconst MINIMUM_ROWS = 1;\n\nexport class FitAddon implements ITerminalAddon , IFitApi {\n private _terminal: Terminal | undefined;\n\n public activate(terminal: Terminal): void {\n this._terminal = terminal;\n }\n\n public dispose(): void {}\n\n public fit(): void {\n const dims = this.proposeDimensions();\n if (!dims || !this._terminal || isNaN(dims.cols) || isNaN(dims.rows)) {\n return;\n }\n\n // TODO: Remove reliance on private API\n const core = (this._terminal as any)._core;\n\n // Force a full render\n if (this._terminal.rows !== dims.rows || this._terminal.cols !== dims.cols) {\n core._renderService.clear();\n this._terminal.resize(dims.cols, dims.rows);\n }\n }\n\n public proposeDimensions(): ITerminalDimensions | undefined {\n if (!this._terminal) {\n return undefined;\n }\n\n if (!this._terminal.element || !this._terminal.element.parentElement) {\n return undefined;\n }\n\n // TODO: Remove reliance on private API\n const core = (this._terminal as any)._core;\n const dims: IRenderDimensions = core._renderService.dimensions;\n\n if (dims.css.cell.width === 0 || dims.css.cell.height === 0) {\n return undefined;\n }\n\n const scrollbarWidth = (this._terminal.options.scrollback === 0\n ? 0\n : (this._terminal.options.overviewRuler?.width || ViewportConstants.DEFAULT_SCROLL_BAR_WIDTH));\n\n const parentElementStyle = window.getComputedStyle(this._terminal.element.parentElement);\n const parentElementHeight = parseInt(parentElementStyle.getPropertyValue('height'));\n const parentElementWidth = Math.max(0, parseInt(parentElementStyle.getPropertyValue('width')));\n const elementStyle = window.getComputedStyle(this._terminal.element);\n const elementPadding = {\n top: parseInt(elementStyle.getPropertyValue('padding-top')),\n bottom: parseInt(elementStyle.getPropertyValue('padding-bottom')),\n right: parseInt(elementStyle.getPropertyValue('padding-right')),\n left: parseInt(elementStyle.getPropertyValue('padding-left'))\n };\n const elementPaddingVer = elementPadding.top + elementPadding.bottom;\n const elementPaddingHor = elementPadding.right + elementPadding.left;\n const availableHeight = parentElementHeight - elementPaddingVer;\n const availableWidth = parentElementWidth - elementPaddingHor - scrollbarWidth;\n const geometry = {\n cols: Math.max(MINIMUM_COLS, Math.floor(availableWidth / dims.css.cell.width)),\n rows: Math.max(MINIMUM_ROWS, Math.floor(availableHeight / dims.css.cell.height))\n };\n return geometry;\n }\n}\n"],"names":["root","factory","exports","module","define","amd","globalThis","activate","terminal","this","_terminal","dispose","fit","dims","proposeDimensions","isNaN","cols","rows","core","_core","_renderService","clear","resize","element","parentElement","dimensions","css","cell","width","height","scrollbarWidth","options","scrollback","overviewRuler","parentElementStyle","window","getComputedStyle","parentElementHeight","parseInt","getPropertyValue","parentElementWidth","Math","max","elementStyle","availableHeight","availableWidth","floor"],"sourceRoot":""} \ No newline at end of file diff --git a/node_modules/@xterm/addon-fit/lib/addon-fit.mjs b/node_modules/@xterm/addon-fit/lib/addon-fit.mjs new file mode 100644 index 0000000..24d4f61 --- /dev/null +++ b/node_modules/@xterm/addon-fit/lib/addon-fit.mjs @@ -0,0 +1,18 @@ +/** + * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved. + * @license MIT + * + * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License) + * @license MIT + * + * Originally forked from (with the author's permission): + * Fabrice Bellard's javascript vt100 for jslinux: + * http://bellard.org/jslinux/ + * Copyright (c) 2011 Fabrice Bellard + */ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +var h=2,_=1,o=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let t=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let t=this._terminal._core._renderService.dimensions;if(t.css.cell.width===0||t.css.cell.height===0)return;let s=this._terminal.options.scrollback===0?0:this._terminal.options.overviewRuler?.width||14,r=window.getComputedStyle(this._terminal.element.parentElement),l=parseInt(r.getPropertyValue("height")),a=Math.max(0,parseInt(r.getPropertyValue("width"))),i=window.getComputedStyle(this._terminal.element),n={top:parseInt(i.getPropertyValue("padding-top")),bottom:parseInt(i.getPropertyValue("padding-bottom")),right:parseInt(i.getPropertyValue("padding-right")),left:parseInt(i.getPropertyValue("padding-left"))},m=n.top+n.bottom,d=n.right+n.left,c=l-m,p=a-d-s;return{cols:Math.max(h,Math.floor(p/t.css.cell.width)),rows:Math.max(_,Math.floor(c/t.css.cell.height))}}};export{o as FitAddon}; +//# sourceMappingURL=addon-fit.mjs.map diff --git a/node_modules/@xterm/addon-fit/lib/addon-fit.mjs.map b/node_modules/@xterm/addon-fit/lib/addon-fit.mjs.map new file mode 100644 index 0000000..f6c8a48 --- /dev/null +++ b/node_modules/@xterm/addon-fit/lib/addon-fit.mjs.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../src/FitAddon.ts"], + "sourcesContent": ["/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport type { Terminal, ITerminalAddon } from '@xterm/xterm';\nimport type { FitAddon as IFitApi } from '@xterm/addon-fit';\nimport { IRenderDimensions } from 'browser/renderer/shared/Types';\nimport { ViewportConstants } from 'browser/shared/Constants';\n\ninterface ITerminalDimensions {\n /**\n * The number of rows in the terminal.\n */\n rows: number;\n\n /**\n * The number of columns in the terminal.\n */\n cols: number;\n}\n\nconst MINIMUM_COLS = 2;\nconst MINIMUM_ROWS = 1;\n\nexport class FitAddon implements ITerminalAddon , IFitApi {\n private _terminal: Terminal | undefined;\n\n public activate(terminal: Terminal): void {\n this._terminal = terminal;\n }\n\n public dispose(): void {}\n\n public fit(): void {\n const dims = this.proposeDimensions();\n if (!dims || !this._terminal || isNaN(dims.cols) || isNaN(dims.rows)) {\n return;\n }\n\n // TODO: Remove reliance on private API\n const core = (this._terminal as any)._core;\n\n // Force a full render\n if (this._terminal.rows !== dims.rows || this._terminal.cols !== dims.cols) {\n core._renderService.clear();\n this._terminal.resize(dims.cols, dims.rows);\n }\n }\n\n public proposeDimensions(): ITerminalDimensions | undefined {\n if (!this._terminal) {\n return undefined;\n }\n\n if (!this._terminal.element || !this._terminal.element.parentElement) {\n return undefined;\n }\n\n // TODO: Remove reliance on private API\n const core = (this._terminal as any)._core;\n const dims: IRenderDimensions = core._renderService.dimensions;\n\n if (dims.css.cell.width === 0 || dims.css.cell.height === 0) {\n return undefined;\n }\n\n const scrollbarWidth = (this._terminal.options.scrollback === 0\n ? 0\n : (this._terminal.options.overviewRuler?.width || ViewportConstants.DEFAULT_SCROLL_BAR_WIDTH));\n\n const parentElementStyle = window.getComputedStyle(this._terminal.element.parentElement);\n const parentElementHeight = parseInt(parentElementStyle.getPropertyValue('height'));\n const parentElementWidth = Math.max(0, parseInt(parentElementStyle.getPropertyValue('width')));\n const elementStyle = window.getComputedStyle(this._terminal.element);\n const elementPadding = {\n top: parseInt(elementStyle.getPropertyValue('padding-top')),\n bottom: parseInt(elementStyle.getPropertyValue('padding-bottom')),\n right: parseInt(elementStyle.getPropertyValue('padding-right')),\n left: parseInt(elementStyle.getPropertyValue('padding-left'))\n };\n const elementPaddingVer = elementPadding.top + elementPadding.bottom;\n const elementPaddingHor = elementPadding.right + elementPadding.left;\n const availableHeight = parentElementHeight - elementPaddingVer;\n const availableWidth = parentElementWidth - elementPaddingHor - scrollbarWidth;\n const geometry = {\n cols: Math.max(MINIMUM_COLS, Math.floor(availableWidth / dims.css.cell.width)),\n rows: Math.max(MINIMUM_ROWS, Math.floor(availableHeight / dims.css.cell.height))\n };\n return geometry;\n }\n}\n"], + "mappings": ";;;;;;;;;;;;;;;;AAsBA,IAAMA,EAAe,EACfC,EAAe,EAERC,EAAN,KAAmD,CAGjD,SAASC,EAA0B,CACxC,KAAK,UAAYA,CACnB,CAEO,SAAgB,CAAC,CAEjB,KAAY,CACjB,IAAMC,EAAO,KAAK,kBAAkB,EACpC,GAAI,CAACA,GAAQ,CAAC,KAAK,WAAa,MAAMA,EAAK,IAAI,GAAK,MAAMA,EAAK,IAAI,EACjE,OAIF,IAAMC,EAAQ,KAAK,UAAkB,OAGjC,KAAK,UAAU,OAASD,EAAK,MAAQ,KAAK,UAAU,OAASA,EAAK,QACpEC,EAAK,eAAe,MAAM,EAC1B,KAAK,UAAU,OAAOD,EAAK,KAAMA,EAAK,IAAI,EAE9C,CAEO,mBAAqD,CAK1D,GAJI,CAAC,KAAK,WAIN,CAAC,KAAK,UAAU,SAAW,CAAC,KAAK,UAAU,QAAQ,cACrD,OAKF,IAAMA,EADQ,KAAK,UAAkB,MACA,eAAe,WAEpD,GAAIA,EAAK,IAAI,KAAK,QAAU,GAAKA,EAAK,IAAI,KAAK,SAAW,EACxD,OAGF,IAAME,EAAkB,KAAK,UAAU,QAAQ,aAAe,EAC1D,EACC,KAAK,UAAU,QAAQ,eAAe,OAAS,GAE9CC,EAAqB,OAAO,iBAAiB,KAAK,UAAU,QAAQ,aAAa,EACjFC,EAAsB,SAASD,EAAmB,iBAAiB,QAAQ,CAAC,EAC5EE,EAAqB,KAAK,IAAI,EAAG,SAASF,EAAmB,iBAAiB,OAAO,CAAC,CAAC,EACvFG,EAAe,OAAO,iBAAiB,KAAK,UAAU,OAAO,EAC7DC,EAAiB,CACrB,IAAK,SAASD,EAAa,iBAAiB,aAAa,CAAC,EAC1D,OAAQ,SAASA,EAAa,iBAAiB,gBAAgB,CAAC,EAChE,MAAO,SAASA,EAAa,iBAAiB,eAAe,CAAC,EAC9D,KAAM,SAASA,EAAa,iBAAiB,cAAc,CAAC,CAC9D,EACME,EAAoBD,EAAe,IAAMA,EAAe,OACxDE,EAAoBF,EAAe,MAAQA,EAAe,KAC1DG,EAAkBN,EAAsBI,EACxCG,EAAiBN,EAAqBI,EAAoBP,EAKhE,MAJiB,CACf,KAAM,KAAK,IAAIN,EAAc,KAAK,MAAMe,EAAiBX,EAAK,IAAI,KAAK,KAAK,CAAC,EAC7E,KAAM,KAAK,IAAIH,EAAc,KAAK,MAAMa,EAAkBV,EAAK,IAAI,KAAK,MAAM,CAAC,CACjF,CAEF,CACF", + "names": ["MINIMUM_COLS", "MINIMUM_ROWS", "FitAddon", "terminal", "dims", "core", "scrollbarWidth", "parentElementStyle", "parentElementHeight", "parentElementWidth", "elementStyle", "elementPadding", "elementPaddingVer", "elementPaddingHor", "availableHeight", "availableWidth"] +} diff --git a/node_modules/@xterm/addon-fit/package.json b/node_modules/@xterm/addon-fit/package.json new file mode 100644 index 0000000..a1291b3 --- /dev/null +++ b/node_modules/@xterm/addon-fit/package.json @@ -0,0 +1,26 @@ +{ + "name": "@xterm/addon-fit", + "version": "0.11.0", + "author": { + "name": "The xterm.js authors", + "url": "https://xtermjs.org/" + }, + "main": "lib/addon-fit.js", + "module": "lib/addon-fit.mjs", + "types": "typings/addon-fit.d.ts", + "repository": "https://github.com/xtermjs/xterm.js/tree/master/addons/addon-fit", + "license": "MIT", + "keywords": [ + "terminal", + "xterm", + "xterm.js" + ], + "scripts": { + "build": "../../node_modules/.bin/tsc -p .", + "prepackage": "npm run build", + "package": "../../node_modules/.bin/webpack", + "prepublishOnly": "npm run package", + "start": "node ../../demo/start" + }, + "commit": "f447274f430fd22513f6adbf9862d19524471c04" +} \ No newline at end of file diff --git a/node_modules/@xterm/addon-fit/src/FitAddon.ts b/node_modules/@xterm/addon-fit/src/FitAddon.ts new file mode 100644 index 0000000..a282ed3 --- /dev/null +++ b/node_modules/@xterm/addon-fit/src/FitAddon.ts @@ -0,0 +1,92 @@ +/** + * Copyright (c) 2017 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import type { Terminal, ITerminalAddon } from '@xterm/xterm'; +import type { FitAddon as IFitApi } from '@xterm/addon-fit'; +import { IRenderDimensions } from 'browser/renderer/shared/Types'; +import { ViewportConstants } from 'browser/shared/Constants'; + +interface ITerminalDimensions { + /** + * The number of rows in the terminal. + */ + rows: number; + + /** + * The number of columns in the terminal. + */ + cols: number; +} + +const MINIMUM_COLS = 2; +const MINIMUM_ROWS = 1; + +export class FitAddon implements ITerminalAddon , IFitApi { + private _terminal: Terminal | undefined; + + public activate(terminal: Terminal): void { + this._terminal = terminal; + } + + public dispose(): void {} + + public fit(): void { + const dims = this.proposeDimensions(); + if (!dims || !this._terminal || isNaN(dims.cols) || isNaN(dims.rows)) { + return; + } + + // TODO: Remove reliance on private API + const core = (this._terminal as any)._core; + + // Force a full render + if (this._terminal.rows !== dims.rows || this._terminal.cols !== dims.cols) { + core._renderService.clear(); + this._terminal.resize(dims.cols, dims.rows); + } + } + + public proposeDimensions(): ITerminalDimensions | undefined { + if (!this._terminal) { + return undefined; + } + + if (!this._terminal.element || !this._terminal.element.parentElement) { + return undefined; + } + + // TODO: Remove reliance on private API + const core = (this._terminal as any)._core; + const dims: IRenderDimensions = core._renderService.dimensions; + + if (dims.css.cell.width === 0 || dims.css.cell.height === 0) { + return undefined; + } + + const scrollbarWidth = (this._terminal.options.scrollback === 0 + ? 0 + : (this._terminal.options.overviewRuler?.width || ViewportConstants.DEFAULT_SCROLL_BAR_WIDTH)); + + const parentElementStyle = window.getComputedStyle(this._terminal.element.parentElement); + const parentElementHeight = parseInt(parentElementStyle.getPropertyValue('height')); + const parentElementWidth = Math.max(0, parseInt(parentElementStyle.getPropertyValue('width'))); + const elementStyle = window.getComputedStyle(this._terminal.element); + const elementPadding = { + top: parseInt(elementStyle.getPropertyValue('padding-top')), + bottom: parseInt(elementStyle.getPropertyValue('padding-bottom')), + right: parseInt(elementStyle.getPropertyValue('padding-right')), + left: parseInt(elementStyle.getPropertyValue('padding-left')) + }; + const elementPaddingVer = elementPadding.top + elementPadding.bottom; + const elementPaddingHor = elementPadding.right + elementPadding.left; + const availableHeight = parentElementHeight - elementPaddingVer; + const availableWidth = parentElementWidth - elementPaddingHor - scrollbarWidth; + const geometry = { + cols: Math.max(MINIMUM_COLS, Math.floor(availableWidth / dims.css.cell.width)), + rows: Math.max(MINIMUM_ROWS, Math.floor(availableHeight / dims.css.cell.height)) + }; + return geometry; + } +} diff --git a/node_modules/@xterm/addon-fit/typings/addon-fit.d.ts b/node_modules/@xterm/addon-fit/typings/addon-fit.d.ts new file mode 100644 index 0000000..784b55d --- /dev/null +++ b/node_modules/@xterm/addon-fit/typings/addon-fit.d.ts @@ -0,0 +1,55 @@ +/** + * Copyright (c) 2019 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { Terminal, ITerminalAddon } from '@xterm/xterm'; + +declare module '@xterm/addon-fit' { + /** + * An xterm.js addon that enables resizing the terminal to the dimensions of + * its containing element. + */ + export class FitAddon implements ITerminalAddon { + /** + * Creates a new fit addon. + */ + constructor(); + + /** + * Activates the addon + * @param terminal The terminal the addon is being loaded in. + */ + public activate(terminal: Terminal): void; + + /** + * Disposes the addon. + */ + public dispose(): void; + + /** + * Resizes the terminal to the dimensions of its containing element. + */ + public fit(): void; + + /** + * Gets the proposed dimensions that will be used for a fit. + */ + public proposeDimensions(): ITerminalDimensions | undefined; + } + + /** + * Represents the dimensions of a terminal. + */ + export interface ITerminalDimensions { + /** + * The number of rows in the terminal. + */ + rows: number; + + /** + * The number of columns in the terminal. + */ + cols: number; + } +} diff --git a/node_modules/@xterm/xterm/LICENSE b/node_modules/@xterm/xterm/LICENSE new file mode 100644 index 0000000..4472336 --- /dev/null +++ b/node_modules/@xterm/xterm/LICENSE @@ -0,0 +1,21 @@ +Copyright (c) 2017-2019, The xterm.js authors (https://github.com/xtermjs/xterm.js) +Copyright (c) 2014-2016, SourceLair Private Company (https://www.sourcelair.com) +Copyright (c) 2012-2013, Christopher Jeffrey (https://github.com/chjj/) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/@xterm/xterm/README.md b/node_modules/@xterm/xterm/README.md new file mode 100644 index 0000000..4ff46aa --- /dev/null +++ b/node_modules/@xterm/xterm/README.md @@ -0,0 +1,243 @@ +# [![xterm.js logo](images/logo-full.png)](https://xtermjs.org) + +Xterm.js is a front-end component written in TypeScript that lets applications bring fully-featured terminals to their users in the browser. It's used by popular projects such as VS Code, Hyper and Theia. + +## Features + +- **Terminal apps just work**: Xterm.js works with most terminal apps such as `bash`, `vim`, and `tmux`, including support for curses-based apps and mouse events. +- **Performant**: Xterm.js is *really* fast, it even includes a GPU-accelerated renderer. +- **Rich Unicode support**: Supports CJK, emojis, and IMEs. +- **Self-contained**: Requires zero dependencies to work. +- **Accessible**: Screen reader and minimum contrast ratio support can be turned on. +- **And much more**: Links, theming, addons, well documented API, etc. + +## What xterm.js is not + +- Xterm.js is not a terminal application that you can download and use on your computer. +- Xterm.js is not `bash`. Xterm.js can be connected to processes like `bash` and let you interact with them (provide input, receive output). + +## Getting Started + +First, you need to install the module, we ship exclusively through [npm](https://www.npmjs.com/), so you need that installed and then add xterm.js as a dependency by running: + +```bash +npm install @xterm/xterm +``` + +To start using xterm.js on your browser, add the `xterm.js` and `xterm.css` to the head of your HTML page. Then create a `
` onto which xterm can attach itself. Finally, instantiate the `Terminal` object and then call the `open` function with the DOM object of the `div`. + +```html + + + + + + + +
+ + + +``` + +### Importing + +The recommended way to load xterm.js is via the ES6 module syntax: + +```javascript +import { Terminal } from '@xterm/xterm'; +``` + +### Addons + +⚠️ *This section describes the new addon format introduced in v3.14.0, see [here](https://github.com/xtermjs/xterm.js/blob/3.14.2/README.md#addons) for the instructions on the old format* + +Addons are separate modules that extend the `Terminal` by building on the [xterm.js API](https://github.com/xtermjs/xterm.js/blob/master/typings/xterm.d.ts). To use an addon, you first need to install it in your project: + +```bash +npm i -S @xterm/addon-web-links +``` + +Then import the addon, instantiate it and call `Terminal.loadAddon`: + +```ts +import { Terminal } from '@xterm/xterm'; +import { WebLinksAddon } from '@xterm/addon-web-links'; + +const terminal = new Terminal(); +// Load WebLinksAddon on terminal, this is all that's needed to get web links +// working in the terminal. +terminal.loadAddon(new WebLinksAddon()); +``` + +The xterm.js team maintains the following addons, but anyone can build them: + +- [`@xterm/addon-attach`](https://github.com/xtermjs/xterm.js/tree/master/addons/addon-attach): Attaches to a server running a process via a websocket +- [`@xterm/addon-clipboard`](https://github.com/xtermjs/xterm.js/tree/master/addons/addon-clipboard): Access the browser's clipboard +- [`@xterm/addon-fit`](https://github.com/xtermjs/xterm.js/tree/master/addons/addon-fit): Fits the terminal to the containing element +- [`@xterm/addon-image`](https://github.com/xtermjs/xterm.js/tree/master/addons/addon-image): Adds image support +- [`@xterm/addon-search`](https://github.com/xtermjs/xterm.js/tree/master/addons/addon-search): Adds search functionality +- [`@xterm/addon-serialize`](https://github.com/xtermjs/xterm.js/tree/master/addons/addon-serialize): Serializes the terminal's buffer to a VT sequences or HTML +- [`@xterm/addon-unicode11`](https://github.com/xtermjs/xterm.js/tree/master/addons/addon-unicode11): Updates character widths to their unicode11 values +- [`@xterm/addon-web-links`](https://github.com/xtermjs/xterm.js/tree/master/addons/addon-web-links): Adds web link detection and interaction +- [`@xterm/addon-webgl`](https://github.com/xtermjs/xterm.js/tree/master/addons/addon-webgl): Renders xterm.js using a `canvas` element's webgl2 context + +## Browser Support + +Since xterm.js is typically implemented as a developer tool, only modern browsers are supported officially. Specifically the latest versions of *Chrome*, *Edge*, *Firefox*, and *Safari*. + +Xterm.js works seamlessly in [Electron](https://electronjs.org/) apps and may even work on earlier versions of the browsers. These are the versions we strive to keep working. + +### Node.js Support + +We also publish [`xterm-headless`](https://www.npmjs.com/package/xterm-headless) which is a stripped down version of xterm.js that runs in Node.js. An example use case for this is to keep track of a terminal's state where the process is running and using the serialize addon so it can get all state restored upon reconnection. + +## API + +The full API for xterm.js is contained within the [TypeScript declaration file](https://github.com/xtermjs/xterm.js/blob/master/typings/xterm.d.ts), use the branch/tag picker in GitHub (`w`) to navigate to the correct version of the API. + +Note that some APIs are marked *experimental*, these are added to enable experimentation with new ideas without committing to support it like a normal [semver](https://semver.org/) API. Note that these APIs can change radically between versions, so be sure to read release notes if you plan on using experimental APIs. + +## Releases + +Xterm.js follows a monthly release cycle roughly. + +All current and past releases are available on this repo's [Releases page](https://github.com/sourcelair/xterm.js/releases), you can view the [high-level roadmap on the wiki](https://github.com/xtermjs/xterm.js/wiki/Roadmap) and see what we're working on now by looking through [Milestones](https://github.com/sourcelair/xterm.js/milestones). + +### Beta builds + +Our CI releases beta builds to npm for every change that goes into master. Install the latest beta build with: + +```bash +npm install -S @xterm/xterm@beta +``` + +These should generally be stable, but some bugs may slip in. We recommend using the beta build primarily to test out new features and to verify bug fixes. + +## Contributing + +You can read the [guide on the wiki](https://github.com/xtermjs/xterm.js/wiki/Contributing) to learn how to contribute and set up xterm.js for development. + +## Real-world uses +Xterm.js is used in several world-class applications to provide great terminal experiences. + +- [**SourceLair**](https://www.sourcelair.com/): In-browser IDE that provides its users with fully-featured Linux terminals based on xterm.js. +- [**Microsoft Visual Studio Code**](http://code.visualstudio.com/): Modern, versatile, and powerful open source code editor that provides an integrated terminal based on xterm.js. +- [**ttyd**](https://github.com/tsl0922/ttyd): A command-line tool for sharing terminal over the web, with fully-featured terminal emulation based on xterm.js. +- [**Eclipse Che**](http://www.eclipse.org/che): Developer workspace server, cloud IDE, and Eclipse next-generation IDE. +- [**Codenvy**](http://www.codenvy.com): Cloud workspaces for development teams. +- [**CoderPad**](https://coderpad.io): Online interviewing platform for programmers. Run code in many programming languages, with results displayed by xterm.js. +- [**WebSSH2**](https://github.com/billchurch/WebSSH2): A web based SSH2 client using xterm.js, socket.io, and ssh2. +- [**Spyder Terminal**](https://github.com/spyder-ide/spyder-terminal): A full fledged system terminal embedded on Spyder IDE. +- [**Cloud Commander**](https://cloudcmd.io "Cloud Commander"): Orthodox web file manager with console and editor. +- [**Next Tech**](https://next.tech "Next Tech"): Online platform for interactive coding and web development courses. Live container-backed terminal uses xterm.js. +- [**RStudio**](https://www.rstudio.com/products/RStudio "RStudio"): RStudio is an integrated development environment (IDE) for R. +- [**Terminal for Atom**](https://github.com/jsmecham/atom-terminal-tab): A simple terminal for the Atom text editor. +- [**Eclipse Orion**](https://orionhub.org): A modern, open source software development environment that runs in the cloud. Code, deploy, and run in the cloud. +- [**Gravitational Teleport**](https://github.com/gravitational/teleport): Gravitational Teleport is a modern SSH server for remotely accessing clusters of Linux servers via SSH or HTTPS. +- [**Hexlet**](https://en.hexlet.io): Practical programming courses (JavaScript, PHP, Unix, databases, functional programming). A steady path from the first line of code to the first job. +- [**Selenoid UI**](https://github.com/aerokube/selenoid-ui): Simple UI for the scalable golang implementation of Selenium Hub named Selenoid. We use XTerm for streaming logs over websockets from docker containers. +- [**Portainer**](https://portainer.io): Simple management UI for Docker. +- [**SSHy**](https://github.com/stuicey/SSHy): HTML5 Based SSHv2 Web Client with E2E encryption utilising xterm.js, SJCL & websockets. +- [**JupyterLab**](https://github.com/jupyterlab/jupyterlab): An extensible computational environment for Jupyter, supporting interactive data science and scientific computing across all programming languages. +- [**Theia**](https://github.com/theia-ide/theia): Theia is a cloud & desktop IDE framework implemented in TypeScript. +- [**Opshell**](https://github.com/ricktbaker/opshell) Ops Helper tool to make life easier working with AWS instances across multiple organizations. +- [**Proxmox VE**](https://www.proxmox.com/en/proxmox-ve): Proxmox VE is a complete open-source platform for enterprise virtualization. It uses xterm.js for container terminals and the host shell. +- [**Script Runner**](https://github.com/ioquatix/script-runner): Run scripts (or a shell) in Atom. +- [**Whack Whack Terminal**](https://github.com/Microsoft/WhackWhackTerminal): Terminal emulator for Visual Studio 2017. +- [**VTerm**](https://github.com/vterm/vterm): Extensible terminal emulator based on Electron and React. +- [**electerm**](http://electerm.html5beta.com): electerm is a terminal/ssh/sftp client(mac, win, linux) based on electron/node-pty/xterm. +- [**Kubebox**](https://github.com/astefanutti/kubebox): Terminal console for Kubernetes clusters. +- [**Azure Cloud Shell**](https://shell.azure.com): Azure Cloud Shell is a Microsoft-managed admin machine built on Azure, for Azure. +- [**atom-xterm**](https://atom.io/packages/atom-xterm): Atom plugin for providing terminals inside your Atom workspace. +- [**rtty**](https://github.com/zhaojh329/rtty): Access your terminals from anywhere via the web. +- [**Pisth**](https://github.com/ColdGrub1384/Pisth): An SFTP and SSH client for iOS. +- [**abstruse**](https://github.com/bleenco/abstruse): Abstruse CI is a continuous integration platform based on Node.JS and Docker. +- [**Azure Data Studio**](https://github.com/Microsoft/azuredatastudio): A data management tool that enables working with SQL Server, Azure SQL DB and SQL DW from Windows, macOS and Linux. +- [**FreeMAN**](https://github.com/matthew-matvei/freeman): A free, cross-platform file manager for power users. +- [**Fluent Terminal**](https://github.com/felixse/FluentTerminal): A terminal emulator based on UWP and web technologies. +- [**Hyper**](https://hyper.is): A terminal built on web technologies. +- [**Diag**](https://diag.ai): A better way to troubleshoot problems faster. Capture, share and reapply troubleshooting knowledge so you can focus on solving problems that matter. +- [**GoTTY**](https://github.com/sorenisanerd/gotty): A simple command line tool that shares your terminal as a web application based on xterm.js. +- [**genact**](https://github.com/svenstaro/genact): A nonsense activity generator. +- [**cPanel & WHM**](https://cpanel.com): The hosting platform of choice. +- [**Nutanix**](https://github.com/nutanix): Nutanix Enterprise Cloud uses xterm in the webssh functionality within Nutanix Calm, and is also looking to move our old noserial (termjs) functionality to xterm.js. +- [**SSH Web Client**](https://github.com/roke22/PHP-SSH2-Web-Client): SSH Web Client with PHP. +- [**Juno**](http://junolab.org/): A flexible Julia IDE, based on Atom. +- [**webssh**](https://github.com/huashengdun/webssh): Web based ssh client. +- [**info-beamer hosted**](https://info-beamer.com): Uses xterm.js to manage digital signage devices from the web dashboard. +- [**Jumpserver**](https://github.com/jumpserver/luna): Jumpserver Luna project, Jumpserver is a bastion server project, Luna use xterm.js for web terminal emulation. +- [**LxdMosaic**](https://github.com/turtle0x1/LxdMosaic): Uses xterm.js to give terminal access to containers through LXD +- [**CodeInterview.io**](https://codeinterview.io): A coding interview platform in 25+ languages and many web frameworks. Uses xterm.js to provide shell access. +- [**Bastillion**](https://www.bastillion.io): Bastillion is an open-source web-based SSH console that centrally manages administrative access to systems. +- [**PHP App Server**](https://github.com/cubiclesoft/php-app-server/): Create lightweight, installable almost-native applications for desktop OSes. ExecTerminal (nicely wraps the xterm.js Terminal), TerminalManager, and RunProcessSDK are self-contained, reusable ES5+ compliant Javascript components. +- [**NgTerminal**](https://github.com/qwefgh90/ng-terminal): NgTerminal is a web terminal that leverages xterm.js on Angular 7+. You can easily add it into your application by adding `` into your component. +- [**tty-share**](https://tty-share.com): Extremely simple terminal sharing over the Internet. +- [**Ten Hands**](https://github.com/saisandeepvaddi/ten-hands): One place to run your command-line tasks. +- [**WebAssembly.sh**](https://webassembly.sh): A WebAssembly WASI browser terminal +- [**Gus**](https://gus.jp): A shared coding pad where you can run Python with xterm.js +- [**Linode**](https://linode.com): Linode uses xterm.js to provide users a web console for their Linode instances. +- [**FluffOS**](https://www.fluffos.info): Active maintained LPMUD driver with websocket support. +- [**x-terminal**](https://atom.io/packages/x-terminal): Atom plugin for providing terminals inside your Atom workspace. +- [**CoCalc**](https://cocalc.com/): Lots of free software pre-installed, to chat, collaborate, develop, program, publish, research, share, teach, in C++, HTML, Julia, Jupyter, LaTeX, Markdown, Python, R, SageMath, Scala, ... +- [**Dank Domain**](https://www.DDgame.us/): Open source multiuser medieval game supporting old & new terminal emulation. +- [**DockerStacks**](https://docker-stacks.com/): Local LAMP/LEMP development studio +- [**Codecademy**](https://codecademy.com/): Uses xterm.js in its courses on Bash. +- [**Laravel Ssh Web Client**](https://github.com/roke22/Laravel-ssh-client): Laravel server inventory with ssh web client to connect at server using xterm.js +- [**Replit**](https://replit.com): Collaborative browser based IDE with support for 50+ different languages. +- [**TeleType**](https://github.com/akshaykmr/TeleType): cli tool that allows you to share your terminal online conveniently. Show off mad cli-fu, help a colleague, teach, or troubleshoot. +- [**Intervue**](https://www.intervue.io): Pair programming for interviews. Multiple programming languages are supported, with results displayed by xterm.js. +- [**TRASA**](https://trasa.io): Zero trust access to Web, SSH, RDP, and Database services. +- [**Commas**](https://github.com/CyanSalt/commas): Commas is a hackable terminal and command runner. +- [**Devtron**](https://github.com/devtron-labs/devtron): Software Delivery Workflow For Kubernetes. +- [**NxShell**](https://github.com/nxshell/nxshell): An easy to use new terminal for SSH. +- [**gifcast**](https://dstein64.github.io/gifcast/): Converts an asciinema cast to an animated GIF. +- [**WizardWebssh**](https://gitlab.com/mikeramsey/wizardwebssh): A terminal with Pyqt5 Widget for embedding, which can be used as an ssh client to connect to your ssh servers. It is written in Python, based on tornado, paramiko, and xterm.js. +- [**Wizard Assistant**](https://wizardassistant.com/): Wizard Assistant comes with advanced automation tools, preloaded common and special time-saving commands, and a built-in SSH terminal. Now you can remotely administer, troubleshoot, and analyze any system with ease. +- [**ucli**](https://github.com/tsadarsh/ucli): Command Line for everyone :family_man_woman_girl_boy: at [www.ucli.tech](https://www.ucli.tech). +- [**Tess**](https://github.com/SquitchYT/Tess/): Simple Terminal Fully Customizable for Everyone. Discover more at [tessapp.dev](https://tessapp.dev) +- [**HashiCorp Nomad**](https://www.nomadproject.io/): A container orchestrator with the ability to connect to remote tasks via a web interface using websockets and xterm.js. +- [**TermPair**](https://github.com/cs01/termpair): View and control terminals from your browser with end-to-end encryption +- [**gdbgui**](https://github.com/cs01/gdbgui): Browser-based frontend to gdb (gnu debugger) +- [**goormIDE**](https://ide.goorm.io/): Run almost every programming languages with real-time collaboration, live pair programming, and built-in messenger. +- [**FleetDeck**](https://fleetdeck.io): Remote desktop & virtual terminal +- [**OpenSumi**](https://github.com/opensumi/core): A framework helps you quickly build Cloud or Desktop IDE products. +- [**KubeSail**](https://kubesail.com): The Self-Hosting Company - uses xterm to allow users to exec into kubernetes pods and build github apps +- [**WiTTY**](https://github.com/syssecfsu/witty): Web-based interactive terminal emulator that allows users to easily record, share, and replay console sessions. +- [**libv86 Terminal Forwarding**](https://github.com/hello-smile6/libv86-terminal-forwarding): Peer-to-peer SSH for the web, using WebRTC via [Bugout](https://github.com/chr15m/bugout) for data transfer and [v86](https://github.com/copy/v86) for web-based virtualization. +- [**hack.courses**](https://hack.courses): Interactive Linux and command-line classes using xterm.js to expose a real terminal available for everyone. +- [**Render**](https://render.com): Platform-as-a-service for your apps, websites, and databases using xterm.js to provide a command prompt for user containers and for streaming build and runtime logs. +- [**CloudTTY**](https://github.com/cloudtty/cloudtty): A Friendly Kubernetes CloudShell (Web Terminal). +- [**Go SSH Web Client**](https://github.com/wuchihsu/go-ssh-web-client): A simple SSH web client using Go, WebSocket and Xterm.js. +- [**web3os**](https://web3os.sh): A decentralized operating system for the next web +- [**Cratecode**](https://cratecode.com): Learn to program for free through interactive online lessons. Cratecode uses xterm.js to give users access to their own Linux environment. +- [**Super Terminal**](https://github.com/bugwheels94/super-terminal): It is a http based terminal for developers who dont like repetition and save time. +- [**graSSHopper**](https://grasshopper.coding.kiwi): A simple SSH client with file explorer, history and many more features. +- [**DomTerm**](https://domterm.org/xtermjs.html): Tiles and tabs. Detachable sessions (like tmux). [Remote connections](https://domterm.org/Remoting-over-ssh.html) using a nice ssh wrapper with predictive echo. Qt, Electron, Tauri/Wry, or desktop browser front-ends. Choose between xterm.js engine (faster) or native DomTerm (more functionality and graphics) - or both. +- [**Cloudtutor.io**](https://cloudtutor.io): innovative online learning platform that offers users access to an interactive lab. +- [**Helix Editor Playground**](https://github.com/tomgroenwoldt/helix-editor-playground): Online playground for the terminal based helix editor. +- [**Coder**](https://github.com/coder/coder): Self-Hosted Remote Development Environments +- [**Wave Terminal**](https://waveterm.dev): An open-source, ai-native, terminal built for seamless workflows. +- [**eva**](https://github.com/info24/eva): Eva is a web application for SSH remote login, developed in Go. +- [**OpenSFTP**](https://opensftp.com): Super beautiful SSH and SFTP integrated workspace client. +- [**balena**](https://www.balena.io/): Balena is a full-stack solution for developing, deploying, updating, and troubleshooting IoT Edge devices. We use xterm.js to manage & debug devices on [balenaCloud](https://www.balena.io/cloud). +- [**Filet Cloud**](https://github.com/fuglaro/filet-cloud): The lean and powerful personal cloud ⛅. +- [**pyTermTk**](https://github.com/ceccopierangiolieugenio/pyTermTk): Python Terminal Toolkit - a Spiced Up Cross Compatible TUI Library 🌶️, use xterm.js for the [HTML5 exporter](https://ceccopierangiolieugenio.github.io/pyTermTk/sandbox/sandbox.html). +- [**ecmaOS**](https://ecmaos.sh): A kernel and suite of applications tying modern web technologies into a browser-based operating system. +- [**LabEx**](https://labex.io): Interactive learning platform with hands-on labs and xterm.js-based online terminals, focused on learn-by-doing approach. +- [**EmuDevz**](https://afska.github.io/emudevz): A free coding game where players learn how to build an emulator from scratch. +- [And much more...](https://github.com/xtermjs/xterm.js/network/dependents?package_id=UGFja2FnZS0xNjYzMjc4OQ%3D%3D) + +Do you use xterm.js in your application as well? Please [open a Pull Request](https://github.com/sourcelair/xterm.js/pulls) to include it here. We would love to have it on our list. Note: Please add any new contributions to the end of the list only. + +## License Agreement + +If you contribute code to this project, you implicitly allow your code to be distributed under the MIT license. You are also implicitly verifying that all code is your original work. + +Copyright (c) 2017-2022, [The xterm.js authors](https://github.com/xtermjs/xterm.js/graphs/contributors) (MIT License)
+Copyright (c) 2014-2017, SourceLair, Private Company ([www.sourcelair.com](https://www.sourcelair.com/home)) (MIT License)
+Copyright (c) 2012-2013, Christopher Jeffrey (MIT License) diff --git a/node_modules/@xterm/xterm/css/xterm.css b/node_modules/@xterm/xterm/css/xterm.css new file mode 100644 index 0000000..819654e --- /dev/null +++ b/node_modules/@xterm/xterm/css/xterm.css @@ -0,0 +1,285 @@ +/** + * Copyright (c) 2014 The xterm.js authors. All rights reserved. + * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License) + * https://github.com/chjj/term.js + * @license MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * Originally forked from (with the author's permission): + * Fabrice Bellard's javascript vt100 for jslinux: + * http://bellard.org/jslinux/ + * Copyright (c) 2011 Fabrice Bellard + * The original design remains. The terminal itself + * has been extended to include xterm CSI codes, among + * other features. + */ + +/** + * Default styles for xterm.js + */ + +.xterm { + cursor: text; + position: relative; + user-select: none; + -ms-user-select: none; + -webkit-user-select: none; +} + +.xterm.focus, +.xterm:focus { + outline: none; +} + +.xterm .xterm-helpers { + position: absolute; + top: 0; + /** + * The z-index of the helpers must be higher than the canvases in order for + * IMEs to appear on top. + */ + z-index: 5; +} + +.xterm .xterm-helper-textarea { + padding: 0; + border: 0; + margin: 0; + /* Move textarea out of the screen to the far left, so that the cursor is not visible */ + position: absolute; + opacity: 0; + left: -9999em; + top: 0; + width: 0; + height: 0; + z-index: -5; + /** Prevent wrapping so the IME appears against the textarea at the correct position */ + white-space: nowrap; + overflow: hidden; + resize: none; +} + +.xterm .composition-view { + /* TODO: Composition position got messed up somewhere */ + background: #000; + color: #FFF; + display: none; + position: absolute; + white-space: nowrap; + z-index: 1; +} + +.xterm .composition-view.active { + display: block; +} + +.xterm .xterm-viewport { + /* On OS X this is required in order for the scroll bar to appear fully opaque */ + background-color: #000; + overflow-y: scroll; + cursor: default; + position: absolute; + right: 0; + left: 0; + top: 0; + bottom: 0; +} + +.xterm .xterm-screen { + position: relative; +} + +.xterm .xterm-screen canvas { + position: absolute; + left: 0; + top: 0; +} + +.xterm-char-measure-element { + display: inline-block; + visibility: hidden; + position: absolute; + top: 0; + left: -9999em; + line-height: normal; +} + +.xterm.enable-mouse-events { + /* When mouse events are enabled (eg. tmux), revert to the standard pointer cursor */ + cursor: default; +} + +.xterm.xterm-cursor-pointer, +.xterm .xterm-cursor-pointer { + cursor: pointer; +} + +.xterm.column-select.focus { + /* Column selection mode */ + cursor: crosshair; +} + +.xterm .xterm-accessibility:not(.debug), +.xterm .xterm-message { + position: absolute; + left: 0; + top: 0; + bottom: 0; + right: 0; + z-index: 10; + color: transparent; + pointer-events: none; +} + +.xterm .xterm-accessibility-tree:not(.debug) *::selection { + color: transparent; +} + +.xterm .xterm-accessibility-tree { + font-family: monospace; + user-select: text; + white-space: pre; +} + +.xterm .xterm-accessibility-tree > div { + transform-origin: left; + width: fit-content; +} + +.xterm .live-region { + position: absolute; + left: -9999px; + width: 1px; + height: 1px; + overflow: hidden; +} + +.xterm-dim { + /* Dim should not apply to background, so the opacity of the foreground color is applied + * explicitly in the generated class and reset to 1 here */ + opacity: 1 !important; +} + +.xterm-underline-1 { text-decoration: underline; } +.xterm-underline-2 { text-decoration: double underline; } +.xterm-underline-3 { text-decoration: wavy underline; } +.xterm-underline-4 { text-decoration: dotted underline; } +.xterm-underline-5 { text-decoration: dashed underline; } + +.xterm-overline { + text-decoration: overline; +} + +.xterm-overline.xterm-underline-1 { text-decoration: overline underline; } +.xterm-overline.xterm-underline-2 { text-decoration: overline double underline; } +.xterm-overline.xterm-underline-3 { text-decoration: overline wavy underline; } +.xterm-overline.xterm-underline-4 { text-decoration: overline dotted underline; } +.xterm-overline.xterm-underline-5 { text-decoration: overline dashed underline; } + +.xterm-strikethrough { + text-decoration: line-through; +} + +.xterm-screen .xterm-decoration-container .xterm-decoration { + z-index: 6; + position: absolute; +} + +.xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer { + z-index: 7; +} + +.xterm-decoration-overview-ruler { + z-index: 8; + position: absolute; + top: 0; + right: 0; + pointer-events: none; +} + +.xterm-decoration-top { + z-index: 2; + position: relative; +} + + + +/* Derived from vs/base/browser/ui/scrollbar/media/scrollbar.css */ + +/* xterm.js customization: Override xterm's cursor style */ +.xterm .xterm-scrollable-element > .scrollbar { + cursor: default; +} + +/* Arrows */ +.xterm .xterm-scrollable-element > .scrollbar > .scra { + cursor: pointer; + font-size: 11px !important; +} + +.xterm .xterm-scrollable-element > .visible { + opacity: 1; + + /* Background rule added for IE9 - to allow clicks on dom node */ + background:rgba(0,0,0,0); + + transition: opacity 100ms linear; + /* In front of peek view */ + z-index: 11; +} +.xterm .xterm-scrollable-element > .invisible { + opacity: 0; + pointer-events: none; +} +.xterm .xterm-scrollable-element > .invisible.fade { + transition: opacity 800ms linear; +} + +/* Scrollable Content Inset Shadow */ +.xterm .xterm-scrollable-element > .shadow { + position: absolute; + display: none; +} +.xterm .xterm-scrollable-element > .shadow.top { + display: block; + top: 0; + left: 3px; + height: 3px; + width: 100%; + box-shadow: var(--vscode-scrollbar-shadow, #000) 0 6px 6px -6px inset; +} +.xterm .xterm-scrollable-element > .shadow.left { + display: block; + top: 3px; + left: 0; + height: 100%; + width: 3px; + box-shadow: var(--vscode-scrollbar-shadow, #000) 6px 0 6px -6px inset; +} +.xterm .xterm-scrollable-element > .shadow.top-left-corner { + display: block; + top: 0; + left: 0; + height: 3px; + width: 3px; +} +.xterm .xterm-scrollable-element > .shadow.top.left { + box-shadow: var(--vscode-scrollbar-shadow, #000) 6px 0 6px -6px inset; +} diff --git a/node_modules/@xterm/xterm/lib/xterm.js b/node_modules/@xterm/xterm/lib/xterm.js new file mode 100644 index 0000000..e47e2dd --- /dev/null +++ b/node_modules/@xterm/xterm/lib/xterm.js @@ -0,0 +1,2 @@ +!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var i=t();for(var s in i)("object"==typeof exports?exports:e)[s]=i[s]}}(globalThis,(()=>(()=>{"use strict";var e={2840:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.AccessibilityManager=void 0;const n=i(7721),o=i(4292),a=i(7150),l=i(7098),h=i(6501),c=i(7093);let d=class extends a.Disposable{constructor(e,t,i,s){super(),this._terminal=e,this._coreBrowserService=i,this._renderService=s,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="";const r=this._coreBrowserService.mainDocument;this._accessibilityContainer=r.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=r.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let e=0;ethis._handleBoundaryFocus(e,0),this._bottomBoundaryFocusListener=e=>this._handleBoundaryFocus(e,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=r.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this._register(new o.TimeBasedDebouncer(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this._register(this._terminal.onResize((e=>this._handleResize(e.rows)))),this._register(this._terminal.onRender((e=>this._refreshRows(e.start,e.end)))),this._register(this._terminal.onScroll((()=>this._refreshRows()))),this._register(this._terminal.onA11yChar((e=>this._handleChar(e)))),this._register(this._terminal.onLineFeed((()=>this._handleChar("\n")))),this._register(this._terminal.onA11yTab((e=>this._handleTab(e)))),this._register(this._terminal.onKey((e=>this._handleKey(e.key)))),this._register(this._terminal.onBlur((()=>this._clearLiveRegion()))),this._register(this._renderService.onDimensionsChange((()=>this._refreshRowsDimensions()))),this._register((0,c.addDisposableListener)(r,"selectionchange",(()=>this._handleSelectionChange()))),this._register(this._coreBrowserService.onDprChange((()=>this._refreshRowsDimensions()))),this._refreshRowsDimensions(),this._refreshRows(),this._register((0,a.toDisposable)((()=>{this._accessibilityContainer.remove(),this._rowElements.length=0})))}_handleTab(e){for(let t=0;t0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,"\n"===e&&(this._liveRegionLineCount++,21===this._liveRegionLineCount&&(this._liveRegion.textContent+=n.tooMuchOutput.get())))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),/\p{Control}/u.test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){const i=this._terminal.buffer,s=i.lines.length.toString();for(let r=e;r<=t;r++){const e=i.lines.get(i.ydisp+r),t=[],n=e?.translateToString(!0,void 0,void 0,t)||"",o=(i.ydisp+r+1).toString(),a=this._rowElements[r];a&&(0===n.length?(a.textContent=" ",this._rowColumns.set(a,[0,1])):(a.textContent=n,this._rowColumns.set(a,t)),a.setAttribute("aria-posinset",o),a.setAttribute("aria-setsize",s),this._alignRowWidth(a))}this._announceCharacters()}_announceCharacters(){0!==this._charsToAnnounce.length&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(e,t){const i=e.target,s=this._rowElements[0===t?1:this._rowElements.length-2];if(i.getAttribute("aria-posinset")===(0===t?"1":`${this._terminal.buffer.lines.length}`))return;if(e.relatedTarget!==s)return;let r,n;if(0===t?(r=i,n=this._rowElements.pop(),this._rowContainer.removeChild(n)):(r=this._rowElements.shift(),n=i,this._rowContainer.removeChild(r)),r.removeEventListener("focus",this._topBoundaryFocusListener),n.removeEventListener("focus",this._bottomBoundaryFocusListener),0===t){const e=this._createAccessibilityTreeNode();this._rowElements.unshift(e),this._rowContainer.insertAdjacentElement("afterbegin",e)}else{const e=this._createAccessibilityTreeNode();this._rowElements.push(e),this._rowContainer.appendChild(e)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(0===t?-1:1),this._rowElements[0===t?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}_handleSelectionChange(){if(0===this._rowElements.length)return;const e=this._coreBrowserService.mainDocument.getSelection();if(!e)return;if(e.isCollapsed)return void(this._rowContainer.contains(e.anchorNode)&&this._terminal.clearSelection());if(!e.anchorNode||!e.focusNode)return void console.error("anchorNode and/or focusNode are null");let t={node:e.anchorNode,offset:e.anchorOffset},i={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(i.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===i.node&&t.offset>i.offset)&&([t,i]=[i,t]),t.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(t={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(t.node))return;const s=this._rowElements.slice(-1)[0];if(i.node.compareDocumentPosition(s)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(i={node:s,offset:s.textContent?.length??0}),!this._rowContainer.contains(i.node))return;const r=({node:e,offset:t})=>{const i=e instanceof Text?e.parentNode:e;let s=parseInt(i?.getAttribute("aria-posinset"),10)-1;if(isNaN(s))return console.warn("row is invalid. Race condition?"),null;const r=this._rowColumns.get(i);if(!r)return console.warn("columns is null. Race condition?"),null;let n=t=this._terminal.cols&&(++s,n=0),{row:s,column:n}},n=r(t),o=r(i);if(n&&o){if(n.row>o.row||n.row===o.row&&n.column>=o.column)throw new Error("invalid range");this._terminal.select(n.column,n.row,(o.row-n.row)*this._terminal.cols-n.column+o.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let e=this._rowContainer.children.length;ee;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){const e=this._coreBrowserService.mainDocument.createElement("div");return e.setAttribute("role","listitem"),e.tabIndex=-1,this._refreshRowDimensions(e),e}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){Object.assign(this._accessibilityContainer.style,{width:`${this._renderService.dimensions.css.canvas.width}px`,fontSize:`${this._terminal.options.fontSize}px`}),this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let e=0;e{function i(e){return e.replace(/\r?\n/g,"\r")}function s(e,t){return t?"[200~"+e+"[201~":e}function r(e,t,r,n){e=s(e=i(e),r.decPrivateModes.bracketedPasteMode&&!0!==n.rawOptions.ignoreBracketedPasteMode),r.triggerDataEvent(e,!0),t.value=""}function n(e,t,i){const s=i.getBoundingClientRect(),r=e.clientX-s.left-10,n=e.clientY-s.top-10;t.style.width="20px",t.style.height="20px",t.style.left=`${r}px`,t.style.top=`${n}px`,t.style.zIndex="1000",t.focus()}Object.defineProperty(t,"__esModule",{value:!0}),t.prepareTextForTerminal=i,t.bracketTextForPaste=s,t.copyHandler=function(e,t){e.clipboardData&&e.clipboardData.setData("text/plain",t.selectionText),e.preventDefault()},t.handlePasteEvent=function(e,t,i,s){e.stopPropagation(),e.clipboardData&&r(e.clipboardData.getData("text/plain"),t,i,s)},t.paste=r,t.moveTextAreaUnderMouseCursor=n,t.rightClickHandler=function(e,t,i,s,r){n(e,t,i),r&&s.rightClickSelect(e),t.value=s.selectionText,t.select()}},7174:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ColorContrastCache=void 0;const s=i(7710);t.ColorContrastCache=class{constructor(){this._color=new s.TwoKeyMap,this._css=new s.TwoKeyMap}setCss(e,t,i){this._css.set(e,t,i)}getCss(e,t){return this._css.get(e,t)}setColor(e,t,i){this._color.set(e,t,i)}getColor(e,t){return this._color.get(e,t)}clear(){this._color.clear(),this._css.clear()}}},1718:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CoreBrowserTerminal=void 0;const s=i(7861),r=i(7721),n=i(3285),o=i(4017),a=i(4196),l=i(9925),h=i(3618),c=i(3955),d=i(4792),u=i(945),_=i(9574),f=i(9820),p=i(9784),g=i(5783),m=i(2079),v=i(7098),S=i(9078),b=i(4103),C=i(5777),y=i(701),w=i(6107),E=i(3534),D=i(706),L=i(8693),R=i(4720),A=i(6501),T=i(2486),k=i(2840),M=i(8906),O=i(802),I=i(7093),P=i(7150);class x extends C.CoreTerminal{get linkifier(){return this._linkifier.value}get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}constructor(e={}){super(e),this._linkifier=this._register(new P.MutableDisposable),this.browser=y,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new P.MutableDisposable),this._onCursorMove=this._register(new O.Emitter),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new O.Emitter),this.onKey=this._onKey.event,this._onRender=this._register(new O.Emitter),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new O.Emitter),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new O.Emitter),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new O.Emitter),this.onBell=this._onBell.event,this._onFocus=this._register(new O.Emitter),this._onBlur=this._register(new O.Emitter),this._onA11yCharEmitter=this._register(new O.Emitter),this._onA11yTabEmitter=this._register(new O.Emitter),this._onWillOpen=this._register(new O.Emitter),this._setup(),this._decorationService=this._instantiationService.createInstance(R.DecorationService),this._instantiationService.setService(A.IDecorationService,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(f.LinkProviderService),this._instantiationService.setService(v.ILinkProviderService,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(n.OscLinkProvider)),this._register(this._inputHandler.onRequestBell((()=>this._onBell.fire()))),this._register(this._inputHandler.onRequestRefreshRows((e=>this.refresh(e?.start??0,e?.end??this.rows-1)))),this._register(this._inputHandler.onRequestSendFocus((()=>this._reportFocus()))),this._register(this._inputHandler.onRequestReset((()=>this.reset()))),this._register(this._inputHandler.onRequestWindowsOptionsReport((e=>this._reportWindowsOptions(e)))),this._register(this._inputHandler.onColor((e=>this._handleColorEvent(e)))),this._register(O.Event.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(O.Event.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(O.Event.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(O.Event.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize((e=>this._afterResize(e.cols,e.rows)))),this._register((0,P.toDisposable)((()=>{this._customKeyEventHandler=void 0,this.element?.parentNode?.removeChild(this.element)})))}_handleColorEvent(e){if(this._themeService)for(const t of e){let e,i="";switch(t.index){case 256:e="foreground",i="10";break;case 257:e="background",i="11";break;case 258:e="cursor",i="12";break;default:e="ansi",i="4;"+t.index}switch(t.type){case 0:const s=b.color.toColorRGB("ansi"===e?this._themeService.colors.ansi[t.index]:this._themeService.colors[e]);this.coreService.triggerDataEvent(`${E.C0.ESC}]${i};${(0,L.toRgbString)(s)}${E.C1_ESCAPED.ST}`);break;case 1:if("ansi"===e)this._themeService.modifyColors((e=>e.ansi[t.index]=b.channels.toColor(...t.color)));else{const i=e;this._themeService.modifyColors((e=>e[i]=b.channels.toColor(...t.color)))}break;case 2:this._themeService.restoreColor(t.index)}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(e){e?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(k.AccessibilityManager,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(E.C0.ESC+"[I"),this.element.classList.add("focus"),this._showCursor(),this._onFocus.fire()}blur(){return this.textarea?.blur()}_handleTextAreaBlur(){this.textarea.value="",this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(E.C0.ESC+"[O"),this.element.classList.remove("focus"),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;const e=this.buffer.ybase+this.buffer.y,t=this.buffer.lines.get(e);if(!t)return;const i=Math.min(this.buffer.x,this.cols-1),s=this._renderService.dimensions.css.cell.height,r=t.getWidth(i),n=this._renderService.dimensions.css.cell.width*r,o=this.buffer.y*this._renderService.dimensions.css.cell.height,a=i*this._renderService.dimensions.css.cell.width;this.textarea.style.left=a+"px",this.textarea.style.top=o+"px",this.textarea.style.width=n+"px",this.textarea.style.height=s+"px",this.textarea.style.lineHeight=s+"px",this.textarea.style.zIndex="-5"}_initGlobal(){this._bindKeys(),this._register((0,I.addDisposableListener)(this.element,"copy",(e=>{this.hasSelection()&&(0,s.copyHandler)(e,this._selectionService)})));const e=e=>(0,s.handlePasteEvent)(e,this.textarea,this.coreService,this.optionsService);this._register((0,I.addDisposableListener)(this.textarea,"paste",e)),this._register((0,I.addDisposableListener)(this.element,"paste",e)),y.isFirefox?this._register((0,I.addDisposableListener)(this.element,"mousedown",(e=>{2===e.button&&(0,s.rightClickHandler)(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)}))):this._register((0,I.addDisposableListener)(this.element,"contextmenu",(e=>{(0,s.rightClickHandler)(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)}))),y.isLinux&&this._register((0,I.addDisposableListener)(this.element,"auxclick",(e=>{1===e.button&&(0,s.moveTextAreaUnderMouseCursor)(e,this.textarea,this.screenElement)})))}_bindKeys(){this._register((0,I.addDisposableListener)(this.textarea,"keyup",(e=>this._keyUp(e)),!0)),this._register((0,I.addDisposableListener)(this.textarea,"keydown",(e=>this._keyDown(e)),!0)),this._register((0,I.addDisposableListener)(this.textarea,"keypress",(e=>this._keyPress(e)),!0)),this._register((0,I.addDisposableListener)(this.textarea,"compositionstart",(()=>this._compositionHelper.compositionstart()))),this._register((0,I.addDisposableListener)(this.textarea,"compositionupdate",(e=>this._compositionHelper.compositionupdate(e)))),this._register((0,I.addDisposableListener)(this.textarea,"compositionend",(()=>this._compositionHelper.compositionend()))),this._register((0,I.addDisposableListener)(this.textarea,"input",(e=>this._inputEvent(e)),!0)),this._register(this.onRender((()=>this._compositionHelper.updateCompositionElements())))}open(e){if(!e)throw new Error("Terminal requires a parent element.");if(e.isConnected||this._logService.debug("Terminal.open was called on an element that was not attached to the DOM"),this.element?.ownerDocument.defaultView&&this._coreBrowserService)return void(this.element.ownerDocument.defaultView!==this._coreBrowserService.window&&(this._coreBrowserService.window=this.element.ownerDocument.defaultView));this._document=e.ownerDocument,this.options.documentOverride&&this.options.documentOverride instanceof Document&&(this._document=this.optionsService.rawOptions.documentOverride),this.element=this._document.createElement("div"),this.element.dir="ltr",this.element.classList.add("terminal"),this.element.classList.add("xterm"),e.appendChild(this.element);const t=this._document.createDocumentFragment();this._viewportElement=this._document.createElement("div"),this._viewportElement.classList.add("xterm-viewport"),t.appendChild(this._viewportElement),this.screenElement=this._document.createElement("div"),this.screenElement.classList.add("xterm-screen"),this._register((0,I.addDisposableListener)(this.screenElement,"mousemove",(e=>this.updateCursorStyle(e)))),this._helperContainer=this._document.createElement("div"),this._helperContainer.classList.add("xterm-helpers"),this.screenElement.appendChild(this._helperContainer),t.appendChild(this.screenElement);const i=this.textarea=this._document.createElement("textarea");this.textarea.classList.add("xterm-helper-textarea"),this.textarea.setAttribute("aria-label",r.promptLabel.get()),y.isChromeOS||this.textarea.setAttribute("aria-multiline","false"),this.textarea.setAttribute("autocorrect","off"),this.textarea.setAttribute("autocapitalize","off"),this.textarea.setAttribute("spellcheck","false"),this.textarea.tabIndex=0,this._register(this.optionsService.onSpecificOptionChange("disableStdin",(()=>i.readOnly=this.optionsService.rawOptions.disableStdin))),this.textarea.readOnly=this.optionsService.rawOptions.disableStdin,this._coreBrowserService=this._register(this._instantiationService.createInstance(_.CoreBrowserService,this.textarea,e.ownerDocument.defaultView??window,this._document??"undefined"!=typeof window?window.document:null)),this._instantiationService.setService(v.ICoreBrowserService,this._coreBrowserService),this._register((0,I.addDisposableListener)(this.textarea,"focus",(e=>this._handleTextAreaFocus(e)))),this._register((0,I.addDisposableListener)(this.textarea,"blur",(()=>this._handleTextAreaBlur()))),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(d.CharSizeService,this._document,this._helperContainer),this._instantiationService.setService(v.ICharSizeService,this._charSizeService),this._themeService=this._instantiationService.createInstance(S.ThemeService),this._instantiationService.setService(v.IThemeService,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(u.CharacterJoinerService),this._instantiationService.setService(v.ICharacterJoinerService,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(g.RenderService,this.rows,this.screenElement)),this._instantiationService.setService(v.IRenderService,this._renderService),this._register(this._renderService.onRenderedViewportChange((e=>this._onRender.fire(e)))),this.onResize((e=>this._renderService.resize(e.cols,e.rows))),this._compositionView=this._document.createElement("div"),this._compositionView.classList.add("composition-view"),this._compositionHelper=this._instantiationService.createInstance(h.CompositionHelper,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(p.MouseService),this._instantiationService.setService(v.IMouseService,this._mouseService);const s=this._linkifier.value=this._register(this._instantiationService.createInstance(M.Linkifier,this.screenElement));this.element.appendChild(t);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this._register(this.onCursorMove((()=>{this._renderService.handleCursorMove(),this._syncTextArea()}))),this._register(this.onResize((()=>this._renderService.handleResize(this.cols,this.rows)))),this._register(this.onBlur((()=>this._renderService.handleBlur()))),this._register(this.onFocus((()=>this._renderService.handleFocus()))),this._viewport=this._register(this._instantiationService.createInstance(o.Viewport,this.element,this.screenElement)),this._register(this._viewport.onRequestScrollLines((e=>{super.scrollLines(e,!1),this.refresh(0,this.rows-1)}))),this._selectionService=this._register(this._instantiationService.createInstance(m.SelectionService,this.element,this.screenElement,s)),this._instantiationService.setService(v.ISelectionService,this._selectionService),this._register(this._selectionService.onRequestScrollLines((e=>this.scrollLines(e.amount,e.suppressScrollEvent)))),this._register(this._selectionService.onSelectionChange((()=>this._onSelectionChange.fire()))),this._register(this._selectionService.onRequestRedraw((e=>this._renderService.handleSelectionChanged(e.start,e.end,e.columnSelectMode)))),this._register(this._selectionService.onLinuxMouseSelection((e=>{this.textarea.value=e,this.textarea.focus(),this.textarea.select()}))),this._register(O.Event.any(this._onScroll.event,this._inputHandler.onScroll)((()=>{this._selectionService.refresh(),this._viewport?.queueSync()}))),this._register(this._instantiationService.createInstance(a.BufferDecorationRenderer,this.screenElement)),this._register((0,I.addDisposableListener)(this.element,"mousedown",(e=>this._selectionService.handleMouseDown(e)))),this.coreMouseService.areMouseEventsActive?(this._selectionService.disable(),this.element.classList.add("enable-mouse-events")):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager.value=this._instantiationService.createInstance(k.AccessibilityManager,this)),this._register(this.optionsService.onSpecificOptionChange("screenReaderMode",(e=>this._handleScreenReaderModeOptionChange(e)))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(l.OverviewRulerRenderer,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRuler",(e=>{!this._overviewRulerRenderer&&e&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(l.OverviewRulerRenderer,this._viewportElement,this.screenElement)))})),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(c.DomRenderer,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){const e=this,t=this.element;function i(t){const i=e._mouseService.getMouseReportCoords(t,e.screenElement);if(!i)return!1;let s,r;switch(t.overrideType||t.type){case"mousemove":r=32,void 0===t.buttons?(s=3,void 0!==t.button&&(s=t.button<3?t.button:3)):s=1&t.buttons?0:4&t.buttons?1:2&t.buttons?2:3;break;case"mouseup":r=0,s=t.button<3?t.button:3;break;case"mousedown":r=1,s=t.button<3?t.button:3;break;case"wheel":if(e._customWheelEventHandler&&!1===e._customWheelEventHandler(t))return!1;const i=t.deltaY;if(0===i)return!1;if(0===e.coreMouseService.consumeWheelEvent(t,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr))return!1;r=i<0?0:1,s=4;break;default:return!1}return!(void 0===r||void 0===s||s>4)&&e.coreMouseService.triggerMouseEvent({col:i.col,row:i.row,x:i.x,y:i.y,button:s,action:r,ctrl:t.ctrlKey,alt:t.altKey,shift:t.shiftKey})}const s={mouseup:null,wheel:null,mousedrag:null,mousemove:null},r={mouseup:e=>(i(e),e.buttons||(this._document.removeEventListener("mouseup",s.mouseup),s.mousedrag&&this._document.removeEventListener("mousemove",s.mousedrag)),this.cancel(e)),wheel:e=>(i(e),this.cancel(e,!0)),mousedrag:e=>{e.buttons&&i(e)},mousemove:e=>{e.buttons||i(e)}};this._register(this.coreMouseService.onProtocolChange((e=>{e?("debug"===this.optionsService.rawOptions.logLevel&&this._logService.debug("Binding to mouse events:",this.coreMouseService.explainEvents(e)),this.element.classList.add("enable-mouse-events"),this._selectionService.disable()):(this._logService.debug("Unbinding from mouse events."),this.element.classList.remove("enable-mouse-events"),this._selectionService.enable()),8&e?s.mousemove||(t.addEventListener("mousemove",r.mousemove),s.mousemove=r.mousemove):(t.removeEventListener("mousemove",s.mousemove),s.mousemove=null),16&e?s.wheel||(t.addEventListener("wheel",r.wheel,{passive:!1}),s.wheel=r.wheel):(t.removeEventListener("wheel",s.wheel),s.wheel=null),2&e?s.mouseup||(s.mouseup=r.mouseup):(this._document.removeEventListener("mouseup",s.mouseup),s.mouseup=null),4&e?s.mousedrag||(s.mousedrag=r.mousedrag):(this._document.removeEventListener("mousemove",s.mousedrag),s.mousedrag=null)}))),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register((0,I.addDisposableListener)(t,"mousedown",(e=>{if(e.preventDefault(),this.focus(),this.coreMouseService.areMouseEventsActive&&!this._selectionService.shouldForceSelection(e))return i(e),s.mouseup&&this._document.addEventListener("mouseup",s.mouseup),s.mousedrag&&this._document.addEventListener("mousemove",s.mousedrag),this.cancel(e)}))),this._register((0,I.addDisposableListener)(t,"wheel",(t=>{if(!s.wheel){if(this._customWheelEventHandler&&!1===this._customWheelEventHandler(t))return!1;if(!this.buffer.hasScrollback){if(0===t.deltaY)return!1;if(0===e.coreMouseService.consumeWheelEvent(t,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr))return this.cancel(t,!0);const i=E.C0.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?"O":"[")+(t.deltaY<0?"A":"B");return this.coreService.triggerDataEvent(i,!0),this.cancel(t,!0)}}}),{passive:!1}))}refresh(e,t){this._renderService?.refreshRows(e,t)}updateCursorStyle(e){this._selectionService?.shouldColumnSelect(e)?this.element.classList.add("column-select"):this.element.classList.remove("column-select")}_showCursor(){this.coreService.isCursorInitialized||(this.coreService.isCursorInitialized=!0,this.refresh(this.buffer.y,this.buffer.y))}scrollLines(e,t){this._viewport?this._viewport.scrollLines(e):super.scrollLines(e,t),this.refresh(0,this.rows-1)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){e&&this._viewport?this._viewport.scrollToLine(this.buffer.ybase,!0):this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){const t=e-this._bufferService.buffer.ydisp;0!==t&&this.scrollLines(t)}paste(e){(0,s.paste)(e,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(e){this._customKeyEventHandler=e}attachCustomWheelEventHandler(e){this._customWheelEventHandler=e}registerLinkProvider(e){return this._linkProviderService.registerLinkProvider(e)}registerCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");const t=this._characterJoinerService.register(e);return this.refresh(0,this.rows-1),t}deregisterCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");this._characterJoinerService.deregister(e)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(e){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+e)}registerDecoration(e){return this._decorationService.registerDecoration(e)}hasSelection(){return!!this._selectionService&&this._selectionService.hasSelection}select(e,t,i){this._selectionService.setSelection(e,t,i)}getSelection(){return this._selectionService?this._selectionService.selectionText:""}getSelectionPosition(){if(this._selectionService&&this._selectionService.hasSelection)return{start:{x:this._selectionService.selectionStart[0],y:this._selectionService.selectionStart[1]},end:{x:this._selectionService.selectionEnd[0],y:this._selectionService.selectionEnd[1]}}}clearSelection(){this._selectionService?.clearSelection()}selectAll(){this._selectionService?.selectAll()}selectLines(e,t){this._selectionService?.selectLines(e,t)}_keyDown(e){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&!1===this._customKeyEventHandler(e))return!1;const t=this.browser.isMac&&this.options.macOptionIsMeta&&e.altKey;if(!t&&!this._compositionHelper.keydown(e))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(!0),!1;t||"Dead"!==e.key&&"AltGraph"!==e.key||(this._unprocessedDeadKey=!0);const i=(0,D.evaluateKeyboardEvent)(e,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),3===i.type||2===i.type){const t=this.rows-1;return this.scrollLines(2===i.type?-t:t),this.cancel(e,!0)}return 1===i.type&&this.selectAll(),!!this._isThirdLevelShift(this.browser,e)||(i.cancel&&this.cancel(e,!0),!i.key||!!(e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&1===e.key.length&&e.key.charCodeAt(0)>=65&&e.key.charCodeAt(0)<=90)||(this._unprocessedDeadKey?(this._unprocessedDeadKey=!1,!0):(i.key!==E.C0.ETX&&i.key!==E.C0.CR||(this.textarea.value=""),this._onKey.fire({key:i.key,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(i.key,!0),!this.optionsService.rawOptions.screenReaderMode||e.altKey||e.ctrlKey?this.cancel(e,!0):void(this._keyDownHandled=!0))))}_isThirdLevelShift(e,t){const i=e.isMac&&!this.options.macOptionIsMeta&&t.altKey&&!t.ctrlKey&&!t.metaKey||e.isWindows&&t.altKey&&t.ctrlKey&&!t.metaKey||e.isWindows&&t.getModifierState("AltGraph");return"keypress"===t.type?i:i&&(!t.keyCode||t.keyCode>47)}_keyUp(e){this._keyDownSeen=!1,this._customKeyEventHandler&&!1===this._customKeyEventHandler(e)||(function(e){return 16===e.keyCode||17===e.keyCode||18===e.keyCode}(e)||this.focus(),this.updateCursorStyle(e),this._keyPressHandled=!1)}_keyPress(e){let t;if(this._keyPressHandled=!1,this._keyDownHandled)return!1;if(this._customKeyEventHandler&&!1===this._customKeyEventHandler(e))return!1;if(this.cancel(e),e.charCode)t=e.charCode;else if(null===e.which||void 0===e.which)t=e.keyCode;else{if(0===e.which||0===e.charCode)return!1;t=e.which}return!(!t||(e.altKey||e.ctrlKey||e.metaKey)&&!this._isThirdLevelShift(this.browser,e)||(t=String.fromCharCode(t),this._onKey.fire({key:t,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(t,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,0))}_inputEvent(e){if(e.data&&"insertText"===e.inputType&&(!e.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;const t=e.data;return this.coreService.triggerDataEvent(t,!0),this.cancel(e),!0}return!1}resize(e,t){e!==this.cols||t!==this.rows?super.resize(e,t):this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure()}_afterResize(e,t){this._charSizeService?.measure()}clear(){if(0!==this.buffer.ybase||0!==this.buffer.y){this.buffer.clearAllMarkers(),this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let e=1;e=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.Linkifier=void 0;const n=i(7150),o=i(6501),a=i(7098),l=i(802),h=i(7093);let c=class extends n.Disposable{get currentLink(){return this._currentLink}constructor(e,t,i,s,r){super(),this._element=e,this._mouseService=t,this._renderService=i,this._bufferService=s,this._linkProviderService=r,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this._register(new l.Emitter),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this._register(new l.Emitter),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this._register((0,n.toDisposable)((()=>{(0,n.dispose)(this._linkCacheDisposables),this._linkCacheDisposables.length=0,this._lastMouseEvent=void 0,this._activeProviderReplies?.clear()}))),this._register(this._bufferService.onResize((()=>{this._clearCurrentLink(),this._wasResized=!0}))),this._register((0,h.addDisposableListener)(this._element,"mouseleave",(()=>{this._isMouseOut=!0,this._clearCurrentLink()}))),this._register((0,h.addDisposableListener)(this._element,"mousemove",this._handleMouseMove.bind(this))),this._register((0,h.addDisposableListener)(this._element,"mousedown",this._handleMouseDown.bind(this))),this._register((0,h.addDisposableListener)(this._element,"mouseup",this._handleMouseUp.bind(this)))}_handleMouseMove(e){this._lastMouseEvent=e;const t=this._positionFromMouseEvent(e,this._element,this._mouseService);if(!t)return;this._isMouseOut=!1;const i=e.composedPath();for(let e=0;e{e?.forEach((e=>{e.link.dispose&&e.link.dispose()}))})),this._activeProviderReplies=new Map,this._activeLine=e.y);let i=!1;for(const[s,r]of this._linkProviderService.linkProviders.entries())if(t){const t=this._activeProviderReplies?.get(s);t&&(i=this._checkLinkProviderResult(s,e,i))}else r.provideLinks(e.y,(t=>{if(this._isMouseOut)return;const r=t?.map((e=>({link:e})));this._activeProviderReplies?.set(s,r),i=this._checkLinkProviderResult(s,e,i),this._activeProviderReplies?.size===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)}))}_removeIntersectingLinks(e,t){const i=new Set;for(let s=0;se?this._bufferService.cols:s.link.range.end.x;for(let e=n;e<=o;e++){if(i.has(e)){r.splice(t--,1);break}i.add(e)}}}}_checkLinkProviderResult(e,t,i){if(!this._activeProviderReplies)return i;const s=this._activeProviderReplies.get(e);let r=!1;for(let t=0;tthis._linkAtPosition(e.link,t)));e&&(i=!0,this._handleNewLink(e))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!i)for(let e=0;ethis._linkAtPosition(e.link,t)));if(s){i=!0,this._handleNewLink(s);break}}return i}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){if(!this._currentLink)return;const t=this._positionFromMouseEvent(e,this._element,this._mouseService);var i,s;t&&this._mouseDownLink&&(i=this._mouseDownLink.link,s=this._currentLink.link,i.text===s.text&&i.range.start.x===s.range.start.x&&i.range.start.y===s.range.start.y&&i.range.end.x===s.range.end.x&&i.range.end.y===s.range.end.y)&&this._linkAtPosition(this._currentLink.link,t)&&this._currentLink.link.activate(e,this._currentLink.link.text)}_clearCurrentLink(e,t){this._currentLink&&this._lastMouseEvent&&(!e||!t||this._currentLink.link.range.start.y>=e&&this._currentLink.link.range.end.y<=t)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,(0,n.dispose)(this._linkCacheDisposables),this._linkCacheDisposables.length=0)}_handleNewLink(e){if(!this._lastMouseEvent)return;const t=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);t&&this._linkAtPosition(e.link,t)&&(this._currentLink=e,this._currentLink.state={decorations:{underline:void 0===e.link.decorations||e.link.decorations.underline,pointerCursor:void 0===e.link.decorations||e.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,e.link,this._lastMouseEvent),e.link.decorations={},Object.defineProperties(e.link.decorations,{pointerCursor:{get:()=>this._currentLink?.state?.decorations.pointerCursor,set:e=>{this._currentLink?.state&&this._currentLink.state.decorations.pointerCursor!==e&&(this._currentLink.state.decorations.pointerCursor=e,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",e))}},underline:{get:()=>this._currentLink?.state?.decorations.underline,set:t=>{this._currentLink?.state&&this._currentLink?.state?.decorations.underline!==t&&(this._currentLink.state.decorations.underline=t,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,t))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange((e=>{if(!this._currentLink)return;const t=0===e.start?0:e.start+1+this._bufferService.buffer.ydisp,i=this._bufferService.buffer.ydisp+1+e.end;if(this._currentLink.link.range.start.y>=t&&this._currentLink.link.range.end.y<=i&&(this._clearCurrentLink(t,i),this._lastMouseEvent)){const e=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);e&&this._askForLink(e,!1)}}))))}_linkHover(e,t,i){this._currentLink?.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!0),this._currentLink.state.decorations.pointerCursor&&e.classList.add("xterm-cursor-pointer")),t.hover&&t.hover(i,t.text)}_fireUnderlineEvent(e,t){const i=e.range,s=this._bufferService.buffer.ydisp,r=this._createLinkUnderlineEvent(i.start.x-1,i.start.y-s-1,i.end.x,i.end.y-s-1,void 0);(t?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(r)}_linkLeave(e,t,i){this._currentLink?.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!1),this._currentLink.state.decorations.pointerCursor&&e.classList.remove("xterm-cursor-pointer")),t.leave&&t.leave(i,t.text)}_linkAtPosition(e,t){const i=e.range.start.y*this._bufferService.cols+e.range.start.x,s=e.range.end.y*this._bufferService.cols+e.range.end.x,r=t.y*this._bufferService.cols+t.x;return i<=r&&r<=s}_positionFromMouseEvent(e,t,i){const s=i.getCoords(e,t,this._bufferService.cols,this._bufferService.rows);if(s)return{x:s[0],y:s[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,t,i,s,r){return{x1:e,y1:t,x2:i,y2:s,cols:this._bufferService.cols,fg:r}}};t.Linkifier=c,t.Linkifier=c=s([r(1,a.IMouseService),r(2,a.IRenderService),r(3,o.IBufferService),r(4,a.ILinkProviderService)],c)},7721:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.tooMuchOutput=t.promptLabel=void 0;let i="Terminal input";const s={get:()=>i,set:e=>i=e};t.promptLabel=s;let r="Too much output to announce, navigate to rows manually to read";const n={get:()=>r,set:e=>r=e};t.tooMuchOutput=n},3285:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.OscLinkProvider=void 0;const n=i(3055),o=i(6501);let a=class{constructor(e,t,i){this._bufferService=e,this._optionsService=t,this._oscLinkService=i}provideLinks(e,t){const i=this._bufferService.buffer.lines.get(e-1);if(!i)return void t(void 0);const s=[],r=this._optionsService.rawOptions.linkHandler,o=new n.CellData,a=i.getTrimmedLength();let h=-1,c=-1,d=!1;for(let t=0;tr?r.activate(e,t,n):l(0,t),hover:(e,t)=>r?.hover?.(e,t,n),leave:(e,t)=>r?.leave?.(e,t,n)})}d=!1,o.hasExtendedAttrs()&&o.extended.urlId?(c=t,h=o.extended.urlId):(c=-1,h=-1)}}t(s)}};function l(e,t){if(confirm(`Do you want to navigate to ${t}?\n\nWARNING: This link could potentially be dangerous`)){const e=window.open();if(e){try{e.opener=null}catch{}e.location.href=t}else console.warn("Opening link blocked as opener could not be cleared")}}t.OscLinkProvider=a,t.OscLinkProvider=a=s([r(0,o.IBufferService),r(1,o.IOptionsService),r(2,o.IOscLinkService)],a)},4852:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RenderDebouncer=void 0,t.RenderDebouncer=class{constructor(e,t){this._renderCallback=e,this._coreBrowserService=t,this._refreshCallbacks=[]}dispose(){this._animationFrame&&(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0)}addRefreshCallback(e){return this._refreshCallbacks.push(e),this._animationFrame||(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame((()=>this._innerRefresh()))),this._animationFrame}refresh(e,t,i){this._rowCount=i,e=void 0!==e?e:0,t=void 0!==t?t:this._rowCount-1,this._rowStart=void 0!==this._rowStart?Math.min(this._rowStart,e):e,this._rowEnd=void 0!==this._rowEnd?Math.max(this._rowEnd,t):t,this._animationFrame||(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame((()=>this._innerRefresh())))}_innerRefresh(){if(this._animationFrame=void 0,void 0===this._rowStart||void 0===this._rowEnd||void 0===this._rowCount)return void this._runRefreshCallbacks();const e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(const e of this._refreshCallbacks)e(0);this._refreshCallbacks=[]}}},4292:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TimeBasedDebouncer=void 0,t.TimeBasedDebouncer=class{constructor(e,t=1e3){this._renderCallback=e,this._debounceThresholdMS=t,this._lastRefreshMs=0,this._additionalRefreshRequested=!1}dispose(){this._refreshTimeoutID&&clearTimeout(this._refreshTimeoutID)}refresh(e,t,i){this._rowCount=i,e=void 0!==e?e:0,t=void 0!==t?t:this._rowCount-1,this._rowStart=void 0!==this._rowStart?Math.min(this._rowStart,e):e,this._rowEnd=void 0!==this._rowEnd?Math.max(this._rowEnd,t):t;const s=performance.now();if(s-this._lastRefreshMs>=this._debounceThresholdMS)this._lastRefreshMs=s,this._innerRefresh();else if(!this._additionalRefreshRequested){const e=s-this._lastRefreshMs,t=this._debounceThresholdMS-e;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout((()=>{this._lastRefreshMs=performance.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0}),t)}}_innerRefresh(){if(void 0===this._rowStart||void 0===this._rowEnd||void 0===this._rowCount)return;const e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t)}}},9302:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DEFAULT_ANSI_COLORS=void 0;const s=i(4103);t.DEFAULT_ANSI_COLORS=Object.freeze((()=>{const e=[s.css.toColor("#2e3436"),s.css.toColor("#cc0000"),s.css.toColor("#4e9a06"),s.css.toColor("#c4a000"),s.css.toColor("#3465a4"),s.css.toColor("#75507b"),s.css.toColor("#06989a"),s.css.toColor("#d3d7cf"),s.css.toColor("#555753"),s.css.toColor("#ef2929"),s.css.toColor("#8ae234"),s.css.toColor("#fce94f"),s.css.toColor("#729fcf"),s.css.toColor("#ad7fa8"),s.css.toColor("#34e2e2"),s.css.toColor("#eeeeec")],t=[0,95,135,175,215,255];for(let i=0;i<216;i++){const r=t[i/36%6|0],n=t[i/6%6|0],o=t[i%6];e.push({css:s.channels.toCss(r,n,o),rgba:s.channels.toRgba(r,n,o)})}for(let t=0;t<24;t++){const i=8+10*t;e.push({css:s.channels.toCss(i,i,i),rgba:s.channels.toRgba(i,i,i)})}return e})())},4017:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.Viewport=void 0;const n=i(7098),o=i(7150),a=i(6501),l=i(7093),h=i(8234),c=i(802),d=i(9881);let u=class extends o.Disposable{constructor(e,t,i,s,r,n,a,u){super(),this._bufferService=i,this._optionsService=a,this._renderService=u,this._onRequestScrollLines=this._register(new c.Emitter),this.onRequestScrollLines=this._onRequestScrollLines.event,this._isSyncing=!1,this._isHandlingScroll=!1,this._suppressOnScrollHandler=!1;const _=this._register(new d.Scrollable({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:e=>(0,l.scheduleAtNextAnimationFrame)(s.window,e)}));this._register(this._optionsService.onSpecificOptionChange("smoothScrollDuration",(()=>{_.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)}))),this._scrollableElement=this._register(new h.SmoothScrollableElement(t,{vertical:1,horizontal:2,useShadows:!1,mouseWheelSmoothScroll:!0,...this._getChangeOptions()},_)),this._register(this._optionsService.onMultipleOptionChange(["scrollSensitivity","fastScrollSensitivity","overviewRuler"],(()=>this._scrollableElement.updateOptions(this._getChangeOptions())))),this._register(r.onProtocolChange((e=>{this._scrollableElement.updateOptions({handleMouseWheel:!(16&e)})}))),this._scrollableElement.setScrollDimensions({height:0,scrollHeight:0}),this._register(c.Event.runAndSubscribe(n.onChangeColors,(()=>{this._scrollableElement.getDomNode().style.backgroundColor=n.colors.background.css}))),e.appendChild(this._scrollableElement.getDomNode()),this._register((0,o.toDisposable)((()=>this._scrollableElement.getDomNode().remove()))),this._styleElement=s.mainDocument.createElement("style"),t.appendChild(this._styleElement),this._register((0,o.toDisposable)((()=>this._styleElement.remove()))),this._register(c.Event.runAndSubscribe(n.onChangeColors,(()=>{this._styleElement.textContent=[".xterm .xterm-scrollable-element > .scrollbar > .slider {",` background: ${n.colors.scrollbarSliderBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider:hover {",` background: ${n.colors.scrollbarSliderHoverBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider.active {",` background: ${n.colors.scrollbarSliderActiveBackground.css};`,"}"].join("\n")}))),this._register(this._bufferService.onResize((()=>this.queueSync()))),this._register(this._bufferService.buffers.onBufferActivate((()=>{this._latestYDisp=void 0,this.queueSync()}))),this._register(this._bufferService.onScroll((()=>this._sync()))),this._register(this._scrollableElement.onScroll((e=>this._handleScroll(e))))}scrollLines(e){const t=this._scrollableElement.getScrollPosition();this._scrollableElement.setScrollPosition({reuseAnimation:!0,scrollTop:t.scrollTop+e*this._renderService.dimensions.css.cell.height})}scrollToLine(e,t){t&&(this._latestYDisp=e),this._scrollableElement.setScrollPosition({reuseAnimation:!t,scrollTop:e*this._renderService.dimensions.css.cell.height})}_getChangeOptions(){return{mouseWheelScrollSensitivity:this._optionsService.rawOptions.scrollSensitivity,fastScrollSensitivity:this._optionsService.rawOptions.fastScrollSensitivity,verticalScrollbarSize:this._optionsService.rawOptions.overviewRuler?.width||14}}queueSync(e){void 0!==e&&(this._latestYDisp=e),void 0===this._queuedAnimationFrame&&(this._queuedAnimationFrame=this._renderService.addRefreshCallback((()=>{this._queuedAnimationFrame=void 0,this._sync(this._latestYDisp)})))}_sync(e=this._bufferService.buffer.ydisp){this._renderService&&!this._isSyncing&&(this._isSyncing=!0,this._suppressOnScrollHandler=!0,this._scrollableElement.setScrollDimensions({height:this._renderService.dimensions.css.canvas.height,scrollHeight:this._renderService.dimensions.css.cell.height*this._bufferService.buffer.lines.length}),this._suppressOnScrollHandler=!1,e!==this._latestYDisp&&this._scrollableElement.setScrollPosition({scrollTop:e*this._renderService.dimensions.css.cell.height}),this._isSyncing=!1)}_handleScroll(e){if(!this._renderService)return;if(this._isHandlingScroll||this._suppressOnScrollHandler)return;this._isHandlingScroll=!0;const t=Math.round(e.scrollTop/this._renderService.dimensions.css.cell.height),i=t-this._bufferService.buffer.ydisp;0!==i&&(this._latestYDisp=t,this._onRequestScrollLines.fire(i)),this._isHandlingScroll=!1}};t.Viewport=u,t.Viewport=u=s([r(2,a.IBufferService),r(3,n.ICoreBrowserService),r(4,a.ICoreMouseService),r(5,n.IThemeService),r(6,a.IOptionsService),r(7,n.IRenderService)],u)},4196:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.BufferDecorationRenderer=void 0;const n=i(7098),o=i(7150),a=i(6501);let l=class extends o.Disposable{constructor(e,t,i,s,r){super(),this._screenElement=e,this._bufferService=t,this._coreBrowserService=i,this._decorationService=s,this._renderService=r,this._decorationElements=new Map,this._altBufferIsActive=!1,this._dimensionsChanged=!1,this._container=document.createElement("div"),this._container.classList.add("xterm-decoration-container"),this._screenElement.appendChild(this._container),this._register(this._renderService.onRenderedViewportChange((()=>this._doRefreshDecorations()))),this._register(this._renderService.onDimensionsChange((()=>{this._dimensionsChanged=!0,this._queueRefresh()}))),this._register(this._coreBrowserService.onDprChange((()=>this._queueRefresh()))),this._register(this._bufferService.buffers.onBufferActivate((()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt}))),this._register(this._decorationService.onDecorationRegistered((()=>this._queueRefresh()))),this._register(this._decorationService.onDecorationRemoved((e=>this._removeDecoration(e)))),this._register((0,o.toDisposable)((()=>{this._container.remove(),this._decorationElements.clear()})))}_queueRefresh(){void 0===this._animationFrame&&(this._animationFrame=this._renderService.addRefreshCallback((()=>{this._doRefreshDecorations(),this._animationFrame=void 0})))}_doRefreshDecorations(){for(const e of this._decorationService.decorations)this._renderDecoration(e);this._dimensionsChanged=!1}_renderDecoration(e){this._refreshStyle(e),this._dimensionsChanged&&this._refreshXPosition(e)}_createElement(e){const t=this._coreBrowserService.mainDocument.createElement("div");t.classList.add("xterm-decoration"),t.classList.toggle("xterm-decoration-top-layer","top"===e?.options?.layer),t.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,t.style.height=(e.options.height||1)*this._renderService.dimensions.css.cell.height+"px",t.style.top=(e.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height+"px",t.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;const i=e.options.x??0;return i&&i>this._bufferService.cols&&(t.style.display="none"),this._refreshXPosition(e,t),t}_refreshStyle(e){const t=e.marker.line-this._bufferService.buffers.active.ydisp;if(t<0||t>=this._bufferService.rows)e.element&&(e.element.style.display="none",e.onRenderEmitter.fire(e.element));else{let i=this._decorationElements.get(e);i||(i=this._createElement(e),e.element=i,this._decorationElements.set(e,i),this._container.appendChild(i),e.onDispose((()=>{this._decorationElements.delete(e),i.remove()}))),i.style.display=this._altBufferIsActive?"none":"block",this._altBufferIsActive||(i.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,i.style.height=(e.options.height||1)*this._renderService.dimensions.css.cell.height+"px",i.style.top=t*this._renderService.dimensions.css.cell.height+"px",i.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`),e.onRenderEmitter.fire(i)}}_refreshXPosition(e,t=e.element){if(!t)return;const i=e.options.x??0;"right"===(e.options.anchor||"left")?t.style.right=i?i*this._renderService.dimensions.css.cell.width+"px":"":t.style.left=i?i*this._renderService.dimensions.css.cell.width+"px":""}_removeDecoration(e){this._decorationElements.get(e)?.remove(),this._decorationElements.delete(e),e.dispose()}};t.BufferDecorationRenderer=l,t.BufferDecorationRenderer=l=s([r(1,a.IBufferService),r(2,n.ICoreBrowserService),r(3,a.IDecorationService),r(4,n.IRenderService)],l)},957:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ColorZoneStore=void 0,t.ColorZoneStore=class{constructor(){this._zones=[],this._zonePool=[],this._zonePoolIndex=0,this._linePadding={full:0,left:0,center:0,right:0}}get zones(){return this._zonePool.length=Math.min(this._zonePool.length,this._zones.length),this._zones}clear(){this._zones.length=0,this._zonePoolIndex=0}addDecoration(e){if(e.options.overviewRulerOptions){for(const t of this._zones)if(t.color===e.options.overviewRulerOptions.color&&t.position===e.options.overviewRulerOptions.position){if(this._lineIntersectsZone(t,e.marker.line))return;if(this._lineAdjacentToZone(t,e.marker.line,e.options.overviewRulerOptions.position))return void this._addLineToZone(t,e.marker.line)}if(this._zonePoolIndex=e.startBufferLine&&t<=e.endBufferLine}_lineAdjacentToZone(e,t,i){return t>=e.startBufferLine-this._linePadding[i||"full"]&&t<=e.endBufferLine+this._linePadding[i||"full"]}_addLineToZone(e,t){e.startBufferLine=Math.min(e.startBufferLine,t),e.endBufferLine=Math.max(e.endBufferLine,t)}}},9925:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.OverviewRulerRenderer=void 0;const n=i(957),o=i(7098),a=i(7150),l=i(6501),h={full:0,left:0,center:0,right:0},c={full:0,left:0,center:0,right:0},d={full:0,left:0,center:0,right:0};let u=class extends a.Disposable{get _width(){return this._optionsService.options.overviewRuler?.width||0}constructor(e,t,i,s,r,o,l,h){super(),this._viewportElement=e,this._screenElement=t,this._bufferService=i,this._decorationService=s,this._renderService=r,this._optionsService=o,this._themeService=l,this._coreBrowserService=h,this._colorZoneStore=new n.ColorZoneStore,this._shouldUpdateDimensions=!0,this._shouldUpdateAnchor=!0,this._lastKnownBufferLength=0,this._canvas=this._coreBrowserService.mainDocument.createElement("canvas"),this._canvas.classList.add("xterm-decoration-overview-ruler"),this._refreshCanvasDimensions(),this._viewportElement.parentElement?.insertBefore(this._canvas,this._viewportElement),this._register((0,a.toDisposable)((()=>this._canvas?.remove())));const c=this._canvas.getContext("2d");if(!c)throw new Error("Ctx cannot be null");this._ctx=c,this._register(this._decorationService.onDecorationRegistered((()=>this._queueRefresh(void 0,!0)))),this._register(this._decorationService.onDecorationRemoved((()=>this._queueRefresh(void 0,!0)))),this._register(this._renderService.onRenderedViewportChange((()=>this._queueRefresh()))),this._register(this._bufferService.buffers.onBufferActivate((()=>{this._canvas.style.display=this._bufferService.buffer===this._bufferService.buffers.alt?"none":"block"}))),this._register(this._bufferService.onScroll((()=>{this._lastKnownBufferLength!==this._bufferService.buffers.normal.lines.length&&(this._refreshDrawHeightConstants(),this._refreshColorZonePadding())}))),this._register(this._renderService.onRender((()=>{this._containerHeight&&this._containerHeight===this._screenElement.clientHeight||(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)}))),this._register(this._coreBrowserService.onDprChange((()=>this._queueRefresh(!0)))),this._register(this._optionsService.onSpecificOptionChange("overviewRuler",(()=>this._queueRefresh(!0)))),this._register(this._themeService.onChangeColors((()=>this._queueRefresh()))),this._queueRefresh(!0)}_refreshDrawConstants(){const e=Math.floor((this._canvas.width-1)/3),t=Math.ceil((this._canvas.width-1)/3);c.full=this._canvas.width,c.left=e,c.center=t,c.right=e,this._refreshDrawHeightConstants(),d.full=1,d.left=1,d.center=1+c.left,d.right=1+c.left+c.center}_refreshDrawHeightConstants(){h.full=Math.round(2*this._coreBrowserService.dpr);const e=this._canvas.height/this._bufferService.buffer.lines.length,t=Math.round(Math.max(Math.min(e,12),6)*this._coreBrowserService.dpr);h.left=t,h.center=t,h.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*h.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*h.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*h.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*h.right)}),this._lastKnownBufferLength=this._bufferService.buffers.normal.lines.length}_refreshCanvasDimensions(){this._canvas.style.width=`${this._width}px`,this._canvas.width=Math.round(this._width*this._coreBrowserService.dpr),this._canvas.style.height=`${this._screenElement.clientHeight}px`,this._canvas.height=Math.round(this._screenElement.clientHeight*this._coreBrowserService.dpr),this._refreshDrawConstants(),this._refreshColorZonePadding()}_refreshDecorations(){this._shouldUpdateDimensions&&this._refreshCanvasDimensions(),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._colorZoneStore.clear();for(const e of this._decorationService.decorations)this._colorZoneStore.addDecoration(e);this._ctx.lineWidth=1,this._renderRulerOutline();const e=this._colorZoneStore.zones;for(const t of e)"full"!==t.position&&this._renderColorZone(t);for(const t of e)"full"===t.position&&this._renderColorZone(t);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderRulerOutline(){this._ctx.fillStyle=this._themeService.colors.overviewRulerBorder.css,this._ctx.fillRect(0,0,1,this._canvas.height),this._optionsService.rawOptions.overviewRuler.showTopBorder&&this._ctx.fillRect(1,0,this._canvas.width-1,1),this._optionsService.rawOptions.overviewRuler.showBottomBorder&&this._ctx.fillRect(1,this._canvas.height-1,this._canvas.width-1,this._canvas.height)}_renderColorZone(e){this._ctx.fillStyle=e.color,this._ctx.fillRect(d[e.position||"full"],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-h[e.position||"full"]/2),c[e.position||"full"],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+h[e.position||"full"]))}_queueRefresh(e,t){this._shouldUpdateDimensions=e||this._shouldUpdateDimensions,this._shouldUpdateAnchor=t||this._shouldUpdateAnchor,void 0===this._animationFrame&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame((()=>{this._refreshDecorations(),this._animationFrame=void 0})))}};t.OverviewRulerRenderer=u,t.OverviewRulerRenderer=u=s([r(2,l.IBufferService),r(3,l.IDecorationService),r(4,o.IRenderService),r(5,l.IOptionsService),r(6,o.IThemeService),r(7,o.ICoreBrowserService)],u)},3618:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.CompositionHelper=void 0;const n=i(7098),o=i(6501),a=i(3534);let l=class{get isComposing(){return this._isComposing}constructor(e,t,i,s,r,n){this._textarea=e,this._compositionView=t,this._bufferService=i,this._optionsService=s,this._coreService=r,this._renderService=n,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=""}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent="",this._dataAlreadySent="",this._compositionView.classList.add("active")}compositionupdate(e){this._compositionView.textContent=e.data,this.updateCompositionElements(),setTimeout((()=>{this._compositionPosition.end=this._textarea.value.length}),0)}compositionend(){this._finalizeComposition(!0)}keydown(e){if(this._isComposing||this._isSendingComposition){if(20===e.keyCode||229===e.keyCode)return!1;if(16===e.keyCode||17===e.keyCode||18===e.keyCode)return!1;this._finalizeComposition(!1)}return 229!==e.keyCode||(this._handleAnyTextareaChanges(),!1)}_finalizeComposition(e){if(this._compositionView.classList.remove("active"),this._isComposing=!1,e){const e={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout((()=>{if(this._isSendingComposition){let t;this._isSendingComposition=!1,e.start+=this._dataAlreadySent.length,t=this._isComposing?this._textarea.value.substring(e.start,this._compositionPosition.start):this._textarea.value.substring(e.start),t.length>0&&this._coreService.triggerDataEvent(t,!0)}}),0)}else{this._isSendingComposition=!1;const e=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(e,!0)}}_handleAnyTextareaChanges(){const e=this._textarea.value;setTimeout((()=>{if(!this._isComposing){const t=this._textarea.value,i=t.replace(e,"");this._dataAlreadySent=i,t.length>e.length?this._coreService.triggerDataEvent(i,!0):t.lengththis.updateCompositionElements(!0)),0)}}};t.CompositionHelper=l,t.CompositionHelper=l=s([r(2,o.IBufferService),r(3,o.IOptionsService),r(4,o.ICoreService),r(5,n.IRenderService)],l)},5251:(e,t)=>{function i(e,t,i){const s=i.getBoundingClientRect(),r=e.getComputedStyle(i),n=parseInt(r.getPropertyValue("padding-left")),o=parseInt(r.getPropertyValue("padding-top"));return[t.clientX-s.left-n,t.clientY-s.top-o]}Object.defineProperty(t,"__esModule",{value:!0}),t.getCoordsRelativeToElement=i,t.getCoords=function(e,t,s,r,n,o,a,l,h){if(!o)return;const c=i(e,t,s);return c?(c[0]=Math.ceil((c[0]+(h?a/2:0))/a),c[1]=Math.ceil(c[1]/l),c[0]=Math.min(Math.max(c[0],1),r+(h?1:0)),c[1]=Math.min(Math.max(c[1],1),n),c):void 0}},9686:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.moveToCellSequence=function(e,t,i,s){const o=i.buffer.x,c=i.buffer.y;if(!i.buffer.hasScrollback)return function(e,t,i,s,o,c){return 0===r(t,s,o,c).length?"":h(a(e,t,e,t-n(t,o),!1,o).length,l("D",c))}(o,c,0,t,i,s)+r(c,t,i,s)+function(e,t,i,s,o,c){let d;d=r(t,s,o,c).length>0?s-n(s,o):t;const u=s,_=function(e,t,i,s,o,a){let l;return l=r(i,s,o,a).length>0?s-n(s,o):t,e=i&&le?"D":"C",h(Math.abs(o-e),l(d,s));d=c>t?"D":"C";const u=Math.abs(c-t);return h(function(e,t){return t.cols-e}(c>t?e:o,i)+(u-1)*i.cols+1+((c>t?o:e)-1),l(d,s))};const s=i(3534);function r(e,t,i,s){const r=e-n(e,i),a=t-n(t,i),c=Math.abs(r-a)-function(e,t,i){let s=0;const r=e-n(e,i),a=t-n(t,i);for(let n=0;n=0&&et?"A":"B"}function a(e,t,i,s,r,n){let o=e,a=t,l="";for(;(o!==i||a!==s)&&a>=0&&an.cols-1?(l+=n.buffer.translateBufferLineToString(a,!1,e,o),o=0,e=0,a++):!r&&o<0&&(l+=n.buffer.translateBufferLineToString(a,!1,0,e+1),o=n.cols-1,e=o,a--);return l+n.buffer.translateBufferLineToString(a,!1,e,o)}function l(e,t){const i=t?"O":"[";return s.C0.ESC+i+e}function h(e,t){e=Math.floor(e);let i="";for(let s=0;s=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.DomRenderer=void 0;const n=i(1433),o=i(2744),a=i(9176),l=i(6181),h=i(2274),c=i(7098),d=i(4103),u=i(7150),_=i(6501),f=i(802),p="xterm-dom-renderer-owner-",g="xterm-rows",m="xterm-fg-",v="xterm-bg-",S="xterm-focus",b="xterm-selection";let C=1,y=class extends u.Disposable{constructor(e,t,i,s,r,a,c,d,_,m,v,S,y,w){super(),this._terminal=e,this._document=t,this._element=i,this._screenElement=s,this._viewportElement=r,this._helperContainer=a,this._linkifier2=c,this._charSizeService=_,this._optionsService=m,this._bufferService=v,this._coreService=S,this._coreBrowserService=y,this._themeService=w,this._terminalClass=C++,this._rowElements=[],this._selectionRenderModel=(0,h.createSelectionRenderModel)(),this.onRequestRedraw=this._register(new f.Emitter).event,this._rowContainer=this._document.createElement("div"),this._rowContainer.classList.add(g),this._rowContainer.style.lineHeight="normal",this._rowContainer.setAttribute("aria-hidden","true"),this._refreshRowElements(this._bufferService.cols,this._bufferService.rows),this._selectionContainer=this._document.createElement("div"),this._selectionContainer.classList.add(b),this._selectionContainer.setAttribute("aria-hidden","true"),this.dimensions=(0,l.createRenderDimensions)(),this._updateDimensions(),this._register(this._optionsService.onOptionChange((()=>this._handleOptionsChanged()))),this._register(this._themeService.onChangeColors((e=>this._injectCss(e)))),this._injectCss(this._themeService.colors),this._rowFactory=d.createInstance(n.DomRendererRowFactory,document),this._element.classList.add(p+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline((e=>this._handleLinkHover(e)))),this._register(this._linkifier2.onHideLinkUnderline((e=>this._handleLinkLeave(e)))),this._register((0,u.toDisposable)((()=>{this._element.classList.remove(p+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()}))),this._widthCache=new o.WidthCache(this._document,this._helperContainer),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}_updateDimensions(){const e=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*e,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*e),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.left=0,this.dimensions.device.char.top=0,this.dimensions.device.canvas.width=this.dimensions.device.cell.width*this._bufferService.cols,this.dimensions.device.canvas.height=this.dimensions.device.cell.height*this._bufferService.rows,this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/e),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/e),this.dimensions.css.cell.width=this.dimensions.css.canvas.width/this._bufferService.cols,this.dimensions.css.cell.height=this.dimensions.css.canvas.height/this._bufferService.rows;for(const e of this._rowElements)e.style.width=`${this.dimensions.css.canvas.width}px`,e.style.height=`${this.dimensions.css.cell.height}px`,e.style.lineHeight=`${this.dimensions.css.cell.height}px`,e.style.overflow="hidden";this._dimensionsStyleElement||(this._dimensionsStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._dimensionsStyleElement));const t=`${this._terminalSelector} .${g} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=t,this._selectionContainer.style.height=this._viewportElement.style.height,this._screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._screenElement.style.height=`${this.dimensions.css.canvas.height}px`}_injectCss(e){this._themeStyleElement||(this._themeStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._themeStyleElement));let t=`${this._terminalSelector} .${g} { pointer-events: none; color: ${e.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;t+=`${this._terminalSelector} .${g} .xterm-dim { color: ${d.color.multiplyOpacity(e.foreground,.5).css};}`,t+=`${this._terminalSelector} span:not(.xterm-bold) { font-weight: ${this._optionsService.rawOptions.fontWeight};}${this._terminalSelector} span.xterm-bold { font-weight: ${this._optionsService.rawOptions.fontWeightBold};}${this._terminalSelector} span.xterm-italic { font-style: italic;}`;const i=`blink_underline_${this._terminalClass}`,s=`blink_bar_${this._terminalClass}`,r=`blink_block_${this._terminalClass}`;t+=`@keyframes ${i} { 50% { border-bottom-style: hidden; }}`,t+=`@keyframes ${s} { 50% { box-shadow: none; }}`,t+=`@keyframes ${r} { 0% { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css}; } 50% { background-color: inherit; color: ${e.cursor.css}; }}`,t+=`${this._terminalSelector} .${g}.${S} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${i} 1s step-end infinite;}${this._terminalSelector} .${g}.${S} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${s} 1s step-end infinite;}${this._terminalSelector} .${g}.${S} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${r} 1s step-end infinite;}${this._terminalSelector} .${g} .xterm-cursor.xterm-cursor-block { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css};}${this._terminalSelector} .${g} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e.cursor.css} !important; color: ${e.cursorAccent.css} !important;}${this._terminalSelector} .${g} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${g} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}${this._terminalSelector} .${g} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,t+=`${this._terminalSelector} .${b} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${b} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${b} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(const[i,s]of e.ansi.entries())t+=`${this._terminalSelector} .${m}${i} { color: ${s.css}; }${this._terminalSelector} .${m}${i}.xterm-dim { color: ${d.color.multiplyOpacity(s,.5).css}; }${this._terminalSelector} .${v}${i} { background-color: ${s.css}; }`;t+=`${this._terminalSelector} .${m}${a.INVERTED_DEFAULT_COLOR} { color: ${d.color.opaque(e.background).css}; }${this._terminalSelector} .${m}${a.INVERTED_DEFAULT_COLOR}.xterm-dim { color: ${d.color.multiplyOpacity(d.color.opaque(e.background),.5).css}; }${this._terminalSelector} .${v}${a.INVERTED_DEFAULT_COLOR} { background-color: ${e.foreground.css}; }`,this._themeStyleElement.textContent=t}_setDefaultSpacing(){const e=this.dimensions.css.cell.width-this._widthCache.get("W",!1,!1);this._rowContainer.style.letterSpacing=`${e}px`,this._rowFactory.defaultSpacing=e}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(e,t){for(let e=this._rowElements.length;e<=t;e++){const e=this._document.createElement("div");this._rowContainer.appendChild(e),this._rowElements.push(e)}for(;this._rowElements.length>t;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(e,t){this._refreshRowElements(e,t),this._updateDimensions(),this.handleSelectionChanged(this._selectionRenderModel.selectionStart,this._selectionRenderModel.selectionEnd,this._selectionRenderModel.columnSelectMode)}handleCharSizeChanged(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}handleBlur(){this._rowContainer.classList.remove(S),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(S),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(e,t,i){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(e,t,i),this.renderRows(0,this._bufferService.rows-1),!e||!t)return;if(this._selectionRenderModel.update(this._terminal,e,t,i),!this._selectionRenderModel.hasSelection)return;const s=this._selectionRenderModel.viewportStartRow,r=this._selectionRenderModel.viewportEndRow,n=this._selectionRenderModel.viewportCappedStartRow,o=this._selectionRenderModel.viewportCappedEndRow,a=this._document.createDocumentFragment();if(i){const i=e[0]>t[0];a.appendChild(this._createSelectionElement(n,i?t[0]:e[0],i?e[0]:t[0],o-n+1))}else{const i=s===n?e[0]:0,l=n===r?t[0]:this._bufferService.cols;a.appendChild(this._createSelectionElement(n,i,l));const h=o-n-1;if(a.appendChild(this._createSelectionElement(n+1,0,this._bufferService.cols,h)),n!==o){const e=r===o?t[0]:this._bufferService.cols;a.appendChild(this._createSelectionElement(o,0,e))}}this._selectionContainer.appendChild(a)}_createSelectionElement(e,t,i,s=1){const r=this._document.createElement("div"),n=t*this.dimensions.css.cell.width;let o=this.dimensions.css.cell.width*(i-t);return n+o>this.dimensions.css.canvas.width&&(o=this.dimensions.css.canvas.width-n),r.style.height=s*this.dimensions.css.cell.height+"px",r.style.top=e*this.dimensions.css.cell.height+"px",r.style.left=`${n}px`,r.style.width=`${o}px`,r}handleCursorMove(){}_handleOptionsChanged(){this._updateDimensions(),this._injectCss(this._themeService.colors),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}clear(){for(const e of this._rowElements)e.replaceChildren()}renderRows(e,t){const i=this._bufferService.buffer,s=i.ybase+i.y,r=Math.min(i.x,this._bufferService.cols-1),n=this._coreService.decPrivateModes.cursorBlink??this._optionsService.rawOptions.cursorBlink,o=this._coreService.decPrivateModes.cursorStyle??this._optionsService.rawOptions.cursorStyle,a=this._optionsService.rawOptions.cursorInactiveStyle;for(let l=e;l<=t;l++){const e=l+i.ydisp,t=this._rowElements[l],h=i.lines.get(e);if(!t||!h)break;t.replaceChildren(...this._rowFactory.createRow(h,e,e===s,o,a,r,n,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${p}${this._terminalClass}`}_handleLinkHover(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!0)}_handleLinkLeave(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!1)}_setCellUnderline(e,t,i,s,r,n){i<0&&(e=0),s<0&&(t=0);const o=this._bufferService.rows-1;i=Math.max(Math.min(i,o),0),s=Math.max(Math.min(s,o),0),r=Math.min(r,this._bufferService.cols);const a=this._bufferService.buffer,l=a.ybase+a.y,h=Math.min(a.x,r-1),c=this._optionsService.rawOptions.cursorBlink,d=this._optionsService.rawOptions.cursorStyle,u=this._optionsService.rawOptions.cursorInactiveStyle;for(let o=i;o<=s;++o){const _=o+a.ydisp,f=this._rowElements[o],p=a.lines.get(_);if(!f||!p)break;f.replaceChildren(...this._rowFactory.createRow(p,_,_===l,d,u,h,c,this.dimensions.css.cell.width,this._widthCache,n?o===i?e:0:-1,n?(o===s?t:r)-1:-1))}}};t.DomRenderer=y,t.DomRenderer=y=s([r(7,_.IInstantiationService),r(8,c.ICharSizeService),r(9,_.IOptionsService),r(10,_.IBufferService),r(11,_.ICoreService),r(12,c.ICoreBrowserService),r(13,c.IThemeService)],y)},1433:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.DomRendererRowFactory=void 0;const n=i(9176),o=i(8938),a=i(3055),l=i(6501),h=i(4103),c=i(7098),d=i(945),u=i(6181),_=i(5451);let f=class{constructor(e,t,i,s,r,n,o){this._document=e,this._characterJoinerService=t,this._optionsService=i,this._coreBrowserService=s,this._coreService=r,this._decorationService=n,this._themeService=o,this._workCell=new a.CellData,this._columnSelectMode=!1,this.defaultSpacing=0}handleSelectionChanged(e,t,i){this._selectionStart=e,this._selectionEnd=t,this._columnSelectMode=i}createRow(e,t,i,s,r,a,l,c,u,f,g){const m=[],v=this._characterJoinerService.getJoinedCharacters(t),S=this._themeService.colors;let b,C=e.getNoBgTrimmedLength();i&&C=O,U=x,F=this._workCell;if(v.length>0&&x===v[0][0]&&N){const s=v.shift(),r=this._isCellInSelection(s[0],t);for(E=s[0]+1;E=s[1],N?(B=!0,F=new d.JoinedCellData(this._workCell,e.translateToString(!0,s[0],s[1]),s[1]-s[0]),U=s[1]-1,C=F.getWidth()):O=s[1]}const W=this._isCellInSelection(x,t),H=i&&x===a,K=P&&x>=f&&x<=g;let z=!1;this._decorationService.forEachDecorationAtCell(x,t,void 0,(e=>{z=!0}));let j=F.getChars()||o.WHITESPACE_CELL_CHAR;if(" "===j&&(F.isUnderline()||F.isOverline())&&(j=" "),M=C*c-u.get(j,F.isBold(),F.isItalic()),b){if(y&&(W&&k||!W&&!k&&F.bg===D)&&(W&&k&&S.selectionForeground||F.fg===L)&&F.extended.ext===R&&K===A&&M===T&&!H&&!B&&!z&&N){F.isInvisible()?w+=o.WHITESPACE_CELL_CHAR:w+=j,y++;continue}y&&(b.textContent=w),b=this._document.createElement("span"),y=0,w=""}else b=this._document.createElement("span");if(D=F.bg,L=F.fg,R=F.extended.ext,A=K,T=M,k=W,B&&a>=x&&a<=U&&(a=x),!this._coreService.isCursorHidden&&H&&this._coreService.isCursorInitialized)if(I.push("xterm-cursor"),this._coreBrowserService.isFocused)l&&I.push("xterm-cursor-blink"),I.push("bar"===s?"xterm-cursor-bar":"underline"===s?"xterm-cursor-underline":"xterm-cursor-block");else if(r)switch(r){case"outline":I.push("xterm-cursor-outline");break;case"block":I.push("xterm-cursor-block");break;case"bar":I.push("xterm-cursor-bar");break;case"underline":I.push("xterm-cursor-underline")}if(F.isBold()&&I.push("xterm-bold"),F.isItalic()&&I.push("xterm-italic"),F.isDim()&&I.push("xterm-dim"),w=F.isInvisible()?o.WHITESPACE_CELL_CHAR:F.getChars()||o.WHITESPACE_CELL_CHAR,F.isUnderline()&&(I.push(`xterm-underline-${F.extended.underlineStyle}`)," "===w&&(w=" "),!F.isUnderlineColorDefault()))if(F.isUnderlineColorRGB())b.style.textDecorationColor=`rgb(${_.AttributeData.toColorRGB(F.getUnderlineColor()).join(",")})`;else{let e=F.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&F.isBold()&&e<8&&(e+=8),b.style.textDecorationColor=S.ansi[e].css}F.isOverline()&&(I.push("xterm-overline")," "===w&&(w=" ")),F.isStrikethrough()&&I.push("xterm-strikethrough"),K&&(b.style.textDecoration="underline");let $=F.getFgColor(),V=F.getFgColorMode(),G=F.getBgColor(),q=F.getBgColorMode();const X=!!F.isInverse();if(X){const e=$;$=G,G=e;const t=V;V=q,q=t}let Y,Z,J,Q=!1;switch(this._decorationService.forEachDecorationAtCell(x,t,void 0,(e=>{"top"!==e.options.layer&&Q||(e.backgroundColorRGB&&(q=50331648,G=e.backgroundColorRGB.rgba>>8&16777215,Y=e.backgroundColorRGB),e.foregroundColorRGB&&(V=50331648,$=e.foregroundColorRGB.rgba>>8&16777215,Z=e.foregroundColorRGB),Q="top"===e.options.layer)})),!Q&&W&&(Y=this._coreBrowserService.isFocused?S.selectionBackgroundOpaque:S.selectionInactiveBackgroundOpaque,G=Y.rgba>>8&16777215,q=50331648,Q=!0,S.selectionForeground&&(V=50331648,$=S.selectionForeground.rgba>>8&16777215,Z=S.selectionForeground)),Q&&I.push("xterm-decoration-top"),q){case 16777216:case 33554432:J=S.ansi[G],I.push(`xterm-bg-${G}`);break;case 50331648:J=h.channels.toColor(G>>16,G>>8&255,255&G),this._addStyle(b,`background-color:#${p((G>>>0).toString(16),"0",6)}`);break;default:X?(J=S.foreground,I.push(`xterm-bg-${n.INVERTED_DEFAULT_COLOR}`)):J=S.background}switch(Y||F.isDim()&&(Y=h.color.multiplyOpacity(J,.5)),V){case 16777216:case 33554432:F.isBold()&&$<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&($+=8),this._applyMinimumContrast(b,J,S.ansi[$],F,Y,void 0)||I.push(`xterm-fg-${$}`);break;case 50331648:const e=h.channels.toColor($>>16&255,$>>8&255,255&$);this._applyMinimumContrast(b,J,e,F,Y,Z)||this._addStyle(b,`color:#${p($.toString(16),"0",6)}`);break;default:this._applyMinimumContrast(b,J,S.foreground,F,Y,Z)||X&&I.push(`xterm-fg-${n.INVERTED_DEFAULT_COLOR}`)}I.length&&(b.className=I.join(" "),I.length=0),H||B||z||!N?b.textContent=w:y++,M!==this.defaultSpacing&&(b.style.letterSpacing=`${M}px`),m.push(b),x=U}return b&&y&&(b.textContent=w),m}_applyMinimumContrast(e,t,i,s,r,n){if(1===this._optionsService.rawOptions.minimumContrastRatio||(0,u.treatGlyphAsBackgroundColor)(s.getCode()))return!1;const o=this._getContrastCache(s);let a;if(r||n||(a=o.getColor(t.rgba,i.rgba)),void 0===a){const e=this._optionsService.rawOptions.minimumContrastRatio/(s.isDim()?2:1);a=h.color.ensureContrastRatio(r||t,n||i,e),o.setColor((r||t).rgba,(n||i).rgba,a??null)}return!!a&&(this._addStyle(e,`color:${a.css}`),!0)}_getContrastCache(e){return e.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(e,t){e.setAttribute("style",`${e.getAttribute("style")||""}${t};`)}_isCellInSelection(e,t){const i=this._selectionStart,s=this._selectionEnd;return!(!i||!s)&&(this._columnSelectMode?i[0]<=s[0]?e>=i[0]&&t>=i[1]&&e=i[1]&&e>=s[0]&&t<=s[1]:t>i[1]&&t=i[0]&&e=i[0])}};function p(e,t,i){for(;e.length{Object.defineProperty(t,"__esModule",{value:!0}),t.WidthCache=void 0,t.WidthCache=class{constructor(e,t){this._flat=new Float32Array(256),this._font="",this._fontSize=0,this._weight="normal",this._weightBold="bold",this._measureElements=[],this._container=e.createElement("div"),this._container.classList.add("xterm-width-cache-measure-container"),this._container.setAttribute("aria-hidden","true"),this._container.style.whiteSpace="pre",this._container.style.fontKerning="none";const i=e.createElement("span");i.classList.add("xterm-char-measure-element");const s=e.createElement("span");s.classList.add("xterm-char-measure-element"),s.style.fontWeight="bold";const r=e.createElement("span");r.classList.add("xterm-char-measure-element"),r.style.fontStyle="italic";const n=e.createElement("span");n.classList.add("xterm-char-measure-element"),n.style.fontWeight="bold",n.style.fontStyle="italic",this._measureElements=[i,s,r,n],this._container.appendChild(i),this._container.appendChild(s),this._container.appendChild(r),this._container.appendChild(n),t.appendChild(this._container),this.clear()}dispose(){this._container.remove(),this._measureElements.length=0,this._holey=void 0}clear(){this._flat.fill(-9999),this._holey=new Map}setFont(e,t,i,s){e===this._font&&t===this._fontSize&&i===this._weight&&s===this._weightBold||(this._font=e,this._fontSize=t,this._weight=i,this._weightBold=s,this._container.style.fontFamily=this._font,this._container.style.fontSize=`${this._fontSize}px`,this._measureElements[0].style.fontWeight=`${i}`,this._measureElements[1].style.fontWeight=`${s}`,this._measureElements[2].style.fontWeight=`${i}`,this._measureElements[3].style.fontWeight=`${s}`,this.clear())}get(e,t,i){let s=0;if(!t&&!i&&1===e.length&&(s=e.charCodeAt(0))<256){if(-9999!==this._flat[s])return this._flat[s];const t=this._measure(e,0);return t>0&&(this._flat[s]=t),t}let r=e;t&&(r+="B"),i&&(r+="I");let n=this._holey.get(r);if(void 0===n){let s=0;t&&(s|=1),i&&(s|=2),n=this._measure(e,s),n>0&&this._holey.set(r,n)}return n}_measure(e,t){const i=this._measureElements[t];return i.textContent=e.repeat(32),i.offsetWidth/32}}},9176:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.INVERTED_DEFAULT_COLOR=void 0,t.INVERTED_DEFAULT_COLOR=257},6181:(e,t)=>{function i(e){return 57508<=e&&e<=57558}function s(e){return e>=128512&&e<=128591||e>=127744&&e<=128511||e>=128640&&e<=128767||e>=9728&&e<=9983||e>=9984&&e<=10175||e>=65024&&e<=65039||e>=129280&&e<=129535||e>=127462&&e<=127487}Object.defineProperty(t,"__esModule",{value:!0}),t.throwIfFalsy=function(e){if(!e)throw new Error("value must not be falsy");return e},t.isPowerlineGlyph=i,t.isRestrictedPowerlineGlyph=function(e){return 57520<=e&&e<=57527},t.isEmoji=s,t.allowRescaling=function(e,t,r,n){return 1===t&&r>Math.ceil(1.5*n)&&void 0!==e&&e>255&&!s(e)&&!i(e)&&!function(e){return 57344<=e&&e<=63743}(e)},t.treatGlyphAsBackgroundColor=function(e){return i(e)||function(e){return 9472<=e&&e<=9631}(e)},t.createRenderDimensions=function(){return{css:{canvas:{width:0,height:0},cell:{width:0,height:0}},device:{canvas:{width:0,height:0},cell:{width:0,height:0},char:{width:0,height:0,left:0,top:0}}}},t.computeNextVariantOffset=function(e,t,i=0){return(e-(2*Math.round(t)-i))%(2*Math.round(t))}},2274:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.createSelectionRenderModel=function(){return new i};class i{constructor(){this.clear()}clear(){this.hasSelection=!1,this.columnSelectMode=!1,this.viewportStartRow=0,this.viewportEndRow=0,this.viewportCappedStartRow=0,this.viewportCappedEndRow=0,this.startCol=0,this.endCol=0,this.selectionStart=void 0,this.selectionEnd=void 0}update(e,t,i,s=!1){if(this.selectionStart=t,this.selectionEnd=i,!t||!i||t[0]===i[0]&&t[1]===i[1])return void this.clear();const r=e.buffers.active.ydisp,n=t[1]-r,o=i[1]-r,a=Math.max(n,0),l=Math.min(o,e.rows-1);a>=e.rows||l<0?this.clear():(this.hasSelection=!0,this.columnSelectMode=s,this.viewportStartRow=n,this.viewportEndRow=o,this.viewportCappedStartRow=a,this.viewportCappedEndRow=l,this.startCol=t[0],this.endCol=i[0])}isCellSelected(e,t,i){return!!this.hasSelection&&(i-=e.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?t>=this.startCol&&i>=this.viewportCappedStartRow&&t=this.viewportCappedStartRow&&t>=this.endCol&&i<=this.viewportCappedEndRow:i>this.viewportStartRow&&i=this.startCol&&t=this.startCol)}}},5959:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SelectionModel=void 0,t.SelectionModel=class{constructor(e){this._bufferService=e,this.isSelectAllActive=!1,this.selectionStartLength=0}clearSelection(){this.selectionStart=void 0,this.selectionEnd=void 0,this.isSelectAllActive=!1,this.selectionStartLength=0}get finalSelectionStart(){return this.isSelectAllActive?[0,0]:this.selectionEnd&&this.selectionStart&&this.areSelectionValuesReversed()?this.selectionEnd:this.selectionStart}get finalSelectionEnd(){if(this.isSelectAllActive)return[this._bufferService.cols,this._bufferService.buffer.ybase+this._bufferService.rows-1];if(this.selectionStart){if(!this.selectionEnd||this.areSelectionValuesReversed()){const e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?e%this._bufferService.cols==0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)-1]:[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[e,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){const e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[Math.max(e,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){const e=this.selectionStart,t=this.selectionEnd;return!(!e||!t)&&(e[1]>t[1]||e[1]===t[1]&&e[0]>t[0])}handleTrim(e){return this.selectionStart&&(this.selectionStart[1]-=e),this.selectionEnd&&(this.selectionEnd[1]-=e),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}}},4792:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.CharSizeService=void 0;const n=i(6501),o=i(7150),a=i(802);let l=class extends o.Disposable{get hasValidSize(){return this.width>0&&this.height>0}constructor(e,t,i){super(),this._optionsService=i,this.width=0,this.height=0,this._onCharSizeChange=this._register(new a.Emitter),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this._register(new d(this._optionsService))}catch{this._measureStrategy=this._register(new c(e,t,this._optionsService))}this._register(this._optionsService.onMultipleOptionChange(["fontFamily","fontSize"],(()=>this.measure())))}measure(){const e=this._measureStrategy.measure();e.width===this.width&&e.height===this.height||(this.width=e.width,this.height=e.height,this._onCharSizeChange.fire())}};t.CharSizeService=l,t.CharSizeService=l=s([r(2,n.IOptionsService)],l);class h extends o.Disposable{constructor(){super(...arguments),this._result={width:0,height:0}}_validateAndSet(e,t){void 0!==e&&e>0&&void 0!==t&&t>0&&(this._result.width=e,this._result.height=t)}}class c extends h{constructor(e,t,i){super(),this._document=e,this._parentElement=t,this._optionsService=i,this._measureElement=this._document.createElement("span"),this._measureElement.classList.add("xterm-char-measure-element"),this._measureElement.textContent="W".repeat(32),this._measureElement.setAttribute("aria-hidden","true"),this._measureElement.style.whiteSpace="pre",this._measureElement.style.fontKerning="none",this._parentElement.appendChild(this._measureElement)}measure(){return this._measureElement.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._measureElement.style.fontSize=`${this._optionsService.rawOptions.fontSize}px`,this._validateAndSet(Number(this._measureElement.offsetWidth)/32,Number(this._measureElement.offsetHeight)),this._result}}class d extends h{constructor(e){super(),this._optionsService=e,this._canvas=new OffscreenCanvas(100,100),this._ctx=this._canvas.getContext("2d");const t=this._ctx.measureText("W");if(!("width"in t&&"fontBoundingBoxAscent"in t&&"fontBoundingBoxDescent"in t))throw new Error("Required font metrics not supported")}measure(){this._ctx.font=`${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`;const e=this._ctx.measureText("W");return this._validateAndSet(e.width,e.fontBoundingBoxAscent+e.fontBoundingBoxDescent),this._result}}},945:function(e,t,i){var s,r=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},n=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.CharacterJoinerService=t.JoinedCellData=void 0;const o=i(5451),a=i(8938),l=i(3055),h=i(6501);class c extends o.AttributeData{constructor(e,t,i){super(),this.content=0,this.combinedData="",this.fg=e.fg,this.bg=e.bg,this.combinedData=t,this._width=i}isCombined(){return 2097152}getWidth(){return this._width}getChars(){return this.combinedData}getCode(){return 2097151}setFromCharData(e){throw new Error("not implemented")}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}}t.JoinedCellData=c;let d=s=class{constructor(e){this._bufferService=e,this._characterJoiners=[],this._nextCharacterJoinerId=0,this._workCell=new l.CellData}register(e){const t={id:this._nextCharacterJoinerId++,handler:e};return this._characterJoiners.push(t),t.id}deregister(e){for(let t=0;t1){const e=this._getJoinedRanges(s,o,n,t,r);for(let t=0;t1){const e=this._getJoinedRanges(s,o,n,t,r);for(let t=0;t{Object.defineProperty(t,"__esModule",{value:!0}),t.CoreBrowserService=void 0;const s=i(802),r=i(7093),n=i(7150);class o extends n.Disposable{constructor(e,t,i){super(),this._textarea=e,this._window=t,this.mainDocument=i,this._isFocused=!1,this._cachedIsFocused=void 0,this._screenDprMonitor=this._register(new a(this._window)),this._onDprChange=this._register(new s.Emitter),this.onDprChange=this._onDprChange.event,this._onWindowChange=this._register(new s.Emitter),this.onWindowChange=this._onWindowChange.event,this._register(this.onWindowChange((e=>this._screenDprMonitor.setWindow(e)))),this._register(s.Event.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register((0,r.addDisposableListener)(this._textarea,"focus",(()=>this._isFocused=!0))),this._register((0,r.addDisposableListener)(this._textarea,"blur",(()=>this._isFocused=!1)))}get window(){return this._window}set window(e){this._window!==e&&(this._window=e,this._onWindowChange.fire(this._window))}get dpr(){return this.window.devicePixelRatio}get isFocused(){return void 0===this._cachedIsFocused&&(this._cachedIsFocused=this._isFocused&&this._textarea.ownerDocument.hasFocus(),queueMicrotask((()=>this._cachedIsFocused=void 0))),this._cachedIsFocused}}t.CoreBrowserService=o;class a extends n.Disposable{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this._register(new n.MutableDisposable),this._onDprChange=this._register(new s.Emitter),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this._register((0,n.toDisposable)((()=>this.clearListener())))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=(0,r.addDisposableListener)(this._parentWindow,"resize",(()=>this._setDprAndFireIfDiffers()))}_setDprAndFireIfDiffers(){this._parentWindow.devicePixelRatio!==this._currentDevicePixelRatio&&this._onDprChange.fire(this._parentWindow.devicePixelRatio),this._updateDpr()}_updateDpr(){this._outerListener&&(this._resolutionMediaMatchList?.removeListener(this._outerListener),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._resolutionMediaMatchList=this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`),this._resolutionMediaMatchList.addListener(this._outerListener))}clearListener(){this._resolutionMediaMatchList&&this._outerListener&&(this._resolutionMediaMatchList.removeListener(this._outerListener),this._resolutionMediaMatchList=void 0,this._outerListener=void 0)}}},9820:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.LinkProviderService=void 0;const s=i(7150);class r extends s.Disposable{constructor(){super(),this.linkProviders=[],this._register((0,s.toDisposable)((()=>this.linkProviders.length=0)))}registerLinkProvider(e){return this.linkProviders.push(e),{dispose:()=>{const t=this.linkProviders.indexOf(e);-1!==t&&this.linkProviders.splice(t,1)}}}}t.LinkProviderService=r},9784:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.MouseService=void 0;const n=i(7098),o=i(5251);let a=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,i,s,r){return(0,o.getCoords)(window,e,t,i,s,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,r)}getMouseReportCoords(e,t){const i=(0,o.getCoordsRelativeToElement)(window,e,t);if(this._charSizeService.hasValidSize)return i[0]=Math.min(Math.max(i[0],0),this._renderService.dimensions.css.canvas.width-1),i[1]=Math.min(Math.max(i[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(i[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(i[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(i[0]),y:Math.floor(i[1])}}};t.MouseService=a,t.MouseService=a=s([r(0,n.IRenderService),r(1,n.ICharSizeService)],a)},5783:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.RenderService=void 0;const n=i(4852),o=i(7098),a=i(7150),l=i(6168),h=i(6501),c=i(802);let d=class extends a.Disposable{get dimensions(){return this._renderer.value.dimensions}constructor(e,t,i,s,r,o,h,d,_){super(),this._rowCount=e,this._optionsService=i,this._charSizeService=s,this._coreService=r,this._coreBrowserService=d,this._renderer=this._register(new a.MutableDisposable),this._pausedResizeTask=new l.DebouncedIdleTask,this._observerDisposable=this._register(new a.MutableDisposable),this._isPaused=!1,this._needsFullRefresh=!1,this._isNextRenderRedrawOnly=!0,this._needsSelectionRefresh=!1,this._canvasWidth=0,this._canvasHeight=0,this._selectionState={start:void 0,end:void 0,columnSelectMode:!1},this._onDimensionsChange=this._register(new c.Emitter),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this._register(new c.Emitter),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this._register(new c.Emitter),this.onRender=this._onRender.event,this._onRefreshRequest=this._register(new c.Emitter),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new n.RenderDebouncer(((e,t)=>this._renderRows(e,t)),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new u(this._coreBrowserService,this._coreService,(()=>this._fullRefresh())),this._register((0,a.toDisposable)((()=>this._syncOutputHandler.dispose()))),this._register(this._coreBrowserService.onDprChange((()=>this.handleDevicePixelRatioChange()))),this._register(h.onResize((()=>this._fullRefresh()))),this._register(h.buffers.onBufferActivate((()=>this._renderer.value?.clear()))),this._register(this._optionsService.onOptionChange((()=>this._handleOptionsChanged()))),this._register(this._charSizeService.onCharSizeChange((()=>this.handleCharSizeChanged()))),this._register(o.onDecorationRegistered((()=>this._fullRefresh()))),this._register(o.onDecorationRemoved((()=>this._fullRefresh()))),this._register(this._optionsService.onMultipleOptionChange(["customGlyphs","drawBoldTextInBrightColors","letterSpacing","lineHeight","fontFamily","fontSize","fontWeight","fontWeightBold","minimumContrastRatio","rescaleOverlappingGlyphs"],(()=>{this.clear(),this.handleResize(h.cols,h.rows),this._fullRefresh()}))),this._register(this._optionsService.onMultipleOptionChange(["cursorBlink","cursorStyle"],(()=>this.refreshRows(h.buffer.y,h.buffer.y,!0)))),this._register(_.onChangeColors((()=>this._fullRefresh()))),this._registerIntersectionObserver(this._coreBrowserService.window,t),this._register(this._coreBrowserService.onWindowChange((e=>this._registerIntersectionObserver(e,t))))}_registerIntersectionObserver(e,t){if("IntersectionObserver"in e){const i=new e.IntersectionObserver((e=>this._handleIntersectionChange(e[e.length-1])),{threshold:0});i.observe(t),this._observerDisposable.value=(0,a.toDisposable)((()=>i.disconnect()))}}_handleIntersectionChange(e){this._isPaused=void 0===e.isIntersecting?0===e.intersectionRatio:!e.isIntersecting,this._isPaused||this._charSizeService.hasValidSize||this._charSizeService.measure(),!this._isPaused&&this._needsFullRefresh&&(this._pausedResizeTask.flush(),this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)}refreshRows(e,t,i=!1){if(this._isPaused)return void(this._needsFullRefresh=!0);if(this._coreService.decPrivateModes.synchronizedOutput)return void this._syncOutputHandler.bufferRows(e,t);const s=this._syncOutputHandler.flush();s&&(e=Math.min(e,s.start),t=Math.max(t,s.end)),i||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(e,t,this._rowCount)}_renderRows(e,t){this._renderer.value&&(this._coreService.decPrivateModes.synchronizedOutput?this._syncOutputHandler.bufferRows(e,t):(e=Math.min(e,this._rowCount-1),t=Math.min(t,this._rowCount-1),this._renderer.value.renderRows(e,t),this._needsSelectionRefresh&&(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),this._needsSelectionRefresh=!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:e,end:t}),this._onRender.fire({start:e,end:t}),this._isNextRenderRedrawOnly=!0))}resize(e,t){this._rowCount=t,this._fireOnCanvasResize()}_handleOptionsChanged(){this._renderer.value&&(this.refreshRows(0,this._rowCount-1),this._fireOnCanvasResize())}_fireOnCanvasResize(){this._renderer.value&&(this._renderer.value.dimensions.css.canvas.width===this._canvasWidth&&this._renderer.value.dimensions.css.canvas.height===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.value.dimensions))}hasRenderer(){return!!this._renderer.value}setRenderer(e){this._renderer.value=e,this._renderer.value&&(this._renderer.value.onRequestRedraw((e=>this.refreshRows(e.start,e.end,!0))),this._needsSelectionRefresh=!0,this._fullRefresh())}addRefreshCallback(e){return this._renderDebouncer.addRefreshCallback(e)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){this._renderer.value&&(this._renderer.value.clearTextureAtlas?.(),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(e,t){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set((()=>this._renderer.value?.handleResize(e,t))):this._renderer.value.handleResize(e,t),this._fullRefresh())}handleCharSizeChanged(){this._renderer.value?.handleCharSizeChanged()}handleBlur(){this._renderer.value?.handleBlur()}handleFocus(){this._renderer.value?.handleFocus()}handleSelectionChanged(e,t,i){this._selectionState.start=e,this._selectionState.end=t,this._selectionState.columnSelectMode=i,this._renderer.value?.handleSelectionChanged(e,t,i)}handleCursorMove(){this._renderer.value?.handleCursorMove()}clear(){this._renderer.value?.clear()}};t.RenderService=d,t.RenderService=d=s([r(2,h.IOptionsService),r(3,o.ICharSizeService),r(4,h.ICoreService),r(5,h.IDecorationService),r(6,h.IBufferService),r(7,o.ICoreBrowserService),r(8,o.IThemeService)],d);class u{constructor(e,t,i){this._coreBrowserService=e,this._coreService=t,this._onTimeout=i,this._start=0,this._end=0,this._isBuffering=!1}bufferRows(e,t){this._isBuffering?(this._start=Math.min(this._start,e),this._end=Math.max(this._end,t)):(this._start=e,this._end=t,this._isBuffering=!0),void 0===this._timeout&&(this._timeout=this._coreBrowserService.window.setTimeout((()=>{this._timeout=void 0,this._coreService.decPrivateModes.synchronizedOutput=!1,this._onTimeout()}),1e3))}flush(){if(void 0!==this._timeout&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0),!this._isBuffering)return;const e={start:this._start,end:this._end};return this._isBuffering=!1,e}dispose(){void 0!==this._timeout&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0)}}},2079:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.SelectionService=void 0;const n=i(5251),o=i(9686),a=i(5959),l=i(7098),h=i(7150),c=i(701),d=i(9384),u=i(3055),_=i(6501),f=i(802),p=String.fromCharCode(160),g=new RegExp(p,"g");let m=class extends h.Disposable{constructor(e,t,i,s,r,n,o,l,c){super(),this._element=e,this._screenElement=t,this._linkifier=i,this._bufferService=s,this._coreService=r,this._mouseService=n,this._optionsService=o,this._renderService=l,this._coreBrowserService=c,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new u.CellData,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this._register(new f.Emitter),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this._register(new f.Emitter),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this._register(new f.Emitter),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this._register(new f.Emitter),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=e=>this._handleMouseMove(e),this._mouseUpListener=e=>this._handleMouseUp(e),this._coreService.onUserInput((()=>{this.hasSelection&&this.clearSelection()})),this._trimListener=this._bufferService.buffer.lines.onTrim((e=>this._handleTrim(e))),this._register(this._bufferService.buffers.onBufferActivate((e=>this._handleBufferActivate(e)))),this.enable(),this._model=new a.SelectionModel(this._bufferService),this._activeSelectionMode=0,this._register((0,h.toDisposable)((()=>{this._removeMouseDownListeners()}))),this._register(this._bufferService.onResize((e=>{e.rowsChanged&&this.clearSelection()})))}reset(){this.clearSelection()}disable(){this.clearSelection(),this._enabled=!1}enable(){this._enabled=!0}get selectionStart(){return this._model.finalSelectionStart}get selectionEnd(){return this._model.finalSelectionEnd}get hasSelection(){const e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;return!(!e||!t||e[0]===t[0]&&e[1]===t[1])}get selectionText(){const e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;if(!e||!t)return"";const i=this._bufferService.buffer,s=[];if(3===this._activeSelectionMode){if(e[0]===t[0])return"";const r=e[0]e.replace(g," "))).join(c.isWindows?"\r\n":"\n")}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame((()=>this._refresh()))),c.isLinux&&e&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:3===this._activeSelectionMode})}_isClickInSelection(e){const t=this._getMouseBufferCoords(e),i=this._model.finalSelectionStart,s=this._model.finalSelectionEnd;return!!(i&&s&&t)&&this._areCoordsInSelection(t,i,s)}isCellInSelection(e,t){const i=this._model.finalSelectionStart,s=this._model.finalSelectionEnd;return!(!i||!s)&&this._areCoordsInSelection([e,t],i,s)}_areCoordsInSelection(e,t,i){return e[1]>t[1]&&e[1]=t[0]&&e[0]=t[0]}_selectWordAtCursor(e,t){const i=this._linkifier.currentLink?.link?.range;if(i)return this._model.selectionStart=[i.start.x-1,i.start.y-1],this._model.selectionStartLength=(0,d.getRangeLength)(i,this._bufferService.cols),this._model.selectionEnd=void 0,!0;const s=this._getMouseBufferCoords(e);return!!s&&(this._selectWordAt(s,t),this._model.selectionEnd=void 0,!0)}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,t){this._model.clearSelection(),e=Math.max(e,0),t=Math.min(t,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,t],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){const t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t}_getMouseEventScrollAmount(e){let t=(0,n.getCoordsRelativeToElement)(this._coreBrowserService.window,e,this._screenElement)[1];const i=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=i?0:(t>i&&(t-=i),t=Math.min(Math.max(t,-50),50),t/=50,t/Math.abs(t)+Math.round(14*t))}shouldForceSelection(e){return c.isMac?e.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:e.shiftKey}handleMouseDown(e){if(this._mouseDownTimeStamp=e.timeStamp,(2!==e.button||!this.hasSelection)&&0===e.button){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._handleIncrementalClick(e):1===e.detail?this._handleSingleClick(e):2===e.detail?this._handleDoubleClick(e):3===e.detail&&this._handleTripleClick(e),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener("mouseup",this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval((()=>this._dragScroll()),50)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener("mouseup",this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))}_handleSingleClick(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(e)?3:0,this._model.selectionStart=this._getMouseBufferCoords(e),!this._model.selectionStart)return;this._model.selectionEnd=void 0;const t=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);t&&t.length!==this._model.selectionStart[0]&&0===t.hasWidth(this._model.selectionStart[0])&&this._model.selectionStart[0]++}_handleDoubleClick(e){this._selectWordAtCursor(e,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(e){const t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))}shouldColumnSelect(e){return e.altKey&&!(c.isMac&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;const t=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!this._model.selectionEnd)return void this.refresh(!0);2===this._activeSelectionMode?this._model.selectionEnd[1]0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));const i=this._bufferService.buffer;if(this._model.selectionEnd[1]0?(3!==this._activeSelectionMode&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(e.ydisp+this._bufferService.rows,e.lines.length-1)):(3!==this._activeSelectionMode&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=e.ydisp),this.refresh()}}_handleMouseUp(e){const t=e.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&t<500&&e.altKey&&this._optionsService.rawOptions.altClickMovesCursor){if(this._bufferService.buffer.ybase===this._bufferService.buffer.ydisp){const t=this._mouseService.getCoords(e,this._element,this._bufferService.cols,this._bufferService.rows,!1);if(t&&void 0!==t[0]&&void 0!==t[1]){const e=(0,o.moveToCellSequence)(t[0]-1,t[1]-1,this._bufferService,this._coreService.decPrivateModes.applicationCursorKeys);this._coreService.triggerDataEvent(e,!0)}}}else this._fireEventIfSelectionChanged()}_fireEventIfSelectionChanged(){const e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd,i=!(!e||!t||e[0]===t[0]&&e[1]===t[1]);i?e&&t&&(this._oldSelectionStart&&this._oldSelectionEnd&&e[0]===this._oldSelectionStart[0]&&e[1]===this._oldSelectionStart[1]&&t[0]===this._oldSelectionEnd[0]&&t[1]===this._oldSelectionEnd[1]||this._fireOnSelectionChange(e,t,i)):this._oldHasSelection&&this._fireOnSelectionChange(e,t,i)}_fireOnSelectionChange(e,t,i){this._oldSelectionStart=e,this._oldSelectionEnd=t,this._oldHasSelection=i,this._onSelectionChange.fire()}_handleBufferActivate(e){this.clearSelection(),this._trimListener.dispose(),this._trimListener=e.activeBuffer.lines.onTrim((e=>this._handleTrim(e)))}_convertViewportColToCharacterIndex(e,t){let i=t;for(let s=0;t>=s;s++){const r=e.loadCell(s,this._workCell).getChars().length;0===this._workCell.getWidth()?i--:r>1&&t!==s&&(i+=r-1)}return i}setSelection(e,t,i){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,t],this._model.selectionStartLength=i,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(e){this._isClickInSelection(e)||(this._selectWordAtCursor(e,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(e,t,i=!0,s=!0){if(e[0]>=this._bufferService.cols)return;const r=this._bufferService.buffer,n=r.lines.get(e[1]);if(!n)return;const o=r.translateBufferLineToString(e[1],!1);let a=this._convertViewportColToCharacterIndex(n,e[0]),l=a;const h=e[0]-a;let c=0,d=0,u=0,_=0;if(" "===o.charAt(a)){for(;a>0&&" "===o.charAt(a-1);)a--;for(;l1&&(_+=s-1,l+=s-1);t>0&&a>0&&!this._isCharWordSeparator(n.loadCell(t-1,this._workCell));){n.loadCell(t-1,this._workCell);const e=this._workCell.getChars().length;0===this._workCell.getWidth()?(c++,t--):e>1&&(u+=e-1,a-=e-1),a--,t--}for(;i1&&(_+=e-1,l+=e-1),l++,i++}}l++;let f=a+h-c+u,p=Math.min(this._bufferService.cols,l-a+c+d-u-_);if(t||""!==o.slice(a,l).trim()){if(i&&0===f&&32!==n.getCodePoint(0)){const t=r.lines.get(e[1]-1);if(t&&n.isWrapped&&32!==t.getCodePoint(this._bufferService.cols-1)){const t=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(t){const e=this._bufferService.cols-t.start;f-=e,p+=e}}}if(s&&f+p===this._bufferService.cols&&32!==n.getCodePoint(this._bufferService.cols-1)){const t=r.lines.get(e[1]+1);if(t?.isWrapped&&32!==t.getCodePoint(0)){const t=this._getWordAt([0,e[1]+1],!1,!1,!0);t&&(p+=t.length)}}return{start:f,length:p}}}_selectWordAt(e,t){const i=this._getWordAt(e,t);if(i){for(;i.start<0;)i.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[i.start,e[1]],this._model.selectionStartLength=i.length}}_selectToWordAt(e){const t=this._getWordAt(e,!0);if(t){let i=e[1];for(;t.start<0;)t.start+=this._bufferService.cols,i--;if(!this._model.areSelectionValuesReversed())for(;t.start+t.length>this._bufferService.cols;)t.length-=this._bufferService.cols,i++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?t.start:t.start+t.length,i]}}_isCharWordSeparator(e){return 0!==e.getWidth()&&this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars())>=0}_selectLineAt(e){const t=this._bufferService.buffer.getWrappedRangeForLine(e),i={start:{x:0,y:t.first},end:{x:this._bufferService.cols-1,y:t.last}};this._model.selectionStart=[0,t.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=(0,d.getRangeLength)(i,this._bufferService.cols)}};t.SelectionService=m,t.SelectionService=m=s([r(3,_.IBufferService),r(4,_.ICoreService),r(5,l.IMouseService),r(6,_.IOptionsService),r(7,l.IRenderService),r(8,l.ICoreBrowserService)],m)},7098:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ILinkProviderService=t.IThemeService=t.ICharacterJoinerService=t.ISelectionService=t.IRenderService=t.IMouseService=t.ICoreBrowserService=t.ICharSizeService=void 0;const s=i(6201);t.ICharSizeService=(0,s.createDecorator)("CharSizeService"),t.ICoreBrowserService=(0,s.createDecorator)("CoreBrowserService"),t.IMouseService=(0,s.createDecorator)("MouseService"),t.IRenderService=(0,s.createDecorator)("RenderService"),t.ISelectionService=(0,s.createDecorator)("SelectionService"),t.ICharacterJoinerService=(0,s.createDecorator)("CharacterJoinerService"),t.IThemeService=(0,s.createDecorator)("ThemeService"),t.ILinkProviderService=(0,s.createDecorator)("LinkProviderService")},9078:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.ThemeService=void 0;const n=i(7174),o=i(9302),a=i(4103),l=i(7150),h=i(6501),c=i(802),d=a.css.toColor("#ffffff"),u=a.css.toColor("#000000"),_=a.css.toColor("#ffffff"),f=u,p={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117},g=d;let m=class extends l.Disposable{get colors(){return this._colors}constructor(e){super(),this._optionsService=e,this._contrastCache=new n.ColorContrastCache,this._halfContrastCache=new n.ColorContrastCache,this._onChangeColors=this._register(new c.Emitter),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:d,background:u,cursor:_,cursorAccent:f,selectionForeground:void 0,selectionBackgroundTransparent:p,selectionBackgroundOpaque:a.color.blend(u,p),selectionInactiveBackgroundTransparent:p,selectionInactiveBackgroundOpaque:a.color.blend(u,p),scrollbarSliderBackground:a.color.opacity(d,.2),scrollbarSliderHoverBackground:a.color.opacity(d,.4),scrollbarSliderActiveBackground:a.color.opacity(d,.5),overviewRulerBorder:d,ansi:o.DEFAULT_ANSI_COLORS.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this._register(this._optionsService.onSpecificOptionChange("minimumContrastRatio",(()=>this._contrastCache.clear()))),this._register(this._optionsService.onSpecificOptionChange("theme",(()=>this._setTheme(this._optionsService.rawOptions.theme))))}_setTheme(e={}){const t=this._colors;if(t.foreground=v(e.foreground,d),t.background=v(e.background,u),t.cursor=a.color.blend(t.background,v(e.cursor,_)),t.cursorAccent=a.color.blend(t.background,v(e.cursorAccent,f)),t.selectionBackgroundTransparent=v(e.selectionBackground,p),t.selectionBackgroundOpaque=a.color.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=v(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=a.color.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?v(e.selectionForeground,a.NULL_COLOR):void 0,t.selectionForeground===a.NULL_COLOR&&(t.selectionForeground=void 0),a.color.isOpaque(t.selectionBackgroundTransparent)){const e=.3;t.selectionBackgroundTransparent=a.color.opacity(t.selectionBackgroundTransparent,e)}if(a.color.isOpaque(t.selectionInactiveBackgroundTransparent)){const e=.3;t.selectionInactiveBackgroundTransparent=a.color.opacity(t.selectionInactiveBackgroundTransparent,e)}if(t.scrollbarSliderBackground=v(e.scrollbarSliderBackground,a.color.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=v(e.scrollbarSliderHoverBackground,a.color.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=v(e.scrollbarSliderActiveBackground,a.color.opacity(t.foreground,.5)),t.overviewRulerBorder=v(e.overviewRulerBorder,g),t.ansi=o.DEFAULT_ANSI_COLORS.slice(),t.ansi[0]=v(e.black,o.DEFAULT_ANSI_COLORS[0]),t.ansi[1]=v(e.red,o.DEFAULT_ANSI_COLORS[1]),t.ansi[2]=v(e.green,o.DEFAULT_ANSI_COLORS[2]),t.ansi[3]=v(e.yellow,o.DEFAULT_ANSI_COLORS[3]),t.ansi[4]=v(e.blue,o.DEFAULT_ANSI_COLORS[4]),t.ansi[5]=v(e.magenta,o.DEFAULT_ANSI_COLORS[5]),t.ansi[6]=v(e.cyan,o.DEFAULT_ANSI_COLORS[6]),t.ansi[7]=v(e.white,o.DEFAULT_ANSI_COLORS[7]),t.ansi[8]=v(e.brightBlack,o.DEFAULT_ANSI_COLORS[8]),t.ansi[9]=v(e.brightRed,o.DEFAULT_ANSI_COLORS[9]),t.ansi[10]=v(e.brightGreen,o.DEFAULT_ANSI_COLORS[10]),t.ansi[11]=v(e.brightYellow,o.DEFAULT_ANSI_COLORS[11]),t.ansi[12]=v(e.brightBlue,o.DEFAULT_ANSI_COLORS[12]),t.ansi[13]=v(e.brightMagenta,o.DEFAULT_ANSI_COLORS[13]),t.ansi[14]=v(e.brightCyan,o.DEFAULT_ANSI_COLORS[14]),t.ansi[15]=v(e.brightWhite,o.DEFAULT_ANSI_COLORS[15]),e.extendedAnsi){const i=Math.min(t.ansi.length-16,e.extendedAnsi.length);for(let s=0;s{Object.defineProperty(t,"__esModule",{value:!0}),t.CircularList=void 0;const s=i(7150),r=i(802);class n extends s.Disposable{constructor(e){super(),this._maxLength=e,this.onDeleteEmitter=this._register(new r.Emitter),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this._register(new r.Emitter),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this._register(new r.Emitter),this.onTrim=this.onTrimEmitter.event,this._array=new Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(e){if(this._maxLength===e)return;const t=new Array(e);for(let i=0;ithis._length)for(let t=this._length;t=e;t--)this._array[this._getCyclicIndex(t+i.length)]=this._array[this._getCyclicIndex(t)];for(let t=0;tthis._maxLength){const e=this._length+i.length-this._maxLength;this._startIndex+=e,this._length=this._maxLength,this.onTrimEmitter.fire(e)}else this._length+=i.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,t,i){if(!(t<=0)){if(e<0||e>=this._length)throw new Error("start argument out of range");if(e+i<0)throw new Error("Cannot shift elements in list beyond index 0");if(i>0){for(let s=t-1;s>=0;s--)this.set(e+s+i,this.get(e+s));const s=e+t+i-this._length;if(s>0)for(this._length+=s;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let s=0;s{Object.defineProperty(t,"__esModule",{value:!0}),t.clone=function e(t,i=5){if("object"!=typeof t)return t;const s=Array.isArray(t)?[]:{};for(const r in t)s[r]=i<=1?t[r]:t[r]&&e(t[r],i-1);return s}},4103:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.rgba=t.rgb=t.css=t.color=t.channels=t.NULL_COLOR=void 0,t.toPaddedHex=d,t.contrastRatio=u;let i=0,s=0,r=0,n=0;var o,a,l,h,c;function d(e){const t=e.toString(16);return t.length<2?"0"+t:t}function u(e,t){return e>>0},e.toColor=function(t,i,s,r){return{css:e.toCss(t,i,s,r),rgba:e.toRgba(t,i,s,r)}}}(o||(t.channels=o={})),function(e){function t(e,t){return n=Math.round(255*t),[i,s,r]=c.toChannels(e.rgba),{css:o.toCss(i,s,r,n),rgba:o.toRgba(i,s,r,n)}}e.blend=function(e,t){if(n=(255&t.rgba)/255,1===n)return{css:t.css,rgba:t.rgba};const a=t.rgba>>24&255,l=t.rgba>>16&255,h=t.rgba>>8&255,c=e.rgba>>24&255,d=e.rgba>>16&255,u=e.rgba>>8&255;return i=c+Math.round((a-c)*n),s=d+Math.round((l-d)*n),r=u+Math.round((h-u)*n),{css:o.toCss(i,s,r),rgba:o.toRgba(i,s,r)}},e.isOpaque=function(e){return!(255&~e.rgba)},e.ensureContrastRatio=function(e,t,i){const s=c.ensureContrastRatio(e.rgba,t.rgba,i);if(s)return o.toColor(s>>24&255,s>>16&255,s>>8&255)},e.opaque=function(e){const t=(255|e.rgba)>>>0;return[i,s,r]=c.toChannels(t),{css:o.toCss(i,s,r),rgba:t}},e.opacity=t,e.multiplyOpacity=function(e,i){return n=255&e.rgba,t(e,n*i/255)},e.toColorRGB=function(e){return[e.rgba>>24&255,e.rgba>>16&255,e.rgba>>8&255]}}(a||(t.color=a={})),function(e){let t,a;try{const e=document.createElement("canvas");e.width=1,e.height=1;const i=e.getContext("2d",{willReadFrequently:!0});i&&(t=i,t.globalCompositeOperation="copy",a=t.createLinearGradient(0,0,1,1))}catch{}e.toColor=function(e){if(e.match(/#[\da-f]{3,8}/i))switch(e.length){case 4:return i=parseInt(e.slice(1,2).repeat(2),16),s=parseInt(e.slice(2,3).repeat(2),16),r=parseInt(e.slice(3,4).repeat(2),16),o.toColor(i,s,r);case 5:return i=parseInt(e.slice(1,2).repeat(2),16),s=parseInt(e.slice(2,3).repeat(2),16),r=parseInt(e.slice(3,4).repeat(2),16),n=parseInt(e.slice(4,5).repeat(2),16),o.toColor(i,s,r,n);case 7:return{css:e,rgba:(parseInt(e.slice(1),16)<<8|255)>>>0};case 9:return{css:e,rgba:parseInt(e.slice(1),16)>>>0}}const l=e.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(l)return i=parseInt(l[1]),s=parseInt(l[2]),r=parseInt(l[3]),n=Math.round(255*(void 0===l[5]?1:parseFloat(l[5]))),o.toColor(i,s,r,n);if(!t||!a)throw new Error("css.toColor: Unsupported css format");if(t.fillStyle=a,t.fillStyle=e,"string"!=typeof t.fillStyle)throw new Error("css.toColor: Unsupported css format");if(t.fillRect(0,0,1,1),[i,s,r,n]=t.getImageData(0,0,1,1).data,255!==n)throw new Error("css.toColor: Unsupported css format");return{rgba:o.toRgba(i,s,r,n),css:e}}}(l||(t.css=l={})),function(e){function t(e,t,i){const s=e/255,r=t/255,n=i/255;return.2126*(s<=.03928?s/12.92:Math.pow((s+.055)/1.055,2.4))+.7152*(r<=.03928?r/12.92:Math.pow((r+.055)/1.055,2.4))+.0722*(n<=.03928?n/12.92:Math.pow((n+.055)/1.055,2.4))}e.relativeLuminance=function(e){return t(e>>16&255,e>>8&255,255&e)},e.relativeLuminance2=t}(h||(t.rgb=h={})),function(e){function t(e,t,i){const s=e>>24&255,r=e>>16&255,n=e>>8&255;let o=t>>24&255,a=t>>16&255,l=t>>8&255,c=u(h.relativeLuminance2(o,a,l),h.relativeLuminance2(s,r,n));for(;c0||a>0||l>0);)o-=Math.max(0,Math.ceil(.1*o)),a-=Math.max(0,Math.ceil(.1*a)),l-=Math.max(0,Math.ceil(.1*l)),c=u(h.relativeLuminance2(o,a,l),h.relativeLuminance2(s,r,n));return(o<<24|a<<16|l<<8|255)>>>0}function a(e,t,i){const s=e>>24&255,r=e>>16&255,n=e>>8&255;let o=t>>24&255,a=t>>16&255,l=t>>8&255,c=u(h.relativeLuminance2(o,a,l),h.relativeLuminance2(s,r,n));for(;c>>0}e.blend=function(e,t){if(n=(255&t)/255,1===n)return t;const a=t>>24&255,l=t>>16&255,h=t>>8&255,c=e>>24&255,d=e>>16&255,u=e>>8&255;return i=c+Math.round((a-c)*n),s=d+Math.round((l-d)*n),r=u+Math.round((h-u)*n),o.toRgba(i,s,r)},e.ensureContrastRatio=function(e,i,s){const r=h.relativeLuminance(e>>8),n=h.relativeLuminance(i>>8);if(u(r,n)>8));if(ou(r,h.relativeLuminance(t>>8))?n:t}return n}const o=a(e,i,s),l=u(r,h.relativeLuminance(o>>8));if(lu(r,h.relativeLuminance(n>>8))?o:n}return o}},e.reduceLuminance=t,e.increaseLuminance=a,e.toChannels=function(e){return[e>>24&255,e>>16&255,e>>8&255,255&e]}}(c||(t.rgba=c={}))},5777:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CoreTerminal=void 0;const s=i(6501),r=i(6025),n=i(7276),o=i(9640),a=i(56),l=i(4071),h=i(7792),c=i(6415),d=i(5746),u=i(5882),_=i(2486),f=i(3562),p=i(8811),g=i(802),m=i(7150);let v=!1;class S extends m.Disposable{get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new g.Emitter),this._onScroll.event((e=>{this._onScrollApi?.fire(e.position)}))),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(e){for(const t in e)this.optionsService.options[t]=e[t]}constructor(e){super(),this._windowsWrappingHeuristics=this._register(new m.MutableDisposable),this._onBinary=this._register(new g.Emitter),this.onBinary=this._onBinary.event,this._onData=this._register(new g.Emitter),this.onData=this._onData.event,this._onLineFeed=this._register(new g.Emitter),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new g.Emitter),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new g.Emitter),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new g.Emitter),this._instantiationService=new r.InstantiationService,this.optionsService=this._register(new a.OptionsService(e)),this._instantiationService.setService(s.IOptionsService,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(o.BufferService)),this._instantiationService.setService(s.IBufferService,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(n.LogService)),this._instantiationService.setService(s.ILogService,this._logService),this.coreService=this._register(this._instantiationService.createInstance(l.CoreService)),this._instantiationService.setService(s.ICoreService,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(h.CoreMouseService)),this._instantiationService.setService(s.ICoreMouseService,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(c.UnicodeService)),this._instantiationService.setService(s.IUnicodeService,this.unicodeService),this._charsetService=this._instantiationService.createInstance(d.CharsetService),this._instantiationService.setService(s.ICharsetService,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(p.OscLinkService),this._instantiationService.setService(s.IOscLinkService,this._oscLinkService),this._inputHandler=this._register(new _.InputHandler(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(g.Event.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(g.Event.forward(this._bufferService.onResize,this._onResize)),this._register(g.Event.forward(this.coreService.onData,this._onData)),this._register(g.Event.forward(this.coreService.onBinary,this._onBinary)),this._register(this.coreService.onRequestScrollToBottom((()=>this.scrollToBottom(!0)))),this._register(this.coreService.onUserInput((()=>this._writeBuffer.handleUserInput()))),this._register(this.optionsService.onMultipleOptionChange(["windowsMode","windowsPty"],(()=>this._handleWindowsPtyOptionChange()))),this._register(this._bufferService.onScroll((()=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)}))),this._writeBuffer=this._register(new f.WriteBuffer(((e,t)=>this._inputHandler.parse(e,t)))),this._register(g.Event.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}write(e,t){this._writeBuffer.write(e,t)}writeSync(e,t){this._logService.logLevel<=s.LogLevelEnum.WARN&&!v&&(this._logService.warn("writeSync is unreliable and will be removed soon."),v=!0),this._writeBuffer.writeSync(e,t)}input(e,t=!0){this.coreService.triggerDataEvent(e,t)}resize(e,t){isNaN(e)||isNaN(t)||(e=Math.max(e,o.MINIMUM_COLS),t=Math.max(t,o.MINIMUM_ROWS),this._bufferService.resize(e,t))}scroll(e,t=!1){this._bufferService.scroll(e,t)}scrollLines(e,t){this._bufferService.scrollLines(e,t)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){const t=e-this._bufferService.buffer.ydisp;0!==t&&this.scrollLines(t)}registerEscHandler(e,t){return this._inputHandler.registerEscHandler(e,t)}registerDcsHandler(e,t){return this._inputHandler.registerDcsHandler(e,t)}registerCsiHandler(e,t){return this._inputHandler.registerCsiHandler(e,t)}registerOscHandler(e,t){return this._inputHandler.registerOscHandler(e,t)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let e=!1;const t=this.optionsService.rawOptions.windowsPty;t&&void 0!==t.buildNumber&&void 0!==t.buildNumber?e=!!("conpty"===t.backend&&t.buildNumber<21376):this.optionsService.rawOptions.windowsMode&&(e=!0),e?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){const e=[];e.push(this.onLineFeed(u.updateWindowsModeWrappedState.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:"H"},(()=>((0,u.updateWindowsModeWrappedState)(this._bufferService),!1)))),this._windowsWrappingHeuristics.value=(0,m.toDisposable)((()=>{for(const t of e)t.dispose()}))}}}t.CoreTerminal=S},2486:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.InputHandler=t.WindowsOptionsReportType=void 0,t.isValidColorIndex=R;const n=i(3534),o=i(6760),a=i(6717),l=i(7150),h=i(726),c=i(6107),d=i(8938),u=i(3055),_=i(5451),f=i(6501),p=i(6415),g=i(1346),m=i(9823),v=i(8693),S=i(802),b={"(":0,")":1,"*":2,"+":3,"-":1,".":2},C=131072;function y(e,t){if(e>24)return t.setWinLines||!1;switch(e){case 1:return!!t.restoreWin;case 2:return!!t.minimizeWin;case 3:return!!t.setWinPosition;case 4:return!!t.setWinSizePixels;case 5:return!!t.raiseWin;case 6:return!!t.lowerWin;case 7:return!!t.refreshWin;case 8:return!!t.setWinSizeChars;case 9:return!!t.maximizeWin;case 10:return!!t.fullscreenWin;case 11:return!!t.getWinState;case 13:return!!t.getWinPosition;case 14:return!!t.getWinSizePixels;case 15:return!!t.getScreenSizePixels;case 16:return!!t.getCellSizePixels;case 18:return!!t.getWinSizeChars;case 19:return!!t.getScreenSizeChars;case 20:return!!t.getIconTitle;case 21:return!!t.getWinTitle;case 22:return!!t.pushTitle;case 23:return!!t.popTitle;case 24:return!!t.setWinLines}return!1}var w;!function(e){e[e.GET_WIN_SIZE_PIXELS=0]="GET_WIN_SIZE_PIXELS",e[e.GET_CELL_SIZE_PIXELS=1]="GET_CELL_SIZE_PIXELS"}(w||(t.WindowsOptionsReportType=w={}));let E=0;class D extends l.Disposable{getAttrData(){return this._curAttrData}constructor(e,t,i,s,r,l,d,u,_=new a.EscapeSequenceParser){super(),this._bufferService=e,this._charsetService=t,this._coreService=i,this._logService=s,this._optionsService=r,this._oscLinkService=l,this._coreMouseService=d,this._unicodeService=u,this._parser=_,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new h.StringToUtf32,this._utf8Decoder=new h.Utf8ToUtf32,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=c.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=c.DEFAULT_ATTR_DATA.clone(),this._onRequestBell=this._register(new S.Emitter),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new S.Emitter),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new S.Emitter),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new S.Emitter),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new S.Emitter),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new S.Emitter),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new S.Emitter),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new S.Emitter),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new S.Emitter),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new S.Emitter),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new S.Emitter),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new S.Emitter),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new S.Emitter),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this._register(this._parser),this._dirtyRowTracker=new L(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate((e=>this._activeBuffer=e.activeBuffer))),this._parser.setCsiHandlerFallback(((e,t)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(e),params:t.toArray()})})),this._parser.setEscHandlerFallback((e=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(e)})})),this._parser.setExecuteHandlerFallback((e=>{this._logService.debug("Unknown EXECUTE code: ",{code:e})})),this._parser.setOscHandlerFallback(((e,t,i)=>{this._logService.debug("Unknown OSC code: ",{identifier:e,action:t,data:i})})),this._parser.setDcsHandlerFallback(((e,t,i)=>{"HOOK"===t&&(i=i.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(e),action:t,payload:i})})),this._parser.setPrintHandler(((e,t,i)=>this.print(e,t,i))),this._parser.registerCsiHandler({final:"@"},(e=>this.insertChars(e))),this._parser.registerCsiHandler({intermediates:" ",final:"@"},(e=>this.scrollLeft(e))),this._parser.registerCsiHandler({final:"A"},(e=>this.cursorUp(e))),this._parser.registerCsiHandler({intermediates:" ",final:"A"},(e=>this.scrollRight(e))),this._parser.registerCsiHandler({final:"B"},(e=>this.cursorDown(e))),this._parser.registerCsiHandler({final:"C"},(e=>this.cursorForward(e))),this._parser.registerCsiHandler({final:"D"},(e=>this.cursorBackward(e))),this._parser.registerCsiHandler({final:"E"},(e=>this.cursorNextLine(e))),this._parser.registerCsiHandler({final:"F"},(e=>this.cursorPrecedingLine(e))),this._parser.registerCsiHandler({final:"G"},(e=>this.cursorCharAbsolute(e))),this._parser.registerCsiHandler({final:"H"},(e=>this.cursorPosition(e))),this._parser.registerCsiHandler({final:"I"},(e=>this.cursorForwardTab(e))),this._parser.registerCsiHandler({final:"J"},(e=>this.eraseInDisplay(e,!1))),this._parser.registerCsiHandler({prefix:"?",final:"J"},(e=>this.eraseInDisplay(e,!0))),this._parser.registerCsiHandler({final:"K"},(e=>this.eraseInLine(e,!1))),this._parser.registerCsiHandler({prefix:"?",final:"K"},(e=>this.eraseInLine(e,!0))),this._parser.registerCsiHandler({final:"L"},(e=>this.insertLines(e))),this._parser.registerCsiHandler({final:"M"},(e=>this.deleteLines(e))),this._parser.registerCsiHandler({final:"P"},(e=>this.deleteChars(e))),this._parser.registerCsiHandler({final:"S"},(e=>this.scrollUp(e))),this._parser.registerCsiHandler({final:"T"},(e=>this.scrollDown(e))),this._parser.registerCsiHandler({final:"X"},(e=>this.eraseChars(e))),this._parser.registerCsiHandler({final:"Z"},(e=>this.cursorBackwardTab(e))),this._parser.registerCsiHandler({final:"`"},(e=>this.charPosAbsolute(e))),this._parser.registerCsiHandler({final:"a"},(e=>this.hPositionRelative(e))),this._parser.registerCsiHandler({final:"b"},(e=>this.repeatPrecedingCharacter(e))),this._parser.registerCsiHandler({final:"c"},(e=>this.sendDeviceAttributesPrimary(e))),this._parser.registerCsiHandler({prefix:">",final:"c"},(e=>this.sendDeviceAttributesSecondary(e))),this._parser.registerCsiHandler({final:"d"},(e=>this.linePosAbsolute(e))),this._parser.registerCsiHandler({final:"e"},(e=>this.vPositionRelative(e))),this._parser.registerCsiHandler({final:"f"},(e=>this.hVPosition(e))),this._parser.registerCsiHandler({final:"g"},(e=>this.tabClear(e))),this._parser.registerCsiHandler({final:"h"},(e=>this.setMode(e))),this._parser.registerCsiHandler({prefix:"?",final:"h"},(e=>this.setModePrivate(e))),this._parser.registerCsiHandler({final:"l"},(e=>this.resetMode(e))),this._parser.registerCsiHandler({prefix:"?",final:"l"},(e=>this.resetModePrivate(e))),this._parser.registerCsiHandler({final:"m"},(e=>this.charAttributes(e))),this._parser.registerCsiHandler({final:"n"},(e=>this.deviceStatus(e))),this._parser.registerCsiHandler({prefix:"?",final:"n"},(e=>this.deviceStatusPrivate(e))),this._parser.registerCsiHandler({intermediates:"!",final:"p"},(e=>this.softReset(e))),this._parser.registerCsiHandler({intermediates:" ",final:"q"},(e=>this.setCursorStyle(e))),this._parser.registerCsiHandler({final:"r"},(e=>this.setScrollRegion(e))),this._parser.registerCsiHandler({final:"s"},(e=>this.saveCursor(e))),this._parser.registerCsiHandler({final:"t"},(e=>this.windowOptions(e))),this._parser.registerCsiHandler({final:"u"},(e=>this.restoreCursor(e))),this._parser.registerCsiHandler({intermediates:"'",final:"}"},(e=>this.insertColumns(e))),this._parser.registerCsiHandler({intermediates:"'",final:"~"},(e=>this.deleteColumns(e))),this._parser.registerCsiHandler({intermediates:'"',final:"q"},(e=>this.selectProtected(e))),this._parser.registerCsiHandler({intermediates:"$",final:"p"},(e=>this.requestMode(e,!0))),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},(e=>this.requestMode(e,!1))),this._parser.setExecuteHandler(n.C0.BEL,(()=>this.bell())),this._parser.setExecuteHandler(n.C0.LF,(()=>this.lineFeed())),this._parser.setExecuteHandler(n.C0.VT,(()=>this.lineFeed())),this._parser.setExecuteHandler(n.C0.FF,(()=>this.lineFeed())),this._parser.setExecuteHandler(n.C0.CR,(()=>this.carriageReturn())),this._parser.setExecuteHandler(n.C0.BS,(()=>this.backspace())),this._parser.setExecuteHandler(n.C0.HT,(()=>this.tab())),this._parser.setExecuteHandler(n.C0.SO,(()=>this.shiftOut())),this._parser.setExecuteHandler(n.C0.SI,(()=>this.shiftIn())),this._parser.setExecuteHandler(n.C1.IND,(()=>this.index())),this._parser.setExecuteHandler(n.C1.NEL,(()=>this.nextLine())),this._parser.setExecuteHandler(n.C1.HTS,(()=>this.tabSet())),this._parser.registerOscHandler(0,new g.OscHandler((e=>(this.setTitle(e),this.setIconName(e),!0)))),this._parser.registerOscHandler(1,new g.OscHandler((e=>this.setIconName(e)))),this._parser.registerOscHandler(2,new g.OscHandler((e=>this.setTitle(e)))),this._parser.registerOscHandler(4,new g.OscHandler((e=>this.setOrReportIndexedColor(e)))),this._parser.registerOscHandler(8,new g.OscHandler((e=>this.setHyperlink(e)))),this._parser.registerOscHandler(10,new g.OscHandler((e=>this.setOrReportFgColor(e)))),this._parser.registerOscHandler(11,new g.OscHandler((e=>this.setOrReportBgColor(e)))),this._parser.registerOscHandler(12,new g.OscHandler((e=>this.setOrReportCursorColor(e)))),this._parser.registerOscHandler(104,new g.OscHandler((e=>this.restoreIndexedColor(e)))),this._parser.registerOscHandler(110,new g.OscHandler((e=>this.restoreFgColor(e)))),this._parser.registerOscHandler(111,new g.OscHandler((e=>this.restoreBgColor(e)))),this._parser.registerOscHandler(112,new g.OscHandler((e=>this.restoreCursorColor(e)))),this._parser.registerEscHandler({final:"7"},(()=>this.saveCursor())),this._parser.registerEscHandler({final:"8"},(()=>this.restoreCursor())),this._parser.registerEscHandler({final:"D"},(()=>this.index())),this._parser.registerEscHandler({final:"E"},(()=>this.nextLine())),this._parser.registerEscHandler({final:"H"},(()=>this.tabSet())),this._parser.registerEscHandler({final:"M"},(()=>this.reverseIndex())),this._parser.registerEscHandler({final:"="},(()=>this.keypadApplicationMode())),this._parser.registerEscHandler({final:">"},(()=>this.keypadNumericMode())),this._parser.registerEscHandler({final:"c"},(()=>this.fullReset())),this._parser.registerEscHandler({final:"n"},(()=>this.setgLevel(2))),this._parser.registerEscHandler({final:"o"},(()=>this.setgLevel(3))),this._parser.registerEscHandler({final:"|"},(()=>this.setgLevel(3))),this._parser.registerEscHandler({final:"}"},(()=>this.setgLevel(2))),this._parser.registerEscHandler({final:"~"},(()=>this.setgLevel(1))),this._parser.registerEscHandler({intermediates:"%",final:"@"},(()=>this.selectDefaultCharset())),this._parser.registerEscHandler({intermediates:"%",final:"G"},(()=>this.selectDefaultCharset()));for(const e in o.CHARSETS)this._parser.registerEscHandler({intermediates:"(",final:e},(()=>this.selectCharset("("+e))),this._parser.registerEscHandler({intermediates:")",final:e},(()=>this.selectCharset(")"+e))),this._parser.registerEscHandler({intermediates:"*",final:e},(()=>this.selectCharset("*"+e))),this._parser.registerEscHandler({intermediates:"+",final:e},(()=>this.selectCharset("+"+e))),this._parser.registerEscHandler({intermediates:"-",final:e},(()=>this.selectCharset("-"+e))),this._parser.registerEscHandler({intermediates:".",final:e},(()=>this.selectCharset("."+e))),this._parser.registerEscHandler({intermediates:"/",final:e},(()=>this.selectCharset("/"+e)));this._parser.registerEscHandler({intermediates:"#",final:"8"},(()=>this.screenAlignmentPattern())),this._parser.setErrorHandler((e=>(this._logService.error("Parsing error: ",e),e))),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new m.DcsHandler(((e,t)=>this.requestStatusString(e,t))))}_preserveStack(e,t,i,s){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=t,this._parseStack.decodedLength=i,this._parseStack.position=s}_logSlowResolvingAsync(e){this._logService.logLevel<=f.LogLevelEnum.WARN&&Promise.race([e,new Promise(((e,t)=>setTimeout((()=>t("#SLOW_TIMEOUT")),5e3)))]).catch((e=>{if("#SLOW_TIMEOUT"!==e)throw e;console.warn("async parser handler taking longer than 5000 ms")}))}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let i,s=this._activeBuffer.x,r=this._activeBuffer.y,n=0;const o=this._parseStack.paused;if(o){if(i=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(i),i;s=this._parseStack.cursorStartX,r=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>C&&(n=this._parseStack.position+C)}if(this._logService.logLevel<=f.LogLevelEnum.DEBUG&&this._logService.debug("parsing data "+("string"==typeof e?` "${e}"`:` "${Array.prototype.map.call(e,(e=>String.fromCharCode(e))).join("")}"`)),this._logService.logLevel===f.LogLevelEnum.TRACE&&this._logService.trace("parsing data (codes)","string"==typeof e?e.split("").map((e=>e.charCodeAt(0))):e),this._parseBuffer.lengthC)for(let t=n;t0&&2===f.getWidth(this._activeBuffer.x-1)&&f.setCellFromCodepoint(this._activeBuffer.x-1,0,1,_);let g=this._parser.precedingJoinState;for(let m=t;ma)if(l){const e=f;let t=this._activeBuffer.x-v;for(this._activeBuffer.x=v,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),f=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),v>0&&f instanceof c.BufferLine&&f.copyCellsFrom(e,t,0,v,!1);t=0;)f.setCellFromCodepoint(this._activeBuffer.x++,0,0,_)}else if(u&&(f.insertCells(this._activeBuffer.x,r-v,this._activeBuffer.getNullCell(_)),2===f.getWidth(a-1)&&f.setCellFromCodepoint(a-1,d.NULL_CELL_CODE,d.NULL_CELL_WIDTH,_)),f.setCellFromCodepoint(this._activeBuffer.x++,s,r,_),r>0)for(;--r;)f.setCellFromCodepoint(this._activeBuffer.x++,0,0,_)}this._parser.precedingJoinState=g,this._activeBuffer.x0&&0===f.getWidth(this._activeBuffer.x)&&!f.hasContent(this._activeBuffer.x)&&f.setCellFromCodepoint(this._activeBuffer.x,0,1,_),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return"t"!==e.final||e.prefix||e.intermediates?this._parser.registerCsiHandler(e,t):this._parser.registerCsiHandler(e,(e=>!y(e.params[0],this._optionsService.rawOptions.windowOptions)||t(e)))}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new m.DcsHandler(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new g.OscHandler(t))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(0===this._activeBuffer.x&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y)?.isWrapped){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;const e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);e.hasWidth(this._activeBuffer.x)&&!e.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;const e=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(e,t){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e,this._activeBuffer.y=this._activeBuffer.scrollTop+t):(this._activeBuffer.x=e,this._activeBuffer.y=t),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e,t){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e,this._activeBuffer.y+t)}cursorUp(e){const t=this._activeBuffer.y-this._activeBuffer.scrollTop;return t>=0?this._moveCursor(0,-Math.min(t,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1)),!0}cursorDown(e){const t=this._activeBuffer.scrollBottom-this._activeBuffer.y;return t>=0?this._moveCursor(0,Math.min(t,e.params[0]||1)):this._moveCursor(0,e.params[0]||1),!0}cursorForward(e){return this._moveCursor(e.params[0]||1,0),!0}cursorBackward(e){return this._moveCursor(-(e.params[0]||1),0),!0}cursorNextLine(e){return this.cursorDown(e),this._activeBuffer.x=0,!0}cursorPrecedingLine(e){return this.cursorUp(e),this._activeBuffer.x=0,!0}cursorCharAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e){return this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1),!0}charPosAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e){return this._moveCursor(e.params[0]||1,0),!0}linePosAbsolute(e){return this._setCursor(this._activeBuffer.x,(e.params[0]||1)-1),!0}vPositionRelative(e){return this._moveCursor(0,e.params[0]||1),!0}hVPosition(e){return this.cursorPosition(e),!0}tabClear(e){const t=e.params[0];return 0===t?delete this._activeBuffer.tabs[this._activeBuffer.x]:3===t&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e){const t=e.params[0];return 1===t&&(this._curAttrData.bg|=536870912),2!==t&&0!==t||(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(e,t,i,s=!1,r=!1){const n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.replaceCells(t,i,this._activeBuffer.getNullCell(this._eraseAttrData()),r),s&&(n.isWrapped=!1)}_resetBufferLine(e,t=!1){const i=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);i&&(i.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),i.isWrapped=!1)}eraseInDisplay(e,t=!1){let i;switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:for(i=this._activeBuffer.y,this._dirtyRowTracker.markDirty(i),this._eraseInBufferLine(i++,this._activeBuffer.x,this._bufferService.cols,0===this._activeBuffer.x,t);i=this._bufferService.cols&&(this._activeBuffer.lines.get(i+1).isWrapped=!1);i--;)this._resetBufferLine(i,t);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(i=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,i-1);i--;){const e=this._activeBuffer.lines.get(this._activeBuffer.ybase+i);if(e?.getTrimmedLength())break}for(;i>=0;i--)this._bufferService.scroll(this._eraseAttrData())}else{for(i=this._bufferService.rows,this._dirtyRowTracker.markDirty(i-1);i--;)this._resetBufferLine(i,t);this._dirtyRowTracker.markDirty(0)}break;case 3:const e=this._activeBuffer.lines.length-this._bufferService.rows;e>0&&(this._activeBuffer.lines.trimStart(e),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-e,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-e,0),this._onScroll.fire(0))}return!0}eraseInLine(e,t=!1){switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,0===this._activeBuffer.x,t);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,t);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,t)}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.y65535?2:1}let l=a;for(let e=1;e0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(n.C0.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(n.C0.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(n.C0.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(n.C0.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(e.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(n.C0.ESC+"[>83;40003;0c")),!0}_is(e){return 0===(this._optionsService.rawOptions.termName+"").indexOf(e)}setMode(e){for(let t=0;te?1:2,_=e.params[0];return f=_,p=t?2===_?4:4===_?u(o.modes.insertMode):12===_?3:20===_?u(d.convertEol):0:1===_?u(i.applicationCursorKeys):3===_?d.windowOptions.setWinLines?80===l?2:132===l?1:0:0:6===_?u(i.origin):7===_?u(i.wraparound):8===_?3:9===_?u("X10"===s):12===_?u(d.cursorBlink):25===_?u(!o.isCursorHidden):45===_?u(i.reverseWraparound):66===_?u(i.applicationKeypad):67===_?4:1e3===_?u("VT200"===s):1002===_?u("DRAG"===s):1003===_?u("ANY"===s):1004===_?u(i.sendFocus):1005===_?4:1006===_?u("SGR"===r):1015===_?4:1016===_?u("SGR_PIXELS"===r):1048===_?1:47===_||1047===_||1049===_?u(h===c):2004===_?u(i.bracketedPasteMode):2026===_?u(i.synchronizedOutput):0,o.triggerDataEvent(`${n.C0.ESC}[${t?"":"?"}${f};${p}$y`),!0;var f,p}_updateAttrColor(e,t,i,s,r){return 2===t?(e|=50331648,e&=-16777216,e|=_.AttributeData.fromColorRGB([i,s,r])):5===t&&(e&=-50331904,e|=33554432|255&i),e}_extractColor(e,t,i){const s=[0,0,-1,0,0,0];let r=0,n=0;do{if(s[n+r]=e.params[t+n],e.hasSubParams(t+n)){const i=e.getSubParams(t+n);let o=0;do{5===s[1]&&(r=1),s[n+o+1+r]=i[o]}while(++o=2||2===s[1]&&n+r>=5)break;s[1]&&(r=1)}while(++n+t5)&&(e=1),t.extended.underlineStyle=e,t.fg|=268435456,0===e&&(t.fg&=-268435457),t.updateExtended()}_processSGR0(e){e.fg=c.DEFAULT_ATTR_DATA.fg,e.bg=c.DEFAULT_ATTR_DATA.bg,e.extended=e.extended.clone(),e.extended.underlineStyle=0,e.extended.underlineColor&=-67108864,e.updateExtended()}charAttributes(e){if(1===e.length&&0===e.params[0])return this._processSGR0(this._curAttrData),!0;const t=e.length;let i;const s=this._curAttrData;for(let r=0;r=30&&i<=37?(s.fg&=-50331904,s.fg|=16777216|i-30):i>=40&&i<=47?(s.bg&=-50331904,s.bg|=16777216|i-40):i>=90&&i<=97?(s.fg&=-50331904,s.fg|=16777224|i-90):i>=100&&i<=107?(s.bg&=-50331904,s.bg|=16777224|i-100):0===i?this._processSGR0(s):1===i?s.fg|=134217728:3===i?s.bg|=67108864:4===i?(s.fg|=268435456,this._processUnderline(e.hasSubParams(r)?e.getSubParams(r)[0]:1,s)):5===i?s.fg|=536870912:7===i?s.fg|=67108864:8===i?s.fg|=1073741824:9===i?s.fg|=2147483648:2===i?s.bg|=134217728:21===i?this._processUnderline(2,s):22===i?(s.fg&=-134217729,s.bg&=-134217729):23===i?s.bg&=-67108865:24===i?(s.fg&=-268435457,this._processUnderline(0,s)):25===i?s.fg&=-536870913:27===i?s.fg&=-67108865:28===i?s.fg&=-1073741825:29===i?s.fg&=2147483647:39===i?(s.fg&=-67108864,s.fg|=16777215&c.DEFAULT_ATTR_DATA.fg):49===i?(s.bg&=-67108864,s.bg|=16777215&c.DEFAULT_ATTR_DATA.bg):38===i||48===i||58===i?r+=this._extractColor(e,r,s):53===i?s.bg|=1073741824:55===i?s.bg&=-1073741825:59===i?(s.extended=s.extended.clone(),s.extended.underlineColor=-1,s.updateExtended()):100===i?(s.fg&=-67108864,s.fg|=16777215&c.DEFAULT_ATTR_DATA.fg,s.bg&=-67108864,s.bg|=16777215&c.DEFAULT_ATTR_DATA.bg):this._logService.debug("Unknown SGR attribute: %d.",i);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${n.C0.ESC}[0n`);break;case 6:const e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${n.C0.ESC}[${e};${t}R`)}return!0}deviceStatusPrivate(e){if(6===e.params[0]){const e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${n.C0.ESC}[?${e};${t}R`)}return!0}softReset(e){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=c.DEFAULT_ATTR_DATA.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(e){const t=0===e.length?1:e.params[0];if(0===t)this._coreService.decPrivateModes.cursorStyle=void 0,this._coreService.decPrivateModes.cursorBlink=void 0;else{switch(t){case 1:case 2:this._coreService.decPrivateModes.cursorStyle="block";break;case 3:case 4:this._coreService.decPrivateModes.cursorStyle="underline";break;case 5:case 6:this._coreService.decPrivateModes.cursorStyle="bar"}const e=t%2==1;this._coreService.decPrivateModes.cursorBlink=e}return!0}setScrollRegion(e){const t=e.params[0]||1;let i;return(e.length<2||(i=e.params[1])>this._bufferService.rows||0===i)&&(i=this._bufferService.rows),i>t&&(this._activeBuffer.scrollTop=t-1,this._activeBuffer.scrollBottom=i-1,this._setCursor(0,0)),!0}windowOptions(e){if(!y(e.params[0],this._optionsService.rawOptions.windowOptions))return!0;const t=e.length>1?e.params[1]:0;switch(e.params[0]){case 14:2!==t&&this._onRequestWindowsOptionsReport.fire(w.GET_WIN_SIZE_PIXELS);break;case 16:this._onRequestWindowsOptionsReport.fire(w.GET_CELL_SIZE_PIXELS);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${n.C0.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:0!==t&&2!==t||(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>10&&this._windowTitleStack.shift()),0!==t&&1!==t||(this._iconNameStack.push(this._iconName),this._iconNameStack.length>10&&this._iconNameStack.shift());break;case 23:0!==t&&2!==t||this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),0!==t&&1!==t||this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop())}return!0}saveCursor(e){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(e){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(e){return this._windowTitle=e,this._onTitleChange.fire(e),!0}setIconName(e){return this._iconName=e,!0}setOrReportIndexedColor(e){const t=[],i=e.split(";");for(;i.length>1;){const e=i.shift(),s=i.shift();if(/^\d+$/.exec(e)){const i=parseInt(e);if(R(i))if("?"===s)t.push({type:0,index:i});else{const e=(0,v.parseColor)(s);e&&t.push({type:1,index:i,color:e})}}}return t.length&&this._onColor.fire(t),!0}setHyperlink(e){const t=e.indexOf(";");if(-1===t)return!0;const i=e.slice(0,t).trim(),s=e.slice(t+1);return s?this._createHyperlink(i,s):!i.trim()&&this._finishHyperlink()}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();const i=e.split(":");let s;const r=i.findIndex((e=>e.startsWith("id=")));return-1!==r&&(s=i[r].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:s,uri:t}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e,t){const i=e.split(";");for(let e=0;e=this._specialColors.length);++e,++t)if("?"===i[e])this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{const s=(0,v.parseColor)(i[e]);s&&this._onColor.fire([{type:1,index:this._specialColors[t],color:s}])}return!0}setOrReportFgColor(e){return this._setOrReportSpecialColor(e,0)}setOrReportBgColor(e){return this._setOrReportSpecialColor(e,1)}setOrReportCursorColor(e){return this._setOrReportSpecialColor(e,2)}restoreIndexedColor(e){if(!e)return this._onColor.fire([{type:2}]),!0;const t=[],i=e.split(";");for(let e=0;e=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){const e=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,e,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=c.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=c.DEFAULT_ATTR_DATA.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=67108863&this._curAttrData.bg,this._eraseAttrDataInternal}setgLevel(e){return this._charsetService.setgLevel(e),!0}screenAlignmentPattern(){const e=new u.CellData;e.content=1<<22|"E".charCodeAt(0),e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let t=0;t(this._coreService.triggerDataEvent(`${n.C0.ESC}${e}${n.C0.ESC}\\`),!0))('"q'===e?`P1$r${this._curAttrData.isProtected()?1:0}"q`:'"p'===e?'P1$r61;1"p':"r"===e?`P1$r${i.scrollTop+1};${i.scrollBottom+1}r`:"m"===e?"P1$r0m":" q"===e?`P1$r${{block:2,underline:4,bar:6}[s.cursorStyle]-(s.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}}t.InputHandler=D;let L=class{constructor(e){this._bufferService=e,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e){ethis.end&&(this.end=e)}markRangeDirty(e,t){e>t&&(E=e,e=t,t=E),ethis.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};function R(e){return 0<=e&&e<256}L=s([r(0,f.IBufferService)],L)},7710:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.FourKeyMap=t.TwoKeyMap=void 0;class i{constructor(){this._data={}}set(e,t,i){this._data[e]||(this._data[e]={}),this._data[e][t]=i}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}}t.TwoKeyMap=i,t.FourKeyMap=class{constructor(){this._data=new i}set(e,t,s,r,n){this._data.get(e,t)||this._data.set(e,t,new i),this._data.get(e,t).set(s,r,n)}get(e,t,i,s){return this._data.get(e,t)?.get(i,s)}clear(){this._data.clear()}}},701:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isChromeOS=t.isLinux=t.isWindows=t.isIphone=t.isIpad=t.isMac=t.isSafari=t.isLegacyEdge=t.isFirefox=t.isNode=void 0,t.getSafariVersion=function(){if(!t.isSafari)return 0;const e=i.match(/Version\/(\d+)/);return null===e||e.length<2?0:parseInt(e[1])},t.isNode="undefined"!=typeof process&&"title"in process;const i=t.isNode?"node":navigator.userAgent,s=t.isNode?"node":navigator.platform;t.isFirefox=i.includes("Firefox"),t.isLegacyEdge=i.includes("Edge"),t.isSafari=/^((?!chrome|android).)*safari/i.test(i),t.isMac=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(s),t.isIpad="iPad"===s,t.isIphone="iPhone"===s,t.isWindows=["Windows","Win16","Win32","WinCE"].includes(s),t.isLinux=s.indexOf("Linux")>=0,t.isChromeOS=/\bCrOS\b/.test(i)},3087:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SortedList=void 0;const s=i(6168);let r=0;t.SortedList=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new s.IdleTaskQueue,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new s.IdleTaskQueue,this._isFlushingDeleted=!1}clear(){this._array.length=0,this._insertedValues.length=0,this._flushInsertedTask.clear(),this._isFlushingInserted=!1,this._deletedIndices.length=0,this._flushDeletedTask.clear(),this._isFlushingDeleted=!1}insert(e){this._flushCleanupDeleted(),0===this._insertedValues.length&&this._flushInsertedTask.enqueue((()=>this._flushInserted())),this._insertedValues.push(e)}_flushInserted(){const e=this._insertedValues.sort(((e,t)=>this._getKey(e)-this._getKey(t)));let t=0,i=0;const s=new Array(this._array.length+this._insertedValues.length);for(let r=0;r=this._array.length||this._getKey(e[t])<=this._getKey(this._array[i])?(s[r]=e[t],t++):s[r]=this._array[i++];this._array=s,this._insertedValues.length=0}_flushCleanupInserted(){!this._isFlushingInserted&&this._insertedValues.length>0&&this._flushInsertedTask.flush()}delete(e){if(this._flushCleanupInserted(),0===this._array.length)return!1;const t=this._getKey(e);if(void 0===t)return!1;if(r=this._search(t),-1===r)return!1;if(this._getKey(this._array[r])!==t)return!1;do{if(this._array[r]===e)return 0===this._deletedIndices.length&&this._flushDeletedTask.enqueue((()=>this._flushDeleted())),this._deletedIndices.push(r),!0}while(++re-t));let t=0;const i=new Array(this._array.length-e.length);let s=0;for(let r=0;r0&&this._flushDeletedTask.flush()}*getKeyIterator(e){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),0!==this._array.length&&(r=this._search(e),!(r<0||r>=this._array.length)&&this._getKey(this._array[r])===e))do{yield this._array[r]}while(++r=this._array.length)&&this._getKey(this._array[r])===e))do{t(this._array[r])}while(++r=t;){let s=t+i>>1;const r=this._getKey(this._array[s]);if(r>e)i=s-1;else{if(!(r0&&this._getKey(this._array[s-1])===e;)s--;return s}t=s+1}}return t}}},6168:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DebouncedIdleTask=t.IdleTaskQueue=t.PriorityTaskQueue=void 0;const s=i(701);class r{constructor(){this._tasks=[],this._i=0}enqueue(e){this._tasks.push(e),this._start()}flush(){for(;this._ir)return s-t<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(s-t))}ms`),void this._start();s=r}this.clear()}}class n extends r{_requestCallback(e){return setTimeout((()=>e(this._createDeadline(16))))}_cancelCallback(e){clearTimeout(e)}_createDeadline(e){const t=performance.now()+e;return{timeRemaining:()=>Math.max(0,t-performance.now())}}}t.PriorityTaskQueue=n,t.IdleTaskQueue=!s.isNode&&"requestIdleCallback"in window?class extends r{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}}:n,t.DebouncedIdleTask=class{constructor(){this._queue=new t.IdleTaskQueue}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}}},5882:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.updateWindowsModeWrappedState=function(e){const t=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1),i=t?.get(e.cols-1),r=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);r&&i&&(r.isWrapped=i[s.CHAR_DATA_CODE_INDEX]!==s.NULL_CELL_CODE&&i[s.CHAR_DATA_CODE_INDEX]!==s.WHITESPACE_CELL_CODE)};const s=i(8938)},5451:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ExtendedAttrs=t.AttributeData=void 0;class i{constructor(){this.fg=0,this.bg=0,this.extended=new s}static toColorRGB(e){return[e>>>16&255,e>>>8&255,255&e]}static fromColorRGB(e){return(255&e[0])<<16|(255&e[1])<<8|255&e[2]}clone(){const e=new i;return e.fg=this.fg,e.bg=this.bg,e.extended=this.extended.clone(),e}isInverse(){return 67108864&this.fg}isBold(){return 134217728&this.fg}isUnderline(){return this.hasExtendedAttrs()&&0!==this.extended.underlineStyle?1:268435456&this.fg}isBlink(){return 536870912&this.fg}isInvisible(){return 1073741824&this.fg}isItalic(){return 67108864&this.bg}isDim(){return 134217728&this.bg}isStrikethrough(){return 2147483648&this.fg}isProtected(){return 536870912&this.bg}isOverline(){return 1073741824&this.bg}getFgColorMode(){return 50331648&this.fg}getBgColorMode(){return 50331648&this.bg}isFgRGB(){return!(50331648&~this.fg)}isBgRGB(){return!(50331648&~this.bg)}isFgPalette(){return 16777216==(50331648&this.fg)||33554432==(50331648&this.fg)}isBgPalette(){return 16777216==(50331648&this.bg)||33554432==(50331648&this.bg)}isFgDefault(){return!(50331648&this.fg)}isBgDefault(){return!(50331648&this.bg)}isAttributeDefault(){return 0===this.fg&&0===this.bg}getFgColor(){switch(50331648&this.fg){case 16777216:case 33554432:return 255&this.fg;case 50331648:return 16777215&this.fg;default:return-1}}getBgColor(){switch(50331648&this.bg){case 16777216:case 33554432:return 255&this.bg;case 50331648:return 16777215&this.bg;default:return-1}}hasExtendedAttrs(){return 268435456&this.bg}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(268435456&this.bg&&~this.extended.underlineColor)switch(50331648&this.extended.underlineColor){case 16777216:case 33554432:return 255&this.extended.underlineColor;case 50331648:return 16777215&this.extended.underlineColor;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return 268435456&this.bg&&~this.extended.underlineColor?50331648&this.extended.underlineColor:this.getFgColorMode()}isUnderlineColorRGB(){return 268435456&this.bg&&~this.extended.underlineColor?!(50331648&~this.extended.underlineColor):this.isFgRGB()}isUnderlineColorPalette(){return 268435456&this.bg&&~this.extended.underlineColor?16777216==(50331648&this.extended.underlineColor)||33554432==(50331648&this.extended.underlineColor):this.isFgPalette()}isUnderlineColorDefault(){return 268435456&this.bg&&~this.extended.underlineColor?!(50331648&this.extended.underlineColor):this.isFgDefault()}getUnderlineStyle(){return 268435456&this.fg?268435456&this.bg?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}}t.AttributeData=i;class s{get ext(){return this._urlId?-469762049&this._ext|this.underlineStyle<<26:this._ext}set ext(e){this._ext=e}get underlineStyle(){return this._urlId?5:(469762048&this._ext)>>26}set underlineStyle(e){this._ext&=-469762049,this._ext|=e<<26&469762048}get underlineColor(){return 67108863&this._ext}set underlineColor(e){this._ext&=-67108864,this._ext|=67108863&e}get urlId(){return this._urlId}set urlId(e){this._urlId=e}get underlineVariantOffset(){const e=(3758096384&this._ext)>>29;return e<0?4294967288^e:e}set underlineVariantOffset(e){this._ext&=536870911,this._ext|=e<<29&3758096384}constructor(e=0,t=0){this._ext=0,this._urlId=0,this._ext=e,this._urlId=t}clone(){return new s(this._ext,this._urlId)}isEmpty(){return 0===this.underlineStyle&&0===this._urlId}}t.ExtendedAttrs=s},1073:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Buffer=t.MAX_BUFFER_SIZE=void 0;const s=i(5639),r=i(6168),n=i(5451),o=i(6107),a=i(732),l=i(3055),h=i(8938),c=i(8158),d=i(6760);t.MAX_BUFFER_SIZE=4294967295,t.Buffer=class{constructor(e,t,i){this._hasScrollback=e,this._optionsService=t,this._bufferService=i,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=o.DEFAULT_ATTR_DATA.clone(),this.savedCharset=d.DEFAULT_CHARSET,this.markers=[],this._nullCell=l.CellData.fromCharData([0,h.NULL_CELL_CHAR,h.NULL_CELL_WIDTH,h.NULL_CELL_CODE]),this._whitespaceCell=l.CellData.fromCharData([0,h.WHITESPACE_CELL_CHAR,h.WHITESPACE_CELL_WIDTH,h.WHITESPACE_CELL_CODE]),this._isClearing=!1,this._memoryCleanupQueue=new r.IdleTaskQueue,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new s.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(e){return e?(this._nullCell.fg=e.fg,this._nullCell.bg=e.bg,this._nullCell.extended=e.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new n.ExtendedAttrs),this._nullCell}getWhitespaceCell(e){return e?(this._whitespaceCell.fg=e.fg,this._whitespaceCell.bg=e.bg,this._whitespaceCell.extended=e.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new n.ExtendedAttrs),this._whitespaceCell}getBlankLine(e,t){return new o.BufferLine(this._bufferService.cols,this.getNullCell(e),t)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){const e=this.ybase+this.y-this.ydisp;return e>=0&&et.MAX_BUFFER_SIZE?t.MAX_BUFFER_SIZE:i}fillViewportRows(e){if(0===this.lines.length){void 0===e&&(e=o.DEFAULT_ATTR_DATA);let t=this._rows;for(;t--;)this.lines.push(this.getBlankLine(e))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new s.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){const i=this.getNullCell(o.DEFAULT_ATTR_DATA);let s=0;const r=this._getCorrectBufferLength(t);if(r>this.lines.maxLength&&(this.lines.maxLength=r),this.lines.length>0){if(this._cols0&&this.lines.length<=this.ybase+this.y+n+1?(this.ybase--,n++,this.ydisp>0&&this.ydisp--):this.lines.push(new o.BufferLine(e,i)));else for(let e=this._rows;e>t;e--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(r0&&(this.lines.trimStart(e),this.ybase=Math.max(this.ybase-e,0),this.ydisp=Math.max(this.ydisp-e,0),this.savedY=Math.max(this.savedY-e,0)),this.lines.maxLength=r}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),n&&(this.y+=n),this.savedX=Math.min(this.savedX,e-1),this.scrollTop=0}if(this.scrollBottom=t-1,this._isReflowEnabled&&(this._reflow(e,t),this._cols>e))for(let t=0;t.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue((()=>this._batchedMemoryCleanup())))}_batchedMemoryCleanup(){let e=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,e=!1);let t=0;for(;this._memoryCleanupPosition100)return!0;return e}get _isReflowEnabled(){const e=this._optionsService.rawOptions.windowsPty;return e&&e.buildNumber?this._hasScrollback&&"conpty"===e.backend&&e.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(e,t){this._cols!==e&&(e>this._cols?this._reflowLarger(e,t):this._reflowSmaller(e,t))}_reflowLarger(e,t){const i=this._optionsService.rawOptions.reflowCursorLine,s=(0,a.reflowLargerGetLinesToRemove)(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(o.DEFAULT_ATTR_DATA),i);if(s.length>0){const i=(0,a.reflowLargerCreateNewLayout)(this.lines,s);(0,a.reflowLargerApplyNewLayout)(this.lines,i.layout),this._reflowLargerAdjustViewport(e,t,i.countRemoved)}}_reflowLargerAdjustViewport(e,t,i){const s=this.getNullCell(o.DEFAULT_ATTR_DATA);let r=i;for(;r-- >0;)0===this.ybase?(this.y>0&&this.y--,this.lines.length=0;l--){let h=this.lines.get(l);if(!h||!h.isWrapped&&h.getTrimmedLength()<=e)continue;const c=[h];for(;h.isWrapped&&l>0;)h=this.lines.get(--l),c.unshift(h);if(!i){const e=this.ybase+this.y;if(e>=l&&e0&&(r.push({start:l+c.length+n,newLines:p}),n+=p.length),c.push(...p);let g=u.length-1,m=u[g];0===m&&(g--,m=u[g]);let v=c.length-_-1,S=d;for(;v>=0;){const e=Math.min(S,m);if(void 0===c[g])break;if(c[g].copyCellsFrom(c[v],S-e,m-e,e,!0),m-=e,0===m&&(g--,m=u[g]),S-=e,0===S){v--;const e=Math.max(v,0);S=(0,a.getWrappedLineTrimmedLength)(c,e,this._cols)}}for(let t=0;t0;)0===this.ybase?this.y0){const e=[],t=[];for(let e=0;e=0;h--)if(a&&a.start>s+l){for(let e=a.newLines.length-1;e>=0;e--)this.lines.set(h--,a.newLines[e]);h++,e.push({index:s+1,amount:a.newLines.length}),l+=a.newLines.length,a=r[++o]}else this.lines.set(h,t[s--]);let h=0;for(let t=e.length-1;t>=0;t--)e[t].index+=h,this.lines.onInsertEmitter.fire(e[t]),h+=e[t].amount;const c=Math.max(0,i+n-this.lines.maxLength);c>0&&this.lines.onTrimEmitter.fire(c)}}translateBufferLineToString(e,t,i=0,s){const r=this.lines.get(e);return r?r.translateToString(t,i,s):""}getWrappedRangeForLine(e){let t=e,i=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;i+10;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(null==e&&(e=this.x);!this.tabs[++e]&&e=this._cols?this._cols-1:e<0?0:e}clearMarkers(e){this._isClearing=!0;for(let t=0;t{t.line-=e,t.line<0&&t.dispose()}))),t.register(this.lines.onInsert((e=>{t.line>=e.index&&(t.line+=e.amount)}))),t.register(this.lines.onDelete((e=>{t.line>=e.index&&t.linee.index&&(t.line-=e.amount)}))),t.register(t.onDispose((()=>this._removeMarker(t)))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}}},6107:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BufferLine=t.DEFAULT_ATTR_DATA=void 0;const s=i(5451),r=i(3055),n=i(8938),o=i(726);t.DEFAULT_ATTR_DATA=Object.freeze(new s.AttributeData);let a=0;class l{constructor(e,t,i=!1){this.isWrapped=i,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(3*e);const s=t||r.CellData.fromCharData([0,n.NULL_CELL_CHAR,n.NULL_CELL_WIDTH,n.NULL_CELL_CODE]);for(let t=0;t>22,2097152&t?this._combined[e].charCodeAt(this._combined[e].length-1):i]}set(e,t){this._data[3*e+1]=t[n.CHAR_DATA_ATTR_INDEX],t[n.CHAR_DATA_CHAR_INDEX].length>1?(this._combined[e]=t[1],this._data[3*e+0]=2097152|e|t[n.CHAR_DATA_WIDTH_INDEX]<<22):this._data[3*e+0]=t[n.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|t[n.CHAR_DATA_WIDTH_INDEX]<<22}getWidth(e){return this._data[3*e+0]>>22}hasWidth(e){return 12582912&this._data[3*e+0]}getFg(e){return this._data[3*e+1]}getBg(e){return this._data[3*e+2]}hasContent(e){return 4194303&this._data[3*e+0]}getCodePoint(e){const t=this._data[3*e+0];return 2097152&t?this._combined[e].charCodeAt(this._combined[e].length-1):2097151&t}isCombined(e){return 2097152&this._data[3*e+0]}getString(e){const t=this._data[3*e+0];return 2097152&t?this._combined[e]:2097151&t?(0,o.stringFromCodePoint)(2097151&t):""}isProtected(e){return 536870912&this._data[3*e+2]}loadCell(e,t){return a=3*e,t.content=this._data[a+0],t.fg=this._data[a+1],t.bg=this._data[a+2],2097152&t.content&&(t.combinedData=this._combined[e]),268435456&t.bg&&(t.extended=this._extendedAttrs[e]),t}setCell(e,t){2097152&t.content&&(this._combined[e]=t.combinedData),268435456&t.bg&&(this._extendedAttrs[e]=t.extended),this._data[3*e+0]=t.content,this._data[3*e+1]=t.fg,this._data[3*e+2]=t.bg}setCellFromCodepoint(e,t,i,s){268435456&s.bg&&(this._extendedAttrs[e]=s.extended),this._data[3*e+0]=t|i<<22,this._data[3*e+1]=s.fg,this._data[3*e+2]=s.bg}addCodepointToCell(e,t,i){let s=this._data[3*e+0];2097152&s?this._combined[e]+=(0,o.stringFromCodePoint)(t):2097151&s?(this._combined[e]=(0,o.stringFromCodePoint)(2097151&s)+(0,o.stringFromCodePoint)(t),s&=-2097152,s|=2097152):s=t|1<<22,i&&(s&=-12582913,s|=i<<22),this._data[3*e+0]=s}insertCells(e,t,i){if((e%=this.length)&&2===this.getWidth(e-1)&&this.setCellFromCodepoint(e-1,0,1,i),t=0;--i)this.setCell(e+t+i,this.loadCell(e+i,s));for(let s=0;sthis.length){if(this._data.buffer.byteLength>=4*i)this._data=new Uint32Array(this._data.buffer,0,i);else{const e=new Uint32Array(i);e.set(this._data),this._data=e}for(let i=this.length;i=e&&delete this._combined[s]}const s=Object.keys(this._extendedAttrs);for(let t=0;t=e&&delete this._extendedAttrs[i]}}return this.length=e,4*i*2=0;--e)if(4194303&this._data[3*e+0])return e+(this._data[3*e+0]>>22);return 0}getNoBgTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(4194303&this._data[3*e+0]||50331648&this._data[3*e+2])return e+(this._data[3*e+0]>>22);return 0}copyCellsFrom(e,t,i,s,r){const n=e._data;if(r)for(let r=s-1;r>=0;r--){for(let e=0;e<3;e++)this._data[3*(i+r)+e]=n[3*(t+r)+e];268435456&n[3*(t+r)+2]&&(this._extendedAttrs[i+r]=e._extendedAttrs[t+r])}else for(let r=0;r=t&&(this._combined[r-t+i]=e._combined[r])}}translateToString(e,t,i,s){t=t??0,i=i??this.length,e&&(i=Math.min(i,this.getTrimmedLength())),s&&(s.length=0);let r="";for(;t>22||1}return s&&s.push(t),r}}t.BufferLine=l},9384:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getRangeLength=function(e,t){if(e.start.y>e.end.y)throw new Error(`Buffer range end (${e.end.x}, ${e.end.y}) cannot be before start (${e.start.x}, ${e.start.y})`);return t*(e.end.y-e.start.y)+(e.end.x-e.start.x+1)}},732:(e,t)=>{function i(e,t,i){if(t===e.length-1)return e[t].getTrimmedLength();const s=!e[t].hasContent(i-1)&&1===e[t].getWidth(i-1),r=2===e[t+1].getWidth(0);return s&&r?i-1:i}Object.defineProperty(t,"__esModule",{value:!0}),t.reflowLargerGetLinesToRemove=function(e,t,s,r,n,o){const a=[];for(let l=0;l=l&&r0&&(e>u||0===d[e].getTrimmedLength());e--)g++;g>0&&(a.push(l+d.length-g),a.push(g)),l+=d.length-1}return a},t.reflowLargerCreateNewLayout=function(e,t){const i=[];let s=0,r=t[s],n=0;for(let o=0;oi(e,r,t))).reduce(((e,t)=>e+t));let o=0,a=0,l=0;for(;lh&&(o-=h,a++);const c=2===e[a].getWidth(o-1);c&&o--;const d=c?s-1:s;r.push(d),l+=d}return r},t.getWrappedLineTrimmedLength=i},4097:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BufferSet=void 0;const s=i(7150),r=i(1073),n=i(802);class o extends s.Disposable{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this._register(new n.Emitter),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this._register(this._optionsService.onSpecificOptionChange("scrollback",(()=>this.resize(this._bufferService.cols,this._bufferService.rows)))),this._register(this._optionsService.onSpecificOptionChange("tabStopWidth",(()=>this.setupTabStops())))}reset(){this._normal=new r.Buffer(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new r.Buffer(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(e){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(e,t){this._normal.resize(e,t),this._alt.resize(e,t),this.setupTabStops(e)}setupTabStops(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)}}t.BufferSet=o},3055:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CellData=void 0;const s=i(726),r=i(8938),n=i(5451);class o extends n.AttributeData{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new n.ExtendedAttrs,this.combinedData=""}static fromCharData(e){const t=new o;return t.setFromCharData(e),t}isCombined(){return 2097152&this.content}getWidth(){return this.content>>22}getChars(){return 2097152&this.content?this.combinedData:2097151&this.content?(0,s.stringFromCodePoint)(2097151&this.content):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):2097151&this.content}setFromCharData(e){this.fg=e[r.CHAR_DATA_ATTR_INDEX],this.bg=0;let t=!1;if(e[r.CHAR_DATA_CHAR_INDEX].length>2)t=!0;else if(2===e[r.CHAR_DATA_CHAR_INDEX].length){const i=e[r.CHAR_DATA_CHAR_INDEX].charCodeAt(0);if(55296<=i&&i<=56319){const s=e[r.CHAR_DATA_CHAR_INDEX].charCodeAt(1);56320<=s&&s<=57343?this.content=1024*(i-55296)+s-56320+65536|e[r.CHAR_DATA_WIDTH_INDEX]<<22:t=!0}else t=!0}else this.content=e[r.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|e[r.CHAR_DATA_WIDTH_INDEX]<<22;t&&(this.combinedData=e[r.CHAR_DATA_CHAR_INDEX],this.content=2097152|e[r.CHAR_DATA_WIDTH_INDEX]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}}t.CellData=o},8938:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WHITESPACE_CELL_CODE=t.WHITESPACE_CELL_WIDTH=t.WHITESPACE_CELL_CHAR=t.NULL_CELL_CODE=t.NULL_CELL_WIDTH=t.NULL_CELL_CHAR=t.CHAR_DATA_CODE_INDEX=t.CHAR_DATA_WIDTH_INDEX=t.CHAR_DATA_CHAR_INDEX=t.CHAR_DATA_ATTR_INDEX=t.DEFAULT_EXT=t.DEFAULT_ATTR=t.DEFAULT_COLOR=void 0,t.DEFAULT_COLOR=0,t.DEFAULT_ATTR=t.DEFAULT_COLOR<<9|256,t.DEFAULT_EXT=0,t.CHAR_DATA_ATTR_INDEX=0,t.CHAR_DATA_CHAR_INDEX=1,t.CHAR_DATA_WIDTH_INDEX=2,t.CHAR_DATA_CODE_INDEX=3,t.NULL_CELL_CHAR="",t.NULL_CELL_WIDTH=1,t.NULL_CELL_CODE=0,t.WHITESPACE_CELL_CHAR=" ",t.WHITESPACE_CELL_WIDTH=1,t.WHITESPACE_CELL_CODE=32},8158:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Marker=void 0;const s=i(802),r=i(7150);class n{get id(){return this._id}constructor(e){this.line=e,this.isDisposed=!1,this._disposables=[],this._id=n._nextId++,this._onDispose=this.register(new s.Emitter),this.onDispose=this._onDispose.event}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),(0,r.dispose)(this._disposables),this._disposables.length=0)}register(e){return this._disposables.push(e),e}}t.Marker=n,n._nextId=1},6760:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DEFAULT_CHARSET=t.CHARSETS=void 0,t.CHARSETS={},t.DEFAULT_CHARSET=t.CHARSETS.B,t.CHARSETS[0]={"`":"◆",a:"▒",b:"␉",c:"␌",d:"␍",e:"␊",f:"°",g:"±",h:"␤",i:"␋",j:"┘",k:"┐",l:"┌",m:"└",n:"┼",o:"⎺",p:"⎻",q:"─",r:"⎼",s:"⎽",t:"├",u:"┤",v:"┴",w:"┬",x:"│",y:"≤",z:"≥","{":"π","|":"≠","}":"£","~":"·"},t.CHARSETS.A={"#":"£"},t.CHARSETS.B=void 0,t.CHARSETS[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"},t.CHARSETS.C=t.CHARSETS[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"},t.CHARSETS.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"},t.CHARSETS.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"},t.CHARSETS.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"},t.CHARSETS.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"},t.CHARSETS.E=t.CHARSETS[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"},t.CHARSETS.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"},t.CHARSETS.H=t.CHARSETS[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"},t.CHARSETS["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"}},3534:(e,t)=>{var i,s,r;Object.defineProperty(t,"__esModule",{value:!0}),t.C1_ESCAPED=t.C1=t.C0=void 0,function(e){e.NUL="\0",e.SOH="",e.STX="",e.ETX="",e.EOT="",e.ENQ="",e.ACK="",e.BEL="",e.BS="\b",e.HT="\t",e.LF="\n",e.VT="\v",e.FF="\f",e.CR="\r",e.SO="",e.SI="",e.DLE="",e.DC1="",e.DC2="",e.DC3="",e.DC4="",e.NAK="",e.SYN="",e.ETB="",e.CAN="",e.EM="",e.SUB="",e.ESC="",e.FS="",e.GS="",e.RS="",e.US="",e.SP=" ",e.DEL=""}(i||(t.C0=i={})),function(e){e.PAD="€",e.HOP="",e.BPH="‚",e.NBH="ƒ",e.IND="„",e.NEL="…",e.SSA="†",e.ESA="‡",e.HTS="ˆ",e.HTJ="‰",e.VTS="Š",e.PLD="‹",e.PLU="Œ",e.RI="",e.SS2="Ž",e.SS3="",e.DCS="",e.PU1="‘",e.PU2="’",e.STS="“",e.CCH="”",e.MW="•",e.SPA="–",e.EPA="—",e.SOS="˜",e.SGCI="™",e.SCI="š",e.CSI="›",e.ST="œ",e.OSC="",e.PM="ž",e.APC="Ÿ"}(s||(t.C1=s={})),function(e){e.ST=`${i.ESC}\\`}(r||(t.C1_ESCAPED=r={}))},706:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.evaluateKeyboardEvent=function(e,t,i,n){const o={type:0,cancel:!1,key:void 0},a=(e.shiftKey?1:0)|(e.altKey?2:0)|(e.ctrlKey?4:0)|(e.metaKey?8:0);switch(e.keyCode){case 0:"UIKeyInputUpArrow"===e.key?o.key=t?s.C0.ESC+"OA":s.C0.ESC+"[A":"UIKeyInputLeftArrow"===e.key?o.key=t?s.C0.ESC+"OD":s.C0.ESC+"[D":"UIKeyInputRightArrow"===e.key?o.key=t?s.C0.ESC+"OC":s.C0.ESC+"[C":"UIKeyInputDownArrow"===e.key&&(o.key=t?s.C0.ESC+"OB":s.C0.ESC+"[B");break;case 8:o.key=e.ctrlKey?"\b":s.C0.DEL,e.altKey&&(o.key=s.C0.ESC+o.key);break;case 9:if(e.shiftKey){o.key=s.C0.ESC+"[Z";break}o.key=s.C0.HT,o.cancel=!0;break;case 13:o.key=e.altKey?s.C0.ESC+s.C0.CR:s.C0.CR,o.cancel=!0;break;case 27:o.key=s.C0.ESC,e.altKey&&(o.key=s.C0.ESC+s.C0.ESC),o.cancel=!0;break;case 37:if(e.metaKey)break;o.key=a?s.C0.ESC+"[1;"+(a+1)+"D":t?s.C0.ESC+"OD":s.C0.ESC+"[D";break;case 39:if(e.metaKey)break;o.key=a?s.C0.ESC+"[1;"+(a+1)+"C":t?s.C0.ESC+"OC":s.C0.ESC+"[C";break;case 38:if(e.metaKey)break;o.key=a?s.C0.ESC+"[1;"+(a+1)+"A":t?s.C0.ESC+"OA":s.C0.ESC+"[A";break;case 40:if(e.metaKey)break;o.key=a?s.C0.ESC+"[1;"+(a+1)+"B":t?s.C0.ESC+"OB":s.C0.ESC+"[B";break;case 45:e.shiftKey||e.ctrlKey||(o.key=s.C0.ESC+"[2~");break;case 46:o.key=a?s.C0.ESC+"[3;"+(a+1)+"~":s.C0.ESC+"[3~";break;case 36:o.key=a?s.C0.ESC+"[1;"+(a+1)+"H":t?s.C0.ESC+"OH":s.C0.ESC+"[H";break;case 35:o.key=a?s.C0.ESC+"[1;"+(a+1)+"F":t?s.C0.ESC+"OF":s.C0.ESC+"[F";break;case 33:e.shiftKey?o.type=2:e.ctrlKey?o.key=s.C0.ESC+"[5;"+(a+1)+"~":o.key=s.C0.ESC+"[5~";break;case 34:e.shiftKey?o.type=3:e.ctrlKey?o.key=s.C0.ESC+"[6;"+(a+1)+"~":o.key=s.C0.ESC+"[6~";break;case 112:o.key=a?s.C0.ESC+"[1;"+(a+1)+"P":s.C0.ESC+"OP";break;case 113:o.key=a?s.C0.ESC+"[1;"+(a+1)+"Q":s.C0.ESC+"OQ";break;case 114:o.key=a?s.C0.ESC+"[1;"+(a+1)+"R":s.C0.ESC+"OR";break;case 115:o.key=a?s.C0.ESC+"[1;"+(a+1)+"S":s.C0.ESC+"OS";break;case 116:o.key=a?s.C0.ESC+"[15;"+(a+1)+"~":s.C0.ESC+"[15~";break;case 117:o.key=a?s.C0.ESC+"[17;"+(a+1)+"~":s.C0.ESC+"[17~";break;case 118:o.key=a?s.C0.ESC+"[18;"+(a+1)+"~":s.C0.ESC+"[18~";break;case 119:o.key=a?s.C0.ESC+"[19;"+(a+1)+"~":s.C0.ESC+"[19~";break;case 120:o.key=a?s.C0.ESC+"[20;"+(a+1)+"~":s.C0.ESC+"[20~";break;case 121:o.key=a?s.C0.ESC+"[21;"+(a+1)+"~":s.C0.ESC+"[21~";break;case 122:o.key=a?s.C0.ESC+"[23;"+(a+1)+"~":s.C0.ESC+"[23~";break;case 123:o.key=a?s.C0.ESC+"[24;"+(a+1)+"~":s.C0.ESC+"[24~";break;default:if(!e.ctrlKey||e.shiftKey||e.altKey||e.metaKey)if(i&&!n||!e.altKey||e.metaKey)!i||e.altKey||e.ctrlKey||e.shiftKey||!e.metaKey?e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.keyCode>=48&&1===e.key.length?o.key=e.key:e.key&&e.ctrlKey&&("_"===e.key&&(o.key=s.C0.US),"@"===e.key&&(o.key=s.C0.NUL)):65===e.keyCode&&(o.type=1);else{const t=r[e.keyCode],i=t?.[e.shiftKey?1:0];if(i)o.key=s.C0.ESC+i;else if(e.keyCode>=65&&e.keyCode<=90){const t=e.ctrlKey?e.keyCode-64:e.keyCode+32;let i=String.fromCharCode(t);e.shiftKey&&(i=i.toUpperCase()),o.key=s.C0.ESC+i}else if(32===e.keyCode)o.key=s.C0.ESC+(e.ctrlKey?s.C0.NUL:" ");else if("Dead"===e.key&&e.code.startsWith("Key")){let t=e.code.slice(3,4);e.shiftKey||(t=t.toLowerCase()),o.key=s.C0.ESC+t,o.cancel=!0}}else e.keyCode>=65&&e.keyCode<=90?o.key=String.fromCharCode(e.keyCode-64):32===e.keyCode?o.key=s.C0.NUL:e.keyCode>=51&&e.keyCode<=55?o.key=String.fromCharCode(e.keyCode-51+27):56===e.keyCode?o.key=s.C0.DEL:219===e.keyCode?o.key=s.C0.ESC:220===e.keyCode?o.key=s.C0.FS:221===e.keyCode&&(o.key=s.C0.GS)}return o};const s=i(3534),r={48:["0",")"],49:["1","!"],50:["2","@"],51:["3","#"],52:["4","$"],53:["5","%"],54:["6","^"],55:["7","&"],56:["8","*"],57:["9","("],186:[";",":"],187:["=","+"],188:[",","<"],189:["-","_"],190:[".",">"],191:["/","?"],192:["`","~"],219:["[","{"],220:["\\","|"],221:["]","}"],222:["'",'"']}},726:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Utf8ToUtf32=t.StringToUtf32=void 0,t.stringFromCodePoint=function(e){return e>65535?(e-=65536,String.fromCharCode(55296+(e>>10))+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)},t.utf32ToString=function(e,t=0,i=e.length){let s="";for(let r=t;r65535?(t-=65536,s+=String.fromCharCode(55296+(t>>10))+String.fromCharCode(t%1024+56320)):s+=String.fromCharCode(t)}return s},t.StringToUtf32=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){const i=e.length;if(!i)return 0;let s=0,r=0;if(this._interim){const i=e.charCodeAt(r++);56320<=i&&i<=57343?t[s++]=1024*(this._interim-55296)+i-56320+65536:(t[s++]=this._interim,t[s++]=i),this._interim=0}for(let n=r;n=i)return this._interim=r,s;const o=e.charCodeAt(n);56320<=o&&o<=57343?t[s++]=1024*(r-55296)+o-56320+65536:(t[s++]=r,t[s++]=o)}else 65279!==r&&(t[s++]=r)}return s}},t.Utf8ToUtf32=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){const i=e.length;if(!i)return 0;let s,r,n,o,a=0,l=0,h=0;if(this.interim[0]){let s=!1,r=this.interim[0];r&=192==(224&r)?31:224==(240&r)?15:7;let n,o=0;for(;(n=63&this.interim[++o])&&o<4;)r<<=6,r|=n;const l=192==(224&this.interim[0])?2:224==(240&this.interim[0])?3:4,c=l-o;for(;h=i)return 0;if(n=e[h++],128!=(192&n)){h--,s=!0;break}this.interim[o++]=n,r<<=6,r|=63&n}s||(2===l?r<128?h--:t[a++]=r:3===l?r<2048||r>=55296&&r<=57343||65279===r||(t[a++]=r):r<65536||r>1114111||(t[a++]=r)),this.interim.fill(0)}const c=i-4;let d=h;for(;d=i)return this.interim[0]=s,a;if(r=e[d++],128!=(192&r)){d--;continue}if(l=(31&s)<<6|63&r,l<128){d--;continue}t[a++]=l}else if(224==(240&s)){if(d>=i)return this.interim[0]=s,a;if(r=e[d++],128!=(192&r)){d--;continue}if(d>=i)return this.interim[0]=s,this.interim[1]=r,a;if(n=e[d++],128!=(192&n)){d--;continue}if(l=(15&s)<<12|(63&r)<<6|63&n,l<2048||l>=55296&&l<=57343||65279===l)continue;t[a++]=l}else if(240==(248&s)){if(d>=i)return this.interim[0]=s,a;if(r=e[d++],128!=(192&r)){d--;continue}if(d>=i)return this.interim[0]=s,this.interim[1]=r,a;if(n=e[d++],128!=(192&n)){d--;continue}if(d>=i)return this.interim[0]=s,this.interim[1]=r,this.interim[2]=n,a;if(o=e[d++],128!=(192&o)){d--;continue}if(l=(7&s)<<18|(63&r)<<12|(63&n)<<6|63&o,l<65536||l>1114111)continue;t[a++]=l}}return a}}},7428:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.UnicodeV6=void 0;const s=i(6415),r=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],n=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]];let o;t.UnicodeV6=class{constructor(){if(this.version="6",!o){o=new Uint8Array(65536),o.fill(1),o[0]=0,o.fill(0,1,32),o.fill(0,127,160),o.fill(2,4352,4448),o[9001]=2,o[9002]=2,o.fill(2,11904,42192),o[12351]=1,o.fill(2,44032,55204),o.fill(2,63744,64256),o.fill(2,65040,65050),o.fill(2,65072,65136),o.fill(2,65280,65377),o.fill(2,65504,65511);for(let e=0;et[r][1])return!1;for(;r>=s;)if(i=s+r>>1,e>t[i][1])s=i+1;else{if(!(e=131072&&e<=196605||e>=196608&&e<=262141?2:1}charProperties(e,t){let i=this.wcwidth(e),r=0===i&&0!==t;if(r){const e=s.UnicodeService.extractWidth(t);0===e?r=!1:e>i&&(i=e)}return s.UnicodeService.createPropertyValue(0,i,r)}}},3562:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WriteBuffer=void 0;const s=i(7150),r=i(802);class n extends s.Disposable{constructor(e){super(),this._action=e,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this._register(new r.Emitter),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(e,t){if(void 0!==t&&this._syncCalls>t)return void(this._syncCalls=0);if(this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;let i;for(this._isSyncWriting=!0;i=this._writeBuffer.shift();){this._action(i);const e=this._callbacks.shift();e&&e()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(e,t){if(this._pendingData>5e7)throw new Error("write data discarded, use flow control to avoid losing data");if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput)return this._didUserInput=!1,this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t),void this._innerWrite();setTimeout((()=>this._innerWrite()))}this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t)}_innerWrite(e=0,t=!0){const i=e||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){const e=this._writeBuffer[this._bufferOffset],s=this._action(e,t);if(s){const e=e=>performance.now()-i>=12?setTimeout((()=>this._innerWrite(0,e))):this._innerWrite(i,e);return void s.catch((e=>(queueMicrotask((()=>{throw e})),Promise.resolve(!1)))).then(e)}const r=this._callbacks[this._bufferOffset];if(r&&r(),this._bufferOffset++,this._pendingData-=e.length,performance.now()-i>=12)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>50&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout((()=>this._innerWrite()))):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}}t.WriteBuffer=n},8693:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseColor=function(e){if(!e)return;let t=e.toLowerCase();if(0===t.indexOf("rgb:")){t=t.slice(4);const e=i.exec(t);if(e){const t=e[1]?15:e[4]?255:e[7]?4095:65535;return[Math.round(parseInt(e[1]||e[4]||e[7]||e[10],16)/t*255),Math.round(parseInt(e[2]||e[5]||e[8]||e[11],16)/t*255),Math.round(parseInt(e[3]||e[6]||e[9]||e[12],16)/t*255)]}}else if(0===t.indexOf("#")&&(t=t.slice(1),s.exec(t)&&[3,6,9,12].includes(t.length))){const e=t.length/3,i=[0,0,0];for(let s=0;s<3;++s){const r=parseInt(t.slice(e*s,e*s+e),16);i[s]=1===e?r<<4:2===e?r:3===e?r>>4:r>>8}return i}},t.toRgbString=function(e,t=16){const[i,s,n]=e;return`rgb:${r(i,t)}/${r(s,t)}/${r(n,t)}`};const i=/^([\da-f])\/([\da-f])\/([\da-f])$|^([\da-f]{2})\/([\da-f]{2})\/([\da-f]{2})$|^([\da-f]{3})\/([\da-f]{3})\/([\da-f]{3})$|^([\da-f]{4})\/([\da-f]{4})\/([\da-f]{4})$/,s=/^[\da-f]+$/;function r(e,t){const i=e.toString(16),s=i.length<2?"0"+i:i;switch(t){case 4:return i[0];case 8:return s;case 12:return(s+s).slice(0,3);default:return s+s}}},1263:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PAYLOAD_LIMIT=void 0,t.PAYLOAD_LIMIT=1e7},9823:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DcsHandler=t.DcsParser=void 0;const s=i(726),r=i(7262),n=i(1263),o=[];t.DcsParser=class{constructor(){this._handlers=Object.create(null),this._active=o,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=o}registerHandler(e,t){void 0===this._handlers[e]&&(this._handlers[e]=[]);const i=this._handlers[e];return i.push(t),{dispose:()=>{const e=i.indexOf(t);-1!==e&&i.splice(e,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}reset(){if(this._active.length)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].unhook(!1);this._stack.paused=!1,this._active=o,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||o,this._active.length)for(let e=this._active.length-1;e>=0;e--)this._active[e].hook(t);else this._handlerFb(this._ident,"HOOK",t)}put(e,t,i){if(this._active.length)for(let s=this._active.length-1;s>=0;s--)this._active[s].put(e,t,i);else this._handlerFb(this._ident,"PUT",(0,s.utf32ToString)(e,t,i))}unhook(e,t=!0){if(this._active.length){let i=!1,s=this._active.length-1,r=!1;if(this._stack.paused&&(s=this._stack.loopPosition-1,i=t,r=this._stack.fallThrough,this._stack.paused=!1),!r&&!1===i){for(;s>=0&&(i=this._active[s].unhook(e),!0!==i);s--)if(i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!1,i;s--}for(;s>=0;s--)if(i=this._active[s].unhook(!1),i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!0,i}else this._handlerFb(this._ident,"UNHOOK",e);this._active=o,this._ident=0}};const a=new r.Params;a.addParam(0),t.DcsHandler=class{constructor(e){this._handler=e,this._data="",this._params=a,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():a,this._data="",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=(0,s.utf32ToString)(e,t,i),this._data.length>n.PAYLOAD_LIMIT&&(this._data="",this._hitLimit=!0))}unhook(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data,this._params),t instanceof Promise))return t.then((e=>(this._params=a,this._data="",this._hitLimit=!1,e)));return this._params=a,this._data="",this._hitLimit=!1,t}}},6717:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EscapeSequenceParser=t.VT500_TRANSITION_TABLE=t.TransitionTable=void 0;const s=i(7150),r=i(7262),n=i(1346),o=i(9823);class a{constructor(e){this.table=new Uint8Array(e)}setDefault(e,t){this.table.fill(e<<4|t)}add(e,t,i,s){this.table[t<<8|e]=i<<4|s}addMany(e,t,i,s){for(let r=0;rt)),i=(e,i)=>t.slice(e,i),s=i(32,127),r=i(0,24);r.push(25),r.push.apply(r,i(28,32));const n=i(0,14);let o;for(o in e.setDefault(1,0),e.addMany(s,0,2,0),n)e.addMany([24,26,153,154],o,3,0),e.addMany(i(128,144),o,3,0),e.addMany(i(144,152),o,3,0),e.add(156,o,0,0),e.add(27,o,11,1),e.add(157,o,4,8),e.addMany([152,158,159],o,0,7),e.add(155,o,11,3),e.add(144,o,11,9);return e.addMany(r,0,3,0),e.addMany(r,1,3,1),e.add(127,1,0,1),e.addMany(r,8,0,8),e.addMany(r,3,3,3),e.add(127,3,0,3),e.addMany(r,4,3,4),e.add(127,4,0,4),e.addMany(r,6,3,6),e.addMany(r,5,3,5),e.add(127,5,0,5),e.addMany(r,2,3,2),e.add(127,2,0,2),e.add(93,1,4,8),e.addMany(s,8,5,8),e.add(127,8,5,8),e.addMany([156,27,24,26,7],8,6,0),e.addMany(i(28,32),8,0,8),e.addMany([88,94,95],1,0,7),e.addMany(s,7,0,7),e.addMany(r,7,0,7),e.add(156,7,0,0),e.add(127,7,0,7),e.add(91,1,11,3),e.addMany(i(64,127),3,7,0),e.addMany(i(48,60),3,8,4),e.addMany([60,61,62,63],3,9,4),e.addMany(i(48,60),4,8,4),e.addMany(i(64,127),4,7,0),e.addMany([60,61,62,63],4,0,6),e.addMany(i(32,64),6,0,6),e.add(127,6,0,6),e.addMany(i(64,127),6,0,0),e.addMany(i(32,48),3,9,5),e.addMany(i(32,48),5,9,5),e.addMany(i(48,64),5,0,6),e.addMany(i(64,127),5,7,0),e.addMany(i(32,48),4,9,5),e.addMany(i(32,48),1,9,2),e.addMany(i(32,48),2,9,2),e.addMany(i(48,127),2,10,0),e.addMany(i(48,80),1,10,0),e.addMany(i(81,88),1,10,0),e.addMany([89,90,92],1,10,0),e.addMany(i(96,127),1,10,0),e.add(80,1,11,9),e.addMany(r,9,0,9),e.add(127,9,0,9),e.addMany(i(28,32),9,0,9),e.addMany(i(32,48),9,9,12),e.addMany(i(48,60),9,8,10),e.addMany([60,61,62,63],9,9,10),e.addMany(r,11,0,11),e.addMany(i(32,128),11,0,11),e.addMany(i(28,32),11,0,11),e.addMany(r,10,0,10),e.add(127,10,0,10),e.addMany(i(28,32),10,0,10),e.addMany(i(48,60),10,8,10),e.addMany([60,61,62,63],10,0,11),e.addMany(i(32,48),10,9,12),e.addMany(r,12,0,12),e.add(127,12,0,12),e.addMany(i(28,32),12,0,12),e.addMany(i(32,48),12,9,12),e.addMany(i(48,64),12,0,11),e.addMany(i(64,127),12,12,13),e.addMany(i(64,127),10,12,13),e.addMany(i(64,127),9,12,13),e.addMany(r,13,13,13),e.addMany(s,13,13,13),e.add(127,13,0,13),e.addMany([27,156,24,26],13,14,0),e.add(l,0,2,0),e.add(l,8,5,8),e.add(l,6,0,6),e.add(l,11,0,11),e.add(l,13,13,13),e}();class h extends s.Disposable{constructor(e=t.VT500_TRANSITION_TABLE){super(),this._transitions=e,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new r.Params,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(e,t,i)=>{},this._executeHandlerFb=e=>{},this._csiHandlerFb=(e,t)=>{},this._escHandlerFb=e=>{},this._errorHandlerFb=e=>e,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this._register((0,s.toDisposable)((()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)}))),this._oscParser=this._register(new n.OscParser),this._dcsParser=this._register(new o.DcsParser),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:"\\"},(()=>!0))}_identifier(e,t=[64,126]){let i=0;if(e.prefix){if(e.prefix.length>1)throw new Error("only one byte as prefix supported");if(i=e.prefix.charCodeAt(0),i&&60>i||i>63)throw new Error("prefix must be in range 0x3c .. 0x3f")}if(e.intermediates){if(e.intermediates.length>2)throw new Error("only two bytes as intermediates are supported");for(let t=0;ts||s>47)throw new Error("intermediate must be in range 0x20 .. 0x2f");i<<=8,i|=s}}if(1!==e.final.length)throw new Error("final must be a single byte");const s=e.final.charCodeAt(0);if(t[0]>s||s>t[1])throw new Error(`final must be in range ${t[0]} .. ${t[1]}`);return i<<=8,i|=s,i}identToString(e){const t=[];for(;e;)t.push(String.fromCharCode(255&e)),e>>=8;return t.reverse().join("")}setPrintHandler(e){this._printHandler=e}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(e,t){const i=this._identifier(e,[48,126]);void 0===this._escHandlers[i]&&(this._escHandlers[i]=[]);const s=this._escHandlers[i];return s.push(t),{dispose:()=>{const e=s.indexOf(t);-1!==e&&s.splice(e,1)}}}clearEscHandler(e){this._escHandlers[this._identifier(e,[48,126])]&&delete this._escHandlers[this._identifier(e,[48,126])]}setEscHandlerFallback(e){this._escHandlerFb=e}setExecuteHandler(e,t){this._executeHandlers[e.charCodeAt(0)]=t}clearExecuteHandler(e){this._executeHandlers[e.charCodeAt(0)]&&delete this._executeHandlers[e.charCodeAt(0)]}setExecuteHandlerFallback(e){this._executeHandlerFb=e}registerCsiHandler(e,t){const i=this._identifier(e);void 0===this._csiHandlers[i]&&(this._csiHandlers[i]=[]);const s=this._csiHandlers[i];return s.push(t),{dispose:()=>{const e=s.indexOf(t);-1!==e&&s.splice(e,1)}}}clearCsiHandler(e){this._csiHandlers[this._identifier(e)]&&delete this._csiHandlers[this._identifier(e)]}setCsiHandlerFallback(e){this._csiHandlerFb=e}registerDcsHandler(e,t){return this._dcsParser.registerHandler(this._identifier(e),t)}clearDcsHandler(e){this._dcsParser.clearHandler(this._identifier(e))}setDcsHandlerFallback(e){this._dcsParser.setHandlerFallback(e)}registerOscHandler(e,t){return this._oscParser.registerHandler(e,t)}clearOscHandler(e){this._oscParser.clearHandler(e)}setOscHandlerFallback(e){this._oscParser.setHandlerFallback(e)}setErrorHandler(e){this._errorHandler=e}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,0!==this._parseStack.state&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(e,t,i,s,r){this._parseStack.state=e,this._parseStack.handlers=t,this._parseStack.handlerPos=i,this._parseStack.transition=s,this._parseStack.chunkPos=r}parse(e,t,i){let s,r=0,n=0,o=0;if(this._parseStack.state)if(2===this._parseStack.state)this._parseStack.state=0,o=this._parseStack.chunkPos+1;else{if(void 0===i||1===this._parseStack.state)throw this._parseStack.state=1,new Error("improper continuation due to previous async handler, giving up parsing");const t=this._parseStack.handlers;let n=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(!1===i&&n>-1)for(;n>=0&&(s=t[n](this._params),!0!==s);n--)if(s instanceof Promise)return this._parseStack.handlerPos=n,s;this._parseStack.handlers=[];break;case 4:if(!1===i&&n>-1)for(;n>=0&&(s=t[n](),!0!==s);n--)if(s instanceof Promise)return this._parseStack.handlerPos=n,s;this._parseStack.handlers=[];break;case 6:if(r=e[this._parseStack.chunkPos],s=this._dcsParser.unhook(24!==r&&26!==r,i),s)return s;27===r&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(r=e[this._parseStack.chunkPos],s=this._oscParser.end(24!==r&&26!==r,i),s)return s;27===r&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0}this._parseStack.state=0,o=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=15&this._parseStack.transition}for(let i=o;i>4){case 2:for(let s=i+1;;++s){if(s>=t||(r=e[s])<32||r>126&&r=t||(r=e[s])<32||r>126&&r=t||(r=e[s])<32||r>126&&r=t||(r=e[s])<32||r>126&&r=0&&(s=o[a](this._params),!0!==s);a--)if(s instanceof Promise)return this._preserveStack(3,o,a,n,i),s;a<0&&this._csiHandlerFb(this._collect<<8|r,this._params),this.precedingJoinState=0;break;case 8:do{switch(r){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(r-48)}}while(++i47&&r<60);i--;break;case 9:this._collect<<=8,this._collect|=r;break;case 10:const h=this._escHandlers[this._collect<<8|r];let c=h?h.length-1:-1;for(;c>=0&&(s=h[c](),!0!==s);c--)if(s instanceof Promise)return this._preserveStack(4,h,c,n,i),s;c<0&&this._escHandlerFb(this._collect<<8|r),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|r,this._params);break;case 13:for(let s=i+1;;++s)if(s>=t||24===(r=e[s])||26===r||27===r||r>127&&r=t||(r=e[s])<32||r>127&&r{Object.defineProperty(t,"__esModule",{value:!0}),t.OscHandler=t.OscParser=void 0;const s=i(1263),r=i(726),n=[];t.OscParser=class{constructor(){this._state=0,this._active=n,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(e,t){void 0===this._handlers[e]&&(this._handlers[e]=[]);const i=this._handlers[e];return i.push(t),{dispose:()=>{const e=i.indexOf(t);-1!==e&&i.splice(e,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=n}reset(){if(2===this._state)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].end(!1);this._stack.paused=!1,this._active=n,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||n,this._active.length)for(let e=this._active.length-1;e>=0;e--)this._active[e].start();else this._handlerFb(this._id,"START")}_put(e,t,i){if(this._active.length)for(let s=this._active.length-1;s>=0;s--)this._active[s].put(e,t,i);else this._handlerFb(this._id,"PUT",(0,r.utf32ToString)(e,t,i))}start(){this.reset(),this._state=1}put(e,t,i){if(3!==this._state){if(1===this._state)for(;t0&&this._put(e,t,i)}}end(e,t=!0){if(0!==this._state){if(3!==this._state)if(1===this._state&&this._start(),this._active.length){let i=!1,s=this._active.length-1,r=!1;if(this._stack.paused&&(s=this._stack.loopPosition-1,i=t,r=this._stack.fallThrough,this._stack.paused=!1),!r&&!1===i){for(;s>=0&&(i=this._active[s].end(e),!0!==i);s--)if(i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!1,i;s--}for(;s>=0;s--)if(i=this._active[s].end(!1),i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!0,i}else this._handlerFb(this._id,"END",e);this._active=n,this._id=-1,this._state=0}}},t.OscHandler=class{constructor(e){this._handler=e,this._data="",this._hitLimit=!1}start(){this._data="",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=(0,r.utf32ToString)(e,t,i),this._data.length>s.PAYLOAD_LIMIT&&(this._data="",this._hitLimit=!0))}end(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data),t instanceof Promise))return t.then((e=>(this._data="",this._hitLimit=!1,e)));return this._data="",this._hitLimit=!1,t}}},7262:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Params=void 0;const i=2147483647;class s{static fromArray(e){const t=new s;if(!e.length)return t;for(let i=Array.isArray(e[0])?1:0;i256)throw new Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(e),this.length=0,this._subParams=new Int32Array(t),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(e),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}clone(){const e=new s(this.maxLength,this.maxSubParamsLength);return e.params.set(this.params),e.length=this.length,e._subParams.set(this._subParams),e._subParamsLength=this._subParamsLength,e._subParamsIdx.set(this._subParamsIdx),e._rejectDigits=this._rejectDigits,e._rejectSubDigits=this._rejectSubDigits,e._digitIsSub=this._digitIsSub,e}toArray(){const e=[];for(let t=0;t>8,s=255&this._subParamsIdx[t];s-i>0&&e.push(Array.prototype.slice.call(this._subParams,i,s))}return e}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(e){if(this._digitIsSub=!1,this.length>=this.maxLength)this._rejectDigits=!0;else{if(e<-1)throw new Error("values lesser than -1 are not allowed");this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=e>i?i:e}}addSubParam(e){if(this._digitIsSub=!0,this.length)if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength)this._rejectSubDigits=!0;else{if(e<-1)throw new Error("values lesser than -1 are not allowed");this._subParams[this._subParamsLength++]=e>i?i:e,this._subParamsIdx[this.length-1]++}}hasSubParams(e){return(255&this._subParamsIdx[e])-(this._subParamsIdx[e]>>8)>0}getSubParams(e){const t=this._subParamsIdx[e]>>8,i=255&this._subParamsIdx[e];return i-t>0?this._subParams.subarray(t,i):null}getSubParamsAll(){const e={};for(let t=0;t>8,s=255&this._subParamsIdx[t];s-i>0&&(e[t]=this._subParams.slice(i,s))}return e}addDigit(e){let t;if(this._rejectDigits||!(t=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;const s=this._digitIsSub?this._subParams:this.params,r=s[t-1];s[t-1]=~r?Math.min(10*r+e,i):e}}t.Params=s},3027:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AddonManager=void 0,t.AddonManager=class{constructor(){this._addons=[]}dispose(){for(let e=this._addons.length-1;e>=0;e--)this._addons[e].instance.dispose()}loadAddon(e,t){const i={instance:t,dispose:t.dispose,isDisposed:!1};this._addons.push(i),t.dispose=()=>this._wrappedAddonDispose(i),t.activate(e)}_wrappedAddonDispose(e){if(e.isDisposed)return;let t=-1;for(let i=0;i{Object.defineProperty(t,"__esModule",{value:!0}),t.BufferApiView=void 0;const s=i(793),r=i(3055);t.BufferApiView=class{constructor(e,t){this._buffer=e,this.type=t}init(e){return this._buffer=e,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(e){const t=this._buffer.lines.get(e);if(t)return new s.BufferLineApiView(t)}getNullCell(){return new r.CellData}}},793:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BufferLineApiView=void 0;const s=i(3055);t.BufferLineApiView=class{constructor(e){this._line=e}get isWrapped(){return this._line.isWrapped}get length(){return this._line.length}getCell(e,t){if(!(e<0||e>=this._line.length))return t?(this._line.loadCell(e,t),t):this._line.loadCell(e,new s.CellData)}translateToString(e,t,i){return this._line.translateToString(e,t,i)}}},5101:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BufferNamespaceApi=void 0;const s=i(3235),r=i(7150),n=i(802);class o extends r.Disposable{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new n.Emitter),this.onBufferChange=this._onBufferChange.event,this._normal=new s.BufferApiView(this._core.buffers.normal,"normal"),this._alternate=new s.BufferApiView(this._core.buffers.alt,"alternate"),this._core.buffers.onBufferActivate((()=>this._onBufferChange.fire(this.active)))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw new Error("Active buffer is neither normal nor alternate")}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}}t.BufferNamespaceApi=o},6097:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ParserApi=void 0,t.ParserApi=class{constructor(e){this._core=e}registerCsiHandler(e,t){return this._core.registerCsiHandler(e,(e=>t(e.toArray())))}addCsiHandler(e,t){return this.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._core.registerDcsHandler(e,((e,i)=>t(e,i.toArray())))}addDcsHandler(e,t){return this.registerDcsHandler(e,t)}registerEscHandler(e,t){return this._core.registerEscHandler(e,t)}addEscHandler(e,t){return this.registerEscHandler(e,t)}registerOscHandler(e,t){return this._core.registerOscHandler(e,t)}addOscHandler(e,t){return this.registerOscHandler(e,t)}}},4335:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.UnicodeApi=void 0,t.UnicodeApi=class{constructor(e){this._core=e}register(e){this._core.unicodeService.register(e)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(e){this._core.unicodeService.activeVersion=e}}},9640:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.BufferService=t.MINIMUM_ROWS=t.MINIMUM_COLS=void 0;const n=i(7150),o=i(4097),a=i(6501),l=i(802);t.MINIMUM_COLS=2,t.MINIMUM_ROWS=1;let h=class extends n.Disposable{get buffer(){return this.buffers.active}constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new l.Emitter),this.onResize=this._onResize.event,this._onScroll=this._register(new l.Emitter),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,t.MINIMUM_COLS),this.rows=Math.max(e.rawOptions.rows||0,t.MINIMUM_ROWS),this.buffers=this._register(new o.BufferSet(e,this)),this._register(this.buffers.onBufferActivate((e=>{this._onScroll.fire(e.activeBuffer.ydisp)})))}resize(e,t){const i=this.cols!==e,s=this.rows!==t;this.cols=e,this.rows=t,this.buffers.resize(e,t),this._onResize.fire({cols:e,rows:t,colsChanged:i,rowsChanged:s})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,t=!1){const i=this.buffer;let s;s=this._cachedBlankLine,s&&s.length===this.cols&&s.getFg(0)===e.fg&&s.getBg(0)===e.bg||(s=i.getBlankLine(e,t),this._cachedBlankLine=s),s.isWrapped=t;const r=i.ybase+i.scrollTop,n=i.ybase+i.scrollBottom;if(0===i.scrollTop){const e=i.lines.isFull;n===i.lines.length-1?e?i.lines.recycle().copyFrom(s):i.lines.push(s.clone()):i.lines.splice(n+1,0,s.clone()),e?this.isUserScrolling&&(i.ydisp=Math.max(i.ydisp-1,0)):(i.ybase++,this.isUserScrolling||i.ydisp++)}else{const e=n-r+1;i.lines.shiftElements(r+1,e-1,-1),i.lines.set(n,s.clone())}this.isUserScrolling||(i.ydisp=i.ybase),this._onScroll.fire(i.ydisp)}scrollLines(e,t){const i=this.buffer;if(e<0){if(0===i.ydisp)return;this.isUserScrolling=!0}else e+i.ydisp>=i.ybase&&(this.isUserScrolling=!1);const s=i.ydisp;i.ydisp=Math.max(Math.min(i.ydisp+e,i.ybase),0),s!==i.ydisp&&(t||this._onScroll.fire(i.ydisp))}};t.BufferService=h,t.BufferService=h=s([r(0,a.IOptionsService)],h)},5746:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CharsetService=void 0,t.CharsetService=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(e){this.glevel=e,this.charset=this._charsets[e]}setgCharset(e,t){this._charsets[e]=t,this.glevel===e&&(this.charset=t)}}},7792:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.CoreMouseService=void 0;const n=i(6501),o=i(7150),a=i(802),l={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:e=>4!==e.button&&1===e.action&&(e.ctrl=!1,e.alt=!1,e.shift=!1,!0)},VT200:{events:19,restrict:e=>32!==e.action},DRAG:{events:23,restrict:e=>32!==e.action||3!==e.button},ANY:{events:31,restrict:e=>!0}};function h(e,t){let i=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return 4===e.button?(i|=64,i|=e.action):(i|=3&e.button,4&e.button&&(i|=64),8&e.button&&(i|=128),32===e.action?i|=32:0!==e.action||t||(i|=3)),i}const c=String.fromCharCode,d={DEFAULT:e=>{const t=[h(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?"":`${c(t[0])}${c(t[1])}${c(t[2])}`},SGR:e=>{const t=0===e.action&&4!==e.button?"m":"M";return`[<${h(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{const t=0===e.action&&4!==e.button?"m":"M";return`[<${h(e,!0)};${e.x};${e.y}${t}`}};let u=class extends o.Disposable{constructor(e,t,i){super(),this._bufferService=e,this._coreService=t,this._optionsService=i,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new a.Emitter),this.onProtocolChange=this._onProtocolChange.event;for(const e of Object.keys(l))this.addProtocol(e,l[e]);for(const e of Object.keys(d))this.addEncoding(e,d[e]);this.reset()}addProtocol(e,t){this._protocols[e]=t}addEncoding(e,t){this._encodings[e]=t}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return 0!==this._protocols[this._activeProtocol].events}set activeProtocol(e){if(!this._protocols[e])throw new Error(`unknown protocol "${e}"`);this._activeProtocol=e,this._onProtocolChange.fire(this._protocols[e].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(e){if(!this._encodings[e])throw new Error(`unknown encoding "${e}"`);this._activeEncoding=e}reset(){this.activeProtocol="NONE",this.activeEncoding="DEFAULT",this._lastEvent=null,this._wheelPartialScroll=0}consumeWheelEvent(e,t,i){if(0===e.deltaY||e.shiftKey)return 0;if(void 0===t||void 0===i)return 0;const s=t/i;let r=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(r/=s+0,Math.abs(e.deltaY)<50&&(r*=.3),this._wheelPartialScroll+=r,r=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(r*=this._bufferService.rows),r}_applyScrollModifier(e,t){return t.altKey||t.ctrlKey||t.shiftKey?e*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:e*this._optionsService.rawOptions.scrollSensitivity}triggerMouseEvent(e){if(e.col<0||e.col>=this._bufferService.cols||e.row<0||e.row>=this._bufferService.rows)return!1;if(4===e.button&&32===e.action)return!1;if(3===e.button&&32!==e.action)return!1;if(4!==e.button&&(2===e.action||3===e.action))return!1;if(e.col++,e.row++,32===e.action&&this._lastEvent&&this._equalEvents(this._lastEvent,e,"SGR_PIXELS"===this._activeEncoding))return!1;if(!this._protocols[this._activeProtocol].restrict(e))return!1;const t=this._encodings[this._activeEncoding](e);return t&&("DEFAULT"===this._activeEncoding?this._coreService.triggerBinaryEvent(t):this._coreService.triggerDataEvent(t,!0)),this._lastEvent=e,!0}explainEvents(e){return{down:!!(1&e),up:!!(2&e),drag:!!(4&e),move:!!(8&e),wheel:!!(16&e)}}_equalEvents(e,t,i){if(i){if(e.x!==t.x)return!1;if(e.y!==t.y)return!1}else{if(e.col!==t.col)return!1;if(e.row!==t.row)return!1}return e.button===t.button&&e.action===t.action&&e.ctrl===t.ctrl&&e.alt===t.alt&&e.shift===t.shift}};t.CoreMouseService=u,t.CoreMouseService=u=s([r(0,n.IBufferService),r(1,n.ICoreService),r(2,n.IOptionsService)],u)},4071:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.CoreService=void 0;const n=i(7453),o=i(7150),a=i(6501),l=i(802),h=Object.freeze({insertMode:!1}),c=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0});let d=class extends o.Disposable{constructor(e,t,i){super(),this._bufferService=e,this._logService=t,this._optionsService=i,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new l.Emitter),this.onData=this._onData.event,this._onUserInput=this._register(new l.Emitter),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new l.Emitter),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new l.Emitter),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=(0,n.clone)(h),this.decPrivateModes=(0,n.clone)(c)}reset(){this.modes=(0,n.clone)(h),this.decPrivateModes=(0,n.clone)(c)}triggerDataEvent(e,t=!1){if(this._optionsService.rawOptions.disableStdin)return;const i=this._bufferService.buffer;t&&this._optionsService.rawOptions.scrollOnUserInput&&i.ybase!==i.ydisp&&this._onRequestScrollToBottom.fire(),t&&this._onUserInput.fire(),this._logService.debug(`sending data "${e}"`),this._logService.trace("sending data (codes)",(()=>e.split("").map((e=>e.charCodeAt(0))))),this._onData.fire(e)}triggerBinaryEvent(e){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${e}"`),this._logService.trace("sending binary (codes)",(()=>e.split("").map((e=>e.charCodeAt(0))))),this._onBinary.fire(e))}};t.CoreService=d,t.CoreService=d=s([r(0,a.IBufferService),r(1,a.ILogService),r(2,a.IOptionsService)],d)},4720:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DecorationService=void 0;const s=i(4103),r=i(7150),n=i(3087),o=i(802);let a=0,l=0;class h extends r.Disposable{get decorations(){return this._decorations.values()}constructor(){super(),this._decorations=new n.SortedList((e=>e?.marker.line)),this._onDecorationRegistered=this._register(new o.Emitter),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new o.Emitter),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register((0,r.toDisposable)((()=>this.reset())))}registerDecoration(e){if(e.marker.isDisposed)return;const t=new c(e);if(t){const e=t.marker.onDispose((()=>t.dispose())),i=t.onDispose((()=>{i.dispose(),t&&(this._decorations.delete(t)&&this._onDecorationRemoved.fire(t),e.dispose())}));this._decorations.insert(t),this._onDecorationRegistered.fire(t)}return t}reset(){for(const e of this._decorations.values())e.dispose();this._decorations.clear()}*getDecorationsAtCell(e,t,i){let s=0,r=0;for(const n of this._decorations.getKeyIterator(t))s=n.options.x??0,r=s+(n.options.width??1),e>=s&&e{a=t.options.x??0,l=a+(t.options.width??1),e>=a&&e{Object.defineProperty(t,"__esModule",{value:!0}),t.InstantiationService=t.ServiceCollection=void 0;const s=i(6501),r=i(6201);class n{constructor(...e){this._entries=new Map;for(const[t,i]of e)this.set(t,i)}set(e,t){const i=this._entries.get(e);return this._entries.set(e,t),i}forEach(e){for(const[t,i]of this._entries.entries())e(t,i)}has(e){return this._entries.has(e)}get(e){return this._entries.get(e)}}t.ServiceCollection=n,t.InstantiationService=class{constructor(){this._services=new n,this._services.set(s.IInstantiationService,this)}setService(e,t){this._services.set(e,t)}getService(e){return this._services.get(e)}createInstance(e,...t){const i=(0,r.getServiceDependencies)(e).sort(((e,t)=>e.index-t.index)),s=[];for(const t of i){const i=this._services.get(t.id);if(!i)throw new Error(`[createInstance] ${e.name} depends on UNKNOWN service ${t.id._id}.`);s.push(i)}const n=i.length>0?i[0].index:t.length;if(t.length!==n)throw new Error(`[createInstance] First service dependency of ${e.name} at position ${n+1} conflicts with ${t.length} static arguments`);return new e(...[...t,...s])}}},7276:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.LogService=void 0,t.setTraceLogger=function(e){l=e},t.traceCall=function(e,t,i){if("function"!=typeof i.value)throw new Error("not supported");const s=i.value;i.value=function(...e){if(l.logLevel!==o.LogLevelEnum.TRACE)return s.apply(this,e);l.trace(`GlyphRenderer#${s.name}(${e.map((e=>JSON.stringify(e))).join(", ")})`);const t=s.apply(this,e);return l.trace(`GlyphRenderer#${s.name} return`,t),t}};const n=i(7150),o=i(6501),a={trace:o.LogLevelEnum.TRACE,debug:o.LogLevelEnum.DEBUG,info:o.LogLevelEnum.INFO,warn:o.LogLevelEnum.WARN,error:o.LogLevelEnum.ERROR,off:o.LogLevelEnum.OFF};let l,h=class extends n.Disposable{get logLevel(){return this._logLevel}constructor(e){super(),this._optionsService=e,this._logLevel=o.LogLevelEnum.OFF,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange("logLevel",(()=>this._updateLogLevel()))),l=this}_updateLogLevel(){this._logLevel=a[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e){for(let t=0;t{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionsService=t.DEFAULT_OPTIONS=void 0;const s=i(7150),r=i(701),n=i(802);t.DEFAULT_OPTIONS={cols:80,rows:24,cursorBlink:!1,cursorStyle:"block",cursorWidth:1,cursorInactiveStyle:"outline",customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:"alt",fastScrollSensitivity:5,fontFamily:"monospace",fontSize:15,fontWeight:"normal",fontWeightBold:"bold",ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:"info",logger:null,scrollback:1e3,scrollOnEraseInDisplay:!1,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},reflowCursorLine:!1,rescaleOverlappingGlyphs:!1,rightClickSelectsWord:r.isMac,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRuler:{}};const o=["normal","bold","100","200","300","400","500","600","700","800","900"];class a extends s.Disposable{constructor(e){super(),this._onOptionChange=this._register(new n.Emitter),this.onOptionChange=this._onOptionChange.event;const i={...t.DEFAULT_OPTIONS};for(const t in e)if(t in i)try{const s=e[t];i[t]=this._sanitizeAndValidateOption(t,s)}catch(e){console.error(e)}this.rawOptions=i,this.options={...i},this._setupOptions(),this._register((0,s.toDisposable)((()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null})))}onSpecificOptionChange(e,t){return this.onOptionChange((i=>{i===e&&t(this.rawOptions[e])}))}onMultipleOptionChange(e,t){return this.onOptionChange((i=>{-1!==e.indexOf(i)&&t()}))}_setupOptions(){const e=e=>{if(!(e in t.DEFAULT_OPTIONS))throw new Error(`No option with key "${e}"`);return this.rawOptions[e]},i=(e,i)=>{if(!(e in t.DEFAULT_OPTIONS))throw new Error(`No option with key "${e}"`);i=this._sanitizeAndValidateOption(e,i),this.rawOptions[e]!==i&&(this.rawOptions[e]=i,this._onOptionChange.fire(e))};for(const t in this.rawOptions){const s={get:e.bind(this,t),set:i.bind(this,t)};Object.defineProperty(this.options,t,s)}}_sanitizeAndValidateOption(e,i){switch(e){case"cursorStyle":if(i||(i=t.DEFAULT_OPTIONS[e]),!function(e){return"block"===e||"underline"===e||"bar"===e}(i))throw new Error(`"${i}" is not a valid value for ${e}`);break;case"wordSeparator":i||(i=t.DEFAULT_OPTIONS[e]);break;case"fontWeight":case"fontWeightBold":if("number"==typeof i&&1<=i&&i<=1e3)break;i=o.includes(i)?i:t.DEFAULT_OPTIONS[e];break;case"cursorWidth":i=Math.floor(i);case"lineHeight":case"tabStopWidth":if(i<1)throw new Error(`${e} cannot be less than 1, value: ${i}`);break;case"minimumContrastRatio":i=Math.max(1,Math.min(21,Math.round(10*i)/10));break;case"scrollback":if((i=Math.min(i,4294967295))<0)throw new Error(`${e} cannot be less than 0, value: ${i}`);break;case"fastScrollSensitivity":case"scrollSensitivity":if(i<=0)throw new Error(`${e} cannot be less than or equal to 0, value: ${i}`);break;case"rows":case"cols":if(!i&&0!==i)throw new Error(`${e} must be numeric, value: ${i}`);break;case"windowsPty":i=i??{}}return i}}t.OptionsService=a},8811:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.OscLinkService=void 0;const n=i(6501);let o=class{constructor(e){this._bufferService=e,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(e){const t=this._bufferService.buffer;if(void 0===e.id){const i=t.addMarker(t.ybase+t.y),s={data:e,id:this._nextId++,lines:[i]};return i.onDispose((()=>this._removeMarkerFromLink(s,i))),this._dataByLinkId.set(s.id,s),s.id}const i=e,s=this._getEntryIdKey(i),r=this._entriesWithId.get(s);if(r)return this.addLineToLink(r.id,t.ybase+t.y),r.id;const n=t.addMarker(t.ybase+t.y),o={id:this._nextId++,key:this._getEntryIdKey(i),data:i,lines:[n]};return n.onDispose((()=>this._removeMarkerFromLink(o,n))),this._entriesWithId.set(o.key,o),this._dataByLinkId.set(o.id,o),o.id}addLineToLink(e,t){const i=this._dataByLinkId.get(e);if(i&&i.lines.every((e=>e.line!==t))){const e=this._bufferService.buffer.addMarker(t);i.lines.push(e),e.onDispose((()=>this._removeMarkerFromLink(i,e)))}}getLinkData(e){return this._dataByLinkId.get(e)?.data}_getEntryIdKey(e){return`${e.id};;${e.uri}`}_removeMarkerFromLink(e,t){const i=e.lines.indexOf(t);-1!==i&&(e.lines.splice(i,1),0===e.lines.length&&(void 0!==e.data.id&&this._entriesWithId.delete(e.key),this._dataByLinkId.delete(e.id)))}};t.OscLinkService=o,t.OscLinkService=o=s([r(0,n.IBufferService)],o)},6201:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.serviceRegistry=void 0,t.getServiceDependencies=function(e){return e[s]||[]},t.createDecorator=function(e){if(t.serviceRegistry.has(e))return t.serviceRegistry.get(e);const r=function(e,t,n){if(3!==arguments.length)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");!function(e,t,r){t[i]===t?t[s].push({id:e,index:r}):(t[s]=[{id:e,index:r}],t[i]=t)}(r,e,n)};return r._id=e,t.serviceRegistry.set(e,r),r};const i="di$target",s="di$dependencies";t.serviceRegistry=new Map},6501:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IDecorationService=t.IUnicodeService=t.IOscLinkService=t.IOptionsService=t.ILogService=t.LogLevelEnum=t.IInstantiationService=t.ICharsetService=t.ICoreService=t.ICoreMouseService=t.IBufferService=void 0;const s=i(6201);var r;t.IBufferService=(0,s.createDecorator)("BufferService"),t.ICoreMouseService=(0,s.createDecorator)("CoreMouseService"),t.ICoreService=(0,s.createDecorator)("CoreService"),t.ICharsetService=(0,s.createDecorator)("CharsetService"),t.IInstantiationService=(0,s.createDecorator)("InstantiationService"),function(e){e[e.TRACE=0]="TRACE",e[e.DEBUG=1]="DEBUG",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.OFF=5]="OFF"}(r||(t.LogLevelEnum=r={})),t.ILogService=(0,s.createDecorator)("LogService"),t.IOptionsService=(0,s.createDecorator)("OptionsService"),t.IOscLinkService=(0,s.createDecorator)("OscLinkService"),t.IUnicodeService=(0,s.createDecorator)("UnicodeService"),t.IDecorationService=(0,s.createDecorator)("DecorationService")},6415:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.UnicodeService=void 0;const s=i(7428),r=i(802);class n{static extractShouldJoin(e){return!!(1&e)}static extractWidth(e){return e>>1&3}static extractCharKind(e){return e>>3}static createPropertyValue(e,t,i=!1){return(16777215&e)<<3|(3&t)<<1|(i?1:0)}constructor(){this._providers=Object.create(null),this._active="",this._onChange=new r.Emitter,this.onChange=this._onChange.event;const e=new s.UnicodeV6;this.register(e),this._active=e.version,this._activeProvider=e}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(e){if(!this._providers[e])throw new Error(`unknown Unicode version "${e}"`);this._active=e,this._activeProvider=this._providers[e],this._onChange.fire(e)}register(e){this._providers[e.version]=e}wcwidth(e){return this._activeProvider.wcwidth(e)}getStringCellWidth(e){let t=0,i=0;const s=e.length;for(let r=0;r=s)return t+this.wcwidth(o);const i=e.charCodeAt(r);56320<=i&&i<=57343?o=1024*(o-55296)+i-56320+65536:t+=this.wcwidth(i)}const a=this.charProperties(o,i);let l=n.extractWidth(a);n.extractShouldJoin(a)&&(l-=n.extractWidth(i)),t+=l,i=a}return t}charProperties(e,t){return this._activeProvider.charProperties(e,t)}}t.UnicodeService=n},4333:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isAndroid=t.isElectron=t.isWebkitWebView=t.isSafari=t.isChrome=t.isWebKit=t.isFirefox=t.onDidChangeFullscreen=t.onDidChangeZoomLevel=void 0,t.addMatchMediaChangeListener=o,t.setZoomLevel=function(e,t){n.INSTANCE.setZoomLevel(e,t)},t.getZoomLevel=function(e){return n.INSTANCE.getZoomLevel(e)},t.getZoomFactor=function(e){return n.INSTANCE.getZoomFactor(e)},t.setZoomFactor=function(e,t){n.INSTANCE.setZoomFactor(e,t)},t.setFullscreen=function(e,t){n.INSTANCE.setFullscreen(e,t)},t.isFullscreen=function(e){return n.INSTANCE.isFullscreen(e)},t.isStandalone=function(){return l},t.isWCOEnabled=function(){return navigator?.windowControlsOverlay?.visible},t.getWCOBoundingRect=function(){return navigator?.windowControlsOverlay?.getTitlebarAreaRect()};const s=i(4693),r=i(802);class n{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new r.Emitter,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new r.Emitter,this.onDidChangeFullscreen=this._onDidChangeFullscreen.event,this.mapWindowIdToFullScreen=new Map}static{this.INSTANCE=new n}getZoomLevel(e){return this.mapWindowIdToZoomLevel.get(this.getWindowId(e))??0}setZoomLevel(e,t){if(this.getZoomLevel(t)===e)return;const i=this.getWindowId(t);this.mapWindowIdToZoomLevel.set(i,e),this._onDidChangeZoomLevel.fire(i)}getZoomFactor(e){return this.mapWindowIdToZoomFactor.get(this.getWindowId(e))??1}setZoomFactor(e,t){this.mapWindowIdToZoomFactor.set(this.getWindowId(t),e)}setFullscreen(e,t){if(this.isFullscreen(t)===e)return;const i=this.getWindowId(t);this.mapWindowIdToFullScreen.set(i,e),this._onDidChangeFullscreen.fire(i)}isFullscreen(e){return!!this.mapWindowIdToFullScreen.get(this.getWindowId(e))}getWindowId(e){return e.vscodeWindowId}}function o(e,t,i){"string"==typeof t&&(t=e.matchMedia(t)),t.addEventListener("change",i)}t.onDidChangeZoomLevel=n.INSTANCE.onDidChangeZoomLevel,t.onDidChangeFullscreen=n.INSTANCE.onDidChangeFullscreen;const a="object"==typeof navigator?navigator.userAgent:"";t.isFirefox=a.indexOf("Firefox")>=0,t.isWebKit=a.indexOf("AppleWebKit")>=0,t.isChrome=a.indexOf("Chrome")>=0,t.isSafari=!t.isChrome&&a.indexOf("Safari")>=0,t.isWebkitWebView=!t.isChrome&&!t.isSafari&&t.isWebKit,t.isElectron=a.indexOf("Electron/")>=0,t.isAndroid=a.indexOf("Android")>=0;let l=!1;if("function"==typeof s.mainWindow.matchMedia){const e=s.mainWindow.matchMedia("(display-mode: standalone) or (display-mode: window-controls-overlay)"),t=s.mainWindow.matchMedia("(display-mode: fullscreen)");l=e.matches,o(s.mainWindow,e,(({matches:e})=>{l&&t.matches||(l=e)}))}},7745:function(e,t,i){var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,r)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&s(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.BrowserFeatures=t.KeyboardSupport=void 0;const o=n(i(4333)),a=i(4693),l=n(i(8163));var h;!function(e){e[e.Always=0]="Always",e[e.FullScreen=1]="FullScreen",e[e.None=2]="None"}(h||(t.KeyboardSupport=h={}));const c="object"==typeof navigator?navigator:{};t.BrowserFeatures={clipboard:{writeText:l.isNative||document.queryCommandSupported&&document.queryCommandSupported("copy")||!!(c&&c.clipboard&&c.clipboard.writeText),readText:l.isNative||!!(c&&c.clipboard&&c.clipboard.readText)},keyboard:l.isNative||o.isStandalone()?h.Always:c.keyboard||o.isSafari?h.FullScreen:h.None,touch:"ontouchstart"in a.mainWindow||c.maxTouchPoints>0,pointerEvents:a.mainWindow.PointerEvent&&("ontouchstart"in a.mainWindow||navigator.maxTouchPoints>0)}},7093:function(e,t,i){var s,r=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,r)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.SafeTriangle=t.DragAndDropObserver=t.ModifierKeyEmitter=t.DetectedFullscreenMode=t.Namespace=t.EventHelper=t.EventType=t.sharedMutationObserver=t.Dimension=t.WindowIntervalTimer=t.scheduleAtNextAnimationFrame=t.runAtThisOrScheduleAtNextAnimationFrame=t.WindowIdleValue=t.addStandardDisposableGenericMouseUpListener=t.addStandardDisposableGenericMouseDownListener=t.addStandardDisposableListener=t.onDidUnregisterWindow=t.onWillUnregisterWindow=t.onDidRegisterWindow=t.hasWindow=t.getWindowById=t.getWindowId=t.getWindowsCount=t.getWindows=t.getDocument=t.getWindow=t.registerWindow=void 0,t.clearNode=function(e){for(;e.firstChild;)e.firstChild.remove()},t.clearNodeRecursively=function e(t){for(;t.firstChild;){const i=t.firstChild;i.remove(),e(i)}},t.addDisposableListener=C,t.addDisposableGenericMouseDownListener=w,t.addDisposableGenericMouseMoveListener=function(e,i,s){return C(e,g.isIOS&&l.BrowserFeatures.pointerEvents?t.EventType.POINTER_MOVE:t.EventType.MOUSE_MOVE,i,s)},t.addDisposableGenericMouseUpListener=E,t.runWhenWindowIdle=function(e,t,i){return(0,d._runWhenIdle)(e,t,i)},t.disposableWindowInterval=function(e,t,i,s){let r=0;const n=e.setInterval((()=>{r++,("number"==typeof s&&r>=s||!0===t())&&o.dispose()}),i),o=(0,p.toDisposable)((()=>{e.clearInterval(n)}));return o},t.measure=function(e,i){return(0,t.scheduleAtNextAnimationFrame)(e,i,1e4)},t.modify=function(e,i){return(0,t.scheduleAtNextAnimationFrame)(e,i,-1e4)},t.addDisposableThrottledListener=function(e,t,i,s,r){return new T(e,t,i,s,r)},t.getComputedStyle=k,t.getClientArea=function e(i,s){const r=(0,t.getWindow)(i),n=r.document;if(i!==n.body)return new O(i.clientWidth,i.clientHeight);if(g.isIOS&&r?.visualViewport)return new O(r.visualViewport.width,r.visualViewport.height);if(r?.innerWidth&&r.innerHeight)return new O(r.innerWidth,r.innerHeight);if(n.body&&n.body.clientWidth&&n.body.clientHeight)return new O(n.body.clientWidth,n.body.clientHeight);if(n.documentElement&&n.documentElement.clientWidth&&n.documentElement.clientHeight)return new O(n.documentElement.clientWidth,n.documentElement.clientHeight);if(s)return e(s);throw new Error("Unable to figure out browser width and height")},t.getTopLeftOffset=I,t.size=function(e,t,i){"number"==typeof t&&(e.style.width=`${t}px`),"number"==typeof i&&(e.style.height=`${i}px`)},t.position=function(e,t,i,s,r,n="absolute"){"number"==typeof t&&(e.style.top=`${t}px`),"number"==typeof i&&(e.style.right=`${i}px`),"number"==typeof s&&(e.style.bottom=`${s}px`),"number"==typeof r&&(e.style.left=`${r}px`),e.style.position=n},t.getDomNodePagePosition=function(e){const i=e.getBoundingClientRect(),s=(0,t.getWindow)(e);return{left:i.left+s.scrollX,top:i.top+s.scrollY,width:i.width,height:i.height}},t.getDomNodeZoomLevel=function(e){let t=e,i=1;do{const e=k(t).zoom;null!=e&&"1"!==e&&(i*=e),t=t.parentElement}while(null!==t&&t!==t.ownerDocument.documentElement);return i},t.getTotalWidth=P,t.getContentWidth=function(e){const t=M.getBorderLeftWidth(e)+M.getBorderRightWidth(e),i=M.getPaddingLeft(e)+M.getPaddingRight(e);return e.offsetWidth-t-i},t.getTotalScrollWidth=x,t.getContentHeight=function(e){const t=M.getBorderTopWidth(e)+M.getBorderBottomWidth(e),i=M.getPaddingTop(e)+M.getPaddingBottom(e);return e.offsetHeight-t-i},t.getTotalHeight=function(e){const t=M.getMarginTop(e)+M.getMarginBottom(e);return e.offsetHeight+t},t.getLargestChildWidth=function(e,t){const i=t.map((t=>Math.max(x(t),P(t))+function(e,t){if(null===e)return 0;const i=I(e),s=I(t);return i.left-s.left}(t,e)||0));return Math.max(...i)},t.isAncestor=B,t.setParentFlowTo=function(e,t){e.dataset[N]=t.id},t.isAncestorUsingFlowTo=function(e,t){let i=e;for(;i;){if(i===t)return!0;if(Q(i)){const e=U(i);if(e){i=e;continue}}i=i.parentNode}return!1},t.findParentWithClass=F,t.hasParentWithClass=function(e,t,i){return!!F(e,t,i)},t.isShadowRoot=W,t.isInShadowDOM=function(e){return!!H(e)},t.getShadowRoot=H,t.getActiveElement=K,t.isActiveElement=function(e){return K()===e},t.isAncestorOfActiveElement=function(e){return B(K(),e)},t.isActiveDocument=function(e){return e.ownerDocument===z()},t.getActiveDocument=z,t.getActiveWindow=function(){const e=z();return e.defaultView?.window??v.mainWindow},t.isGlobalStylesheet=function(e){return j.has(e)},t.createStyleSheet2=function(){return new $},t.createStyleSheet=V,t.cloneGlobalStylesheets=function(e){const t=new p.DisposableStore;for(const[i,s]of j)t.add(G(i,s,e));return t},t.createMetaElement=function(e=v.mainWindow.document.head){return q("meta",e)},t.createLinkElement=function(e=v.mainWindow.document.head){return q("link",e)},t.createCSSRule=function e(t,i,s=Y()){if(s&&i){s.sheet?.insertRule(`${t} {${i}}`,0);for(const r of j.get(s)??[])e(t,i,r)}},t.removeCSSRulesContainingSelector=function e(t,i=Y()){if(!i)return;const s=Z(i),r=[];for(let e=0;e=0;e--)i.sheet?.deleteRule(r[e]);for(const s of j.get(i)??[])e(t,s)},t.isHTMLElement=Q,t.isHTMLAnchorElement=function(e){return e instanceof HTMLAnchorElement||e instanceof(0,t.getWindow)(e).HTMLAnchorElement},t.isHTMLSpanElement=function(e){return e instanceof HTMLSpanElement||e instanceof(0,t.getWindow)(e).HTMLSpanElement},t.isHTMLTextAreaElement=function(e){return e instanceof HTMLTextAreaElement||e instanceof(0,t.getWindow)(e).HTMLTextAreaElement},t.isHTMLInputElement=function(e){return e instanceof HTMLInputElement||e instanceof(0,t.getWindow)(e).HTMLInputElement},t.isHTMLButtonElement=function(e){return e instanceof HTMLButtonElement||e instanceof(0,t.getWindow)(e).HTMLButtonElement},t.isHTMLDivElement=function(e){return e instanceof HTMLDivElement||e instanceof(0,t.getWindow)(e).HTMLDivElement},t.isSVGElement=function(e){return e instanceof SVGElement||e instanceof(0,t.getWindow)(e).SVGElement},t.isMouseEvent=function(e){return e instanceof MouseEvent||e instanceof(0,t.getWindow)(e).MouseEvent},t.isKeyboardEvent=function(e){return e instanceof KeyboardEvent||e instanceof(0,t.getWindow)(e).KeyboardEvent},t.isPointerEvent=function(e){return e instanceof PointerEvent||e instanceof(0,t.getWindow)(e).PointerEvent},t.isDragEvent=function(e){return e instanceof DragEvent||e instanceof(0,t.getWindow)(e).DragEvent},t.isEventLike=function(e){const t=e;return!(!t||"function"!=typeof t.preventDefault||"function"!=typeof t.stopPropagation)},t.saveParentsScrollTop=function(e){const t=[];for(let i=0;e&&e.nodeType===e.ELEMENT_NODE;i++)t[i]=e.scrollTop,e=e.parentNode;return t},t.restoreParentsScrollTop=function(e,t){for(let i=0;e&&e.nodeType===e.ELEMENT_NODE;i++)e.scrollTop!==t[i]&&(e.scrollTop=t[i]),e=e.parentNode},t.trackFocus=function(e){return new ee(e)},t.after=function(e,t){return e.after(t),t},t.append=te,t.prepend=function(e,t){return e.insertBefore(t,e.firstChild),t},t.reset=function(e,...t){e.innerText="",te(e,...t)},t.$=ne,t.join=function(e,t){const i=[];return e.forEach(((e,s)=>{s>0&&(t instanceof Node?i.push(t.cloneNode()):i.push(document.createTextNode(t))),i.push(e)})),i},t.setVisibility=function(e,...t){e?oe(...t):ae(...t)},t.show=oe,t.hide=ae,t.removeTabIndexAndUpdateFocus=function(e){if(e&&e.hasAttribute("tabIndex")){if(e.ownerDocument.activeElement===e){const t=function(e){for(;e&&e.nodeType===e.ELEMENT_NODE;){if(Q(e)&&e.hasAttribute("tabIndex"))return e;e=e.parentNode}return null}(e.parentElement);t?.focus()}e.removeAttribute("tabindex")}},t.finalHandler=function(e){return t=>{t.preventDefault(),t.stopPropagation(),e(t)}},t.domContentLoaded=function(e){return new Promise((t=>{if("complete"===e.document.readyState||e.document&&null!==e.document.body)t(void 0);else{const i=()=>{e.window.removeEventListener("DOMContentLoaded",i,!1),t()};e.window.addEventListener("DOMContentLoaded",i,!1)}}))},t.computeScreenAwareSize=function(e,t){const i=e.devicePixelRatio*t;return Math.max(1,Math.floor(i))/e.devicePixelRatio},t.windowOpenNoOpener=function(e){v.mainWindow.open(e,"_blank","noopener")},t.windowOpenPopup=function(e){const t=Math.floor(v.mainWindow.screenLeft+v.mainWindow.innerWidth/2-le/2),i=Math.floor(v.mainWindow.screenTop+v.mainWindow.innerHeight/2-he/2);v.mainWindow.open(e,"_blank",`width=${le},height=${he},top=${i},left=${t}`)},t.windowOpenWithSuccess=function(e,t=!0){const i=v.mainWindow.open();return!!i&&(t&&(i.opener=null),i.location.href=e,!0)},t.animate=function(e,i){const s=()=>{i(),r=(0,t.scheduleAtNextAnimationFrame)(e,s)};let r=(0,t.scheduleAtNextAnimationFrame)(e,s);return(0,p.toDisposable)((()=>r.dispose()))},t.asCSSPropertyValue=function(e){return`'${e.replace(/'/g,"%27")}'`},t.asCssValueWithDefault=function e(t,i){if(void 0!==t){const s=t.match(/^\s*var\((.+)\)$/);if(s){const t=s[1].split(",",2);return 2===t.length&&(i=e(t[1].trim(),i)),`var(${t[0]}, ${i})`}return t}return i},t.detectFullscreen=function(e){return e.document.fullscreenElement||e.document.webkitFullscreenElement||e.document.webkitIsFullScreen?{mode:ce.DOCUMENT,guess:!1}:e.innerHeight===e.screen.height?{mode:ce.BROWSER,guess:!1}:(g.isMacintosh||g.isLinux)&&e.outerHeight===e.screen.height&&e.outerWidth===e.screen.width?{mode:ce.BROWSER,guess:!0}:null},t.multibyteAwareBtoa=function(e){return btoa(function(e){const t=new Uint16Array(e.length);for(let i=0;i0&&(o.className=a.join(" "));const l={};if(r.groups.name&&(l[r.groups.name]=o),s)for(const e of s)Q(e)?o.appendChild(e):"string"==typeof e?o.append(e):"root"in e&&(Object.assign(l,e),o.appendChild(e.root));for(const[e,t]of Object.entries(i))if("className"!==e)if("style"===e)for(const[e,i]of Object.entries(t))o.style.setProperty(fe(e),"number"==typeof i?i+"px":""+i);else"tabIndex"===e?o.tabIndex=t:o.setAttribute(fe(e),t.toString());return l.root=o,l},t.svgElem=function(e,...t){let i,s;Array.isArray(t[0])?(i={},s=t[0]):(i=t[0]||{},s=t[1]);const r=_e.exec(e);if(!r||!r.groups)throw new Error("Bad use of h");const n=r.groups.tag||"div",o=document.createElementNS("http://www.w3.org/2000/svg",n);r.groups.id&&(o.id=r.groups.id);const a=[];if(r.groups.class)for(const e of r.groups.class.split("."))""!==e&&a.push(e);if(void 0!==i.className)for(const e of i.className.split("."))""!==e&&a.push(e);a.length>0&&(o.className=a.join(" "));const l={};if(r.groups.name&&(l[r.groups.name]=o),s)for(const e of s)Q(e)?o.appendChild(e):"string"==typeof e?o.append(e):"root"in e&&(Object.assign(l,e),o.appendChild(e.root));for(const[e,t]of Object.entries(i))if("className"!==e)if("style"===e)for(const[e,i]of Object.entries(t))o.style.setProperty(fe(e),"number"==typeof i?i+"px":""+i);else"tabIndex"===e?o.tabIndex=t:o.setAttribute(fe(e),t.toString());return l.root=o,l},t.copyAttributes=pe,t.trackAttributes=function(e,i,s){pe(e,i,s);const r=new p.DisposableStore;return r.add(t.sharedMutationObserver.observe(e,r,{attributes:!0,attributeFilter:s})((t=>{for(const s of t)"attributes"===s.type&&s.attributeName&&ge(e,i,s.attributeName)}))),r};const a=o(i(4333)),l=i(7745),h=i(5394),c=i(5964),d=i(1758),u=i(9807),_=o(i(802)),f=i(7883),p=i(7150),g=o(i(8163)),m=i(6304),v=i(4693),S=i(7704);s=function(){const e=new Map;(0,v.ensureCodeWindow)(v.mainWindow,1);const i={window:v.mainWindow,disposables:new p.DisposableStore};e.set(v.mainWindow.vscodeWindowId,i);const s=new _.Emitter,r=new _.Emitter,n=new _.Emitter;return{onDidRegisterWindow:s.event,onWillUnregisterWindow:n.event,onDidUnregisterWindow:r.event,registerWindow(i){if(e.has(i.vscodeWindowId))return p.Disposable.None;const o=new p.DisposableStore,a={window:i,disposables:o.add(new p.DisposableStore)};return e.set(i.vscodeWindowId,a),o.add((0,p.toDisposable)((()=>{e.delete(i.vscodeWindowId),r.fire(i)}))),o.add(C(i,t.EventType.BEFORE_UNLOAD,(()=>{n.fire(i)}))),s.fire(a),o},getWindows:()=>e.values(),getWindowsCount:()=>e.size,getWindowId:e=>e.vscodeWindowId,hasWindow:t=>e.has(t),getWindowById:function(t,s){return("number"==typeof t?e.get(t):void 0)??(s?i:void 0)},getWindow(e){const t=e;if(t?.ownerDocument?.defaultView)return t.ownerDocument.defaultView.window;const i=e;return i?.view?i.view.window:v.mainWindow},getDocument(e){const i=e;return(0,t.getWindow)(i).document}}}(),t.registerWindow=s.registerWindow,t.getWindow=s.getWindow,t.getDocument=s.getDocument,t.getWindows=s.getWindows,t.getWindowsCount=s.getWindowsCount,t.getWindowId=s.getWindowId,t.getWindowById=s.getWindowById,t.hasWindow=s.hasWindow,t.onDidRegisterWindow=s.onDidRegisterWindow,t.onWillUnregisterWindow=s.onWillUnregisterWindow,t.onDidUnregisterWindow=s.onDidUnregisterWindow;class b{constructor(e,t,i,s){this._node=e,this._type=t,this._handler=i,this._options=s||!1,this._node.addEventListener(this._type,this._handler,this._options)}dispose(){this._handler&&(this._node.removeEventListener(this._type,this._handler,this._options),this._node=null,this._handler=null)}}function C(e,t,i,s){return new b(e,t,i,s)}function y(e,t){return function(i){return t(new c.StandardMouseEvent(e,i))}}function w(e,i,s){return C(e,g.isIOS&&l.BrowserFeatures.pointerEvents?t.EventType.POINTER_DOWN:t.EventType.MOUSE_DOWN,i,s)}function E(e,i,s){return C(e,g.isIOS&&l.BrowserFeatures.pointerEvents?t.EventType.POINTER_UP:t.EventType.MOUSE_UP,i,s)}t.addStandardDisposableListener=function(e,i,s,r){let n=s;return"click"===i||"mousedown"===i||"contextmenu"===i?n=y((0,t.getWindow)(e),s):"keydown"!==i&&"keypress"!==i&&"keyup"!==i||(n=function(e){return function(t){return e(new h.StandardKeyboardEvent(t))}}(s)),C(e,i,n,r)},t.addStandardDisposableGenericMouseDownListener=function(e,i,s){return w(e,y((0,t.getWindow)(e),i),s)},t.addStandardDisposableGenericMouseUpListener=function(e,i,s){return E(e,y((0,t.getWindow)(e),i),s)};class D extends d.AbstractIdleValue{constructor(e,t){super(e,t)}}t.WindowIdleValue=D;class L extends d.IntervalTimer{constructor(e){super(),this.defaultTarget=e&&(0,t.getWindow)(e)}cancelAndSet(e,t,i){return super.cancelAndSet(e,t,i??this.defaultTarget)}}t.WindowIntervalTimer=L;class R{constructor(e,t=0){this._runner=e,this.priority=t,this._canceled=!1}dispose(){this._canceled=!0}execute(){if(!this._canceled)try{this._runner()}catch(e){(0,u.onUnexpectedError)(e)}}static sort(e,t){return t.priority-e.priority}}!function(){const e=new Map,i=new Map,s=new Map,r=new Map;t.scheduleAtNextAnimationFrame=(n,o,a=0)=>{const l=(0,t.getWindowId)(n),h=new R(o,a);let c=e.get(l);return c||(c=[],e.set(l,c)),c.push(h),s.get(l)||(s.set(l,!0),n.requestAnimationFrame((()=>(t=>{s.set(t,!1);const n=e.get(t)??[];for(i.set(t,n),e.set(t,[]),r.set(t,!0);n.length>0;)n.sort(R.sort),n.shift().execute();r.set(t,!1)})(l)))),h},t.runAtThisOrScheduleAtNextAnimationFrame=(e,s,n)=>{const o=(0,t.getWindowId)(e);if(r.get(o)){const e=new R(s,n);let t=i.get(o);return t||(t=[],i.set(o,t)),t.push(e),e}return(0,t.scheduleAtNextAnimationFrame)(e,s,n)}}();const A=function(e,t){return t};class T extends p.Disposable{constructor(e,t,i,s=A,r=8){super();let n=null,o=0;const a=this._register(new d.TimeoutTimer),l=()=>{o=(new Date).getTime(),i(n),n=null};this._register(C(e,t,(e=>{n=s(n,e);const t=(new Date).getTime()-o;t>=r?(a.cancel(),l()):a.setIfNotSet(l,r-t)})))}}function k(e){return(0,t.getWindow)(e).getComputedStyle(e,null)}class M{static convertToPixels(e,t){return parseFloat(t)||0}static getDimension(e,t,i){const s=k(e),r=s?s.getPropertyValue(t):"0";return M.convertToPixels(e,r)}static getBorderLeftWidth(e){return M.getDimension(e,"border-left-width","borderLeftWidth")}static getBorderRightWidth(e){return M.getDimension(e,"border-right-width","borderRightWidth")}static getBorderTopWidth(e){return M.getDimension(e,"border-top-width","borderTopWidth")}static getBorderBottomWidth(e){return M.getDimension(e,"border-bottom-width","borderBottomWidth")}static getPaddingLeft(e){return M.getDimension(e,"padding-left","paddingLeft")}static getPaddingRight(e){return M.getDimension(e,"padding-right","paddingRight")}static getPaddingTop(e){return M.getDimension(e,"padding-top","paddingTop")}static getPaddingBottom(e){return M.getDimension(e,"padding-bottom","paddingBottom")}static getMarginLeft(e){return M.getDimension(e,"margin-left","marginLeft")}static getMarginTop(e){return M.getDimension(e,"margin-top","marginTop")}static getMarginRight(e){return M.getDimension(e,"margin-right","marginRight")}static getMarginBottom(e){return M.getDimension(e,"margin-bottom","marginBottom")}}class O{static{this.None=new O(0,0)}constructor(e,t){this.width=e,this.height=t}with(e=this.width,t=this.height){return e!==this.width||t!==this.height?new O(e,t):this}static is(e){return"object"==typeof e&&"number"==typeof e.height&&"number"==typeof e.width}static lift(e){return e instanceof O?e:new O(e.width,e.height)}static equals(e,t){return e===t||!(!e||!t)&&e.width===t.width&&e.height===t.height}}function I(e){let t=e.offsetParent,i=e.offsetTop,s=e.offsetLeft;for(;null!==(e=e.parentNode)&&e!==e.ownerDocument.body&&e!==e.ownerDocument.documentElement;){i-=e.scrollTop;const r=W(e)?null:k(e);r&&(s-="rtl"!==r.direction?e.scrollLeft:-e.scrollLeft),e===t&&(s+=M.getBorderLeftWidth(e),i+=M.getBorderTopWidth(e),i+=e.offsetTop,s+=e.offsetLeft,t=e.offsetParent)}return{left:s,top:i}}function P(e){const t=M.getMarginLeft(e)+M.getMarginRight(e);return e.offsetWidth+t}function x(e){const t=M.getMarginLeft(e)+M.getMarginRight(e);return e.scrollWidth+t}function B(e,t){return Boolean(t?.contains(e))}t.Dimension=O;const N="parentFlowToElementId";function U(e){const t=e.dataset[N];return"string"==typeof t?e.ownerDocument.getElementById(t):null}function F(e,t,i){for(;e&&e.nodeType===e.ELEMENT_NODE;){if(e.classList.contains(t))return e;if(i)if("string"==typeof i){if(e.classList.contains(i))return null}else if(e===i)return null;e=e.parentNode}return null}function W(e){return e&&!!e.host&&!!e.mode}function H(e){for(;e.parentNode;){if(e===e.ownerDocument?.body)return null;e=e.parentNode}return W(e)?e:null}function K(){let e=z().activeElement;for(;e?.shadowRoot;)e=e.shadowRoot.activeElement;return e}function z(){return(0,t.getWindowsCount)()<=1?v.mainWindow.document:Array.from((0,t.getWindows)()).map((({window:e})=>e.document)).find((e=>e.hasFocus()))??v.mainWindow.document}const j=new Map;class ${constructor(){this._currentCssStyle="",this._styleSheet=void 0}setStyle(e){e!==this._currentCssStyle&&(this._currentCssStyle=e,this._styleSheet?this._styleSheet.innerText=e:this._styleSheet=V(v.mainWindow.document.head,(t=>t.innerText=e)))}dispose(){this._styleSheet&&(this._styleSheet.remove(),this._styleSheet=void 0)}}function V(e=v.mainWindow.document.head,i,s){const r=document.createElement("style");if(r.type="text/css",r.media="screen",i?.(r),e.appendChild(r),s&&s.add((0,p.toDisposable)((()=>r.remove()))),e===v.mainWindow.document.head){const e=new Set;j.set(r,e);for(const{window:i,disposables:n}of(0,t.getWindows)()){if(i===v.mainWindow)continue;const t=n.add(G(r,e,i));s?.add(t)}}return r}function G(e,i,s){const r=new p.DisposableStore,n=e.cloneNode(!0);s.document.head.appendChild(n),r.add((0,p.toDisposable)((()=>n.remove())));for(const t of Z(e))n.sheet?.insertRule(t.cssText,n.sheet?.cssRules.length);return r.add(t.sharedMutationObserver.observe(e,r,{childList:!0})((()=>{n.textContent=e.textContent}))),i.add(n),r.add((0,p.toDisposable)((()=>i.delete(n)))),r}function q(e,t=v.mainWindow.document.head){const i=document.createElement(e);return t.appendChild(i),i}t.sharedMutationObserver=new class{constructor(){this.mutationObservers=new Map}observe(e,t,i){let s=this.mutationObservers.get(e);s||(s=new Map,this.mutationObservers.set(e,s));const r=(0,m.hash)(i);let n=s.get(r);if(n)n.users+=1;else{const o=new _.Emitter,a=new MutationObserver((e=>o.fire(e)));a.observe(e,i);const l=n={users:1,observer:a,onDidMutate:o.event};t.add((0,p.toDisposable)((()=>{l.users-=1,0===l.users&&(o.dispose(),a.disconnect(),s?.delete(r),0===s?.size&&this.mutationObservers.delete(e))}))),s.set(r,n)}return n.onDidMutate}};let X=null;function Y(){return X||(X=V()),X}function Z(e){return e?.sheet?.rules?e.sheet.rules:e?.sheet?.cssRules?e.sheet.cssRules:[]}function J(e){return"string"==typeof e.selectorText}function Q(e){return e instanceof HTMLElement||e instanceof(0,t.getWindow)(e).HTMLElement}t.EventType={CLICK:"click",AUXCLICK:"auxclick",DBLCLICK:"dblclick",MOUSE_UP:"mouseup",MOUSE_DOWN:"mousedown",MOUSE_OVER:"mouseover",MOUSE_MOVE:"mousemove",MOUSE_OUT:"mouseout",MOUSE_ENTER:"mouseenter",MOUSE_LEAVE:"mouseleave",MOUSE_WHEEL:"wheel",POINTER_UP:"pointerup",POINTER_DOWN:"pointerdown",POINTER_MOVE:"pointermove",POINTER_LEAVE:"pointerleave",CONTEXT_MENU:"contextmenu",WHEEL:"wheel",KEY_DOWN:"keydown",KEY_PRESS:"keypress",KEY_UP:"keyup",LOAD:"load",BEFORE_UNLOAD:"beforeunload",UNLOAD:"unload",PAGE_SHOW:"pageshow",PAGE_HIDE:"pagehide",PASTE:"paste",ABORT:"abort",ERROR:"error",RESIZE:"resize",SCROLL:"scroll",FULLSCREEN_CHANGE:"fullscreenchange",WK_FULLSCREEN_CHANGE:"webkitfullscreenchange",SELECT:"select",CHANGE:"change",SUBMIT:"submit",RESET:"reset",FOCUS:"focus",FOCUS_IN:"focusin",FOCUS_OUT:"focusout",BLUR:"blur",INPUT:"input",STORAGE:"storage",DRAG_START:"dragstart",DRAG:"drag",DRAG_ENTER:"dragenter",DRAG_LEAVE:"dragleave",DRAG_OVER:"dragover",DROP:"drop",DRAG_END:"dragend",ANIMATION_START:a.isWebKit?"webkitAnimationStart":"animationstart",ANIMATION_END:a.isWebKit?"webkitAnimationEnd":"animationend",ANIMATION_ITERATION:a.isWebKit?"webkitAnimationIteration":"animationiteration"},t.EventHelper={stop:(e,t)=>(e.preventDefault(),t&&e.stopPropagation(),e)};class ee extends p.Disposable{static hasFocusWithin(e){if(Q(e)){const t=H(e);return B(t?t.activeElement:e.ownerDocument.activeElement,e)}{const t=e;return B(t.document.activeElement,t.document)}}constructor(e){super(),this._onDidFocus=this._register(new _.Emitter),this.onDidFocus=this._onDidFocus.event,this._onDidBlur=this._register(new _.Emitter),this.onDidBlur=this._onDidBlur.event;let i=ee.hasFocusWithin(e),s=!1;const r=()=>{s=!1,i||(i=!0,this._onDidFocus.fire())},n=()=>{i&&(s=!0,(Q(e)?(0,t.getWindow)(e):e).setTimeout((()=>{s&&(s=!1,i=!1,this._onDidBlur.fire())}),0))};this._refreshStateHandler=()=>{ee.hasFocusWithin(e)!==i&&(i?n():r())},this._register(C(e,t.EventType.FOCUS,r,!0)),this._register(C(e,t.EventType.BLUR,n,!0)),Q(e)&&(this._register(C(e,t.EventType.FOCUS_IN,(()=>this._refreshStateHandler()))),this._register(C(e,t.EventType.FOCUS_OUT,(()=>this._refreshStateHandler()))))}refreshState(){this._refreshStateHandler()}}function te(e,...t){if(e.append(...t),1===t.length&&"string"!=typeof t[0])return t[0]}const ie=/([\w\-]+)?(#([\w\-]+))?((\.([\w\-]+))*)/;var se;function re(e,t,i,...s){const r=ie.exec(t);if(!r)throw new Error("Bad use of emmet");const n=r[1]||"div";let o;return o=e!==se.HTML?document.createElementNS(e,n):document.createElement(n),r[3]&&(o.id=r[3]),r[4]&&(o.className=r[4].replace(/\./g," ").trim()),i&&Object.entries(i).forEach((([e,t])=>{void 0!==t&&(/^on\w+$/.test(e)?o[e]=t:"selected"===e?t&&o.setAttribute(e,"true"):o.setAttribute(e,t))})),o.append(...s),o}function ne(e,t,...i){return re(se.HTML,e,t,...i)}function oe(...e){for(const t of e)t.style.display="",t.removeAttribute("aria-hidden")}function ae(...e){for(const t of e)t.style.display="none",t.setAttribute("aria-hidden","true")}!function(e){e.HTML="http://www.w3.org/1999/xhtml",e.SVG="http://www.w3.org/2000/svg"}(se||(t.Namespace=se={})),ne.SVG=function(e,t,...i){return re(se.SVG,e,t,...i)};const le=780,he=640;var ce;!function(e){e[e.DOCUMENT=1]="DOCUMENT",e[e.BROWSER=2]="BROWSER"}(ce||(t.DetectedFullscreenMode=ce={}));class de extends _.Emitter{constructor(){super(),this._subscriptions=new p.DisposableStore,this._keyStatus={altKey:!1,shiftKey:!1,ctrlKey:!1,metaKey:!1},this._subscriptions.add(_.Event.runAndSubscribe(t.onDidRegisterWindow,(({window:e,disposables:t})=>this.registerListeners(e,t)),{window:v.mainWindow,disposables:this._subscriptions}))}registerListeners(e,t){t.add(C(e,"keydown",(e=>{if(e.defaultPrevented)return;const t=new h.StandardKeyboardEvent(e);if(t.keyCode!==f.KeyCode.Alt||!e.repeat){if(e.altKey&&!this._keyStatus.altKey)this._keyStatus.lastKeyPressed="alt";else if(e.ctrlKey&&!this._keyStatus.ctrlKey)this._keyStatus.lastKeyPressed="ctrl";else if(e.metaKey&&!this._keyStatus.metaKey)this._keyStatus.lastKeyPressed="meta";else if(e.shiftKey&&!this._keyStatus.shiftKey)this._keyStatus.lastKeyPressed="shift";else{if(t.keyCode===f.KeyCode.Alt)return;this._keyStatus.lastKeyPressed=void 0}this._keyStatus.altKey=e.altKey,this._keyStatus.ctrlKey=e.ctrlKey,this._keyStatus.metaKey=e.metaKey,this._keyStatus.shiftKey=e.shiftKey,this._keyStatus.lastKeyPressed&&(this._keyStatus.event=e,this.fire(this._keyStatus))}}),!0)),t.add(C(e,"keyup",(e=>{e.defaultPrevented||(!e.altKey&&this._keyStatus.altKey?this._keyStatus.lastKeyReleased="alt":!e.ctrlKey&&this._keyStatus.ctrlKey?this._keyStatus.lastKeyReleased="ctrl":!e.metaKey&&this._keyStatus.metaKey?this._keyStatus.lastKeyReleased="meta":!e.shiftKey&&this._keyStatus.shiftKey?this._keyStatus.lastKeyReleased="shift":this._keyStatus.lastKeyReleased=void 0,this._keyStatus.lastKeyPressed!==this._keyStatus.lastKeyReleased&&(this._keyStatus.lastKeyPressed=void 0),this._keyStatus.altKey=e.altKey,this._keyStatus.ctrlKey=e.ctrlKey,this._keyStatus.metaKey=e.metaKey,this._keyStatus.shiftKey=e.shiftKey,this._keyStatus.lastKeyReleased&&(this._keyStatus.event=e,this.fire(this._keyStatus)))}),!0)),t.add(C(e.document.body,"mousedown",(()=>{this._keyStatus.lastKeyPressed=void 0}),!0)),t.add(C(e.document.body,"mouseup",(()=>{this._keyStatus.lastKeyPressed=void 0}),!0)),t.add(C(e.document.body,"mousemove",(e=>{e.buttons&&(this._keyStatus.lastKeyPressed=void 0)}),!0)),t.add(C(e,"blur",(()=>{this.resetKeyStatus()})))}get keyStatus(){return this._keyStatus}get isModifierPressed(){return this._keyStatus.altKey||this._keyStatus.ctrlKey||this._keyStatus.metaKey||this._keyStatus.shiftKey}resetKeyStatus(){this.doResetKeyStatus(),this.fire(this._keyStatus)}doResetKeyStatus(){this._keyStatus={altKey:!1,shiftKey:!1,ctrlKey:!1,metaKey:!1}}static getInstance(){return de.instance||(de.instance=new de),de.instance}dispose(){super.dispose(),this._subscriptions.dispose()}}t.ModifierKeyEmitter=de;class ue extends p.Disposable{constructor(e,t){super(),this.element=e,this.callbacks=t,this.counter=0,this.dragStartTime=0,this.registerListeners()}registerListeners(){this.callbacks.onDragStart&&this._register(C(this.element,t.EventType.DRAG_START,(e=>{this.callbacks.onDragStart?.(e)}))),this.callbacks.onDrag&&this._register(C(this.element,t.EventType.DRAG,(e=>{this.callbacks.onDrag?.(e)}))),this._register(C(this.element,t.EventType.DRAG_ENTER,(e=>{this.counter++,this.dragStartTime=e.timeStamp,this.callbacks.onDragEnter?.(e)}))),this._register(C(this.element,t.EventType.DRAG_OVER,(e=>{e.preventDefault(),this.callbacks.onDragOver?.(e,e.timeStamp-this.dragStartTime)}))),this._register(C(this.element,t.EventType.DRAG_LEAVE,(e=>{this.counter--,0===this.counter&&(this.dragStartTime=0,this.callbacks.onDragLeave?.(e))}))),this._register(C(this.element,t.EventType.DRAG_END,(e=>{this.counter=0,this.dragStartTime=0,this.callbacks.onDragEnd?.(e)}))),this._register(C(this.element,t.EventType.DROP,(e=>{this.counter=0,this.dragStartTime=0,this.callbacks.onDrop?.(e)})))}}t.DragAndDropObserver=ue;const _e=/(?[\w\-]+)?(?:#(?[\w\-]+))?(?(?:\.(?:[\w\-]+))*)(?:@(?(?:[\w\_])+))?/;function fe(e){return e.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function pe(e,t,i){for(const{name:s,value:r}of e.attributes)i&&!i.includes(s)||t.setAttribute(s,r)}function ge(e,t,i){const s=e.getAttribute(i);s?t.setAttribute(i,s):t.removeAttribute(i)}t.SafeTriangle=class{constructor(e,t,i){this.originX=e,this.originY=t,this.triangles=[];const{top:s,left:r,right:n,bottom:o}=i.getBoundingClientRect(),a=this.triangles;let l=0;a[l++]=r,a[l++]=s,a[l++]=n,a[l++]=s,a[l++]=r,a[l++]=s,a[l++]=r,a[l++]=o,a[l++]=n,a[l++]=s,a[l++]=n,a[l++]=o,a[l++]=r,a[l++]=o,a[l++]=n,a[l++]=o}contains(e,t){const{triangles:i,originX:s,originY:r}=this;for(let n=0;n<4;n++)if((0,S.isPointWithinTriangle)(e,t,s,r,i[2*n],i[2*n+1],i[2*n+2],i[2*n+3]))return!0;return!1}}},9675:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.FastDomNode=void 0,t.createFastDomNode=function(e){return new i(e)};class i{constructor(e){this.domNode=e,this._maxWidth="",this._width="",this._height="",this._top="",this._left="",this._bottom="",this._right="",this._paddingTop="",this._paddingLeft="",this._paddingBottom="",this._paddingRight="",this._fontFamily="",this._fontWeight="",this._fontSize="",this._fontStyle="",this._fontFeatureSettings="",this._fontVariationSettings="",this._textDecoration="",this._lineHeight="",this._letterSpacing="",this._className="",this._display="",this._position="",this._visibility="",this._color="",this._backgroundColor="",this._layerHint=!1,this._contain="none",this._boxShadow=""}setMaxWidth(e){const t=s(e);this._maxWidth!==t&&(this._maxWidth=t,this.domNode.style.maxWidth=this._maxWidth)}setWidth(e){const t=s(e);this._width!==t&&(this._width=t,this.domNode.style.width=this._width)}setHeight(e){const t=s(e);this._height!==t&&(this._height=t,this.domNode.style.height=this._height)}setTop(e){const t=s(e);this._top!==t&&(this._top=t,this.domNode.style.top=this._top)}setLeft(e){const t=s(e);this._left!==t&&(this._left=t,this.domNode.style.left=this._left)}setBottom(e){const t=s(e);this._bottom!==t&&(this._bottom=t,this.domNode.style.bottom=this._bottom)}setRight(e){const t=s(e);this._right!==t&&(this._right=t,this.domNode.style.right=this._right)}setPaddingTop(e){const t=s(e);this._paddingTop!==t&&(this._paddingTop=t,this.domNode.style.paddingTop=this._paddingTop)}setPaddingLeft(e){const t=s(e);this._paddingLeft!==t&&(this._paddingLeft=t,this.domNode.style.paddingLeft=this._paddingLeft)}setPaddingBottom(e){const t=s(e);this._paddingBottom!==t&&(this._paddingBottom=t,this.domNode.style.paddingBottom=this._paddingBottom)}setPaddingRight(e){const t=s(e);this._paddingRight!==t&&(this._paddingRight=t,this.domNode.style.paddingRight=this._paddingRight)}setFontFamily(e){this._fontFamily!==e&&(this._fontFamily=e,this.domNode.style.fontFamily=this._fontFamily)}setFontWeight(e){this._fontWeight!==e&&(this._fontWeight=e,this.domNode.style.fontWeight=this._fontWeight)}setFontSize(e){const t=s(e);this._fontSize!==t&&(this._fontSize=t,this.domNode.style.fontSize=this._fontSize)}setFontStyle(e){this._fontStyle!==e&&(this._fontStyle=e,this.domNode.style.fontStyle=this._fontStyle)}setFontFeatureSettings(e){this._fontFeatureSettings!==e&&(this._fontFeatureSettings=e,this.domNode.style.fontFeatureSettings=this._fontFeatureSettings)}setFontVariationSettings(e){this._fontVariationSettings!==e&&(this._fontVariationSettings=e,this.domNode.style.fontVariationSettings=this._fontVariationSettings)}setTextDecoration(e){this._textDecoration!==e&&(this._textDecoration=e,this.domNode.style.textDecoration=this._textDecoration)}setLineHeight(e){const t=s(e);this._lineHeight!==t&&(this._lineHeight=t,this.domNode.style.lineHeight=this._lineHeight)}setLetterSpacing(e){const t=s(e);this._letterSpacing!==t&&(this._letterSpacing=t,this.domNode.style.letterSpacing=this._letterSpacing)}setClassName(e){this._className!==e&&(this._className=e,this.domNode.className=this._className)}toggleClassName(e,t){this.domNode.classList.toggle(e,t),this._className=this.domNode.className}setDisplay(e){this._display!==e&&(this._display=e,this.domNode.style.display=this._display)}setPosition(e){this._position!==e&&(this._position=e,this.domNode.style.position=this._position)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this.domNode.style.visibility=this._visibility)}setColor(e){this._color!==e&&(this._color=e,this.domNode.style.color=this._color)}setBackgroundColor(e){this._backgroundColor!==e&&(this._backgroundColor=e,this.domNode.style.backgroundColor=this._backgroundColor)}setLayerHinting(e){this._layerHint!==e&&(this._layerHint=e,this.domNode.style.transform=this._layerHint?"translate3d(0px, 0px, 0px)":"")}setBoxShadow(e){this._boxShadow!==e&&(this._boxShadow=e,this.domNode.style.boxShadow=e)}setContain(e){this._contain!==e&&(this._contain=e,this.domNode.style.contain=this._contain)}setAttribute(e,t){this.domNode.setAttribute(e,t)}removeAttribute(e){this.domNode.removeAttribute(e)}appendChild(e){this.domNode.appendChild(e.domNode)}removeChild(e){this.domNode.removeChild(e.domNode)}}function s(e){return"number"==typeof e?`${e}px`:e}t.FastDomNode=i},8328:function(e,t,i){var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,r)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&s(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.GlobalPointerMoveMonitor=void 0;const o=n(i(7093)),a=i(7150);t.GlobalPointerMoveMonitor=class{constructor(){this._hooks=new a.DisposableStore,this._pointerMoveCallback=null,this._onStopCallback=null}dispose(){this.stopMonitoring(!1),this._hooks.dispose()}stopMonitoring(e,t){if(!this.isMonitoring())return;this._hooks.clear(),this._pointerMoveCallback=null;const i=this._onStopCallback;this._onStopCallback=null,e&&i&&i(t)}isMonitoring(){return!!this._pointerMoveCallback}startMonitoring(e,t,i,s,r){this.isMonitoring()&&this.stopMonitoring(!1),this._pointerMoveCallback=s,this._onStopCallback=r;let n=e;try{e.setPointerCapture(t),this._hooks.add((0,a.toDisposable)((()=>{try{e.releasePointerCapture(t)}catch(e){}})))}catch(t){n=o.getWindow(e)}this._hooks.add(o.addDisposableListener(n,o.EventType.POINTER_MOVE,(e=>{e.buttons===i?(e.preventDefault(),this._pointerMoveCallback(e)):this.stopMonitoring(!0)}))),this._hooks.add(o.addDisposableListener(n,o.EventType.POINTER_UP,(e=>this.stopMonitoring(!0))))}}},6609:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IframeUtils=void 0,t.parentOriginHash=async function(e,t){if(!crypto.subtle)throw new Error("'crypto.subtle' is not available so webviews will not work. This is likely because the editor is not running in a secure context (https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts).");const i=JSON.stringify({parentOrigin:e,salt:t}),s=(new TextEncoder).encode(i);return function(e){const t=Array.from(new Uint8Array(e)).map((e=>e.toString(16).padStart(2,"0"))).join("");return BigInt(`0x${t}`).toString(32).padStart(52,"0")}(await crypto.subtle.digest("sha-256",s))};const i=new WeakMap;function s(e){if(!e.parent||e.parent===e)return null;try{const t=e.location,i=e.parent.location;if("null"!==t.origin&&"null"!==i.origin&&t.origin!==i.origin)return null}catch(e){return null}return e.parent}t.IframeUtils=class{static getSameOriginWindowChain(e){let t=i.get(e);if(!t){t=[],i.set(e,t);let r,n=e;do{r=s(n),r?t.push({window:new WeakRef(n),iframeElement:n.frameElement||null}):t.push({window:new WeakRef(n),iframeElement:null}),n=r}while(n)}return t.slice(0)}static getPositionOfChildWindowRelativeToAncestorWindow(e,t){if(!t||e===t)return{top:0,left:0};let i=0,s=0;const r=this.getSameOriginWindowChain(e);for(const e of r){const r=e.window.deref();if(i+=r?.scrollY??0,s+=r?.scrollX??0,r===t)break;if(!e.iframeElement)break;const n=e.iframeElement.getBoundingClientRect();i+=n.top,s+=n.left}return{top:i,left:s}}}},5394:function(e,t,i){var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,r)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&s(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.StandardKeyboardEvent=void 0,t.printKeyboardEvent=function(e){const t=[];return e.ctrlKey&&t.push("ctrl"),e.shiftKey&&t.push("shift"),e.altKey&&t.push("alt"),e.metaKey&&t.push("meta"),`modifiers: [${t.join(",")}], code: ${e.code}, keyCode: ${e.keyCode}, key: ${e.key}`},t.printStandardKeyboardEvent=function(e){const t=[];return e.ctrlKey&&t.push("ctrl"),e.shiftKey&&t.push("shift"),e.altKey&&t.push("alt"),e.metaKey&&t.push("meta"),`modifiers: [${t.join(",")}], code: ${e.code}, keyCode: ${e.keyCode} ('${a.KeyCodeUtils.toString(e.keyCode)}')`};const o=n(i(4333)),a=i(7883),l=i(2811),h=n(i(8163)),c=h.isMacintosh?a.KeyMod.WinCtrl:a.KeyMod.CtrlCmd,d=a.KeyMod.Alt,u=a.KeyMod.Shift,_=h.isMacintosh?a.KeyMod.CtrlCmd:a.KeyMod.WinCtrl;t.StandardKeyboardEvent=class{constructor(e){this._standardKeyboardEventBrand=!0;const t=e;this.browserEvent=t,this.target=t.target,this.ctrlKey=t.ctrlKey,this.shiftKey=t.shiftKey,this.altKey=t.altKey,this.metaKey=t.metaKey,this.altGraphKey=t.getModifierState?.("AltGraph"),this.keyCode=function(e){if(e.charCode){const t=String.fromCharCode(e.charCode).toUpperCase();return a.KeyCodeUtils.fromString(t)}const t=e.keyCode;if(3===t)return a.KeyCode.PauseBreak;if(o.isFirefox)switch(t){case 59:return a.KeyCode.Semicolon;case 60:if(h.isLinux)return a.KeyCode.IntlBackslash;break;case 61:return a.KeyCode.Equal;case 107:return a.KeyCode.NumpadAdd;case 109:return a.KeyCode.NumpadSubtract;case 173:return a.KeyCode.Minus;case 224:if(h.isMacintosh)return a.KeyCode.Meta}else if(o.isWebKit){if(h.isMacintosh&&93===t)return a.KeyCode.Meta;if(!h.isMacintosh&&92===t)return a.KeyCode.Meta}return a.EVENT_KEY_CODE_MAP[t]||a.KeyCode.Unknown}(t),this.code=t.code,this.ctrlKey=this.ctrlKey||this.keyCode===a.KeyCode.Ctrl,this.altKey=this.altKey||this.keyCode===a.KeyCode.Alt,this.shiftKey=this.shiftKey||this.keyCode===a.KeyCode.Shift,this.metaKey=this.metaKey||this.keyCode===a.KeyCode.Meta,this._asKeybinding=this._computeKeybinding(),this._asKeyCodeChord=this._computeKeyCodeChord()}preventDefault(){this.browserEvent&&this.browserEvent.preventDefault&&this.browserEvent.preventDefault()}stopPropagation(){this.browserEvent&&this.browserEvent.stopPropagation&&this.browserEvent.stopPropagation()}toKeyCodeChord(){return this._asKeyCodeChord}equals(e){return this._asKeybinding===e}_computeKeybinding(){let e=a.KeyCode.Unknown;this.keyCode!==a.KeyCode.Ctrl&&this.keyCode!==a.KeyCode.Shift&&this.keyCode!==a.KeyCode.Alt&&this.keyCode!==a.KeyCode.Meta&&(e=this.keyCode);let t=0;return this.ctrlKey&&(t|=c),this.altKey&&(t|=d),this.shiftKey&&(t|=u),this.metaKey&&(t|=_),t|=e,t}_computeKeyCodeChord(){let e=a.KeyCode.Unknown;return this.keyCode!==a.KeyCode.Ctrl&&this.keyCode!==a.KeyCode.Shift&&this.keyCode!==a.KeyCode.Alt&&this.keyCode!==a.KeyCode.Meta&&(e=this.keyCode),new l.KeyCodeChord(this.ctrlKey,this.shiftKey,this.altKey,this.metaKey,e)}}},5964:function(e,t,i){var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,r)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&s(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.StandardWheelEvent=t.DragMouseEvent=t.StandardMouseEvent=void 0;const o=n(i(4333)),a=i(6609),l=n(i(8163));class h{constructor(e,t){this.timestamp=Date.now(),this.browserEvent=t,this.leftButton=0===t.button,this.middleButton=1===t.button,this.rightButton=2===t.button,this.buttons=t.buttons,this.target=t.target,this.detail=t.detail||1,"dblclick"===t.type&&(this.detail=2),this.ctrlKey=t.ctrlKey,this.shiftKey=t.shiftKey,this.altKey=t.altKey,this.metaKey=t.metaKey,"number"==typeof t.pageX?(this.posx=t.pageX,this.posy=t.pageY):(this.posx=t.clientX+this.target.ownerDocument.body.scrollLeft+this.target.ownerDocument.documentElement.scrollLeft,this.posy=t.clientY+this.target.ownerDocument.body.scrollTop+this.target.ownerDocument.documentElement.scrollTop);const i=a.IframeUtils.getPositionOfChildWindowRelativeToAncestorWindow(e,t.view);this.posx-=i.left,this.posy-=i.top}preventDefault(){this.browserEvent.preventDefault()}stopPropagation(){this.browserEvent.stopPropagation()}}t.StandardMouseEvent=h,t.DragMouseEvent=class extends h{constructor(e,t){super(e,t),this.dataTransfer=t.dataTransfer}},t.StandardWheelEvent=class{constructor(e,t=0,i=0){this.browserEvent=e||null,this.target=e?e.target||e.targetNode||e.srcElement:null,this.deltaY=i,this.deltaX=t;let s=!1;if(o.isChrome){const e=navigator.userAgent.match(/Chrome\/(\d+)/);s=(e?parseInt(e[1]):123)<=122}if(e){const t=e,i=e,r=e.view?.devicePixelRatio||1;if(void 0!==t.wheelDeltaY)this.deltaY=s?t.wheelDeltaY/(120*r):t.wheelDeltaY/120;else if(void 0!==i.VERTICAL_AXIS&&i.axis===i.VERTICAL_AXIS)this.deltaY=-i.detail/3;else if("wheel"===e.type){const t=e;t.deltaMode===t.DOM_DELTA_LINE?o.isFirefox&&!l.isMacintosh?this.deltaY=-e.deltaY/3:this.deltaY=-e.deltaY:this.deltaY=-e.deltaY/40}if(void 0!==t.wheelDeltaX)o.isSafari&&l.isWindows?this.deltaX=-t.wheelDeltaX/120:this.deltaX=s?t.wheelDeltaX/(120*r):t.wheelDeltaX/120;else if(void 0!==i.HORIZONTAL_AXIS&&i.axis===i.HORIZONTAL_AXIS)this.deltaX=-e.detail/3;else if("wheel"===e.type){const t=e;t.deltaMode===t.DOM_DELTA_LINE?o.isFirefox&&!l.isMacintosh?this.deltaX=-e.deltaX/3:this.deltaX=-e.deltaX:this.deltaX=-e.deltaX/40}0===this.deltaY&&0===this.deltaX&&e.wheelDelta&&(this.deltaY=s?e.wheelDelta/(120*r):e.wheelDelta/120)}}preventDefault(){this.browserEvent?.preventDefault()}stopPropagation(){this.browserEvent?.stopPropagation()}}},8594:function(e,t,i){var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,r)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&s(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.Gesture=t.EventType=void 0;const a=o(i(7093)),l=i(4693),h=o(i(3058)),c=i(4838),d=i(802),u=i(7150),_=i(6317);var f;!function(e){e.Tap="-xterm-gesturetap",e.Change="-xterm-gesturechange",e.Start="-xterm-gesturestart",e.End="-xterm-gesturesend",e.Contextmenu="-xterm-gesturecontextmenu"}(f||(t.EventType=f={}));class p extends u.Disposable{static{this.SCROLL_FRICTION=-.005}static{this.HOLD_DELAY=700}static{this.CLEAR_TAP_COUNT_TIME=400}constructor(){super(),this.dispatched=!1,this.targets=new _.LinkedList,this.ignoreTargets=new _.LinkedList,this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register(d.Event.runAndSubscribe(a.onDidRegisterWindow,(({window:e,disposables:t})=>{t.add(a.addDisposableListener(e.document,"touchstart",(e=>this.onTouchStart(e)),{passive:!1})),t.add(a.addDisposableListener(e.document,"touchend",(t=>this.onTouchEnd(e,t)))),t.add(a.addDisposableListener(e.document,"touchmove",(e=>this.onTouchMove(e)),{passive:!1}))}),{window:l.mainWindow,disposables:this._store}))}static addTarget(e){if(!p.isTouchDevice())return u.Disposable.None;p.INSTANCE||(p.INSTANCE=(0,u.markAsSingleton)(new p));const t=p.INSTANCE.targets.push(e);return(0,u.toDisposable)(t)}static ignoreTarget(e){if(!p.isTouchDevice())return u.Disposable.None;p.INSTANCE||(p.INSTANCE=(0,u.markAsSingleton)(new p));const t=p.INSTANCE.ignoreTargets.push(e);return(0,u.toDisposable)(t)}static isTouchDevice(){return"ontouchstart"in l.mainWindow||navigator.maxTouchPoints>0}dispose(){this.handle&&(this.handle.dispose(),this.handle=null),super.dispose()}onTouchStart(e){const t=Date.now();this.handle&&(this.handle.dispose(),this.handle=null);for(let i=0,s=e.targetTouches.length;i=p.HOLD_DELAY&&Math.abs(o.initialPageX-h.tail(o.rollingPageX))<30&&Math.abs(o.initialPageY-h.tail(o.rollingPageY))<30){const e=this.newGestureEvent(f.Contextmenu,o.initialTarget);e.pageX=h.tail(o.rollingPageX),e.pageY=h.tail(o.rollingPageY),this.dispatchEvent(e)}else if(1===s){const t=h.tail(o.rollingPageX),s=h.tail(o.rollingPageY),r=h.tail(o.rollingTimestamps)-o.rollingTimestamps[0],n=t-o.rollingPageX[0],a=s-o.rollingPageY[0],l=[...this.targets].filter((e=>o.initialTarget instanceof Node&&e.contains(o.initialTarget)));this.inertia(e,l,i,Math.abs(n)/r,n>0?1:-1,t,Math.abs(a)/r,a>0?1:-1,s)}this.dispatchEvent(this.newGestureEvent(f.End,o.initialTarget)),delete this.activeTouches[n.identifier]}this.dispatched&&(t.preventDefault(),t.stopPropagation(),this.dispatched=!1)}newGestureEvent(e,t){const i=document.createEvent("CustomEvent");return i.initEvent(e,!1,!0),i.initialTarget=t,i.tapCount=0,i}dispatchEvent(e){if(e.type===f.Tap){const t=(new Date).getTime();let i=0;i=t-this._lastSetTapCountTime>p.CLEAR_TAP_COUNT_TIME?1:2,this._lastSetTapCountTime=t,e.tapCount=i}else e.type!==f.Change&&e.type!==f.Contextmenu||(this._lastSetTapCountTime=0);if(e.initialTarget instanceof Node){for(const t of this.ignoreTargets)if(t.contains(e.initialTarget))return;const t=[];for(const i of this.targets)if(i.contains(e.initialTarget)){let s=0,r=e.initialTarget;for(;r&&r!==i;)s++,r=r.parentElement;t.push([s,i])}t.sort(((e,t)=>e[0]-t[0]));for(const[i,s]of t)s.dispatchEvent(e),this.dispatched=!0}}inertia(e,t,i,s,r,n,o,l,h){this.handle=a.scheduleAtNextAnimationFrame(e,(()=>{const a=Date.now(),c=a-i;let d=0,u=0,_=!0;s+=p.SCROLL_FRICTION*c,o+=p.SCROLL_FRICTION*c,s>0&&(_=!1,d=r*s*c),o>0&&(_=!1,u=l*o*c);const g=this.newGestureEvent(f.Change);g.translationX=d,g.translationY=u,t.forEach((e=>e.dispatchEvent(g))),_||this.inertia(e,t,a,s,r,n+d,o,l,h+u)}))}onTouchMove(e){const t=Date.now();for(let i=0,s=e.changedTouches.length;i3&&(r.rollingPageX.shift(),r.rollingPageY.shift(),r.rollingTimestamps.shift()),r.rollingPageX.push(s.pageX),r.rollingPageY.push(s.pageY),r.rollingTimestamps.push(t)}this.dispatched&&(e.preventDefault(),e.stopPropagation(),this.dispatched=!1)}}t.Gesture=p,n([c.memoize],p,"isTouchDevice",null)},8801:function(e,t,i){var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,r)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&s(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractScrollbar=void 0;const o=n(i(7093)),a=i(9675),l=i(8328),h=i(8974),c=i(79),d=i(8286),u=n(i(8163));class _ extends d.Widget{constructor(e){super(),this._lazyRender=e.lazyRender,this._host=e.host,this._scrollable=e.scrollable,this._scrollByPage=e.scrollByPage,this._scrollbarState=e.scrollbarState,this._visibilityController=this._register(new c.ScrollbarVisibilityController(e.visibility,"visible scrollbar "+e.extraScrollbarClassName,"invisible scrollbar "+e.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new l.GlobalPointerMoveMonitor),this._shouldRender=!0,this.domNode=(0,a.createFastDomNode)(document.createElement("div")),this.domNode.setAttribute("role","presentation"),this.domNode.setAttribute("aria-hidden","true"),this._visibilityController.setDomNode(this.domNode),this.domNode.setPosition("absolute"),this._register(o.addDisposableListener(this.domNode.domNode,o.EventType.POINTER_DOWN,(e=>this._domNodePointerDown(e))))}_createArrow(e){const t=this._register(new h.ScrollbarArrow(e));this.domNode.domNode.appendChild(t.bgDomNode),this.domNode.domNode.appendChild(t.domNode)}_createSlider(e,t,i,s){this.slider=(0,a.createFastDomNode)(document.createElement("div")),this.slider.setClassName("slider"),this.slider.setPosition("absolute"),this.slider.setTop(e),this.slider.setLeft(t),"number"==typeof i&&this.slider.setWidth(i),"number"==typeof s&&this.slider.setHeight(s),this.slider.setLayerHinting(!0),this.slider.setContain("strict"),this.domNode.domNode.appendChild(this.slider.domNode),this._register(o.addDisposableListener(this.slider.domNode,o.EventType.POINTER_DOWN,(e=>{0===e.button&&(e.preventDefault(),this._sliderPointerDown(e))}))),this.onclick(this.slider.domNode,(e=>{e.leftButton&&e.stopPropagation()}))}_onElementSize(e){return this._scrollbarState.setVisibleSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollSize(e){return this._scrollbarState.setScrollSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollPosition(e){return this._scrollbarState.setScrollPosition(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}beginReveal(){this._visibilityController.setShouldBeVisible(!0)}beginHide(){this._visibilityController.setShouldBeVisible(!1)}render(){this._shouldRender&&(this._shouldRender=!1,this._renderDomNode(this._scrollbarState.getRectangleLargeSize(),this._scrollbarState.getRectangleSmallSize()),this._updateSlider(this._scrollbarState.getSliderSize(),this._scrollbarState.getArrowSize()+this._scrollbarState.getSliderPosition()))}_domNodePointerDown(e){e.target===this.domNode.domNode&&this._onPointerDown(e)}delegatePointerDown(e){const t=this.domNode.domNode.getClientRects()[0].top,i=t+this._scrollbarState.getSliderPosition(),s=t+this._scrollbarState.getSliderPosition()+this._scrollbarState.getSliderSize(),r=this._sliderPointerPosition(e);i<=r&&r<=s?0===e.button&&(e.preventDefault(),this._sliderPointerDown(e)):this._onPointerDown(e)}_onPointerDown(e){let t,i;if(e.target===this.domNode.domNode&&"number"==typeof e.offsetX&&"number"==typeof e.offsetY)t=e.offsetX,i=e.offsetY;else{const s=o.getDomNodePagePosition(this.domNode.domNode);t=e.pageX-s.left,i=e.pageY-s.top}const s=this._pointerDownRelativePosition(t,i);this._setDesiredScrollPositionNow(this._scrollByPage?this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(s):this._scrollbarState.getDesiredScrollPositionFromOffset(s)),0===e.button&&(e.preventDefault(),this._sliderPointerDown(e))}_sliderPointerDown(e){if(!(e.target&&e.target instanceof Element))return;const t=this._sliderPointerPosition(e),i=this._sliderOrthogonalPointerPosition(e),s=this._scrollbarState.clone();this.slider.toggleClassName("active",!0),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,(e=>{const r=this._sliderOrthogonalPointerPosition(e),n=Math.abs(r-i);if(u.isWindows&&n>140)return void this._setDesiredScrollPositionNow(s.getScrollPosition());const o=this._sliderPointerPosition(e)-t;this._setDesiredScrollPositionNow(s.getDesiredScrollPositionFromDelta(o))}),(()=>{this.slider.toggleClassName("active",!1),this._host.onDragEnd()})),this._host.onDragStart()}_setDesiredScrollPositionNow(e){const t={};this.writeScrollPosition(t,e),this._scrollable.setScrollPositionNow(t)}updateScrollbarSize(e){this._updateScrollbarSize(e),this._scrollbarState.setScrollbarSize(e),this._shouldRender=!0,this._lazyRender||this.render()}isNeeded(){return this._scrollbarState.isNeeded()}}t.AbstractScrollbar=_},151:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HorizontalScrollbar=void 0;const s=i(8801),r=i(8245),n=i(9881);class o extends s.AbstractScrollbar{constructor(e,t,i){const s=e.getScrollDimensions(),o=e.getCurrentScrollPosition();if(super({lazyRender:t.lazyRender,host:i,scrollbarState:new r.ScrollbarState(t.horizontalHasArrows?t.arrowSize:0,t.horizontal===n.ScrollbarVisibility.Hidden?0:t.horizontalScrollbarSize,t.vertical===n.ScrollbarVisibility.Hidden?0:t.verticalScrollbarSize,s.width,s.scrollWidth,o.scrollLeft),visibility:t.horizontal,extraScrollbarClassName:"horizontal",scrollable:e,scrollByPage:t.scrollByPage}),t.horizontalHasArrows)throw new Error("horizontalHasArrows is not supported in xterm.js");this._createSlider(Math.floor((t.horizontalScrollbarSize-t.horizontalSliderSize)/2),0,void 0,t.horizontalSliderSize)}_updateSlider(e,t){this.slider.setWidth(e),this.slider.setLeft(t)}_renderDomNode(e,t){this.domNode.setWidth(e),this.domNode.setHeight(t),this.domNode.setLeft(0),this.domNode.setBottom(0)}onDidScroll(e){return this._shouldRender=this._onElementScrollSize(e.scrollWidth)||this._shouldRender,this._shouldRender=this._onElementScrollPosition(e.scrollLeft)||this._shouldRender,this._shouldRender=this._onElementSize(e.width)||this._shouldRender,this._shouldRender}_pointerDownRelativePosition(e,t){return e}_sliderPointerPosition(e){return e.pageX}_sliderOrthogonalPointerPosition(e){return e.pageY}_updateScrollbarSize(e){this.slider.setHeight(e)}writeScrollPosition(e,t){e.scrollLeft=t}updateOptions(e){this.updateScrollbarSize(e.horizontal===n.ScrollbarVisibility.Hidden?0:e.horizontalScrollbarSize),this._scrollbarState.setOppositeScrollbarSize(e.vertical===n.ScrollbarVisibility.Hidden?0:e.verticalScrollbarSize),this._visibilityController.setVisibility(e.horizontal),this._scrollByPage=e.scrollByPage}}t.HorizontalScrollbar=o},8234:function(e,t,i){var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,r)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&s(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.DomScrollableElement=t.SmoothScrollableElement=t.ScrollableElement=t.AbstractScrollableElement=t.MouseWheelClassifier=void 0;const o=i(4333),a=n(i(7093)),l=i(9675),h=i(5964),c=i(151),d=i(5473),u=i(8286),_=i(1758),f=i(802),p=i(7150),g=n(i(8163)),m=i(9881);class v{constructor(e,t,i){this.timestamp=e,this.deltaX=t,this.deltaY=i,this.score=0}}class S{static{this.INSTANCE=new S}constructor(){this._capacity=5,this._memory=[],this._front=-1,this._rear=-1}isPhysicalMouseWheel(){if(-1===this._front&&-1===this._rear)return!1;let e=1,t=0,i=1,s=this._rear;for(;;){const r=s===this._front?e:Math.pow(2,-i);if(e-=r,t+=this._memory[s].score*r,s===this._front)break;s=(this._capacity+s-1)%this._capacity,i++}return t<=.5}acceptStandardWheelEvent(e){if(o.isChrome){const t=a.getWindow(e.browserEvent),i=(0,o.getZoomFactor)(t);this.accept(Date.now(),e.deltaX*i,e.deltaY*i)}else this.accept(Date.now(),e.deltaX,e.deltaY)}accept(e,t,i){let s=null;const r=new v(e,t,i);-1===this._front&&-1===this._rear?(this._memory[0]=r,this._front=0,this._rear=0):(s=this._memory[this._rear],this._rear=(this._rear+1)%this._capacity,this._rear===this._front&&(this._front=(this._front+1)%this._capacity),this._memory[this._rear]=r),r.score=this._computeScore(r,s)}_computeScore(e,t){if(Math.abs(e.deltaX)>0&&Math.abs(e.deltaY)>0)return 1;let i=.5;if(this._isAlmostInt(e.deltaX)&&this._isAlmostInt(e.deltaY)||(i+=.25),t){const s=Math.abs(e.deltaX),r=Math.abs(e.deltaY),n=Math.abs(t.deltaX),o=Math.abs(t.deltaY),a=Math.max(Math.min(s,n),1),l=Math.max(Math.min(r,o),1),h=Math.max(s,n),c=Math.max(r,o);h%a==0&&c%l==0&&(i-=.5)}return Math.min(Math.max(i,0),1)}_isAlmostInt(e){return Math.abs(Math.round(e)-e)<.01}}t.MouseWheelClassifier=S;class b extends u.Widget{get options(){return this._options}constructor(e,t,i){super(),this._onScroll=this._register(new f.Emitter),this.onScroll=this._onScroll.event,this._onWillScroll=this._register(new f.Emitter),this.onWillScroll=this._onWillScroll.event,this._options=function(e){const t={lazyRender:void 0!==e.lazyRender&&e.lazyRender,className:void 0!==e.className?e.className:"",useShadows:void 0===e.useShadows||e.useShadows,handleMouseWheel:void 0===e.handleMouseWheel||e.handleMouseWheel,flipAxes:void 0!==e.flipAxes&&e.flipAxes,consumeMouseWheelIfScrollbarIsNeeded:void 0!==e.consumeMouseWheelIfScrollbarIsNeeded&&e.consumeMouseWheelIfScrollbarIsNeeded,alwaysConsumeMouseWheel:void 0!==e.alwaysConsumeMouseWheel&&e.alwaysConsumeMouseWheel,scrollYToX:void 0!==e.scrollYToX&&e.scrollYToX,mouseWheelScrollSensitivity:void 0!==e.mouseWheelScrollSensitivity?e.mouseWheelScrollSensitivity:1,fastScrollSensitivity:void 0!==e.fastScrollSensitivity?e.fastScrollSensitivity:5,scrollPredominantAxis:void 0===e.scrollPredominantAxis||e.scrollPredominantAxis,mouseWheelSmoothScroll:void 0===e.mouseWheelSmoothScroll||e.mouseWheelSmoothScroll,arrowSize:void 0!==e.arrowSize?e.arrowSize:11,listenOnDomNode:void 0!==e.listenOnDomNode?e.listenOnDomNode:null,horizontal:void 0!==e.horizontal?e.horizontal:m.ScrollbarVisibility.Auto,horizontalScrollbarSize:void 0!==e.horizontalScrollbarSize?e.horizontalScrollbarSize:10,horizontalSliderSize:void 0!==e.horizontalSliderSize?e.horizontalSliderSize:0,horizontalHasArrows:void 0!==e.horizontalHasArrows&&e.horizontalHasArrows,vertical:void 0!==e.vertical?e.vertical:m.ScrollbarVisibility.Auto,verticalScrollbarSize:void 0!==e.verticalScrollbarSize?e.verticalScrollbarSize:10,verticalHasArrows:void 0!==e.verticalHasArrows&&e.verticalHasArrows,verticalSliderSize:void 0!==e.verticalSliderSize?e.verticalSliderSize:0,scrollByPage:void 0!==e.scrollByPage&&e.scrollByPage};return t.horizontalSliderSize=void 0!==e.horizontalSliderSize?e.horizontalSliderSize:t.horizontalScrollbarSize,t.verticalSliderSize=void 0!==e.verticalSliderSize?e.verticalSliderSize:t.verticalScrollbarSize,g.isMacintosh&&(t.className+=" mac"),t}(t),this._scrollable=i,this._register(this._scrollable.onScroll((e=>{this._onWillScroll.fire(e),this._onDidScroll(e),this._onScroll.fire(e)})));const s={onMouseWheel:e=>this._onMouseWheel(e),onDragStart:()=>this._onDragStart(),onDragEnd:()=>this._onDragEnd()};this._verticalScrollbar=this._register(new d.VerticalScrollbar(this._scrollable,this._options,s)),this._horizontalScrollbar=this._register(new c.HorizontalScrollbar(this._scrollable,this._options,s)),this._domNode=document.createElement("div"),this._domNode.className="xterm-scrollable-element "+this._options.className,this._domNode.setAttribute("role","presentation"),this._domNode.style.position="relative",this._domNode.appendChild(e),this._domNode.appendChild(this._horizontalScrollbar.domNode.domNode),this._domNode.appendChild(this._verticalScrollbar.domNode.domNode),this._options.useShadows?(this._leftShadowDomNode=(0,l.createFastDomNode)(document.createElement("div")),this._leftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=(0,l.createFastDomNode)(document.createElement("div")),this._topShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=(0,l.createFastDomNode)(document.createElement("div")),this._topLeftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topLeftShadowDomNode.domNode)):(this._leftShadowDomNode=null,this._topShadowDomNode=null,this._topLeftShadowDomNode=null),this._listenOnDomNode=this._options.listenOnDomNode||this._domNode,this._mouseWheelToDispose=[],this._setListeningToMouseWheel(this._options.handleMouseWheel),this.onmouseover(this._listenOnDomNode,(e=>this._onMouseOver(e))),this.onmouseleave(this._listenOnDomNode,(e=>this._onMouseLeave(e))),this._hideTimeout=this._register(new _.TimeoutTimer),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}dispose(){this._mouseWheelToDispose=(0,p.dispose)(this._mouseWheelToDispose),super.dispose()}getDomNode(){return this._domNode}getOverviewRulerLayoutInfo(){return{parent:this._domNode,insertBefore:this._verticalScrollbar.domNode.domNode}}delegateVerticalScrollbarPointerDown(e){this._verticalScrollbar.delegatePointerDown(e)}getScrollDimensions(){return this._scrollable.getScrollDimensions()}setScrollDimensions(e){this._scrollable.setScrollDimensions(e,!1)}updateClassName(e){this._options.className=e,g.isMacintosh&&(this._options.className+=" mac"),this._domNode.className="xterm-scrollable-element "+this._options.className}updateOptions(e){void 0!==e.handleMouseWheel&&(this._options.handleMouseWheel=e.handleMouseWheel,this._setListeningToMouseWheel(this._options.handleMouseWheel)),void 0!==e.mouseWheelScrollSensitivity&&(this._options.mouseWheelScrollSensitivity=e.mouseWheelScrollSensitivity),void 0!==e.fastScrollSensitivity&&(this._options.fastScrollSensitivity=e.fastScrollSensitivity),void 0!==e.scrollPredominantAxis&&(this._options.scrollPredominantAxis=e.scrollPredominantAxis),void 0!==e.horizontal&&(this._options.horizontal=e.horizontal),void 0!==e.vertical&&(this._options.vertical=e.vertical),void 0!==e.horizontalScrollbarSize&&(this._options.horizontalScrollbarSize=e.horizontalScrollbarSize),void 0!==e.verticalScrollbarSize&&(this._options.verticalScrollbarSize=e.verticalScrollbarSize),void 0!==e.scrollByPage&&(this._options.scrollByPage=e.scrollByPage),this._horizontalScrollbar.updateOptions(this._options),this._verticalScrollbar.updateOptions(this._options),this._options.lazyRender||this._render()}setRevealOnScroll(e){this._revealOnScroll=e}delegateScrollFromMouseWheelEvent(e){this._onMouseWheel(new h.StandardWheelEvent(e))}_setListeningToMouseWheel(e){if(this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=(0,p.dispose)(this._mouseWheelToDispose),e)){const e=e=>{this._onMouseWheel(new h.StandardWheelEvent(e))};this._mouseWheelToDispose.push(a.addDisposableListener(this._listenOnDomNode,a.EventType.MOUSE_WHEEL,e,{passive:!1}))}}_onMouseWheel(e){if(e.browserEvent?.defaultPrevented)return;const t=S.INSTANCE;t.acceptStandardWheelEvent(e);let i=!1;if(e.deltaY||e.deltaX){let s=e.deltaY*this._options.mouseWheelScrollSensitivity,r=e.deltaX*this._options.mouseWheelScrollSensitivity;this._options.scrollPredominantAxis&&(this._options.scrollYToX&&r+s===0?r=s=0:Math.abs(s)>=Math.abs(r)?r=0:s=0),this._options.flipAxes&&([s,r]=[r,s]);const n=!g.isMacintosh&&e.browserEvent&&e.browserEvent.shiftKey;!this._options.scrollYToX&&!n||r||(r=s,s=0),e.browserEvent&&e.browserEvent.altKey&&(r*=this._options.fastScrollSensitivity,s*=this._options.fastScrollSensitivity);const o=this._scrollable.getFutureScrollPosition();let a={};if(s){const e=50*s,t=o.scrollTop-(e<0?Math.floor(e):Math.ceil(e));this._verticalScrollbar.writeScrollPosition(a,t)}if(r){const e=50*r,t=o.scrollLeft-(e<0?Math.floor(e):Math.ceil(e));this._horizontalScrollbar.writeScrollPosition(a,t)}a=this._scrollable.validateScrollPosition(a),(o.scrollLeft!==a.scrollLeft||o.scrollTop!==a.scrollTop)&&(this._options.mouseWheelSmoothScroll&&t.isPhysicalMouseWheel()?this._scrollable.setScrollPositionSmooth(a):this._scrollable.setScrollPositionNow(a),i=!0)}let s=i;!s&&this._options.alwaysConsumeMouseWheel&&(s=!0),!s&&this._options.consumeMouseWheelIfScrollbarIsNeeded&&(this._verticalScrollbar.isNeeded()||this._horizontalScrollbar.isNeeded())&&(s=!0),s&&(e.preventDefault(),e.stopPropagation())}_onDidScroll(e){this._shouldRender=this._horizontalScrollbar.onDidScroll(e)||this._shouldRender,this._shouldRender=this._verticalScrollbar.onDidScroll(e)||this._shouldRender,this._options.useShadows&&(this._shouldRender=!0),this._revealOnScroll&&this._reveal(),this._options.lazyRender||this._render()}renderNow(){if(!this._options.lazyRender)throw new Error("Please use `lazyRender` together with `renderNow`!");this._render()}_render(){if(this._shouldRender&&(this._shouldRender=!1,this._horizontalScrollbar.render(),this._verticalScrollbar.render(),this._options.useShadows)){const e=this._scrollable.getCurrentScrollPosition(),t=e.scrollTop>0,i=e.scrollLeft>0,s=i?" left":"",r=t?" top":"",n=i||t?" top-left-corner":"";this._leftShadowDomNode.setClassName(`shadow${s}`),this._topShadowDomNode.setClassName(`shadow${r}`),this._topLeftShadowDomNode.setClassName(`shadow${n}${r}${s}`)}}_onDragStart(){this._isDragging=!0,this._reveal()}_onDragEnd(){this._isDragging=!1,this._hide()}_onMouseLeave(e){this._mouseIsOver=!1,this._hide()}_onMouseOver(e){this._mouseIsOver=!0,this._reveal()}_reveal(){this._verticalScrollbar.beginReveal(),this._horizontalScrollbar.beginReveal(),this._scheduleHide()}_hide(){this._mouseIsOver||this._isDragging||(this._verticalScrollbar.beginHide(),this._horizontalScrollbar.beginHide())}_scheduleHide(){this._mouseIsOver||this._isDragging||this._hideTimeout.cancelAndSet((()=>this._hide()),500)}}t.AbstractScrollableElement=b,t.ScrollableElement=class extends b{constructor(e,t){(t=t||{}).mouseWheelSmoothScroll=!1;const i=new m.Scrollable({forceIntegerValues:!0,smoothScrollDuration:0,scheduleAtNextAnimationFrame:t=>a.scheduleAtNextAnimationFrame(a.getWindow(e),t)});super(e,t,i),this._register(i)}setScrollPosition(e){this._scrollable.setScrollPositionNow(e)}getScrollPosition(){return this._scrollable.getCurrentScrollPosition()}},t.SmoothScrollableElement=class extends b{constructor(e,t,i){super(e,t,i)}setScrollPosition(e){e.reuseAnimation?this._scrollable.setScrollPositionSmooth(e,e.reuseAnimation):this._scrollable.setScrollPositionNow(e)}getScrollPosition(){return this._scrollable.getCurrentScrollPosition()}},t.DomScrollableElement=class extends b{constructor(e,t){(t=t||{}).mouseWheelSmoothScroll=!1;const i=new m.Scrollable({forceIntegerValues:!1,smoothScrollDuration:0,scheduleAtNextAnimationFrame:t=>a.scheduleAtNextAnimationFrame(a.getWindow(e),t)});super(e,t,i),this._register(i),this._element=e,this._register(this.onScroll((e=>{e.scrollTopChanged&&(this._element.scrollTop=e.scrollTop),e.scrollLeftChanged&&(this._element.scrollLeft=e.scrollLeft)}))),this.scanDomNode()}setScrollPosition(e){this._scrollable.setScrollPositionNow(e)}getScrollPosition(){return this._scrollable.getCurrentScrollPosition()}scanDomNode(){this.setScrollDimensions({width:this._element.clientWidth,scrollWidth:this._element.scrollWidth,height:this._element.clientHeight,scrollHeight:this._element.scrollHeight}),this.setScrollPosition({scrollLeft:this._element.scrollLeft,scrollTop:this._element.scrollTop})}}},8974:function(e,t,i){var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,r)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&s(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.ScrollbarArrow=t.ARROW_IMG_SIZE=void 0;const o=i(8328),a=i(8286),l=i(1758),h=n(i(7093));t.ARROW_IMG_SIZE=11;class c extends a.Widget{constructor(e){super(),this._onActivate=e.onActivate,this.bgDomNode=document.createElement("div"),this.bgDomNode.className="arrow-background",this.bgDomNode.style.position="absolute",this.bgDomNode.style.width=e.bgWidth+"px",this.bgDomNode.style.height=e.bgHeight+"px",void 0!==e.top&&(this.bgDomNode.style.top="0px"),void 0!==e.left&&(this.bgDomNode.style.left="0px"),void 0!==e.bottom&&(this.bgDomNode.style.bottom="0px"),void 0!==e.right&&(this.bgDomNode.style.right="0px"),this.domNode=document.createElement("div"),this.domNode.className=e.className,this.domNode.style.position="absolute",this.domNode.style.width=t.ARROW_IMG_SIZE+"px",this.domNode.style.height=t.ARROW_IMG_SIZE+"px",void 0!==e.top&&(this.domNode.style.top=e.top+"px"),void 0!==e.left&&(this.domNode.style.left=e.left+"px"),void 0!==e.bottom&&(this.domNode.style.bottom=e.bottom+"px"),void 0!==e.right&&(this.domNode.style.right=e.right+"px"),this._pointerMoveMonitor=this._register(new o.GlobalPointerMoveMonitor),this._register(h.addStandardDisposableListener(this.bgDomNode,h.EventType.POINTER_DOWN,(e=>this._arrowPointerDown(e)))),this._register(h.addStandardDisposableListener(this.domNode,h.EventType.POINTER_DOWN,(e=>this._arrowPointerDown(e)))),this._pointerdownRepeatTimer=this._register(new h.WindowIntervalTimer),this._pointerdownScheduleRepeatTimer=this._register(new l.TimeoutTimer)}_arrowPointerDown(e){e.target&&e.target instanceof Element&&(this._onActivate(),this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancelAndSet((()=>{this._pointerdownRepeatTimer.cancelAndSet((()=>this._onActivate()),1e3/24,h.getWindow(e))}),200),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,(e=>{}),(()=>{this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancel()})),e.preventDefault())}}t.ScrollbarArrow=c},8245:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ScrollbarState=void 0;class i{constructor(e,t,i,s,r,n){this._scrollbarSize=Math.round(t),this._oppositeScrollbarSize=Math.round(i),this._arrowSize=Math.round(e),this._visibleSize=s,this._scrollSize=r,this._scrollPosition=n,this._computedAvailableSize=0,this._computedIsNeeded=!1,this._computedSliderSize=0,this._computedSliderRatio=0,this._computedSliderPosition=0,this._refreshComputedValues()}clone(){return new i(this._arrowSize,this._scrollbarSize,this._oppositeScrollbarSize,this._visibleSize,this._scrollSize,this._scrollPosition)}setVisibleSize(e){const t=Math.round(e);return this._visibleSize!==t&&(this._visibleSize=t,this._refreshComputedValues(),!0)}setScrollSize(e){const t=Math.round(e);return this._scrollSize!==t&&(this._scrollSize=t,this._refreshComputedValues(),!0)}setScrollPosition(e){const t=Math.round(e);return this._scrollPosition!==t&&(this._scrollPosition=t,this._refreshComputedValues(),!0)}setScrollbarSize(e){this._scrollbarSize=Math.round(e)}setOppositeScrollbarSize(e){this._oppositeScrollbarSize=Math.round(e)}static _computeValues(e,t,i,s,r){const n=Math.max(0,i-e),o=Math.max(0,n-2*t),a=s>0&&s>i;if(!a)return{computedAvailableSize:Math.round(n),computedIsNeeded:a,computedSliderSize:Math.round(o),computedSliderRatio:0,computedSliderPosition:0};const l=Math.round(Math.max(20,Math.floor(i*o/s))),h=(o-l)/(s-i),c=r*h;return{computedAvailableSize:Math.round(n),computedIsNeeded:a,computedSliderSize:Math.round(l),computedSliderRatio:h,computedSliderPosition:Math.round(c)}}_refreshComputedValues(){const e=i._computeValues(this._oppositeScrollbarSize,this._arrowSize,this._visibleSize,this._scrollSize,this._scrollPosition);this._computedAvailableSize=e.computedAvailableSize,this._computedIsNeeded=e.computedIsNeeded,this._computedSliderSize=e.computedSliderSize,this._computedSliderRatio=e.computedSliderRatio,this._computedSliderPosition=e.computedSliderPosition}getArrowSize(){return this._arrowSize}getScrollPosition(){return this._scrollPosition}getRectangleLargeSize(){return this._computedAvailableSize}getRectangleSmallSize(){return this._scrollbarSize}isNeeded(){return this._computedIsNeeded}getSliderSize(){return this._computedSliderSize}getSliderPosition(){return this._computedSliderPosition}getDesiredScrollPositionFromOffset(e){if(!this._computedIsNeeded)return 0;const t=e-this._arrowSize-this._computedSliderSize/2;return Math.round(t/this._computedSliderRatio)}getDesiredScrollPositionFromOffsetPaged(e){if(!this._computedIsNeeded)return 0;const t=e-this._arrowSize;let i=this._scrollPosition;return t{Object.defineProperty(t,"__esModule",{value:!0}),t.ScrollbarVisibilityController=void 0;const s=i(1758),r=i(7150),n=i(9881);class o extends r.Disposable{constructor(e,t,i){super(),this._visibility=e,this._visibleClassName=t,this._invisibleClassName=i,this._domNode=null,this._isVisible=!1,this._isNeeded=!1,this._rawShouldBeVisible=!1,this._shouldBeVisible=!1,this._revealTimer=this._register(new s.TimeoutTimer)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this._updateShouldBeVisible())}setShouldBeVisible(e){this._rawShouldBeVisible=e,this._updateShouldBeVisible()}_applyVisibilitySetting(){return this._visibility!==n.ScrollbarVisibility.Hidden&&(this._visibility===n.ScrollbarVisibility.Visible||this._rawShouldBeVisible)}_updateShouldBeVisible(){const e=this._applyVisibilitySetting();this._shouldBeVisible!==e&&(this._shouldBeVisible=e,this.ensureVisibility())}setIsNeeded(e){this._isNeeded!==e&&(this._isNeeded=e,this.ensureVisibility())}setDomNode(e){this._domNode=e,this._domNode.setClassName(this._invisibleClassName),this.setShouldBeVisible(!1)}ensureVisibility(){this._isNeeded?this._shouldBeVisible?this._reveal():this._hide(!0):this._hide(!1)}_reveal(){this._isVisible||(this._isVisible=!0,this._revealTimer.setIfNotSet((()=>{this._domNode?.setClassName(this._visibleClassName)}),0))}_hide(e){this._revealTimer.cancel(),this._isVisible&&(this._isVisible=!1,this._domNode?.setClassName(this._invisibleClassName+(e?" fade":"")))}}t.ScrollbarVisibilityController=o},5473:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.VerticalScrollbar=void 0;const s=i(8801),r=i(8245),n=i(9881);class o extends s.AbstractScrollbar{constructor(e,t,i){const s=e.getScrollDimensions(),o=e.getCurrentScrollPosition();if(super({lazyRender:t.lazyRender,host:i,scrollbarState:new r.ScrollbarState(t.verticalHasArrows?t.arrowSize:0,t.vertical===n.ScrollbarVisibility.Hidden?0:t.verticalScrollbarSize,0,s.height,s.scrollHeight,o.scrollTop),visibility:t.vertical,extraScrollbarClassName:"vertical",scrollable:e,scrollByPage:t.scrollByPage}),t.verticalHasArrows)throw new Error("horizontalHasArrows is not supported in xterm.js");this._createSlider(0,Math.floor((t.verticalScrollbarSize-t.verticalSliderSize)/2),t.verticalSliderSize,void 0)}_updateSlider(e,t){this.slider.setHeight(e),this.slider.setTop(t)}_renderDomNode(e,t){this.domNode.setWidth(t),this.domNode.setHeight(e),this.domNode.setRight(0),this.domNode.setTop(0)}onDidScroll(e){return this._shouldRender=this._onElementScrollSize(e.scrollHeight)||this._shouldRender,this._shouldRender=this._onElementScrollPosition(e.scrollTop)||this._shouldRender,this._shouldRender=this._onElementSize(e.height)||this._shouldRender,this._shouldRender}_pointerDownRelativePosition(e,t){return t}_sliderPointerPosition(e){return e.pageY}_sliderOrthogonalPointerPosition(e){return e.pageX}_updateScrollbarSize(e){this.slider.setWidth(e)}writeScrollPosition(e,t){e.scrollTop=t}updateOptions(e){this.updateScrollbarSize(e.vertical===n.ScrollbarVisibility.Hidden?0:e.verticalScrollbarSize),this._scrollbarState.setOppositeScrollbarSize(0),this._visibilityController.setVisibility(e.vertical),this._scrollByPage=e.scrollByPage}}t.VerticalScrollbar=o},8286:function(e,t,i){var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,r)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&s(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.Widget=void 0;const o=n(i(7093)),a=i(5394),l=i(5964),h=i(8594),c=i(7150);class d extends c.Disposable{onclick(e,t){this._register(o.addDisposableListener(e,o.EventType.CLICK,(i=>t(new l.StandardMouseEvent(o.getWindow(e),i)))))}onmousedown(e,t){this._register(o.addDisposableListener(e,o.EventType.MOUSE_DOWN,(i=>t(new l.StandardMouseEvent(o.getWindow(e),i)))))}onmouseover(e,t){this._register(o.addDisposableListener(e,o.EventType.MOUSE_OVER,(i=>t(new l.StandardMouseEvent(o.getWindow(e),i)))))}onmouseleave(e,t){this._register(o.addDisposableListener(e,o.EventType.MOUSE_LEAVE,(i=>t(new l.StandardMouseEvent(o.getWindow(e),i)))))}onkeydown(e,t){this._register(o.addDisposableListener(e,o.EventType.KEY_DOWN,(e=>t(new a.StandardKeyboardEvent(e)))))}onkeyup(e,t){this._register(o.addDisposableListener(e,o.EventType.KEY_UP,(e=>t(new a.StandardKeyboardEvent(e)))))}oninput(e,t){this._register(o.addDisposableListener(e,o.EventType.INPUT,t))}onblur(e,t){this._register(o.addDisposableListener(e,o.EventType.BLUR,t))}onfocus(e,t){this._register(o.addDisposableListener(e,o.EventType.FOCUS,t))}onchange(e,t){this._register(o.addDisposableListener(e,o.EventType.CHANGE,t))}ignoreGesture(e){return h.Gesture.ignoreTarget(e)}}t.Widget=d},4693:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mainWindow=void 0,t.ensureCodeWindow=function(e,t){},t.mainWindow="object"==typeof window?window:globalThis},3058:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Permutation=t.CallbackIterable=t.ArrayQueue=t.booleanComparator=t.numberComparator=t.CompareResult=void 0,t.tail=function(e,t=0){return e[e.length-(1+t)]},t.tail2=function(e){if(0===e.length)throw new Error("Invalid tail call");return[e.slice(0,e.length-1),e[e.length-1]]},t.equals=function(e,t,i=(e,t)=>e===t){if(e===t)return!0;if(!e||!t)return!1;if(e.length!==t.length)return!1;for(let s=0,r=e.length;si(e[s],t)))},t.binarySearch2=n,t.quickSelect=function e(t,i,s){if((t|=0)>=i.length)throw new TypeError("invalid index");const r=i[Math.floor(i.length*Math.random())],n=[],o=[],a=[];for(const e of i){const t=s(e,r);t<0?n.push(e):t>0?o.push(e):a.push(e)}return t{(async()=>{const o=e.length,l=e.slice(0,i).sort(t);for(let h=i,c=Math.min(i+r,o);hi&&await new Promise((e=>setTimeout(e))),n&&n.isCancellationRequested)throw new s.CancellationError;a(e,t,l,h,c)}return l})().then(o,l)}))},t.coalesce=function(e){return e.filter((e=>!!e))},t.coalesceInPlace=function(e){let t=0;for(let i=0;i0},t.distinct=function(e,t=e=>e){const i=new Set;return e.filter((e=>{const s=t(e);return!i.has(s)&&(i.add(s),!0)}))},t.uniqueFilter=function(e){const t=new Set;return i=>{const s=e(i);return!t.has(s)&&(t.add(s),!0)}},t.firstOrDefault=function(e,t){return e.length>0?e[0]:t},t.lastOrDefault=function(e,t){return e.length>0?e[e.length-1]:t},t.commonPrefixLength=function(e,t,i=(e,t)=>e===t){let s=0;for(let r=0,n=Math.min(e.length,t.length);rt;e--)s.push(e);return s},t.index=function(e,t,i){return e.reduce(((e,s)=>(e[t(s)]=i?i(s):s,e)),Object.create(null))},t.insert=function(e,t){return e.push(t),()=>l(e,t)},t.remove=l,t.arrayInsert=function(e,t,i){const s=e.slice(0,t),r=e.slice(t);return s.concat(i,r)},t.shuffle=function(e,t){let i;if("number"==typeof t){let e=t;i=()=>{const t=179426549*Math.sin(e++);return t-Math.floor(t)}}else i=Math.random;for(let t=e.length-1;t>0;t-=1){const s=Math.floor(i()*(t+1)),r=e[t];e[t]=e[s],e[s]=r}},t.pushToStart=function(e,t){const i=e.indexOf(t);i>-1&&(e.splice(i,1),e.unshift(t))},t.pushToEnd=function(e,t){const i=e.indexOf(t);i>-1&&(e.splice(i,1),e.push(t))},t.pushMany=function(e,t){for(const i of t)e.push(i)},t.mapArrayOrNot=function(e,t){return Array.isArray(e)?e.map(t):t(e)},t.asArray=function(e){return Array.isArray(e)?e:[e]},t.getRandomElement=function(e){return e[Math.floor(Math.random()*e.length)]},t.insertInto=h,t.splice=function(e,t,i,s){const r=c(e,t);let n=e.splice(r,i);return void 0===n&&(n=[]),h(e,r,s),n},t.compareBy=function(e,t){return(i,s)=>t(e(i),e(s))},t.tieBreakComparators=function(...e){return(t,i)=>{for(const s of e){const e=s(t,i);if(!d.isNeitherLessOrGreaterThan(e))return e}return d.neitherLessOrGreaterThan}},t.reverseOrder=function(e){return(t,i)=>-e(t,i)};const s=i(9807),r=i(8297);function n(e,t){let i=0,s=e-1;for(;i<=s;){const e=(i+s)/2|0,r=t(e);if(r<0)i=e+1;else{if(!(r>0))return e;s=e-1}}return-(i+1)}function o(e,t,i){const s=[];function r(e,t,i){if(0===t&&0===i.length)return;const r=s[s.length-1];r&&r.start+r.deleteCount===e?(r.deleteCount+=t,r.toInsert.push(...i)):s.push({start:e,deleteCount:t,toInsert:i})}let n=0,o=0;for(;;){if(n===e.length){r(n,0,t.slice(o));break}if(o===t.length){r(n,e.length-n,[]);break}const s=e[n],a=t[o],l=i(s,a);0===l?(n+=1,o+=1):l<0?(r(n,1,[]),n+=1):l>0&&(r(n,0,[a]),o+=1)}return s}function a(e,t,i,s,n){for(const o=i.length;st(n,e)<0));i.splice(e,0,n)}}}function l(e,t){const i=e.indexOf(t);if(i>-1)return e.splice(i,1),t}function h(e,t,i){const s=c(e,t),r=e.length,n=i.length;e.length=r+n;for(let t=r-1;t>=s;t--)e[t+n]=e[t];for(let t=0;t0},e.isNeitherLessOrGreaterThan=function(e){return 0===e},e.greaterThan=1,e.lessThan=-1,e.neitherLessOrGreaterThan=0}(d||(t.CompareResult=d={})),t.numberComparator=(e,t)=>e-t,t.booleanComparator=(e,i)=>(0,t.numberComparator)(e?1:0,i?1:0),t.ArrayQueue=class{constructor(e){this.items=e,this.firstIdx=0,this.lastIdx=this.items.length-1}get length(){return this.lastIdx-this.firstIdx+1}takeWhile(e){let t=this.firstIdx;for(;t=0&&e(this.items[t]);)t--;const i=t===this.lastIdx?null:this.items.slice(t+1,this.lastIdx+1);return this.lastIdx=t,i}peek(){if(0!==this.length)return this.items[this.firstIdx]}peekLast(){if(0!==this.length)return this.items[this.lastIdx]}dequeue(){const e=this.items[this.firstIdx];return this.firstIdx++,e}removeLast(){const e=this.items[this.lastIdx];return this.lastIdx--,e}takeCount(e){const t=this.items.slice(this.firstIdx,this.firstIdx+e);return this.firstIdx+=e,t}};class u{static{this.empty=new u((e=>{}))}constructor(e){this.iterate=e}forEach(e){this.iterate((t=>(e(t),!0)))}toArray(){const e=[];return this.iterate((t=>(e.push(t),!0))),e}filter(e){return new u((t=>this.iterate((i=>!e(i)||t(i)))))}map(e){return new u((t=>this.iterate((i=>t(e(i))))))}some(e){let t=!1;return this.iterate((i=>(t=e(i),!t))),t}findFirst(e){let t;return this.iterate((i=>!e(i)||(t=i,!1))),t}findLast(e){let t;return this.iterate((i=>(e(i)&&(t=i),!0))),t}findLastMaxBy(e){let t,i=!0;return this.iterate((s=>((i||d.isGreaterThan(e(s,t)))&&(i=!1,t=s),!0))),t}}t.CallbackIterable=u;class _{constructor(e){this._indexMap=e}static createSortPermutation(e,t){const i=Array.from(e.keys()).sort(((i,s)=>t(e[i],e[s])));return new _(i)}apply(e){return e.map(((t,i)=>e[this._indexMap[i]]))}inverse(){const e=this._indexMap.slice();for(let t=0;t{function i(e,t,i=e.length-1){for(let s=i;s>=0;s--)if(t(e[s]))return s;return-1}function s(e,t,i=0,s=e.length){let r=i,n=s;for(;r=0&&(i=r)}return i},t.findFirstMin=function(e,t){return o(e,((e,i)=>-t(e,i)))},t.findMaxIdx=function(e,t){if(0===e.length)return-1;let i=0;for(let s=1;s0&&(i=s);return i},t.mapFindFirst=function(e,t){for(const i of e){const e=t(i);if(void 0!==e)return e}};class n{static{this.assertInvariants=!1}constructor(e){this._array=e,this._findLastMonotonousLastIdx=0}findLastMonotonous(e){if(n.assertInvariants){if(this._prevFindLastPredicate)for(const t of this._array)if(this._prevFindLastPredicate(t)&&!e(t))throw new Error("MonotonousArray: current predicate must be weaker than (or equal to) the previous predicate.");this._prevFindLastPredicate=e}const t=s(this._array,e,this._findLastMonotonousLastIdx);return this._findLastMonotonousLastIdx=t+1,-1===t?void 0:this._array[t]}}function o(e,t){if(0===e.length)return;let i=e[0];for(let s=1;s0&&(i=r)}return i}t.MonotonousArray=n},1758:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AsyncIterableSource=t.CancelableAsyncIterableObject=t.AsyncIterableObject=t.LazyStatefulPromise=t.StatefulPromise=t.Promises=t.DeferredPromise=t.IntervalCounter=t.TaskSequentializer=t.GlobalIdleValue=t.AbstractIdleValue=t._runWhenIdle=t.runWhenGlobalIdle=t.ThrottledWorker=t.RunOnceWorker=t.ProcessTimeRunOnceScheduler=t.RunOnceScheduler=t.IntervalTimer=t.TimeoutTimer=t.LimitedQueue=t.Queue=t.Limiter=t.AutoOpenBarrier=t.Barrier=t.ThrottledDelayer=t.Delayer=t.SequencerByKey=t.Sequencer=t.Throttler=void 0,t.isThenable=c,t.createCancelablePromise=d,t.raceCancellation=function(e,t,i){return new Promise(((s,r)=>{const n=t.onCancellationRequested((()=>{n.dispose(),s(i)}));e.then(s,r).finally((()=>n.dispose()))}))},t.raceCancellationError=function(e,t){return new Promise(((i,s)=>{const n=t.onCancellationRequested((()=>{n.dispose(),s(new r.CancellationError)}));e.then(i,s).finally((()=>n.dispose()))}))},t.raceCancellablePromises=async function(e){let t=-1;const i=e.map(((e,i)=>e.then((e=>(t=i,e)))));try{return await Promise.race(i)}finally{e.forEach(((e,i)=>{i!==t&&e.cancel()}))}},t.raceTimeout=function(e,t,i){let s;const r=setTimeout((()=>{s?.(void 0),i?.()}),t);return Promise.race([e.finally((()=>clearTimeout(r))),new Promise((e=>s=e))])},t.asPromise=function(e){return new Promise(((t,i)=>{const s=e();c(s)?s.then(t,i):t(s)}))},t.promiseWithResolvers=u,t.timeout=g,t.disposableTimeout=function(e,t=0,i){const s=setTimeout((()=>{e(),i&&r.dispose()}),t),r=(0,o.toDisposable)((()=>{clearTimeout(s),i?.deleteAndLeak(r)}));return i?.add(r),r},t.sequence=function(e){const t=[];let i=0;const s=e.length;return Promise.resolve(null).then((function r(n){null!=n&&t.push(n);const o=i!!e,i=null){let s=0;const r=e.length,n=()=>{if(s>=r)return Promise.resolve(i);const o=e[s++];return Promise.resolve(o()).then((e=>t(e)?Promise.resolve(e):n()))};return n()},t.firstParallel=function(e,t=e=>!!e,i=null){if(0===e.length)return Promise.resolve(i);let s=e.length;const r=()=>{s=-1;for(const t of e)t.cancel?.()};return new Promise(((n,o)=>{for(const a of e)a.then((e=>{--s>=0&&t(e)?(r(),n(e)):0===s&&n(i)})).catch((e=>{--s>=0&&(r(),o(e))}))}))},t.retry=async function(e,t,i){let s;for(let r=0;r{const s=t.token.onCancellationRequested((()=>{s.dispose(),t.dispose(),e.reject(new r.CancellationError)}));try{for await(const s of i){if(t.token.isCancellationRequested)return;e.emitOne(s)}s.dispose(),t.dispose()}catch(i){s.dispose(),t.dispose(),e.reject(i)}}))};const s=i(8447),r=i(9807),n=i(802),o=i(7150),a=i(8163),l=i(5015),h=i(626);function c(e){return!!e&&"function"==typeof e.then}function d(e){const t=new s.CancellationTokenSource,i=e(t.token),n=new Promise(((e,s)=>{const n=t.token.onCancellationRequested((()=>{n.dispose(),s(new r.CancellationError)}));Promise.resolve(i).then((i=>{n.dispose(),t.dispose(),e(i)}),(e=>{n.dispose(),t.dispose(),s(e)}))}));return new class{cancel(){t.cancel(),t.dispose()}then(e,t){return n.then(e,t)}catch(e){return this.then(void 0,e)}finally(e){return n.finally(e)}}}function u(){let e,t;return{promise:new Promise(((i,s)=>{e=i,t=s})),resolve:e,reject:t}}class _{constructor(){this.isDisposed=!1,this.activePromise=null,this.queuedPromise=null,this.queuedPromiseFactory=null}queue(e){if(this.isDisposed)return Promise.reject(new Error("Throttler is disposed"));if(this.activePromise){if(this.queuedPromiseFactory=e,!this.queuedPromise){const e=()=>{if(this.queuedPromise=null,this.isDisposed)return;const e=this.queue(this.queuedPromiseFactory);return this.queuedPromiseFactory=null,e};this.queuedPromise=new Promise((t=>{this.activePromise.then(e,e).then(t)}))}return new Promise(((e,t)=>{this.queuedPromise.then(e,t)}))}return this.activePromise=e(),new Promise(((e,t)=>{this.activePromise.then((t=>{this.activePromise=null,e(t)}),(e=>{this.activePromise=null,t(e)}))}))}dispose(){this.isDisposed=!0}}t.Throttler=_,t.Sequencer=class{constructor(){this.current=Promise.resolve(null)}queue(e){return this.current=this.current.then((()=>e()),(()=>e()))}},t.SequencerByKey=class{constructor(){this.promiseMap=new Map}queue(e,t){const i=(this.promiseMap.get(e)??Promise.resolve()).catch((()=>{})).then(t).finally((()=>{this.promiseMap.get(e)===i&&this.promiseMap.delete(e)}));return this.promiseMap.set(e,i),i}};class f{constructor(e){this.defaultDelay=e,this.deferred=null,this.completionPromise=null,this.doResolve=null,this.doReject=null,this.task=null}trigger(e,t=this.defaultDelay){this.task=e,this.cancelTimeout(),this.completionPromise||(this.completionPromise=new Promise(((e,t)=>{this.doResolve=e,this.doReject=t})).then((()=>{if(this.completionPromise=null,this.doResolve=null,this.task){const e=this.task;return this.task=null,e()}})));const i=()=>{this.deferred=null,this.doResolve?.(null)};return this.deferred=t===l.MicrotaskDelay?(e=>{let t=!0;return queueMicrotask((()=>{t&&(t=!1,e())})),{isTriggered:()=>t,dispose:()=>{t=!1}}})(i):((e,t)=>{let i=!0;const s=setTimeout((()=>{i=!1,t()}),e);return{isTriggered:()=>i,dispose:()=>{clearTimeout(s),i=!1}}})(t,i),this.completionPromise}isTriggered(){return!!this.deferred?.isTriggered()}cancel(){this.cancelTimeout(),this.completionPromise&&(this.doReject?.(new r.CancellationError),this.completionPromise=null)}cancelTimeout(){this.deferred?.dispose(),this.deferred=null}dispose(){this.cancel()}}t.Delayer=f,t.ThrottledDelayer=class{constructor(e){this.delayer=new f(e),this.throttler=new _}trigger(e,t){return this.delayer.trigger((()=>this.throttler.queue(e)),t)}isTriggered(){return this.delayer.isTriggered()}cancel(){this.delayer.cancel()}dispose(){this.delayer.dispose(),this.throttler.dispose()}};class p{constructor(){this._isOpen=!1,this._promise=new Promise(((e,t)=>{this._completePromise=e}))}isOpen(){return this._isOpen}open(){this._isOpen=!0,this._completePromise(!0)}wait(){return this._promise}}function g(e,t){return t?new Promise(((i,s)=>{const n=setTimeout((()=>{o.dispose(),i()}),e),o=t.onCancellationRequested((()=>{clearTimeout(n),o.dispose(),s(new r.CancellationError)}))})):d((t=>g(e,t)))}t.Barrier=p,t.AutoOpenBarrier=class extends p{constructor(e){super(),this._timeout=setTimeout((()=>this.open()),e)}open(){clearTimeout(this._timeout),super.open()}};class m{constructor(e){this._size=0,this._isDisposed=!1,this.maxDegreeOfParalellism=e,this.outstandingPromises=[],this.runningPromises=0,this._onDrained=new n.Emitter}whenIdle(){return this.size>0?n.Event.toPromise(this.onDrained):Promise.resolve()}get onDrained(){return this._onDrained.event}get size(){return this._size}queue(e){if(this._isDisposed)throw new Error("Object has been disposed");return this._size++,new Promise(((t,i)=>{this.outstandingPromises.push({factory:e,c:t,e:i}),this.consume()}))}consume(){for(;this.outstandingPromises.length&&this.runningPromisesthis.consumed()),(()=>this.consumed()))}}consumed(){this._isDisposed||(this.runningPromises--,0==--this._size&&this._onDrained.fire(),this.outstandingPromises.length>0&&this.consume())}clear(){if(this._isDisposed)throw new Error("Object has been disposed");this.outstandingPromises.length=0,this._size=this.runningPromises}dispose(){this._isDisposed=!0,this.outstandingPromises.length=0,this._size=0,this._onDrained.dispose()}}t.Limiter=m,t.Queue=class extends m{constructor(){super(1)}},t.LimitedQueue=class{constructor(){this.sequentializer=new C,this.tasks=0}queue(e){return this.sequentializer.isRunning()?this.sequentializer.queue((()=>this.sequentializer.run(this.tasks++,e()))):this.sequentializer.run(this.tasks++,e())}},t.TimeoutTimer=class{constructor(e,t){this._isDisposed=!1,this._token=-1,"function"==typeof e&&"number"==typeof t&&this.setIfNotSet(e,t)}dispose(){this.cancel(),this._isDisposed=!0}cancel(){-1!==this._token&&(clearTimeout(this._token),this._token=-1)}cancelAndSet(e,t){if(this._isDisposed)throw new r.BugIndicatingError("Calling 'cancelAndSet' on a disposed TimeoutTimer");this.cancel(),this._token=setTimeout((()=>{this._token=-1,e()}),t)}setIfNotSet(e,t){if(this._isDisposed)throw new r.BugIndicatingError("Calling 'setIfNotSet' on a disposed TimeoutTimer");-1===this._token&&(this._token=setTimeout((()=>{this._token=-1,e()}),t))}},t.IntervalTimer=class{constructor(){this.disposable=void 0,this.isDisposed=!1}cancel(){this.disposable?.dispose(),this.disposable=void 0}cancelAndSet(e,t,i=globalThis){if(this.isDisposed)throw new r.BugIndicatingError("Calling 'cancelAndSet' on a disposed IntervalTimer");this.cancel();const s=i.setInterval((()=>{e()}),t);this.disposable=(0,o.toDisposable)((()=>{i.clearInterval(s),this.disposable=void 0}))}dispose(){this.cancel(),this.isDisposed=!0}};class v{constructor(e,t){this.timeoutToken=-1,this.runner=e,this.timeout=t,this.timeoutHandler=this.onTimeout.bind(this)}dispose(){this.cancel(),this.runner=null}cancel(){this.isScheduled()&&(clearTimeout(this.timeoutToken),this.timeoutToken=-1)}schedule(e=this.timeout){this.cancel(),this.timeoutToken=setTimeout(this.timeoutHandler,e)}get delay(){return this.timeout}set delay(e){this.timeout=e}isScheduled(){return-1!==this.timeoutToken}flush(){this.isScheduled()&&(this.cancel(),this.doRun())}onTimeout(){this.timeoutToken=-1,this.runner&&this.doRun()}doRun(){this.runner?.()}}t.RunOnceScheduler=v,t.ProcessTimeRunOnceScheduler=class{constructor(e,t){t%1e3!=0&&console.warn(`ProcessTimeRunOnceScheduler resolution is 1s, ${t}ms is not a multiple of 1000ms.`),this.runner=e,this.timeout=t,this.counter=0,this.intervalToken=-1,this.intervalHandler=this.onInterval.bind(this)}dispose(){this.cancel(),this.runner=null}cancel(){this.isScheduled()&&(clearInterval(this.intervalToken),this.intervalToken=-1)}schedule(e=this.timeout){e%1e3!=0&&console.warn(`ProcessTimeRunOnceScheduler resolution is 1s, ${e}ms is not a multiple of 1000ms.`),this.cancel(),this.counter=Math.ceil(e/1e3),this.intervalToken=setInterval(this.intervalHandler,1e3)}isScheduled(){return-1!==this.intervalToken}onInterval(){this.counter--,this.counter>0||(clearInterval(this.intervalToken),this.intervalToken=-1,this.runner?.())}},t.RunOnceWorker=class extends v{constructor(e,t){super(e,t),this.units=[]}work(e){this.units.push(e),this.isScheduled()||this.schedule()}doRun(){const e=this.units;this.units=[],this.runner?.(e)}dispose(){this.units=[],super.dispose()}};class S extends o.Disposable{constructor(e,t){super(),this.options=e,this.handler=t,this.pendingWork=[],this.throttler=this._register(new o.MutableDisposable),this.disposed=!1}get pending(){return this.pendingWork.length}work(e){if(this.disposed)return!1;if("number"==typeof this.options.maxBufferedWork)if(this.throttler.value){if(this.pending+e.length>this.options.maxBufferedWork)return!1}else if(this.pending+e.length-this.options.maxWorkChunkSize>this.options.maxBufferedWork)return!1;for(const t of e)this.pendingWork.push(t);return this.throttler.value||this.doWork(),!0}doWork(){this.handler(this.pendingWork.splice(0,this.options.maxWorkChunkSize)),this.pendingWork.length>0&&(this.throttler.value=new v((()=>{this.throttler.clear(),this.doWork()}),this.options.throttleDelay),this.throttler.value.schedule())}dispose(){super.dispose(),this.disposed=!0}}t.ThrottledWorker=S,"function"!=typeof globalThis.requestIdleCallback||"function"!=typeof globalThis.cancelIdleCallback?t._runWhenIdle=(e,t)=>{(0,a.setTimeout0)((()=>{if(i)return;const e=Date.now()+15,s={didTimeout:!0,timeRemaining:()=>Math.max(0,e-Date.now())};t(Object.freeze(s))}));let i=!1;return{dispose(){i||(i=!0)}}}:t._runWhenIdle=(e,t,i)=>{const s=e.requestIdleCallback(t,"number"==typeof i?{timeout:i}:void 0);let r=!1;return{dispose(){r||(r=!0,e.cancelIdleCallback(s))}}},t.runWhenGlobalIdle=e=>(0,t._runWhenIdle)(globalThis,e);class b{constructor(e,i){this._didRun=!1,this._executor=()=>{try{this._value=i()}catch(e){this._error=e}finally{this._didRun=!0}},this._handle=(0,t._runWhenIdle)(e,(()=>this._executor()))}dispose(){this._handle.dispose()}get value(){if(this._didRun||(this._handle.dispose(),this._executor()),this._error)throw this._error;return this._value}get isInitialized(){return this._didRun}}t.AbstractIdleValue=b,t.GlobalIdleValue=class extends b{constructor(e){super(globalThis,e)}};class C{isRunning(e){return"number"==typeof e?this._running?.taskId===e:!!this._running}get running(){return this._running?.promise}cancelRunning(){this._running?.cancel()}run(e,t,i){return this._running={taskId:e,cancel:()=>i?.(),promise:t},t.then((()=>this.doneRunning(e)),(()=>this.doneRunning(e))),t}doneRunning(e){this._running&&e===this._running.taskId&&(this._running=void 0,this.runQueued())}runQueued(){if(this._queued){const e=this._queued;this._queued=void 0,e.run().then(e.promiseResolve,e.promiseReject)}}queue(e){if(this._queued)this._queued.run=e;else{const{promise:t,resolve:i,reject:s}=u();this._queued={run:e,promise:t,promiseResolve:i,promiseReject:s}}return this._queued.promise}hasQueued(){return!!this._queued}async join(){return this._queued?.promise??this._running?.promise}}var y,w,E;t.TaskSequentializer=C,t.IntervalCounter=class{constructor(e,t=()=>Date.now()){this.interval=e,this.nowFn=t,this.lastIncrementTime=0,this.value=0}increment(){const e=this.nowFn();return e-this.lastIncrementTime>this.interval&&(this.lastIncrementTime=e,this.value=0),this.value++,this.value}},function(e){e[e.Resolved=0]="Resolved",e[e.Rejected=1]="Rejected"}(y||(y={}));class D{get isRejected(){return this.outcome?.outcome===y.Rejected}get isResolved(){return this.outcome?.outcome===y.Resolved}get isSettled(){return!!this.outcome}get value(){return this.outcome?.outcome===y.Resolved?this.outcome?.value:void 0}constructor(){this.p=new Promise(((e,t)=>{this.completeCallback=e,this.errorCallback=t}))}complete(e){return new Promise((t=>{this.completeCallback(e),this.outcome={outcome:y.Resolved,value:e},t()}))}error(e){return new Promise((t=>{this.errorCallback(e),this.outcome={outcome:y.Rejected,value:e},t()}))}cancel(){return this.error(new r.CancellationError)}}t.DeferredPromise=D,function(e){e.settled=async function(e){let t;const i=await Promise.all(e.map((e=>e.then((e=>e),(e=>{t||(t=e)})))));if(void 0!==t)throw t;return i},e.withAsyncBody=function(e){return new Promise((async(t,i)=>{try{await e(t,i)}catch(e){i(e)}}))}}(w||(t.Promises=w={}));class L{get value(){return this._value}get error(){return this._error}get isResolved(){return this._isResolved}constructor(e){this._value=void 0,this._error=void 0,this._isResolved=!1,this.promise=e.then((e=>(this._value=e,this._isResolved=!0,e)),(e=>{throw this._error=e,this._isResolved=!0,e}))}requireValue(){if(!this._isResolved)throw new r.BugIndicatingError("Promise is not resolved yet");if(this._error)throw this._error;return this._value}}t.StatefulPromise=L,t.LazyStatefulPromise=class{constructor(e){this._compute=e,this._promise=new h.Lazy((()=>new L(this._compute())))}requireValue(){return this._promise.value.requireValue()}getPromise(){return this._promise.value.promise}get currentValue(){return this._promise.rawValue?.value}},function(e){e[e.Initial=0]="Initial",e[e.DoneOK=1]="DoneOK",e[e.DoneError=2]="DoneError"}(E||(E={}));class R{static fromArray(e){return new R((t=>{t.emitMany(e)}))}static fromPromise(e){return new R((async t=>{t.emitMany(await e)}))}static fromPromises(e){return new R((async t=>{await Promise.all(e.map((async e=>t.emitOne(await e))))}))}static merge(e){return new R((async t=>{await Promise.all(e.map((async e=>{for await(const i of e)t.emitOne(i)})))}))}static{this.EMPTY=R.fromArray([])}constructor(e,t){this._state=E.Initial,this._results=[],this._error=null,this._onReturn=t,this._onStateChanged=new n.Emitter,queueMicrotask((async()=>{const t={emitOne:e=>this.emitOne(e),emitMany:e=>this.emitMany(e),reject:e=>this.reject(e)};try{await Promise.resolve(e(t)),this.resolve()}catch(e){this.reject(e)}finally{t.emitOne=void 0,t.emitMany=void 0,t.reject=void 0}}))}[Symbol.asyncIterator](){let e=0;return{next:async()=>{for(;;){if(this._state===E.DoneError)throw this._error;if(e(this._onReturn?.(),{done:!0,value:void 0})}}static map(e,t){return new R((async i=>{for await(const s of e)i.emitOne(t(s))}))}map(e){return R.map(this,e)}static filter(e,t){return new R((async i=>{for await(const s of e)t(s)&&i.emitOne(s)}))}filter(e){return R.filter(this,e)}static coalesce(e){return R.filter(e,(e=>!!e))}coalesce(){return R.coalesce(this)}static async toPromise(e){const t=[];for await(const i of e)t.push(i);return t}toPromise(){return R.toPromise(this)}emitOne(e){this._state===E.Initial&&(this._results.push(e),this._onStateChanged.fire())}emitMany(e){this._state===E.Initial&&(this._results=this._results.concat(e),this._onStateChanged.fire())}resolve(){this._state===E.Initial&&(this._state=E.DoneOK,this._onStateChanged.fire())}reject(e){this._state===E.Initial&&(this._state=E.DoneError,this._error=e,this._onStateChanged.fire())}}t.AsyncIterableObject=R;class A extends R{constructor(e,t){super(t),this._source=e}cancel(){this._source.cancel()}}t.CancelableAsyncIterableObject=A,t.AsyncIterableSource=class{constructor(e){let t,i;this._deferred=new D,this._asyncIterable=new R((e=>{if(!t)return i&&e.emitMany(i),this._errorFn=t=>e.reject(t),this._emitFn=t=>e.emitOne(t),this._deferred.p;e.reject(t)}),e),this._emitFn=e=>{i||(i=[]),i.push(e)},this._errorFn=e=>{t||(t=e)}}get asyncIterable(){return this._asyncIterable}resolve(){this._deferred.complete()}reject(e){this._errorFn(e),this._deferred.complete()}emitOne(e){this._emitFn(e)}}},8447:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CancellationTokenSource=t.CancellationToken=void 0,t.cancelOnDispose=function(e){const t=new a;return e.add({dispose(){t.cancel()}}),t.token};const s=i(802),r=Object.freeze((function(e,t){const i=setTimeout(e.bind(t),0);return{dispose(){clearTimeout(i)}}}));var n;!function(e){e.isCancellationToken=function(t){return t===e.None||t===e.Cancelled||t instanceof o||!(!t||"object"!=typeof t)&&"boolean"==typeof t.isCancellationRequested&&"function"==typeof t.onCancellationRequested},e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:s.Event.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:r})}(n||(t.CancellationToken=n={}));class o{constructor(){this._isCancelled=!1,this._emitter=null}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?r:(this._emitter||(this._emitter=new s.Emitter),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=null)}}class a{constructor(e){this._token=void 0,this._parentListener=void 0,this._parentListener=e&&e.onCancellationRequested(this.cancel,this)}get token(){return this._token||(this._token=new o),this._token}cancel(){this._token?this._token instanceof o&&this._token.cancel():this._token=n.Cancelled}dispose(e=!1){e&&this.cancel(),this._parentListener?.dispose(),this._token?this._token instanceof o&&this._token.dispose():this._token=n.None}}t.CancellationTokenSource=a},4869:(e,t)=>{var i;Object.defineProperty(t,"__esModule",{value:!0}),t.CharCode=void 0,function(e){e[e.Null=0]="Null",e[e.Backspace=8]="Backspace",e[e.Tab=9]="Tab",e[e.LineFeed=10]="LineFeed",e[e.CarriageReturn=13]="CarriageReturn",e[e.Space=32]="Space",e[e.ExclamationMark=33]="ExclamationMark",e[e.DoubleQuote=34]="DoubleQuote",e[e.Hash=35]="Hash",e[e.DollarSign=36]="DollarSign",e[e.PercentSign=37]="PercentSign",e[e.Ampersand=38]="Ampersand",e[e.SingleQuote=39]="SingleQuote",e[e.OpenParen=40]="OpenParen",e[e.CloseParen=41]="CloseParen",e[e.Asterisk=42]="Asterisk",e[e.Plus=43]="Plus",e[e.Comma=44]="Comma",e[e.Dash=45]="Dash",e[e.Period=46]="Period",e[e.Slash=47]="Slash",e[e.Digit0=48]="Digit0",e[e.Digit1=49]="Digit1",e[e.Digit2=50]="Digit2",e[e.Digit3=51]="Digit3",e[e.Digit4=52]="Digit4",e[e.Digit5=53]="Digit5",e[e.Digit6=54]="Digit6",e[e.Digit7=55]="Digit7",e[e.Digit8=56]="Digit8",e[e.Digit9=57]="Digit9",e[e.Colon=58]="Colon",e[e.Semicolon=59]="Semicolon",e[e.LessThan=60]="LessThan",e[e.Equals=61]="Equals",e[e.GreaterThan=62]="GreaterThan",e[e.QuestionMark=63]="QuestionMark",e[e.AtSign=64]="AtSign",e[e.A=65]="A",e[e.B=66]="B",e[e.C=67]="C",e[e.D=68]="D",e[e.E=69]="E",e[e.F=70]="F",e[e.G=71]="G",e[e.H=72]="H",e[e.I=73]="I",e[e.J=74]="J",e[e.K=75]="K",e[e.L=76]="L",e[e.M=77]="M",e[e.N=78]="N",e[e.O=79]="O",e[e.P=80]="P",e[e.Q=81]="Q",e[e.R=82]="R",e[e.S=83]="S",e[e.T=84]="T",e[e.U=85]="U",e[e.V=86]="V",e[e.W=87]="W",e[e.X=88]="X",e[e.Y=89]="Y",e[e.Z=90]="Z",e[e.OpenSquareBracket=91]="OpenSquareBracket",e[e.Backslash=92]="Backslash",e[e.CloseSquareBracket=93]="CloseSquareBracket",e[e.Caret=94]="Caret",e[e.Underline=95]="Underline",e[e.BackTick=96]="BackTick",e[e.a=97]="a",e[e.b=98]="b",e[e.c=99]="c",e[e.d=100]="d",e[e.e=101]="e",e[e.f=102]="f",e[e.g=103]="g",e[e.h=104]="h",e[e.i=105]="i",e[e.j=106]="j",e[e.k=107]="k",e[e.l=108]="l",e[e.m=109]="m",e[e.n=110]="n",e[e.o=111]="o",e[e.p=112]="p",e[e.q=113]="q",e[e.r=114]="r",e[e.s=115]="s",e[e.t=116]="t",e[e.u=117]="u",e[e.v=118]="v",e[e.w=119]="w",e[e.x=120]="x",e[e.y=121]="y",e[e.z=122]="z",e[e.OpenCurlyBrace=123]="OpenCurlyBrace",e[e.Pipe=124]="Pipe",e[e.CloseCurlyBrace=125]="CloseCurlyBrace",e[e.Tilde=126]="Tilde",e[e.NoBreakSpace=160]="NoBreakSpace",e[e.U_Combining_Grave_Accent=768]="U_Combining_Grave_Accent",e[e.U_Combining_Acute_Accent=769]="U_Combining_Acute_Accent",e[e.U_Combining_Circumflex_Accent=770]="U_Combining_Circumflex_Accent",e[e.U_Combining_Tilde=771]="U_Combining_Tilde",e[e.U_Combining_Macron=772]="U_Combining_Macron",e[e.U_Combining_Overline=773]="U_Combining_Overline",e[e.U_Combining_Breve=774]="U_Combining_Breve",e[e.U_Combining_Dot_Above=775]="U_Combining_Dot_Above",e[e.U_Combining_Diaeresis=776]="U_Combining_Diaeresis",e[e.U_Combining_Hook_Above=777]="U_Combining_Hook_Above",e[e.U_Combining_Ring_Above=778]="U_Combining_Ring_Above",e[e.U_Combining_Double_Acute_Accent=779]="U_Combining_Double_Acute_Accent",e[e.U_Combining_Caron=780]="U_Combining_Caron",e[e.U_Combining_Vertical_Line_Above=781]="U_Combining_Vertical_Line_Above",e[e.U_Combining_Double_Vertical_Line_Above=782]="U_Combining_Double_Vertical_Line_Above",e[e.U_Combining_Double_Grave_Accent=783]="U_Combining_Double_Grave_Accent",e[e.U_Combining_Candrabindu=784]="U_Combining_Candrabindu",e[e.U_Combining_Inverted_Breve=785]="U_Combining_Inverted_Breve",e[e.U_Combining_Turned_Comma_Above=786]="U_Combining_Turned_Comma_Above",e[e.U_Combining_Comma_Above=787]="U_Combining_Comma_Above",e[e.U_Combining_Reversed_Comma_Above=788]="U_Combining_Reversed_Comma_Above",e[e.U_Combining_Comma_Above_Right=789]="U_Combining_Comma_Above_Right",e[e.U_Combining_Grave_Accent_Below=790]="U_Combining_Grave_Accent_Below",e[e.U_Combining_Acute_Accent_Below=791]="U_Combining_Acute_Accent_Below",e[e.U_Combining_Left_Tack_Below=792]="U_Combining_Left_Tack_Below",e[e.U_Combining_Right_Tack_Below=793]="U_Combining_Right_Tack_Below",e[e.U_Combining_Left_Angle_Above=794]="U_Combining_Left_Angle_Above",e[e.U_Combining_Horn=795]="U_Combining_Horn",e[e.U_Combining_Left_Half_Ring_Below=796]="U_Combining_Left_Half_Ring_Below",e[e.U_Combining_Up_Tack_Below=797]="U_Combining_Up_Tack_Below",e[e.U_Combining_Down_Tack_Below=798]="U_Combining_Down_Tack_Below",e[e.U_Combining_Plus_Sign_Below=799]="U_Combining_Plus_Sign_Below",e[e.U_Combining_Minus_Sign_Below=800]="U_Combining_Minus_Sign_Below",e[e.U_Combining_Palatalized_Hook_Below=801]="U_Combining_Palatalized_Hook_Below",e[e.U_Combining_Retroflex_Hook_Below=802]="U_Combining_Retroflex_Hook_Below",e[e.U_Combining_Dot_Below=803]="U_Combining_Dot_Below",e[e.U_Combining_Diaeresis_Below=804]="U_Combining_Diaeresis_Below",e[e.U_Combining_Ring_Below=805]="U_Combining_Ring_Below",e[e.U_Combining_Comma_Below=806]="U_Combining_Comma_Below",e[e.U_Combining_Cedilla=807]="U_Combining_Cedilla",e[e.U_Combining_Ogonek=808]="U_Combining_Ogonek",e[e.U_Combining_Vertical_Line_Below=809]="U_Combining_Vertical_Line_Below",e[e.U_Combining_Bridge_Below=810]="U_Combining_Bridge_Below",e[e.U_Combining_Inverted_Double_Arch_Below=811]="U_Combining_Inverted_Double_Arch_Below",e[e.U_Combining_Caron_Below=812]="U_Combining_Caron_Below",e[e.U_Combining_Circumflex_Accent_Below=813]="U_Combining_Circumflex_Accent_Below",e[e.U_Combining_Breve_Below=814]="U_Combining_Breve_Below",e[e.U_Combining_Inverted_Breve_Below=815]="U_Combining_Inverted_Breve_Below",e[e.U_Combining_Tilde_Below=816]="U_Combining_Tilde_Below",e[e.U_Combining_Macron_Below=817]="U_Combining_Macron_Below",e[e.U_Combining_Low_Line=818]="U_Combining_Low_Line",e[e.U_Combining_Double_Low_Line=819]="U_Combining_Double_Low_Line",e[e.U_Combining_Tilde_Overlay=820]="U_Combining_Tilde_Overlay",e[e.U_Combining_Short_Stroke_Overlay=821]="U_Combining_Short_Stroke_Overlay",e[e.U_Combining_Long_Stroke_Overlay=822]="U_Combining_Long_Stroke_Overlay",e[e.U_Combining_Short_Solidus_Overlay=823]="U_Combining_Short_Solidus_Overlay",e[e.U_Combining_Long_Solidus_Overlay=824]="U_Combining_Long_Solidus_Overlay",e[e.U_Combining_Right_Half_Ring_Below=825]="U_Combining_Right_Half_Ring_Below",e[e.U_Combining_Inverted_Bridge_Below=826]="U_Combining_Inverted_Bridge_Below",e[e.U_Combining_Square_Below=827]="U_Combining_Square_Below",e[e.U_Combining_Seagull_Below=828]="U_Combining_Seagull_Below",e[e.U_Combining_X_Above=829]="U_Combining_X_Above",e[e.U_Combining_Vertical_Tilde=830]="U_Combining_Vertical_Tilde",e[e.U_Combining_Double_Overline=831]="U_Combining_Double_Overline",e[e.U_Combining_Grave_Tone_Mark=832]="U_Combining_Grave_Tone_Mark",e[e.U_Combining_Acute_Tone_Mark=833]="U_Combining_Acute_Tone_Mark",e[e.U_Combining_Greek_Perispomeni=834]="U_Combining_Greek_Perispomeni",e[e.U_Combining_Greek_Koronis=835]="U_Combining_Greek_Koronis",e[e.U_Combining_Greek_Dialytika_Tonos=836]="U_Combining_Greek_Dialytika_Tonos",e[e.U_Combining_Greek_Ypogegrammeni=837]="U_Combining_Greek_Ypogegrammeni",e[e.U_Combining_Bridge_Above=838]="U_Combining_Bridge_Above",e[e.U_Combining_Equals_Sign_Below=839]="U_Combining_Equals_Sign_Below",e[e.U_Combining_Double_Vertical_Line_Below=840]="U_Combining_Double_Vertical_Line_Below",e[e.U_Combining_Left_Angle_Below=841]="U_Combining_Left_Angle_Below",e[e.U_Combining_Not_Tilde_Above=842]="U_Combining_Not_Tilde_Above",e[e.U_Combining_Homothetic_Above=843]="U_Combining_Homothetic_Above",e[e.U_Combining_Almost_Equal_To_Above=844]="U_Combining_Almost_Equal_To_Above",e[e.U_Combining_Left_Right_Arrow_Below=845]="U_Combining_Left_Right_Arrow_Below",e[e.U_Combining_Upwards_Arrow_Below=846]="U_Combining_Upwards_Arrow_Below",e[e.U_Combining_Grapheme_Joiner=847]="U_Combining_Grapheme_Joiner",e[e.U_Combining_Right_Arrowhead_Above=848]="U_Combining_Right_Arrowhead_Above",e[e.U_Combining_Left_Half_Ring_Above=849]="U_Combining_Left_Half_Ring_Above",e[e.U_Combining_Fermata=850]="U_Combining_Fermata",e[e.U_Combining_X_Below=851]="U_Combining_X_Below",e[e.U_Combining_Left_Arrowhead_Below=852]="U_Combining_Left_Arrowhead_Below",e[e.U_Combining_Right_Arrowhead_Below=853]="U_Combining_Right_Arrowhead_Below",e[e.U_Combining_Right_Arrowhead_And_Up_Arrowhead_Below=854]="U_Combining_Right_Arrowhead_And_Up_Arrowhead_Below",e[e.U_Combining_Right_Half_Ring_Above=855]="U_Combining_Right_Half_Ring_Above",e[e.U_Combining_Dot_Above_Right=856]="U_Combining_Dot_Above_Right",e[e.U_Combining_Asterisk_Below=857]="U_Combining_Asterisk_Below",e[e.U_Combining_Double_Ring_Below=858]="U_Combining_Double_Ring_Below",e[e.U_Combining_Zigzag_Above=859]="U_Combining_Zigzag_Above",e[e.U_Combining_Double_Breve_Below=860]="U_Combining_Double_Breve_Below",e[e.U_Combining_Double_Breve=861]="U_Combining_Double_Breve",e[e.U_Combining_Double_Macron=862]="U_Combining_Double_Macron",e[e.U_Combining_Double_Macron_Below=863]="U_Combining_Double_Macron_Below",e[e.U_Combining_Double_Tilde=864]="U_Combining_Double_Tilde",e[e.U_Combining_Double_Inverted_Breve=865]="U_Combining_Double_Inverted_Breve",e[e.U_Combining_Double_Rightwards_Arrow_Below=866]="U_Combining_Double_Rightwards_Arrow_Below",e[e.U_Combining_Latin_Small_Letter_A=867]="U_Combining_Latin_Small_Letter_A",e[e.U_Combining_Latin_Small_Letter_E=868]="U_Combining_Latin_Small_Letter_E",e[e.U_Combining_Latin_Small_Letter_I=869]="U_Combining_Latin_Small_Letter_I",e[e.U_Combining_Latin_Small_Letter_O=870]="U_Combining_Latin_Small_Letter_O",e[e.U_Combining_Latin_Small_Letter_U=871]="U_Combining_Latin_Small_Letter_U",e[e.U_Combining_Latin_Small_Letter_C=872]="U_Combining_Latin_Small_Letter_C",e[e.U_Combining_Latin_Small_Letter_D=873]="U_Combining_Latin_Small_Letter_D",e[e.U_Combining_Latin_Small_Letter_H=874]="U_Combining_Latin_Small_Letter_H",e[e.U_Combining_Latin_Small_Letter_M=875]="U_Combining_Latin_Small_Letter_M",e[e.U_Combining_Latin_Small_Letter_R=876]="U_Combining_Latin_Small_Letter_R",e[e.U_Combining_Latin_Small_Letter_T=877]="U_Combining_Latin_Small_Letter_T",e[e.U_Combining_Latin_Small_Letter_V=878]="U_Combining_Latin_Small_Letter_V",e[e.U_Combining_Latin_Small_Letter_X=879]="U_Combining_Latin_Small_Letter_X",e[e.LINE_SEPARATOR=8232]="LINE_SEPARATOR",e[e.PARAGRAPH_SEPARATOR=8233]="PARAGRAPH_SEPARATOR",e[e.NEXT_LINE=133]="NEXT_LINE",e[e.U_CIRCUMFLEX=94]="U_CIRCUMFLEX",e[e.U_GRAVE_ACCENT=96]="U_GRAVE_ACCENT",e[e.U_DIAERESIS=168]="U_DIAERESIS",e[e.U_MACRON=175]="U_MACRON",e[e.U_ACUTE_ACCENT=180]="U_ACUTE_ACCENT",e[e.U_CEDILLA=184]="U_CEDILLA",e[e.U_MODIFIER_LETTER_LEFT_ARROWHEAD=706]="U_MODIFIER_LETTER_LEFT_ARROWHEAD",e[e.U_MODIFIER_LETTER_RIGHT_ARROWHEAD=707]="U_MODIFIER_LETTER_RIGHT_ARROWHEAD",e[e.U_MODIFIER_LETTER_UP_ARROWHEAD=708]="U_MODIFIER_LETTER_UP_ARROWHEAD",e[e.U_MODIFIER_LETTER_DOWN_ARROWHEAD=709]="U_MODIFIER_LETTER_DOWN_ARROWHEAD",e[e.U_MODIFIER_LETTER_CENTRED_RIGHT_HALF_RING=722]="U_MODIFIER_LETTER_CENTRED_RIGHT_HALF_RING",e[e.U_MODIFIER_LETTER_CENTRED_LEFT_HALF_RING=723]="U_MODIFIER_LETTER_CENTRED_LEFT_HALF_RING",e[e.U_MODIFIER_LETTER_UP_TACK=724]="U_MODIFIER_LETTER_UP_TACK",e[e.U_MODIFIER_LETTER_DOWN_TACK=725]="U_MODIFIER_LETTER_DOWN_TACK",e[e.U_MODIFIER_LETTER_PLUS_SIGN=726]="U_MODIFIER_LETTER_PLUS_SIGN",e[e.U_MODIFIER_LETTER_MINUS_SIGN=727]="U_MODIFIER_LETTER_MINUS_SIGN",e[e.U_BREVE=728]="U_BREVE",e[e.U_DOT_ABOVE=729]="U_DOT_ABOVE",e[e.U_RING_ABOVE=730]="U_RING_ABOVE",e[e.U_OGONEK=731]="U_OGONEK",e[e.U_SMALL_TILDE=732]="U_SMALL_TILDE",e[e.U_DOUBLE_ACUTE_ACCENT=733]="U_DOUBLE_ACUTE_ACCENT",e[e.U_MODIFIER_LETTER_RHOTIC_HOOK=734]="U_MODIFIER_LETTER_RHOTIC_HOOK",e[e.U_MODIFIER_LETTER_CROSS_ACCENT=735]="U_MODIFIER_LETTER_CROSS_ACCENT",e[e.U_MODIFIER_LETTER_EXTRA_HIGH_TONE_BAR=741]="U_MODIFIER_LETTER_EXTRA_HIGH_TONE_BAR",e[e.U_MODIFIER_LETTER_HIGH_TONE_BAR=742]="U_MODIFIER_LETTER_HIGH_TONE_BAR",e[e.U_MODIFIER_LETTER_MID_TONE_BAR=743]="U_MODIFIER_LETTER_MID_TONE_BAR",e[e.U_MODIFIER_LETTER_LOW_TONE_BAR=744]="U_MODIFIER_LETTER_LOW_TONE_BAR",e[e.U_MODIFIER_LETTER_EXTRA_LOW_TONE_BAR=745]="U_MODIFIER_LETTER_EXTRA_LOW_TONE_BAR",e[e.U_MODIFIER_LETTER_YIN_DEPARTING_TONE_MARK=746]="U_MODIFIER_LETTER_YIN_DEPARTING_TONE_MARK",e[e.U_MODIFIER_LETTER_YANG_DEPARTING_TONE_MARK=747]="U_MODIFIER_LETTER_YANG_DEPARTING_TONE_MARK",e[e.U_MODIFIER_LETTER_UNASPIRATED=749]="U_MODIFIER_LETTER_UNASPIRATED",e[e.U_MODIFIER_LETTER_LOW_DOWN_ARROWHEAD=751]="U_MODIFIER_LETTER_LOW_DOWN_ARROWHEAD",e[e.U_MODIFIER_LETTER_LOW_UP_ARROWHEAD=752]="U_MODIFIER_LETTER_LOW_UP_ARROWHEAD",e[e.U_MODIFIER_LETTER_LOW_LEFT_ARROWHEAD=753]="U_MODIFIER_LETTER_LOW_LEFT_ARROWHEAD",e[e.U_MODIFIER_LETTER_LOW_RIGHT_ARROWHEAD=754]="U_MODIFIER_LETTER_LOW_RIGHT_ARROWHEAD",e[e.U_MODIFIER_LETTER_LOW_RING=755]="U_MODIFIER_LETTER_LOW_RING",e[e.U_MODIFIER_LETTER_MIDDLE_GRAVE_ACCENT=756]="U_MODIFIER_LETTER_MIDDLE_GRAVE_ACCENT",e[e.U_MODIFIER_LETTER_MIDDLE_DOUBLE_GRAVE_ACCENT=757]="U_MODIFIER_LETTER_MIDDLE_DOUBLE_GRAVE_ACCENT",e[e.U_MODIFIER_LETTER_MIDDLE_DOUBLE_ACUTE_ACCENT=758]="U_MODIFIER_LETTER_MIDDLE_DOUBLE_ACUTE_ACCENT",e[e.U_MODIFIER_LETTER_LOW_TILDE=759]="U_MODIFIER_LETTER_LOW_TILDE",e[e.U_MODIFIER_LETTER_RAISED_COLON=760]="U_MODIFIER_LETTER_RAISED_COLON",e[e.U_MODIFIER_LETTER_BEGIN_HIGH_TONE=761]="U_MODIFIER_LETTER_BEGIN_HIGH_TONE",e[e.U_MODIFIER_LETTER_END_HIGH_TONE=762]="U_MODIFIER_LETTER_END_HIGH_TONE",e[e.U_MODIFIER_LETTER_BEGIN_LOW_TONE=763]="U_MODIFIER_LETTER_BEGIN_LOW_TONE",e[e.U_MODIFIER_LETTER_END_LOW_TONE=764]="U_MODIFIER_LETTER_END_LOW_TONE",e[e.U_MODIFIER_LETTER_SHELF=765]="U_MODIFIER_LETTER_SHELF",e[e.U_MODIFIER_LETTER_OPEN_SHELF=766]="U_MODIFIER_LETTER_OPEN_SHELF",e[e.U_MODIFIER_LETTER_LOW_LEFT_ARROW=767]="U_MODIFIER_LETTER_LOW_LEFT_ARROW",e[e.U_GREEK_LOWER_NUMERAL_SIGN=885]="U_GREEK_LOWER_NUMERAL_SIGN",e[e.U_GREEK_TONOS=900]="U_GREEK_TONOS",e[e.U_GREEK_DIALYTIKA_TONOS=901]="U_GREEK_DIALYTIKA_TONOS",e[e.U_GREEK_KORONIS=8125]="U_GREEK_KORONIS",e[e.U_GREEK_PSILI=8127]="U_GREEK_PSILI",e[e.U_GREEK_PERISPOMENI=8128]="U_GREEK_PERISPOMENI",e[e.U_GREEK_DIALYTIKA_AND_PERISPOMENI=8129]="U_GREEK_DIALYTIKA_AND_PERISPOMENI",e[e.U_GREEK_PSILI_AND_VARIA=8141]="U_GREEK_PSILI_AND_VARIA",e[e.U_GREEK_PSILI_AND_OXIA=8142]="U_GREEK_PSILI_AND_OXIA",e[e.U_GREEK_PSILI_AND_PERISPOMENI=8143]="U_GREEK_PSILI_AND_PERISPOMENI",e[e.U_GREEK_DASIA_AND_VARIA=8157]="U_GREEK_DASIA_AND_VARIA",e[e.U_GREEK_DASIA_AND_OXIA=8158]="U_GREEK_DASIA_AND_OXIA",e[e.U_GREEK_DASIA_AND_PERISPOMENI=8159]="U_GREEK_DASIA_AND_PERISPOMENI",e[e.U_GREEK_DIALYTIKA_AND_VARIA=8173]="U_GREEK_DIALYTIKA_AND_VARIA",e[e.U_GREEK_DIALYTIKA_AND_OXIA=8174]="U_GREEK_DIALYTIKA_AND_OXIA",e[e.U_GREEK_VARIA=8175]="U_GREEK_VARIA",e[e.U_GREEK_OXIA=8189]="U_GREEK_OXIA",e[e.U_GREEK_DASIA=8190]="U_GREEK_DASIA",e[e.U_IDEOGRAPHIC_FULL_STOP=12290]="U_IDEOGRAPHIC_FULL_STOP",e[e.U_LEFT_CORNER_BRACKET=12300]="U_LEFT_CORNER_BRACKET",e[e.U_RIGHT_CORNER_BRACKET=12301]="U_RIGHT_CORNER_BRACKET",e[e.U_LEFT_BLACK_LENTICULAR_BRACKET=12304]="U_LEFT_BLACK_LENTICULAR_BRACKET",e[e.U_RIGHT_BLACK_LENTICULAR_BRACKET=12305]="U_RIGHT_BLACK_LENTICULAR_BRACKET",e[e.U_OVERLINE=8254]="U_OVERLINE",e[e.UTF8_BOM=65279]="UTF8_BOM",e[e.U_FULLWIDTH_SEMICOLON=65307]="U_FULLWIDTH_SEMICOLON",e[e.U_FULLWIDTH_COMMA=65292]="U_FULLWIDTH_COMMA"}(i||(t.CharCode=i={}))},9087:(e,t)=>{var i;Object.defineProperty(t,"__esModule",{value:!0}),t.SetWithKey=void 0,t.groupBy=function(e,t){const i=Object.create(null);for(const s of e){const e=t(s);let r=i[e];r||(r=i[e]=[]),r.push(s)}return i},t.diffSets=function(e,t){const i=[],s=[];for(const s of e)t.has(s)||i.push(s);for(const i of t)e.has(i)||s.push(i);return{removed:i,added:s}},t.diffMaps=function(e,t){const i=[],s=[];for(const[s,r]of e)t.has(s)||i.push(r);for(const[i,r]of t)e.has(i)||s.push(r);return{removed:i,added:s}},t.intersection=function(e,t){const i=new Set;for(const s of t)e.has(s)&&i.add(s);return i};class s{static{i=Symbol.toStringTag}constructor(e,t){this.toKey=t,this._map=new Map,this[i]="SetWithKey";for(const t of e)this.add(t)}get size(){return this._map.size}add(e){const t=this.toKey(e);return this._map.set(t,e),this}delete(e){return this._map.delete(this.toKey(e))}has(e){return this._map.has(this.toKey(e))}*entries(){for(const e of this._map.values())yield[e,e]}keys(){return this.values()}*values(){for(const e of this._map.values())yield e}clear(){this._map.clear()}forEach(e,t){this._map.forEach((i=>e.call(t,i,i,this)))}[Symbol.iterator](){return this.values()}}t.SetWithKey=s},4838:(e,t)=>{function i(e){return(t,i,s)=>{let r=null,n=null;if("function"==typeof s.value?(r="value",n=s.value):"function"==typeof s.get&&(r="get",n=s.get),!n)throw new Error("not supported");s[r]=e(n,i)}}Object.defineProperty(t,"__esModule",{value:!0}),t.memoize=function(e,t,i){let s=null,r=null;if("function"==typeof i.value?(s="value",r=i.value,0!==r.length&&console.warn("Memoize should only be used in functions with zero parameters")):"function"==typeof i.get&&(s="get",r=i.get),!r)throw new Error("not supported");const n=`$memoize$${t}`;i[s]=function(...e){return this.hasOwnProperty(n)||Object.defineProperty(this,n,{configurable:!1,enumerable:!1,writable:!1,value:r.apply(this,e)}),this[n]}},t.debounce=function(e,t,s){return i(((i,r)=>{const n=`$debounce$${r}`,o=`$debounce$result$${r}`;return function(...r){this[o]||(this[o]=s?s():void 0),clearTimeout(this[n]),t&&(this[o]=t(this[o],...r),r=[this[o]]),this[n]=setTimeout((()=>{i.apply(this,r),this[o]=s?s():void 0}),e)}}))},t.throttle=function(e,t,s){return i(((i,r)=>{const n=`$throttle$timer$${r}`,o=`$throttle$result$${r}`,a=`$throttle$lastRun$${r}`,l=`$throttle$pending$${r}`;return function(...r){if(this[o]||(this[o]=s?s():void 0),null!==this[a]&&void 0!==this[a]||(this[a]=-Number.MAX_VALUE),t&&(this[o]=t(this[o],...r)),this[l])return;const h=this[a]+e;h<=Date.now()?(this[a]=Date.now(),i.apply(this,[this[o]]),this[o]=s?s():void 0):(this[l]=!0,this[n]=setTimeout((()=>{this[l]=!1,this[a]=Date.now(),i.apply(this,[this[o]]),this[o]=s?s():void 0}),h-Date.now()))}}))}},9807:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BugIndicatingError=t.ErrorNoTelemetry=t.ExpectedError=t.NotSupportedError=t.NotImplementedError=t.ReadonlyError=t.CancellationError=t.errorHandler=t.ErrorHandler=void 0,t.setUnexpectedErrorHandler=function(e){t.errorHandler.setUnexpectedErrorHandler(e)},t.isSigPipeError=function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"EPIPE"===t.code&&"WRITE"===t.syscall?.toUpperCase()},t.onUnexpectedError=function(e){r(e)||t.errorHandler.onUnexpectedError(e)},t.onUnexpectedExternalError=function(e){r(e)||t.errorHandler.onUnexpectedExternalError(e)},t.transformErrorForSerialization=function(e){if(e instanceof Error){const{name:t,message:i}=e;return{$isError:!0,name:t,message:i,stack:e.stacktrace||e.stack,noTelemetry:c.isErrorNoTelemetry(e)}}return e},t.transformErrorFromSerialization=function(e){let t;return e.noTelemetry?t=new c:(t=new Error,t.name=e.name),t.message=e.message,t.stack=e.stack,t},t.isCancellationError=r,t.canceled=function(){const e=new Error(s);return e.name=e.message,e},t.illegalArgument=function(e){return e?new Error(`Illegal argument: ${e}`):new Error("Illegal argument")},t.illegalState=function(e){return e?new Error(`Illegal state: ${e}`):new Error("Illegal state")},t.getErrorMessage=function(e){return e?e.message?e.message:e.stack?e.stack.split("\n")[0]:String(e):"Error"};class i{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout((()=>{if(e.stack){if(c.isErrorNoTelemetry(e))throw new c(e.message+"\n\n"+e.stack);throw new Error(e.message+"\n\n"+e.stack)}throw e}),0)}}addListener(e){return this.listeners.push(e),()=>{this._removeListener(e)}}emit(e){this.listeners.forEach((t=>{t(e)}))}_removeListener(e){this.listeners.splice(this.listeners.indexOf(e),1)}setUnexpectedErrorHandler(e){this.unexpectedErrorHandler=e}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(e){this.unexpectedErrorHandler(e),this.emit(e)}onUnexpectedExternalError(e){this.unexpectedErrorHandler(e)}}t.ErrorHandler=i,t.errorHandler=new i;const s="Canceled";function r(e){return e instanceof n||e instanceof Error&&e.name===s&&e.message===s}class n extends Error{constructor(){super(s),this.name=this.message}}t.CancellationError=n;class o extends TypeError{constructor(e){super(e?`${e} is read-only and cannot be changed`:"Cannot change read-only property")}}t.ReadonlyError=o;class a extends Error{constructor(e){super("NotImplemented"),e&&(this.message=e)}}t.NotImplementedError=a;class l extends Error{constructor(e){super("NotSupported"),e&&(this.message=e)}}t.NotSupportedError=l;class h extends Error{constructor(){super(...arguments),this.isExpected=!0}}t.ExpectedError=h;class c extends Error{constructor(e){super(e),this.name="CodeExpectedError"}static fromError(e){if(e instanceof c)return e;const t=new c;return t.message=e.message,t.stack=e.stack,t}static isErrorNoTelemetry(e){return"CodeExpectedError"===e.name}}t.ErrorNoTelemetry=c;class d extends Error{constructor(e){super(e||"An unexpected bug occurred."),Object.setPrototypeOf(this,d.prototype)}}t.BugIndicatingError=d},802:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ValueWithChangeEvent=t.Relay=t.EventBufferer=t.DynamicListEventMultiplexer=t.EventMultiplexer=t.MicrotaskEmitter=t.DebounceEmitter=t.PauseableEmitter=t.AsyncEmitter=t.createEventDeliveryQueue=t.Emitter=t.ListenerRefusalError=t.ListenerLeakError=t.EventProfiling=t.Event=void 0,t.setGlobalLeakWarningThreshold=function(e){const t=c;return c=e,{dispose(){c=t}}};const s=i(9807),r=i(8841),n=i(7150),o=i(6317),a=i(9725);var l;!function(e){function t(e){return(t,i=null,s)=>{let r,n=!1;return r=e((e=>{if(!n)return r?r.dispose():n=!0,t.call(i,e)}),null,s),n&&r.dispose(),r}}function i(e,t,i){return r(((i,s=null,r)=>e((e=>i.call(s,t(e))),null,r)),i)}function s(e,t,i){return r(((i,s=null,r)=>e((e=>t(e)&&i.call(s,e)),null,r)),i)}function r(e,t){let i;const s=new m({onWillAddFirstListener(){i=e(s.fire,s)},onDidRemoveLastListener(){i?.dispose()}});return t?.add(s),s.event}function o(e,t,i=100,s=!1,r=!1,n,o){let a,l,h,c,d=0;const u=new m({leakWarningThreshold:n,onWillAddFirstListener(){a=e((e=>{d++,l=t(l,e),s&&!h&&(u.fire(l),l=void 0),c=()=>{const e=l;l=void 0,h=void 0,(!s||d>1)&&u.fire(e),d=0},"number"==typeof i?(clearTimeout(h),h=setTimeout(c,i)):void 0===h&&(h=0,queueMicrotask(c))}))},onWillRemoveListener(){r&&d>0&&c?.()},onDidRemoveLastListener(){c=void 0,a.dispose()}});return o?.add(u),u.event}e.None=()=>n.Disposable.None,e.defer=function(e,t){return o(e,(()=>{}),0,void 0,!0,void 0,t)},e.once=t,e.map=i,e.forEach=function(e,t,i){return r(((i,s=null,r)=>e((e=>{t(e),i.call(s,e)}),null,r)),i)},e.filter=s,e.signal=function(e){return e},e.any=function(...e){return(t,i=null,s)=>{return r=(0,n.combinedDisposable)(...e.map((e=>e((e=>t.call(i,e)))))),(o=s)instanceof Array?o.push(r):o&&o.add(r),r;var r,o}},e.reduce=function(e,t,s,r){let n=s;return i(e,(e=>(n=t(n,e),n)),r)},e.debounce=o,e.accumulate=function(t,i=0,s){return e.debounce(t,((e,t)=>e?(e.push(t),e):[t]),i,void 0,!0,void 0,s)},e.latch=function(e,t=(e,t)=>e===t,i){let r,n=!0;return s(e,(e=>{const i=n||!t(e,r);return n=!1,r=e,i}),i)},e.split=function(t,i,s){return[e.filter(t,i,s),e.filter(t,(e=>!i(e)),s)]},e.buffer=function(e,t=!1,i=[],s){let r=i.slice(),n=e((e=>{r?r.push(e):a.fire(e)}));s&&s.add(n);const o=()=>{r?.forEach((e=>a.fire(e))),r=null},a=new m({onWillAddFirstListener(){n||(n=e((e=>a.fire(e))),s&&s.add(n))},onDidAddFirstListener(){r&&(t?setTimeout(o):o())},onDidRemoveLastListener(){n&&n.dispose(),n=null}});return s&&s.add(a),a.event},e.chain=function(e,t){return(i,s,r)=>{const n=t(new l);return e((function(e){const t=n.evaluate(e);t!==a&&i.call(s,t)}),void 0,r)}};const a=Symbol("HaltChainable");class l{constructor(){this.steps=[]}map(e){return this.steps.push(e),this}forEach(e){return this.steps.push((t=>(e(t),t))),this}filter(e){return this.steps.push((t=>e(t)?t:a)),this}reduce(e,t){let i=t;return this.steps.push((t=>(i=e(i,t),i))),this}latch(e=(e,t)=>e===t){let t,i=!0;return this.steps.push((s=>{const r=i||!e(s,t);return i=!1,t=s,r?s:a})),this}evaluate(e){for(const t of this.steps)if((e=t(e))===a)break;return e}}e.fromNodeEventEmitter=function(e,t,i=e=>e){const s=(...e)=>r.fire(i(...e)),r=new m({onWillAddFirstListener:()=>e.on(t,s),onDidRemoveLastListener:()=>e.removeListener(t,s)});return r.event},e.fromDOMEventEmitter=function(e,t,i=e=>e){const s=(...e)=>r.fire(i(...e)),r=new m({onWillAddFirstListener:()=>e.addEventListener(t,s),onDidRemoveLastListener:()=>e.removeEventListener(t,s)});return r.event},e.toPromise=function(e){return new Promise((i=>t(e)(i)))},e.fromPromise=function(e){const t=new m;return e.then((e=>{t.fire(e)}),(()=>{t.fire(void 0)})).finally((()=>{t.dispose()})),t.event},e.forward=function(e,t){return e((e=>t.fire(e)))},e.runAndSubscribe=function(e,t,i){return t(i),e((e=>t(e)))};class h{constructor(e,t){this._observable=e,this._counter=0,this._hasChanged=!1;const i={onWillAddFirstListener:()=>{e.addObserver(this)},onDidRemoveLastListener:()=>{e.removeObserver(this)}};this.emitter=new m(i),t&&t.add(this.emitter)}beginUpdate(e){this._counter++}handlePossibleChange(e){}handleChange(e,t){this._hasChanged=!0}endUpdate(e){this._counter--,0===this._counter&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}e.fromObservable=function(e,t){return new h(e,t).emitter.event},e.fromObservableLight=function(e){return(t,i,s)=>{let r=0,o=!1;const a={beginUpdate(){r++},endUpdate(){r--,0===r&&(e.reportChanges(),o&&(o=!1,t.call(i)))},handlePossibleChange(){},handleChange(){o=!0}};e.addObserver(a),e.reportChanges();const l={dispose(){e.removeObserver(a)}};return s instanceof n.DisposableStore?s.add(l):Array.isArray(s)&&s.push(l),l}}}(l||(t.Event=l={}));class h{static{this.all=new Set}static{this._idPool=0}constructor(e){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${e}_${h._idPool++}`,h.all.add(this)}start(e){this._stopWatch=new a.StopWatch,this.listenerCount=e}stop(){if(this._stopWatch){const e=this._stopWatch.elapsed();this.durations.push(e),this.elapsedOverall+=e,this.invocationCount+=1,this._stopWatch=void 0}}}t.EventProfiling=h;let c=-1;class d{static{this._idPool=1}constructor(e,t,i=(d._idPool++).toString(16).padStart(3,"0")){this._errorHandler=e,this.threshold=t,this.name=i,this._warnCountdown=0}dispose(){this._stacks?.clear()}check(e,t){const i=this.threshold;if(i<=0||t{const t=this._stacks.get(e.value)||0;this._stacks.set(e.value,t-1)}}getMostFrequentStack(){if(!this._stacks)return;let e,t=0;for(const[i,s]of this._stacks)(!e||t0||this._options?.leakWarningThreshold?new d(e?.onListenerError??s.onUnexpectedError,this._options?.leakWarningThreshold??c):void 0,this._perfMon=this._options?._profName?new h(this._options._profName):void 0,this._deliveryQueue=this._options?.deliveryQueue}dispose(){this._disposed||(this._disposed=!0,this._deliveryQueue?.current===this&&this._deliveryQueue.reset(),this._listeners&&(this._listeners=void 0,this._size=0),this._options?.onDidRemoveLastListener?.(),this._leakageMon?.dispose())}get event(){return this._event??=(e,t,i)=>{if(this._leakageMon&&this._size>this._leakageMon.threshold**2){const e=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(e);const t=this._leakageMon.getMostFrequentStack()??["UNKNOWN stack",-1],i=new f(`${e}. HINT: Stack shows most frequent listener (${t[1]}-times)`,t[0]);return(this._options?.onListenerError||s.onUnexpectedError)(i),n.Disposable.None}if(this._disposed)return n.Disposable.None;t&&(e=e.bind(t));const r=new g(e);let o;this._leakageMon&&this._size>=Math.ceil(.2*this._leakageMon.threshold)&&(r.stack=u.create(),o=this._leakageMon.check(r.stack,this._size+1)),this._listeners?this._listeners instanceof g?(this._deliveryQueue??=new v,this._listeners=[this._listeners,r]):this._listeners.push(r):(this._options?.onWillAddFirstListener?.(this),this._listeners=r,this._options?.onDidAddFirstListener?.(this)),this._size++;const a=(0,n.toDisposable)((()=>{o?.(),this._removeListener(r)}));return i instanceof n.DisposableStore?i.add(a):Array.isArray(i)&&i.push(a),a},this._event}_removeListener(e){if(this._options?.onWillRemoveListener?.(this),!this._listeners)return;if(1===this._size)return this._listeners=void 0,this._options?.onDidRemoveLastListener?.(this),void(this._size=0);const t=this._listeners,i=t.indexOf(e);if(-1===i)throw console.log("disposed?",this._disposed),console.log("size?",this._size),console.log("arr?",JSON.stringify(this._listeners)),new Error("Attempted to dispose unknown listener");this._size--,t[i]=void 0;const s=this._deliveryQueue.current===this;if(2*this._size<=t.length){let e=0;for(let i=0;i0}}t.Emitter=m,t.createEventDeliveryQueue=()=>new v;class v{constructor(){this.i=-1,this.end=0}enqueue(e,t,i){this.i=0,this.end=i,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}}t.AsyncEmitter=class extends m{async fireAsync(e,t,i){if(this._listeners)for(this._asyncDeliveryQueue||(this._asyncDeliveryQueue=new o.LinkedList),((e,t)=>{if(e instanceof g)t(e);else for(let i=0;ithis._asyncDeliveryQueue.push([t.value,e])));this._asyncDeliveryQueue.size>0&&!t.isCancellationRequested;){const[e,r]=this._asyncDeliveryQueue.shift(),n=[],o={...r,token:t,waitUntil:t=>{if(Object.isFrozen(n))throw new Error("waitUntil can NOT be called asynchronous");i&&(t=i(t,e)),n.push(t)}};try{e(o)}catch(e){(0,s.onUnexpectedError)(e);continue}Object.freeze(n),await Promise.allSettled(n).then((e=>{for(const t of e)"rejected"===t.status&&(0,s.onUnexpectedError)(t.reason)}))}}};class S extends m{get isPaused(){return 0!==this._isPaused}constructor(e){super(e),this._isPaused=0,this._eventQueue=new o.LinkedList,this._mergeFn=e?.merge}pause(){this._isPaused++}resume(){if(0!==this._isPaused&&0==--this._isPaused)if(this._mergeFn){if(this._eventQueue.size>0){const e=Array.from(this._eventQueue);this._eventQueue.clear(),super.fire(this._mergeFn(e))}}else for(;!this._isPaused&&0!==this._eventQueue.size;)super.fire(this._eventQueue.shift())}fire(e){this._size&&(0!==this._isPaused?this._eventQueue.push(e):super.fire(e))}}t.PauseableEmitter=S,t.DebounceEmitter=class extends S{constructor(e){super(e),this._delay=e.delay??100}fire(e){this._handle||(this.pause(),this._handle=setTimeout((()=>{this._handle=void 0,this.resume()}),this._delay)),super.fire(e)}},t.MicrotaskEmitter=class extends m{constructor(e){super(e),this._queuedEvents=[],this._mergeFn=e?.merge}fire(e){this.hasListeners()&&(this._queuedEvents.push(e),1===this._queuedEvents.length&&queueMicrotask((()=>{this._mergeFn?super.fire(this._mergeFn(this._queuedEvents)):this._queuedEvents.forEach((e=>super.fire(e))),this._queuedEvents=[]})))}};class b{constructor(){this.hasListeners=!1,this.events=[],this.emitter=new m({onWillAddFirstListener:()=>this.onFirstListenerAdd(),onDidRemoveLastListener:()=>this.onLastListenerRemove()})}get event(){return this.emitter.event}add(e){const t={event:e,listener:null};return this.events.push(t),this.hasListeners&&this.hook(t),(0,n.toDisposable)((0,r.createSingleCallFunction)((()=>{this.hasListeners&&this.unhook(t);const e=this.events.indexOf(t);this.events.splice(e,1)})))}onFirstListenerAdd(){this.hasListeners=!0,this.events.forEach((e=>this.hook(e)))}onLastListenerRemove(){this.hasListeners=!1,this.events.forEach((e=>this.unhook(e)))}hook(e){e.listener=e.event((e=>this.emitter.fire(e)))}unhook(e){e.listener?.dispose(),e.listener=null}dispose(){this.emitter.dispose();for(const e of this.events)e.listener?.dispose();this.events=[]}}t.EventMultiplexer=b,t.DynamicListEventMultiplexer=class{constructor(e,t,i,s){this._store=new n.DisposableStore;const r=this._store.add(new b),o=this._store.add(new n.DisposableMap);function a(e){o.set(e,r.add(s(e)))}for(const t of e)a(t);this._store.add(t((e=>{a(e)}))),this._store.add(i((e=>{o.deleteAndDispose(e)}))),this.event=r.event}dispose(){this._store.dispose()}},t.EventBufferer=class{constructor(){this.data=[]}wrapEvent(e,t,i){return(s,r,n)=>e((e=>{const n=this.data[this.data.length-1];if(!t)return void(n?n.buffers.push((()=>s.call(r,e))):s.call(r,e));const o=n;o?(o.items??=[],o.items.push(e),0===o.buffers.length&&n.buffers.push((()=>{o.reducedResult??=i?o.items.reduce(t,i):o.items.reduce(t),s.call(r,o.reducedResult)}))):s.call(r,t(i,e))}),void 0,n)}bufferEvents(e){const t={buffers:new Array};this.data.push(t);const i=e();return this.data.pop(),t.buffers.forEach((e=>e())),i}},t.Relay=class{constructor(){this.listening=!1,this.inputEvent=l.None,this.inputEventListener=n.Disposable.None,this.emitter=new m({onDidAddFirstListener:()=>{this.listening=!0,this.inputEventListener=this.inputEvent(this.emitter.fire,this.emitter)},onDidRemoveLastListener:()=>{this.listening=!1,this.inputEventListener.dispose()}}),this.event=this.emitter.event}set input(e){this.inputEvent=e,this.listening&&(this.inputEventListener.dispose(),this.inputEventListener=e(this.emitter.fire,this.emitter))}dispose(){this.inputEventListener.dispose(),this.emitter.dispose()}},t.ValueWithChangeEvent=class{static const(e){return new C(e)}constructor(e){this._value=e,this._onDidChange=new m,this.onDidChange=this._onDidChange.event}get value(){return this._value}set value(e){e!==this._value&&(this._value=e,this._onDidChange.fire(void 0))}};class C{constructor(e){this.value=e,this.onDidChange=l.None}}},8841:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.createSingleCallFunction=function(e,t){const i=this;let s,r=!1;return function(){if(r)return s;if(r=!0,t)try{s=e.apply(i,arguments)}finally{t()}else s=e.apply(i,arguments);return s}}},6304:function(e,t,i){var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,r)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&s(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.StringSHA1=t.Hasher=void 0,t.hash=function(e){return a(e,0)},t.doHash=a,t.numberHash=l,t.stringHash=h,t.toHexString=_;const o=n(i(1316));function a(e,t){switch(typeof e){case"object":return null===e?l(349,t):Array.isArray(e)?(i=e,s=l(104579,s=t),i.reduce(((e,t)=>a(t,e)),s)):function(e,t){return t=l(181387,t),Object.keys(e).sort().reduce(((t,i)=>(t=h(i,t),a(e[i],t))),t)}(e,t);case"string":return h(e,t);case"boolean":return function(e,t){return l(e?433:863,t)}(e,t);case"number":return l(e,t);case"undefined":return l(937,t);default:return l(617,t)}var i,s}function l(e,t){return(t<<5)-t+e|0}function h(e,t){t=l(149417,t);for(let i=0,s=e.length;i>>s)>>>0}function u(e,t=0,i=e.byteLength,s=0){for(let r=0;re.toString(16).padStart(2,"0"))).join(""):function(e,t,i="0"){for(;e.length>>0).toString(16),t/4)}t.Hasher=class{constructor(){this._value=0}get value(){return this._value}hash(e){return this._value=a(e,this._value),this._value}},function(e){e[e.BLOCK_SIZE=64]="BLOCK_SIZE",e[e.UNICODE_REPLACEMENT=65533]="UNICODE_REPLACEMENT"}(c||(c={}));class f{static{this._bigBlock32=new DataView(new ArrayBuffer(320))}constructor(){this._h0=1732584193,this._h1=4023233417,this._h2=2562383102,this._h3=271733878,this._h4=3285377520,this._buff=new Uint8Array(c.BLOCK_SIZE+3),this._buffDV=new DataView(this._buff.buffer),this._buffLen=0,this._totalLen=0,this._leftoverHighSurrogate=0,this._finished=!1}update(e){const t=e.length;if(0===t)return;const i=this._buff;let s,r,n=this._buffLen,a=this._leftoverHighSurrogate;for(0!==a?(s=a,r=-1,a=0):(s=e.charCodeAt(0),r=0);;){let l=s;if(o.isHighSurrogate(s)){if(!(r+1>>6,e[t++]=128|(63&i)>>>0):i<65536?(e[t++]=224|(61440&i)>>>12,e[t++]=128|(4032&i)>>>6,e[t++]=128|(63&i)>>>0):(e[t++]=240|(1835008&i)>>>18,e[t++]=128|(258048&i)>>>12,e[t++]=128|(4032&i)>>>6,e[t++]=128|(63&i)>>>0),t>=c.BLOCK_SIZE&&(this._step(),t-=c.BLOCK_SIZE,this._totalLen+=c.BLOCK_SIZE,e[0]=e[c.BLOCK_SIZE+0],e[1]=e[c.BLOCK_SIZE+1],e[2]=e[c.BLOCK_SIZE+2]),t}digest(){return this._finished||(this._finished=!0,this._leftoverHighSurrogate&&(this._leftoverHighSurrogate=0,this._buffLen=this._push(this._buff,this._buffLen,c.UNICODE_REPLACEMENT)),this._totalLen+=this._buffLen,this._wrapUp()),_(this._h0)+_(this._h1)+_(this._h2)+_(this._h3)+_(this._h4)}_wrapUp(){this._buff[this._buffLen++]=128,u(this._buff,this._buffLen),this._buffLen>56&&(this._step(),u(this._buff));const e=8*this._totalLen;this._buffDV.setUint32(56,Math.floor(e/4294967296),!1),this._buffDV.setUint32(60,e%4294967296,!1),this._step()}_step(){const e=f._bigBlock32,t=this._buffDV;for(let i=0;i<64;i+=4)e.setUint32(i,t.getUint32(i,!1),!1);for(let t=64;t<320;t+=4)e.setUint32(t,d(e.getUint32(t-12,!1)^e.getUint32(t-32,!1)^e.getUint32(t-56,!1)^e.getUint32(t-64,!1),1),!1);let i,s,r,n=this._h0,o=this._h1,a=this._h2,l=this._h3,h=this._h4;for(let t=0;t<80;t++)t<20?(i=o&a|~o&l,s=1518500249):t<40?(i=o^a^l,s=1859775393):t<60?(i=o&a|o&l|a&l,s=2400959708):(i=o^a^l,s=3395469782),r=d(n,5)+i+h+s+e.getUint32(4*t,!1)&4294967295,h=l,l=a,a=d(o,30),o=n,n=r;this._h0=this._h0+n&4294967295,this._h1=this._h1+o&4294967295,this._h2=this._h2+a&4294967295,this._h3=this._h3+l&4294967295,this._h4=this._h4+h&4294967295}}t.StringSHA1=f},4218:(e,t)=>{var i;Object.defineProperty(t,"__esModule",{value:!0}),t.Iterable=void 0,function(e){function t(e){return e&&"object"==typeof e&&"function"==typeof e[Symbol.iterator]}e.is=t;const i=Object.freeze([]);function*s(e){yield e}e.empty=function(){return i},e.single=s,e.wrap=function(e){return t(e)?e:s(e)},e.from=function(e){return e||i},e.reverse=function*(e){for(let t=e.length-1;t>=0;t--)yield e[t]},e.isEmpty=function(e){return!e||!0===e[Symbol.iterator]().next().done},e.first=function(e){return e[Symbol.iterator]().next().value},e.some=function(e,t){let i=0;for(const s of e)if(t(s,i++))return!0;return!1},e.find=function(e,t){for(const i of e)if(t(i))return i},e.filter=function*(e,t){for(const i of e)t(i)&&(yield i)},e.map=function*(e,t){let i=0;for(const s of e)yield t(s,i++)},e.flatMap=function*(e,t){let i=0;for(const s of e)yield*t(s,i++)},e.concat=function*(...e){for(const t of e)yield*t},e.reduce=function(e,t,i){let s=i;for(const i of e)s=t(s,i);return s},e.slice=function*(e,t,i=e.length){for(t<0&&(t+=e.length),i<0?i+=e.length:i>e.length&&(i=e.length);tr}]},e.asyncToArray=async function(e){const t=[];for await(const i of e)t.push(i);return Promise.resolve(t)}}(i||(t.Iterable=i={}))},7883:(e,t)=>{var i,s;Object.defineProperty(t,"__esModule",{value:!0}),t.KeyMod=t.KeyCodeUtils=t.ScanCodeUtils=t.NATIVE_WINDOWS_KEY_CODE_TO_KEY_CODE=t.EVENT_KEY_CODE_MAP=t.ScanCode=t.KeyCode=void 0,t.KeyChord=function(e,t){return(e|(65535&t)<<16>>>0)>>>0},function(e){e[e.DependsOnKbLayout=-1]="DependsOnKbLayout",e[e.Unknown=0]="Unknown",e[e.Backspace=1]="Backspace",e[e.Tab=2]="Tab",e[e.Enter=3]="Enter",e[e.Shift=4]="Shift",e[e.Ctrl=5]="Ctrl",e[e.Alt=6]="Alt",e[e.PauseBreak=7]="PauseBreak",e[e.CapsLock=8]="CapsLock",e[e.Escape=9]="Escape",e[e.Space=10]="Space",e[e.PageUp=11]="PageUp",e[e.PageDown=12]="PageDown",e[e.End=13]="End",e[e.Home=14]="Home",e[e.LeftArrow=15]="LeftArrow",e[e.UpArrow=16]="UpArrow",e[e.RightArrow=17]="RightArrow",e[e.DownArrow=18]="DownArrow",e[e.Insert=19]="Insert",e[e.Delete=20]="Delete",e[e.Digit0=21]="Digit0",e[e.Digit1=22]="Digit1",e[e.Digit2=23]="Digit2",e[e.Digit3=24]="Digit3",e[e.Digit4=25]="Digit4",e[e.Digit5=26]="Digit5",e[e.Digit6=27]="Digit6",e[e.Digit7=28]="Digit7",e[e.Digit8=29]="Digit8",e[e.Digit9=30]="Digit9",e[e.KeyA=31]="KeyA",e[e.KeyB=32]="KeyB",e[e.KeyC=33]="KeyC",e[e.KeyD=34]="KeyD",e[e.KeyE=35]="KeyE",e[e.KeyF=36]="KeyF",e[e.KeyG=37]="KeyG",e[e.KeyH=38]="KeyH",e[e.KeyI=39]="KeyI",e[e.KeyJ=40]="KeyJ",e[e.KeyK=41]="KeyK",e[e.KeyL=42]="KeyL",e[e.KeyM=43]="KeyM",e[e.KeyN=44]="KeyN",e[e.KeyO=45]="KeyO",e[e.KeyP=46]="KeyP",e[e.KeyQ=47]="KeyQ",e[e.KeyR=48]="KeyR",e[e.KeyS=49]="KeyS",e[e.KeyT=50]="KeyT",e[e.KeyU=51]="KeyU",e[e.KeyV=52]="KeyV",e[e.KeyW=53]="KeyW",e[e.KeyX=54]="KeyX",e[e.KeyY=55]="KeyY",e[e.KeyZ=56]="KeyZ",e[e.Meta=57]="Meta",e[e.ContextMenu=58]="ContextMenu",e[e.F1=59]="F1",e[e.F2=60]="F2",e[e.F3=61]="F3",e[e.F4=62]="F4",e[e.F5=63]="F5",e[e.F6=64]="F6",e[e.F7=65]="F7",e[e.F8=66]="F8",e[e.F9=67]="F9",e[e.F10=68]="F10",e[e.F11=69]="F11",e[e.F12=70]="F12",e[e.F13=71]="F13",e[e.F14=72]="F14",e[e.F15=73]="F15",e[e.F16=74]="F16",e[e.F17=75]="F17",e[e.F18=76]="F18",e[e.F19=77]="F19",e[e.F20=78]="F20",e[e.F21=79]="F21",e[e.F22=80]="F22",e[e.F23=81]="F23",e[e.F24=82]="F24",e[e.NumLock=83]="NumLock",e[e.ScrollLock=84]="ScrollLock",e[e.Semicolon=85]="Semicolon",e[e.Equal=86]="Equal",e[e.Comma=87]="Comma",e[e.Minus=88]="Minus",e[e.Period=89]="Period",e[e.Slash=90]="Slash",e[e.Backquote=91]="Backquote",e[e.BracketLeft=92]="BracketLeft",e[e.Backslash=93]="Backslash",e[e.BracketRight=94]="BracketRight",e[e.Quote=95]="Quote",e[e.OEM_8=96]="OEM_8",e[e.IntlBackslash=97]="IntlBackslash",e[e.Numpad0=98]="Numpad0",e[e.Numpad1=99]="Numpad1",e[e.Numpad2=100]="Numpad2",e[e.Numpad3=101]="Numpad3",e[e.Numpad4=102]="Numpad4",e[e.Numpad5=103]="Numpad5",e[e.Numpad6=104]="Numpad6",e[e.Numpad7=105]="Numpad7",e[e.Numpad8=106]="Numpad8",e[e.Numpad9=107]="Numpad9",e[e.NumpadMultiply=108]="NumpadMultiply",e[e.NumpadAdd=109]="NumpadAdd",e[e.NUMPAD_SEPARATOR=110]="NUMPAD_SEPARATOR",e[e.NumpadSubtract=111]="NumpadSubtract",e[e.NumpadDecimal=112]="NumpadDecimal",e[e.NumpadDivide=113]="NumpadDivide",e[e.KEY_IN_COMPOSITION=114]="KEY_IN_COMPOSITION",e[e.ABNT_C1=115]="ABNT_C1",e[e.ABNT_C2=116]="ABNT_C2",e[e.AudioVolumeMute=117]="AudioVolumeMute",e[e.AudioVolumeUp=118]="AudioVolumeUp",e[e.AudioVolumeDown=119]="AudioVolumeDown",e[e.BrowserSearch=120]="BrowserSearch",e[e.BrowserHome=121]="BrowserHome",e[e.BrowserBack=122]="BrowserBack",e[e.BrowserForward=123]="BrowserForward",e[e.MediaTrackNext=124]="MediaTrackNext",e[e.MediaTrackPrevious=125]="MediaTrackPrevious",e[e.MediaStop=126]="MediaStop",e[e.MediaPlayPause=127]="MediaPlayPause",e[e.LaunchMediaPlayer=128]="LaunchMediaPlayer",e[e.LaunchMail=129]="LaunchMail",e[e.LaunchApp2=130]="LaunchApp2",e[e.Clear=131]="Clear",e[e.MAX_VALUE=132]="MAX_VALUE"}(i||(t.KeyCode=i={})),function(e){e[e.DependsOnKbLayout=-1]="DependsOnKbLayout",e[e.None=0]="None",e[e.Hyper=1]="Hyper",e[e.Super=2]="Super",e[e.Fn=3]="Fn",e[e.FnLock=4]="FnLock",e[e.Suspend=5]="Suspend",e[e.Resume=6]="Resume",e[e.Turbo=7]="Turbo",e[e.Sleep=8]="Sleep",e[e.WakeUp=9]="WakeUp",e[e.KeyA=10]="KeyA",e[e.KeyB=11]="KeyB",e[e.KeyC=12]="KeyC",e[e.KeyD=13]="KeyD",e[e.KeyE=14]="KeyE",e[e.KeyF=15]="KeyF",e[e.KeyG=16]="KeyG",e[e.KeyH=17]="KeyH",e[e.KeyI=18]="KeyI",e[e.KeyJ=19]="KeyJ",e[e.KeyK=20]="KeyK",e[e.KeyL=21]="KeyL",e[e.KeyM=22]="KeyM",e[e.KeyN=23]="KeyN",e[e.KeyO=24]="KeyO",e[e.KeyP=25]="KeyP",e[e.KeyQ=26]="KeyQ",e[e.KeyR=27]="KeyR",e[e.KeyS=28]="KeyS",e[e.KeyT=29]="KeyT",e[e.KeyU=30]="KeyU",e[e.KeyV=31]="KeyV",e[e.KeyW=32]="KeyW",e[e.KeyX=33]="KeyX",e[e.KeyY=34]="KeyY",e[e.KeyZ=35]="KeyZ",e[e.Digit1=36]="Digit1",e[e.Digit2=37]="Digit2",e[e.Digit3=38]="Digit3",e[e.Digit4=39]="Digit4",e[e.Digit5=40]="Digit5",e[e.Digit6=41]="Digit6",e[e.Digit7=42]="Digit7",e[e.Digit8=43]="Digit8",e[e.Digit9=44]="Digit9",e[e.Digit0=45]="Digit0",e[e.Enter=46]="Enter",e[e.Escape=47]="Escape",e[e.Backspace=48]="Backspace",e[e.Tab=49]="Tab",e[e.Space=50]="Space",e[e.Minus=51]="Minus",e[e.Equal=52]="Equal",e[e.BracketLeft=53]="BracketLeft",e[e.BracketRight=54]="BracketRight",e[e.Backslash=55]="Backslash",e[e.IntlHash=56]="IntlHash",e[e.Semicolon=57]="Semicolon",e[e.Quote=58]="Quote",e[e.Backquote=59]="Backquote",e[e.Comma=60]="Comma",e[e.Period=61]="Period",e[e.Slash=62]="Slash",e[e.CapsLock=63]="CapsLock",e[e.F1=64]="F1",e[e.F2=65]="F2",e[e.F3=66]="F3",e[e.F4=67]="F4",e[e.F5=68]="F5",e[e.F6=69]="F6",e[e.F7=70]="F7",e[e.F8=71]="F8",e[e.F9=72]="F9",e[e.F10=73]="F10",e[e.F11=74]="F11",e[e.F12=75]="F12",e[e.PrintScreen=76]="PrintScreen",e[e.ScrollLock=77]="ScrollLock",e[e.Pause=78]="Pause",e[e.Insert=79]="Insert",e[e.Home=80]="Home",e[e.PageUp=81]="PageUp",e[e.Delete=82]="Delete",e[e.End=83]="End",e[e.PageDown=84]="PageDown",e[e.ArrowRight=85]="ArrowRight",e[e.ArrowLeft=86]="ArrowLeft",e[e.ArrowDown=87]="ArrowDown",e[e.ArrowUp=88]="ArrowUp",e[e.NumLock=89]="NumLock",e[e.NumpadDivide=90]="NumpadDivide",e[e.NumpadMultiply=91]="NumpadMultiply",e[e.NumpadSubtract=92]="NumpadSubtract",e[e.NumpadAdd=93]="NumpadAdd",e[e.NumpadEnter=94]="NumpadEnter",e[e.Numpad1=95]="Numpad1",e[e.Numpad2=96]="Numpad2",e[e.Numpad3=97]="Numpad3",e[e.Numpad4=98]="Numpad4",e[e.Numpad5=99]="Numpad5",e[e.Numpad6=100]="Numpad6",e[e.Numpad7=101]="Numpad7",e[e.Numpad8=102]="Numpad8",e[e.Numpad9=103]="Numpad9",e[e.Numpad0=104]="Numpad0",e[e.NumpadDecimal=105]="NumpadDecimal",e[e.IntlBackslash=106]="IntlBackslash",e[e.ContextMenu=107]="ContextMenu",e[e.Power=108]="Power",e[e.NumpadEqual=109]="NumpadEqual",e[e.F13=110]="F13",e[e.F14=111]="F14",e[e.F15=112]="F15",e[e.F16=113]="F16",e[e.F17=114]="F17",e[e.F18=115]="F18",e[e.F19=116]="F19",e[e.F20=117]="F20",e[e.F21=118]="F21",e[e.F22=119]="F22",e[e.F23=120]="F23",e[e.F24=121]="F24",e[e.Open=122]="Open",e[e.Help=123]="Help",e[e.Select=124]="Select",e[e.Again=125]="Again",e[e.Undo=126]="Undo",e[e.Cut=127]="Cut",e[e.Copy=128]="Copy",e[e.Paste=129]="Paste",e[e.Find=130]="Find",e[e.AudioVolumeMute=131]="AudioVolumeMute",e[e.AudioVolumeUp=132]="AudioVolumeUp",e[e.AudioVolumeDown=133]="AudioVolumeDown",e[e.NumpadComma=134]="NumpadComma",e[e.IntlRo=135]="IntlRo",e[e.KanaMode=136]="KanaMode",e[e.IntlYen=137]="IntlYen",e[e.Convert=138]="Convert",e[e.NonConvert=139]="NonConvert",e[e.Lang1=140]="Lang1",e[e.Lang2=141]="Lang2",e[e.Lang3=142]="Lang3",e[e.Lang4=143]="Lang4",e[e.Lang5=144]="Lang5",e[e.Abort=145]="Abort",e[e.Props=146]="Props",e[e.NumpadParenLeft=147]="NumpadParenLeft",e[e.NumpadParenRight=148]="NumpadParenRight",e[e.NumpadBackspace=149]="NumpadBackspace",e[e.NumpadMemoryStore=150]="NumpadMemoryStore",e[e.NumpadMemoryRecall=151]="NumpadMemoryRecall",e[e.NumpadMemoryClear=152]="NumpadMemoryClear",e[e.NumpadMemoryAdd=153]="NumpadMemoryAdd",e[e.NumpadMemorySubtract=154]="NumpadMemorySubtract",e[e.NumpadClear=155]="NumpadClear",e[e.NumpadClearEntry=156]="NumpadClearEntry",e[e.ControlLeft=157]="ControlLeft",e[e.ShiftLeft=158]="ShiftLeft",e[e.AltLeft=159]="AltLeft",e[e.MetaLeft=160]="MetaLeft",e[e.ControlRight=161]="ControlRight",e[e.ShiftRight=162]="ShiftRight",e[e.AltRight=163]="AltRight",e[e.MetaRight=164]="MetaRight",e[e.BrightnessUp=165]="BrightnessUp",e[e.BrightnessDown=166]="BrightnessDown",e[e.MediaPlay=167]="MediaPlay",e[e.MediaRecord=168]="MediaRecord",e[e.MediaFastForward=169]="MediaFastForward",e[e.MediaRewind=170]="MediaRewind",e[e.MediaTrackNext=171]="MediaTrackNext",e[e.MediaTrackPrevious=172]="MediaTrackPrevious",e[e.MediaStop=173]="MediaStop",e[e.Eject=174]="Eject",e[e.MediaPlayPause=175]="MediaPlayPause",e[e.MediaSelect=176]="MediaSelect",e[e.LaunchMail=177]="LaunchMail",e[e.LaunchApp2=178]="LaunchApp2",e[e.LaunchApp1=179]="LaunchApp1",e[e.SelectTask=180]="SelectTask",e[e.LaunchScreenSaver=181]="LaunchScreenSaver",e[e.BrowserSearch=182]="BrowserSearch",e[e.BrowserHome=183]="BrowserHome",e[e.BrowserBack=184]="BrowserBack",e[e.BrowserForward=185]="BrowserForward",e[e.BrowserStop=186]="BrowserStop",e[e.BrowserRefresh=187]="BrowserRefresh",e[e.BrowserFavorites=188]="BrowserFavorites",e[e.ZoomToggle=189]="ZoomToggle",e[e.MailReply=190]="MailReply",e[e.MailForward=191]="MailForward",e[e.MailSend=192]="MailSend",e[e.MAX_VALUE=193]="MAX_VALUE"}(s||(t.ScanCode=s={}));class r{constructor(){this._keyCodeToStr=[],this._strToKeyCode=Object.create(null)}define(e,t){this._keyCodeToStr[e]=t,this._strToKeyCode[t.toLowerCase()]=e}keyCodeToStr(e){return this._keyCodeToStr[e]}strToKeyCode(e){return this._strToKeyCode[e.toLowerCase()]||i.Unknown}}const n=new r,o=new r,a=new r;t.EVENT_KEY_CODE_MAP=new Array(230),t.NATIVE_WINDOWS_KEY_CODE_TO_KEY_CODE={};const l=[],h=Object.create(null),c=Object.create(null);var d,u;t.ScanCodeUtils={lowerCaseToEnum:e=>c[e]||s.None,toEnum:e=>h[e]||s.None,toString:e=>l[e]||"None"},function(e){e.toString=function(e){return n.keyCodeToStr(e)},e.fromString=function(e){return n.strToKeyCode(e)},e.toUserSettingsUS=function(e){return o.keyCodeToStr(e)},e.toUserSettingsGeneral=function(e){return a.keyCodeToStr(e)},e.fromUserSettings=function(e){return o.strToKeyCode(e)||a.strToKeyCode(e)},e.toElectronAccelerator=function(e){if(e>=i.Numpad0&&e<=i.NumpadDivide)return null;switch(e){case i.UpArrow:return"Up";case i.DownArrow:return"Down";case i.LeftArrow:return"Left";case i.RightArrow:return"Right"}return n.keyCodeToStr(e)}}(d||(t.KeyCodeUtils=d={})),function(e){e[e.CtrlCmd=2048]="CtrlCmd",e[e.Shift=1024]="Shift",e[e.Alt=512]="Alt",e[e.WinCtrl=256]="WinCtrl"}(u||(t.KeyMod=u={}))},2811:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ResolvedKeybinding=t.ResolvedChord=t.Keybinding=t.ScanCodeChord=t.KeyCodeChord=void 0,t.decodeKeybinding=function(e,t){if("number"==typeof e){if(0===e)return null;const i=(65535&e)>>>0,s=(4294901760&e)>>>16;return new c(0!==s?[a(i,t),a(s,t)]:[a(i,t)])}{const i=[];for(let s=0;s{Object.defineProperty(t,"__esModule",{value:!0}),t.Lazy=void 0,t.Lazy=class{constructor(e){this.executor=e,this._didRun=!1}get hasValue(){return this._didRun}get value(){if(!this._didRun)try{this._value=this.executor()}catch(e){this._error=e}finally{this._didRun=!0}if(this._error)throw this._error;return this._value}get rawValue(){return this._value}}},7150:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DisposableMap=t.ImmortalReference=t.AsyncReferenceCollection=t.ReferenceCollection=t.SafeDisposable=t.RefCountedDisposable=t.MandatoryMutableDisposable=t.MutableDisposable=t.Disposable=t.DisposableStore=t.DisposableTracker=void 0,t.setDisposableTracker=function(e){l=e},t.trackDisposable=c,t.markAsDisposed=d,t.markAsSingleton=function(e){return l?.markAsSingleton(e),e},t.isDisposable=_,t.dispose=f,t.disposeIfDisposable=function(e){for(const t of e)_(t)&&t.dispose();return[]},t.combinedDisposable=function(...e){const t=p((()=>f(e)));return function(e,t){if(l)for(const i of e)l.setParent(i,t)}(e,t),t},t.toDisposable=p,t.disposeOnReturn=function(e){const t=new g;try{e(t)}finally{t.dispose()}};const s=i(3058),r=i(9087),n=i(2608),o=i(8841),a=i(4218);let l=null;class h{constructor(){this.livingDisposables=new Map}static{this.idx=0}getDisposableData(e){let t=this.livingDisposables.get(e);return t||(t={parent:null,source:null,isSingleton:!1,value:e,idx:h.idx++},this.livingDisposables.set(e,t)),t}trackDisposable(e){const t=this.getDisposableData(e);t.source||(t.source=(new Error).stack)}setParent(e,t){this.getDisposableData(e).parent=t}markAsDisposed(e){this.livingDisposables.delete(e)}markAsSingleton(e){this.getDisposableData(e).isSingleton=!0}getRootParent(e,t){const i=t.get(e);if(i)return i;const s=e.parent?this.getRootParent(this.getDisposableData(e.parent),t):e;return t.set(e,s),s}getTrackedDisposables(){const e=new Map;return[...this.livingDisposables.entries()].filter((([,t])=>null!==t.source&&!this.getRootParent(t,e).isSingleton)).flatMap((([e])=>e))}computeLeakingDisposables(e=10,t){let i;if(t)i=t;else{const e=new Map,t=[...this.livingDisposables.values()].filter((t=>null!==t.source&&!this.getRootParent(t,e).isSingleton));if(0===t.length)return;const s=new Set(t.map((e=>e.value)));if(i=t.filter((e=>!(e.parent&&s.has(e.parent)))),0===i.length)throw new Error("There are cyclic diposable chains!")}if(!i)return;function o(e){const t=e.source.split("\n").map((e=>e.trim().replace("at ",""))).filter((e=>""!==e));return function(e,t){for(;e.length>0&&t.some((t=>"string"==typeof t?t===e[0]:e[0].match(t)));)e.shift()}(t,["Error",/^trackDisposable \(.*\)$/,/^DisposableTracker.trackDisposable \(.*\)$/]),t.reverse()}const a=new n.SetMap;for(const e of i){const t=o(e);for(let i=0;i<=t.length;i++)a.add(t.slice(0,i).join("\n"),e)}i.sort((0,s.compareBy)((e=>e.idx),s.numberComparator));let l="",h=0;for(const t of i.slice(0,e)){h++;const e=o(t),s=[];for(let t=0;to(e)[t])),(e=>e));delete h[e[t]];for(const[e,t]of Object.entries(h))s.unshift(` - stacktraces of ${t.length} other leaks continue with ${e}`);s.unshift(n)}l+=`\n\n\n==================== Leaking disposable ${h}/${i.length}: ${t.value.constructor.name} ====================\n${s.join("\n")}\n============================================================\n\n`}return i.length>e&&(l+=`\n\n\n... and ${i.length-e} more leaking disposables\n\n`),{leaks:i,details:l}}}function c(e){return l?.trackDisposable(e),e}function d(e){l?.markAsDisposed(e)}function u(e,t){l?.setParent(e,t)}function _(e){return"object"==typeof e&&null!==e&&"function"==typeof e.dispose&&0===e.dispose.length}function f(e){if(a.Iterable.is(e)){const t=[];for(const i of e)if(i)try{i.dispose()}catch(e){t.push(e)}if(1===t.length)throw t[0];if(t.length>1)throw new AggregateError(t,"Encountered errors while disposing of store");return Array.isArray(e)?[]:e}if(e)return e.dispose(),e}function p(e){const t=c({dispose:(0,o.createSingleCallFunction)((()=>{d(t),e()}))});return t}t.DisposableTracker=h;class g{static{this.DISABLE_DISPOSED_WARNING=!1}constructor(){this._toDispose=new Set,this._isDisposed=!1,c(this)}dispose(){this._isDisposed||(d(this),this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(0!==this._toDispose.size)try{f(this._toDispose)}finally{this._toDispose.clear()}}add(e){if(!e)return e;if(e===this)throw new Error("Cannot register a disposable on itself!");return u(e,this),this._isDisposed?g.DISABLE_DISPOSED_WARNING||console.warn(new Error("Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!").stack):this._toDispose.add(e),e}delete(e){if(e){if(e===this)throw new Error("Cannot dispose a disposable on itself!");this._toDispose.delete(e),e.dispose()}}deleteAndLeak(e){e&&this._toDispose.has(e)&&(this._toDispose.delete(e),u(e,null))}}t.DisposableStore=g;class m{static{this.None=Object.freeze({dispose(){}})}constructor(){this._store=new g,c(this),u(this._store,this)}dispose(){d(this),this._store.dispose()}_register(e){if(e===this)throw new Error("Cannot register a disposable on itself!");return this._store.add(e)}}t.Disposable=m;class v{constructor(){this._isDisposed=!1,c(this)}get value(){return this._isDisposed?void 0:this._value}set value(e){this._isDisposed||e===this._value||(this._value?.dispose(),e&&u(e,this),this._value=e)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,d(this),this._value?.dispose(),this._value=void 0}clearAndLeak(){const e=this._value;return this._value=void 0,e&&u(e,null),e}}t.MutableDisposable=v,t.MandatoryMutableDisposable=class{constructor(e){this._disposable=new v,this._isDisposed=!1,this._disposable.value=e}get value(){return this._disposable.value}set value(e){this._isDisposed||e===this._disposable.value||(this._disposable.value=e)}dispose(){this._isDisposed=!0,this._disposable.dispose()}},t.RefCountedDisposable=class{constructor(e){this._disposable=e,this._counter=1}acquire(){return this._counter++,this}release(){return 0==--this._counter&&this._disposable.dispose(),this}},t.SafeDisposable=class{constructor(){this.dispose=()=>{},this.unset=()=>{},this.isset=()=>!1,c(this)}set(e){let t=e;return this.unset=()=>t=void 0,this.isset=()=>void 0!==t,this.dispose=()=>{t&&(t(),t=void 0,d(this))},this}},t.ReferenceCollection=class{constructor(){this.references=new Map}acquire(e,...t){let i=this.references.get(e);i||(i={counter:0,object:this.createReferencedObject(e,...t)},this.references.set(e,i));const{object:s}=i,r=(0,o.createSingleCallFunction)((()=>{0==--i.counter&&(this.destroyReferencedObject(e,i.object),this.references.delete(e))}));return i.counter++,{object:s,dispose:r}}},t.AsyncReferenceCollection=class{constructor(e){this.referenceCollection=e}async acquire(e,...t){const i=this.referenceCollection.acquire(e,...t);try{return{object:await i.object,dispose:()=>i.dispose()}}catch(e){throw i.dispose(),e}}},t.ImmortalReference=class{constructor(e){this.object=e}dispose(){}};class S{constructor(){this._store=new Map,this._isDisposed=!1,c(this)}dispose(){d(this),this._isDisposed=!0,this.clearAndDisposeAll()}clearAndDisposeAll(){if(this._store.size)try{f(this._store.values())}finally{this._store.clear()}}has(e){return this._store.has(e)}get size(){return this._store.size}get(e){return this._store.get(e)}set(e,t,i=!1){this._isDisposed&&console.warn(new Error("Trying to add a disposable to a DisposableMap that has already been disposed of. The added object will be leaked!").stack),i||this._store.get(e)?.dispose(),this._store.set(e,t)}deleteAndDispose(e){this._store.get(e)?.dispose(),this._store.delete(e)}deleteAndLeak(e){const t=this._store.get(e);return this._store.delete(e),t}keys(){return this._store.keys()}values(){return this._store.values()}[Symbol.iterator](){return this._store[Symbol.iterator]()}}t.DisposableMap=S},6317:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.LinkedList=void 0;class i{static{this.Undefined=new i(void 0)}constructor(e){this.element=e,this.next=i.Undefined,this.prev=i.Undefined}}class s{constructor(){this._first=i.Undefined,this._last=i.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===i.Undefined}clear(){let e=this._first;for(;e!==i.Undefined;){const t=e.next;e.prev=i.Undefined,e.next=i.Undefined,e=t}this._first=i.Undefined,this._last=i.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){const s=new i(e);if(this._first===i.Undefined)this._first=s,this._last=s;else if(t){const e=this._last;this._last=s,s.prev=e,e.next=s}else{const e=this._first;this._first=s,s.next=e,e.prev=s}this._size+=1;let r=!1;return()=>{r||(r=!0,this._remove(s))}}shift(){if(this._first!==i.Undefined){const e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==i.Undefined){const e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==i.Undefined&&e.next!==i.Undefined){const t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===i.Undefined&&e.next===i.Undefined?(this._first=i.Undefined,this._last=i.Undefined):e.next===i.Undefined?(this._last=this._last.prev,this._last.next=i.Undefined):e.prev===i.Undefined&&(this._first=this._first.next,this._first.prev=i.Undefined);this._size-=1}*[Symbol.iterator](){let e=this._first;for(;e!==i.Undefined;)yield e.element,e=e.next}}t.LinkedList=s},2608:(e,t)=>{var i;Object.defineProperty(t,"__esModule",{value:!0}),t.SetMap=t.BidirectionalMap=t.CounterSet=t.Touch=void 0,t.getOrSet=function(e,t,i){let s=e.get(t);return void 0===s&&(s=i,e.set(t,s)),s},t.mapToString=function(e){const t=[];return e.forEach(((e,i)=>{t.push(`${i} => ${e}`)})),`Map(${e.size}) {${t.join(", ")}}`},t.setToString=function(e){const t=[];return e.forEach((e=>{t.push(e)})),`Set(${e.size}) {${t.join(", ")}}`},t.mapsStrictEqualIgnoreOrder=function(e,t){if(e===t)return!0;if(e.size!==t.size)return!1;for(const[i,s]of e)if(!t.has(i)||t.get(i)!==s)return!1;for(const[i]of t)if(!e.has(i))return!1;return!0},function(e){e[e.None=0]="None",e[e.AsOld=1]="AsOld",e[e.AsNew=2]="AsNew"}(i||(t.Touch=i={})),t.CounterSet=class{constructor(){this.map=new Map}add(e){return this.map.set(e,(this.map.get(e)||0)+1),this}delete(e){let t=this.map.get(e)||0;return 0!==t&&(t--,0===t?this.map.delete(e):this.map.set(e,t),!0)}has(e){return this.map.has(e)}},t.BidirectionalMap=class{constructor(e){if(this._m1=new Map,this._m2=new Map,e)for(const[t,i]of e)this.set(t,i)}clear(){this._m1.clear(),this._m2.clear()}set(e,t){this._m1.set(e,t),this._m2.set(t,e)}get(e){return this._m1.get(e)}getKey(e){return this._m2.get(e)}delete(e){const t=this._m1.get(e);return void 0!==t&&(this._m1.delete(e),this._m2.delete(t),!0)}forEach(e,t){this._m1.forEach(((i,s)=>{e.call(t,i,s,this)}))}keys(){return this._m1.keys()}values(){return this._m1.values()}},t.SetMap=class{constructor(){this.map=new Map}add(e,t){let i=this.map.get(e);i||(i=new Set,this.map.set(e,i)),i.add(t)}delete(e,t){const i=this.map.get(e);i&&(i.delete(t),0===i.size&&this.map.delete(e))}forEach(e,t){const i=this.map.get(e);i&&i.forEach(t)}get(e){return this.map.get(e)||new Set}}},7704:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SlidingWindowAverage=t.MovingAverage=t.Counter=void 0,t.clamp=function(e,t,i){return Math.min(Math.max(e,t),i)},t.rot=function(e,t){return(t+e%t)%t},t.isPointWithinTriangle=function(e,t,i,s,r,n,o,a){const l=o-i,h=a-s,c=r-i,d=n-s,u=e-i,_=t-s,f=l*l+h*h,p=l*c+h*d,g=l*u+h*_,m=c*c+d*d,v=c*u+d*_,S=1/(f*m-p*p),b=(m*g-p*v)*S,C=(f*v-p*g)*S;return b>=0&&C>=0&&b+C<1},t.Counter=class{constructor(){this._next=0}getNext(){return this._next++}},t.MovingAverage=class{constructor(){this._n=1,this._val=0}update(e){return this._val=this._val+(e-this._val)/this._n,this._n+=1,this._val}get value(){return this._val}},t.SlidingWindowAverage=class{constructor(e){this._n=0,this._val=0,this._values=[],this._index=0,this._sum=0,this._values=new Array(e),this._values.fill(0,0,e)}update(e){const t=this._values[this._index];return this._values[this._index]=e,this._index=(this._index+1)%this._values.length,this._sum-=t,this._sum+=e,this._n{Object.defineProperty(t,"__esModule",{value:!0}),t.isAndroid=t.isEdge=t.isSafari=t.isFirefox=t.isChrome=t.OS=t.OperatingSystem=t.setTimeout0=t.setTimeout0IsFaster=t.translationsConfigFile=t.platformLocale=t.locale=t.Language=t.language=t.userAgent=t.platform=t.isCI=t.isMobile=t.isIOS=t.webWorkerOrigin=t.isWebWorker=t.isWeb=t.isElectron=t.isNative=t.isLinuxSnap=t.isLinux=t.isMacintosh=t.isWindows=t.Platform=t.LANGUAGE_DEFAULT=void 0,t.PlatformToString=function(e){switch(e){case C.Web:return"Web";case C.Mac:return"Mac";case C.Linux:return"Linux";case C.Windows:return"Windows"}},t.isLittleEndian=function(){if(!L){L=!0;const e=new Uint8Array(2);e[0]=1,e[1]=2;const t=new Uint16Array(e.buffer);D=513===t[0]}return D},t.isBigSurOrNewer=function(e){return parseFloat(e)>=20},t.LANGUAGE_DEFAULT="en";let i,s,r,n=!1,o=!1,a=!1,l=!1,h=!1,c=!1,d=!1,u=!1,_=!1,f=!1,p=t.LANGUAGE_DEFAULT,g=t.LANGUAGE_DEFAULT;const m=globalThis;let v;void 0!==m.vscode&&void 0!==m.vscode.process?v=m.vscode.process:"undefined"!=typeof process&&"string"==typeof process?.versions?.node&&(v=process);const S="string"==typeof v?.versions?.electron,b=S&&"renderer"===v?.type;if("object"==typeof v){n="win32"===v.platform,o="darwin"===v.platform,a="linux"===v.platform,l=a&&!!v.env.SNAP&&!!v.env.SNAP_REVISION,d=S,_=!!v.env.CI||!!v.env.BUILD_ARTIFACTSTAGINGDIRECTORY,i=t.LANGUAGE_DEFAULT,p=t.LANGUAGE_DEFAULT;const e=v.env.VSCODE_NLS_CONFIG;if(e)try{const r=JSON.parse(e);i=r.userLocale,g=r.osLocale,p=r.resolvedLanguage||t.LANGUAGE_DEFAULT,s=r.languagePack?.translationsConfigFile}catch(e){}h=!0}else"object"!=typeof navigator||b?console.error("Unable to resolve platform."):(r=navigator.userAgent,n=r.indexOf("Windows")>=0,o=r.indexOf("Macintosh")>=0,u=(r.indexOf("Macintosh")>=0||r.indexOf("iPad")>=0||r.indexOf("iPhone")>=0)&&!!navigator.maxTouchPoints&&navigator.maxTouchPoints>0,a=r.indexOf("Linux")>=0,f=r?.indexOf("Mobi")>=0,c=!0,p=globalThis._VSCODE_NLS_LANGUAGE||t.LANGUAGE_DEFAULT,i=navigator.language.toLowerCase(),g=i);var C;!function(e){e[e.Web=0]="Web",e[e.Mac=1]="Mac",e[e.Linux=2]="Linux",e[e.Windows=3]="Windows"}(C||(t.Platform=C={}));let y=C.Web;var w,E;o?y=C.Mac:n?y=C.Windows:a&&(y=C.Linux),t.isWindows=n,t.isMacintosh=o,t.isLinux=a,t.isLinuxSnap=l,t.isNative=h,t.isElectron=d,t.isWeb=c,t.isWebWorker=c&&"function"==typeof m.importScripts,t.webWorkerOrigin=t.isWebWorker?m.origin:void 0,t.isIOS=u,t.isMobile=f,t.isCI=_,t.platform=y,t.userAgent=r,t.language=p,function(e){e.value=function(){return t.language},e.isDefaultVariant=function(){return 2===t.language.length?"en"===t.language:t.language.length>=3&&"e"===t.language[0]&&"n"===t.language[1]&&"-"===t.language[2]},e.isDefault=function(){return"en"===t.language}}(w||(t.Language=w={})),t.locale=i,t.platformLocale=g,t.translationsConfigFile=s,t.setTimeout0IsFaster="function"==typeof m.postMessage&&!m.importScripts,t.setTimeout0=(()=>{if(t.setTimeout0IsFaster){const e=[];m.addEventListener("message",(t=>{if(t.data&&t.data.vscodeScheduleAsyncWork)for(let i=0,s=e.length;i{const s=++t;e.push({id:s,callback:i}),m.postMessage({vscodeScheduleAsyncWork:s},"*")}}return e=>setTimeout(e)})(),function(e){e[e.Windows=1]="Windows",e[e.Macintosh=2]="Macintosh",e[e.Linux=3]="Linux"}(E||(t.OperatingSystem=E={})),t.OS=o||u?E.Macintosh:n?E.Windows:E.Linux;let D=!0,L=!1;t.isChrome=!!(t.userAgent&&t.userAgent.indexOf("Chrome")>=0),t.isFirefox=!!(t.userAgent&&t.userAgent.indexOf("Firefox")>=0),t.isSafari=!!(!t.isChrome&&t.userAgent&&t.userAgent.indexOf("Safari")>=0),t.isEdge=!!(t.userAgent&&t.userAgent.indexOf("Edg/")>=0),t.isAndroid=!!(t.userAgent&&t.userAgent.indexOf("Android")>=0)},9881:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SmoothScrollingOperation=t.SmoothScrollingUpdate=t.Scrollable=t.ScrollState=t.ScrollbarVisibility=void 0;const s=i(802),r=i(7150);var n;!function(e){e[e.Auto=1]="Auto",e[e.Hidden=2]="Hidden",e[e.Visible=3]="Visible"}(n||(t.ScrollbarVisibility=n={}));class o{constructor(e,t,i,s,r,n,o){this._forceIntegerValues=e,this._scrollStateBrand=void 0,this._forceIntegerValues&&(t|=0,i|=0,s|=0,r|=0,n|=0,o|=0),this.rawScrollLeft=s,this.rawScrollTop=o,t<0&&(t=0),s+t>i&&(s=i-t),s<0&&(s=0),r<0&&(r=0),o+r>n&&(o=n-r),o<0&&(o=0),this.width=t,this.scrollWidth=i,this.scrollLeft=s,this.height=r,this.scrollHeight=n,this.scrollTop=o}equals(e){return this.rawScrollLeft===e.rawScrollLeft&&this.rawScrollTop===e.rawScrollTop&&this.width===e.width&&this.scrollWidth===e.scrollWidth&&this.scrollLeft===e.scrollLeft&&this.height===e.height&&this.scrollHeight===e.scrollHeight&&this.scrollTop===e.scrollTop}withScrollDimensions(e,t){return new o(this._forceIntegerValues,void 0!==e.width?e.width:this.width,void 0!==e.scrollWidth?e.scrollWidth:this.scrollWidth,t?this.rawScrollLeft:this.scrollLeft,void 0!==e.height?e.height:this.height,void 0!==e.scrollHeight?e.scrollHeight:this.scrollHeight,t?this.rawScrollTop:this.scrollTop)}withScrollPosition(e){return new o(this._forceIntegerValues,this.width,this.scrollWidth,void 0!==e.scrollLeft?e.scrollLeft:this.rawScrollLeft,this.height,this.scrollHeight,void 0!==e.scrollTop?e.scrollTop:this.rawScrollTop)}createScrollEvent(e,t){const i=this.width!==e.width,s=this.scrollWidth!==e.scrollWidth,r=this.scrollLeft!==e.scrollLeft,n=this.height!==e.height,o=this.scrollHeight!==e.scrollHeight,a=this.scrollTop!==e.scrollTop;return{inSmoothScrolling:t,oldWidth:e.width,oldScrollWidth:e.scrollWidth,oldScrollLeft:e.scrollLeft,width:this.width,scrollWidth:this.scrollWidth,scrollLeft:this.scrollLeft,oldHeight:e.height,oldScrollHeight:e.scrollHeight,oldScrollTop:e.scrollTop,height:this.height,scrollHeight:this.scrollHeight,scrollTop:this.scrollTop,widthChanged:i,scrollWidthChanged:s,scrollLeftChanged:r,heightChanged:n,scrollHeightChanged:o,scrollTopChanged:a}}}t.ScrollState=o;class a extends r.Disposable{constructor(e){super(),this._scrollableBrand=void 0,this._onScroll=this._register(new s.Emitter),this.onScroll=this._onScroll.event,this._smoothScrollDuration=e.smoothScrollDuration,this._scheduleAtNextAnimationFrame=e.scheduleAtNextAnimationFrame,this._state=new o(e.forceIntegerValues,0,0,0,0,0,0),this._smoothScrolling=null}dispose(){this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),super.dispose()}setSmoothScrollDuration(e){this._smoothScrollDuration=e}validateScrollPosition(e){return this._state.withScrollPosition(e)}getScrollDimensions(){return this._state}setScrollDimensions(e,t){const i=this._state.withScrollDimensions(e,t);this._setState(i,Boolean(this._smoothScrolling)),this._smoothScrolling?.acceptScrollDimensions(this._state)}getFutureScrollPosition(){return this._smoothScrolling?this._smoothScrolling.to:this._state}getCurrentScrollPosition(){return this._state}setScrollPositionNow(e){const t=this._state.withScrollPosition(e);this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),this._setState(t,!1)}setScrollPositionSmooth(e,t){if(0===this._smoothScrollDuration)return this.setScrollPositionNow(e);if(this._smoothScrolling){e={scrollLeft:void 0===e.scrollLeft?this._smoothScrolling.to.scrollLeft:e.scrollLeft,scrollTop:void 0===e.scrollTop?this._smoothScrolling.to.scrollTop:e.scrollTop};const i=this._state.withScrollPosition(e);if(this._smoothScrolling.to.scrollLeft===i.scrollLeft&&this._smoothScrolling.to.scrollTop===i.scrollTop)return;let s;s=t?new c(this._smoothScrolling.from,i,this._smoothScrolling.startTime,this._smoothScrolling.duration):this._smoothScrolling.combine(this._state,i,this._smoothScrollDuration),this._smoothScrolling.dispose(),this._smoothScrolling=s}else{const t=this._state.withScrollPosition(e);this._smoothScrolling=c.start(this._state,t,this._smoothScrollDuration)}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame((()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())}))}hasPendingScrollAnimation(){return Boolean(this._smoothScrolling)}_performSmoothScrolling(){if(!this._smoothScrolling)return;const e=this._smoothScrolling.tick(),t=this._state.withScrollPosition(e);return this._setState(t,!0),this._smoothScrolling?e.isDone?(this._smoothScrolling.dispose(),void(this._smoothScrolling=null)):void(this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame((()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())}))):void 0}_setState(e,t){const i=this._state;i.equals(e)||(this._state=e,this._onScroll.fire(this._state.createScrollEvent(i,t)))}}t.Scrollable=a;class l{constructor(e,t,i){this.scrollLeft=e,this.scrollTop=t,this.isDone=i}}function h(e,t){const i=t-e;return function(t){return e+i*(1-(s=1-t,Math.pow(s,3)));var s}}t.SmoothScrollingUpdate=l;class c{constructor(e,t,i,s){this.from=e,this.to=t,this.duration=s,this.startTime=i,this.animationFrameDisposable=null,this._initAnimations()}_initAnimations(){this.scrollLeft=this._initAnimation(this.from.scrollLeft,this.to.scrollLeft,this.to.width),this.scrollTop=this._initAnimation(this.from.scrollTop,this.to.scrollTop,this.to.height)}_initAnimation(e,t,i){if(Math.abs(e-t)>2.5*i){let o,a;return e{Object.defineProperty(t,"__esModule",{value:!0}),t.StopWatch=void 0;const i=globalThis.performance&&"function"==typeof globalThis.performance.now;class s{static create(e){return new s(e)}constructor(e){this._now=i&&!1===e?Date.now:globalThis.performance.now.bind(globalThis.performance),this._startTime=this._now(),this._stopTime=-1}stop(){this._stopTime=this._now()}reset(){this._startTime=this._now(),this._stopTime=-1}elapsed(){return-1!==this._stopTime?this._stopTime-this._startTime:this._now()-this._startTime}}t.StopWatch=s},1316:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.noBreakWhitespace=t.CodePointIterator=void 0,t.isFalsyOrWhitespace=function(e){return!e||"string"!=typeof e||0===e.trim().length},t.format=function(e,...t){return 0===t.length?e:e.replace(n,(function(e,i){const s=parseInt(i,10);return isNaN(s)||s<0||s>=t.length?e:t[s]}))},t.format2=function(e,t){return 0===Object.keys(t).length?e:e.replace(o,((e,i)=>t[i]??e))},t.htmlAttributeEncodeValue=function(e){return e.replace(/[<>"'&]/g,(e=>{switch(e){case"<":return"<";case">":return">";case'"':return""";case"'":return"'";case"&":return"&"}return e}))},t.escape=function(e){return e.replace(/[<>&]/g,(function(e){switch(e){case"<":return"<";case">":return">";case"&":return"&";default:return e}}))},t.escapeRegExpCharacters=a,t.count=function(e,t){let i=0,s=e.indexOf(t);for(;-1!==s;)i++,s=e.indexOf(t,s+t.length);return i},t.truncate=function(e,t,i="…"){return e.length<=t?e:`${e.substr(0,t)}${i}`},t.truncateMiddle=function(e,t,i="…"){if(e.length<=t)return e;const s=Math.ceil(t/2)-i.length/2,r=Math.floor(t/2)-i.length/2;return`${e.substr(0,s)}${i}${e.substr(e.length-r)}`},t.trim=function(e,t=" "){return h(l(e,t),t)},t.ltrim=l,t.rtrim=h,t.convertSimple2RegExpPattern=function(e){return e.replace(/[\-\\\{\}\+\?\|\^\$\.\,\[\]\(\)\#\s]/g,"\\$&").replace(/[\*]/g,".*")},t.stripWildcards=function(e){return e.replace(/\*/g,"")},t.createRegExp=function(e,t,i={}){if(!e)throw new Error("Cannot create regex from empty string");t||(e=a(e)),i.wholeWord&&(/\B/.test(e.charAt(0))||(e="\\b"+e),/\B/.test(e.charAt(e.length-1))||(e+="\\b"));let s="";return i.global&&(s+="g"),i.matchCase||(s+="i"),i.multiline&&(s+="m"),i.unicode&&(s+="u"),new RegExp(e,s)},t.regExpLeadsToEndlessLoop=function(e){return"^"!==e.source&&"^$"!==e.source&&"$"!==e.source&&"^\\s*$"!==e.source&&!(!e.exec("")||0!==e.lastIndex)},t.splitLines=function(e){return e.split(/\r\n|\r|\n/)},t.splitLinesIncludeSeparators=function(e){const t=[],i=e.split(/(\r\n|\r|\n)/);for(let e=0;e=0;i--){const t=e.charCodeAt(i);if(t!==s.CharCode.Space&&t!==s.CharCode.Tab)return i}return-1},t.replaceAsync=function(e,t,i){const s=[];let r=0;for(const n of e.matchAll(t)){if(s.push(e.slice(r,n.index)),void 0===n.index)throw new Error("match.index should be defined");r=n.index+n[0].length,s.push(i(n[0],...n.slice(1),n.index,e,n.groups))}return s.push(e.slice(r)),Promise.all(s).then((e=>e.join("")))},t.compare=function(e,t){return et?1:0},t.compareSubstring=c,t.compareIgnoreCase=function(e,t){return d(e,t,0,e.length,0,t.length)},t.compareSubstringIgnoreCase=d,t.isAsciiDigit=function(e){return e>=s.CharCode.Digit0&&e<=s.CharCode.Digit9},t.isLowerAsciiLetter=u,t.isUpperAsciiLetter=function(e){return e>=s.CharCode.A&&e<=s.CharCode.Z},t.equalsIgnoreCase=function(e,t){return e.length===t.length&&0===d(e,t)},t.startsWithIgnoreCase=function(e,t){const i=t.length;return!(t.length>e.length)&&0===d(e,t,0,i)},t.commonPrefixLength=function(e,t){const i=Math.min(e.length,t.length);let s;for(s=0;sn)return 1}const o=s-i,a=n-r;return oa?1:0}function d(e,t,i=0,s=e.length,r=0,n=t.length){for(;i=128||a>=128)return c(e.toLowerCase(),t.toLowerCase(),i,s,r,n);u(o)&&(o-=32),u(a)&&(a-=32);const l=o-a;if(0!==l)return l}const o=s-i,a=n-r;return oa?1:0}function u(e){return e>=s.CharCode.a&&e<=s.CharCode.z}function _(e){return 55296<=e&&e<=56319}function f(e){return 56320<=e&&e<=57343}function p(e,t){return t-56320+(e-55296<<10)+65536}function g(e,t,i){const s=e.charCodeAt(i);if(_(s)&&i+11){const s=e.charCodeAt(t-2);if(_(s))return p(s,i)}return i}(this._str,this._offset);return this._offset-=e>=r.Constants.UNICODE_SUPPLEMENTARY_PLANE_BEGIN?2:1,e}nextCodePoint(){const e=g(this._str,this._len,this._offset);return this._offset+=e>=r.Constants.UNICODE_SUPPLEMENTARY_PLANE_BEGIN?2:1,e}eol(){return this._offset>=this._len}},t.noBreakWhitespace=" "},5015:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MicrotaskDelay=void 0,t.MicrotaskDelay=Symbol("MicrotaskDelay")},8960:(e,t)=>{var i;Object.defineProperty(t,"__esModule",{value:!0}),t.Constants=void 0,t.toUint8=function(e){return e<0?0:e>i.MAX_UINT_8?i.MAX_UINT_8:0|e},t.toUint32=function(e){return e<0?0:e>i.MAX_UINT_32?i.MAX_UINT_32:0|e},function(e){e[e.MAX_SAFE_SMALL_INTEGER=1073741824]="MAX_SAFE_SMALL_INTEGER",e[e.MIN_SAFE_SMALL_INTEGER=-1073741824]="MIN_SAFE_SMALL_INTEGER",e[e.MAX_UINT_8=255]="MAX_UINT_8",e[e.MAX_UINT_16=65535]="MAX_UINT_16",e[e.MAX_UINT_32=4294967295]="MAX_UINT_32",e[e.UNICODE_SUPPLEMENTARY_PLANE_BEGIN=65536]="UNICODE_SUPPLEMENTARY_PLANE_BEGIN"}(i||(t.Constants=i={}))}},t={};function i(s){var r=t[s];if(void 0!==r)return r.exports;var n=t[s]={exports:{}};return e[s].call(n.exports,n,n.exports,i),n.exports}var s={};return(()=>{var e=s;Object.defineProperty(e,"__esModule",{value:!0}),e.Terminal=void 0;const t=i(7721),r=i(1718),n=i(7150),o=i(3027),a=i(5101),l=i(6097),h=i(4335),c=["cols","rows"];let d=0;class u extends n.Disposable{constructor(e){super(),this._core=this._register(new r.CoreBrowserTerminal(e)),this._addonManager=this._register(new o.AddonManager),this._publicOptions={...this._core.options};const t=e=>this._core.options[e],i=(e,t)=>{this._checkReadonlyOptions(e),this._core.options[e]=t};for(const e in this._core.options){const s={get:t.bind(this,e),set:i.bind(this,e)};Object.defineProperty(this._publicOptions,e,s)}}_checkReadonlyOptions(e){if(c.includes(e))throw new Error(`Option "${e}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw new Error("You must set the allowProposedApi option to true to use proposed API")}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onKey(){return this._core.onKey}get onLineFeed(){return this._core.onLineFeed}get onRender(){return this._core.onRender}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onSelectionChange(){return this._core.onSelectionChange}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get element(){return this._core.element}get parser(){return this._parser||(this._parser=new l.ParserApi(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new h.UnicodeApi(this._core)}get textarea(){return this._core.textarea}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._buffer||(this._buffer=this._register(new a.BufferNamespaceApi(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){const e=this._core.coreService.decPrivateModes;let t="none";switch(this._core.coreMouseService.activeProtocol){case"X10":t="x10";break;case"VT200":t="vt200";break;case"DRAG":t="drag";break;case"ANY":t="any"}return{applicationCursorKeysMode:e.applicationCursorKeys,applicationKeypadMode:e.applicationKeypad,bracketedPasteMode:e.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:t,originMode:e.origin,reverseWraparoundMode:e.reverseWraparound,sendFocusMode:e.sendFocus,synchronizedOutputMode:e.synchronizedOutput,wraparoundMode:e.wraparound}}get options(){return this._publicOptions}set options(e){for(const t in e)this._publicOptions[t]=e[t]}blur(){this._core.blur()}focus(){this._core.focus()}input(e,t=!0){this._core.input(e,t)}resize(e,t){this._verifyIntegers(e,t),this._core.resize(e,t)}open(e){this._core.open(e)}attachCustomKeyEventHandler(e){this._core.attachCustomKeyEventHandler(e)}attachCustomWheelEventHandler(e){this._core.attachCustomWheelEventHandler(e)}registerLinkProvider(e){return this._core.registerLinkProvider(e)}registerCharacterJoiner(e){return this._checkProposedApi(),this._core.registerCharacterJoiner(e)}deregisterCharacterJoiner(e){this._checkProposedApi(),this._core.deregisterCharacterJoiner(e)}registerMarker(e=0){return this._verifyIntegers(e),this._core.registerMarker(e)}registerDecoration(e){return this._checkProposedApi(),this._verifyPositiveIntegers(e.x??0,e.width??0,e.height??0),this._core.registerDecoration(e)}hasSelection(){return this._core.hasSelection()}select(e,t,i){this._verifyIntegers(e,t,i),this._core.select(e,t,i)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(e,t){this._verifyIntegers(e,t),this._core.selectLines(e,t)}dispose(){super.dispose()}scrollLines(e){this._verifyIntegers(e),this._core.scrollLines(e)}scrollPages(e){this._verifyIntegers(e),this._core.scrollPages(e)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(e){this._verifyIntegers(e),this._core.scrollToLine(e)}clear(){this._core.clear()}write(e,t){this._core.write(e,t)}writeln(e,t){this._core.write(e),this._core.write("\r\n",t)}paste(e){this._core.paste(e)}refresh(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return t.promptLabel.get()},set promptLabel(e){t.promptLabel.set(e)},get tooMuchOutput(){return t.tooMuchOutput.get()},set tooMuchOutput(e){t.tooMuchOutput.set(e)}}}_verifyIntegers(...e){for(d of e)if(d===1/0||isNaN(d)||d%1!=0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...e){for(d of e)if(d&&(d===1/0||isNaN(d)||d%1!=0||d<0))throw new Error("This API only accepts positive integers")}}e.Terminal=u})(),s})())); +//# sourceMappingURL=xterm.js.map \ No newline at end of file diff --git a/node_modules/@xterm/xterm/lib/xterm.js.map b/node_modules/@xterm/xterm/lib/xterm.js.map new file mode 100644 index 0000000..1a2e154 --- /dev/null +++ b/node_modules/@xterm/xterm/lib/xterm.js.map @@ -0,0 +1 @@ +{"version":3,"file":"xterm.js","mappings":"CAAA,SAA2CA,EAAMC,GAChD,GAAsB,iBAAZC,SAA0C,iBAAXC,OACxCA,OAAOD,QAAUD,SACb,GAAqB,mBAAXG,QAAyBA,OAAOC,IAC9CD,OAAO,GAAIH,OACP,CACJ,IAAIK,EAAIL,IACR,IAAI,IAAIM,KAAKD,GAAuB,iBAAZJ,QAAuBA,QAAUF,GAAMO,GAAKD,EAAEC,EACvE,CACA,CATD,CASGC,YAAY,I,miBCJf,gBAEA,UACA,UACA,UAEA,UACA,UAaO,IAAMC,EAAN,cAAmC,EAAAC,WA4BxC,WAAAC,CACmBC,EACMC,EACF,EACL,GAEhBC,QALiB,KAAAF,UAAAA,EAEqB,KAAAG,oBAAAA,EACL,KAAAC,eAAAA,EA1B3B,KAAAC,YAA8C,IAAIC,QAGlD,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B,OAAOD,EAAQC,cAAcC,KAAO,EAClE,iBAAID,CAAc0G,GAAiB3G,EAAQC,cAAciB,IAAIyF,EAAQ,EAEzE,CAEQ,eAAA6qI,IAAmB7kF,GACzB,IAAK4jF,KAAU5jF,EACb,GAAI4jF,IAAWqB,KAAY1tI,MAAMqsI,IAAWA,EAAS,GAAM,EACzD,MAAM,IAAItyI,MAAM,iCAGtB,CAEQ,uBAAAwzI,IAA2B9kF,GACjC,IAAK4jF,KAAU5jF,EACb,GAAI4jF,IAAWA,IAAWqB,KAAY1tI,MAAMqsI,IAAWA,EAAS,GAAM,GAAKA,EAAS,GAClF,MAAM,IAAItyI,MAAM,0CAGtB,EAzPF,Y","sources":["webpack://@xterm/xterm/webpack/universalModuleDefinition","webpack://@xterm/xterm/./src/browser/AccessibilityManager.ts","webpack://@xterm/xterm/./src/browser/Clipboard.ts","webpack://@xterm/xterm/./src/browser/ColorContrastCache.ts","webpack://@xterm/xterm/./src/browser/CoreBrowserTerminal.ts","webpack://@xterm/xterm/./src/browser/Linkifier.ts","webpack://@xterm/xterm/./src/browser/LocalizableStrings.ts","webpack://@xterm/xterm/./src/browser/OscLinkProvider.ts","webpack://@xterm/xterm/./src/browser/RenderDebouncer.ts","webpack://@xterm/xterm/./src/browser/TimeBasedDebouncer.ts","webpack://@xterm/xterm/./src/browser/Types.ts","webpack://@xterm/xterm/./src/browser/Viewport.ts","webpack://@xterm/xterm/./src/browser/decorations/BufferDecorationRenderer.ts","webpack://@xterm/xterm/./src/browser/decorations/ColorZoneStore.ts","webpack://@xterm/xterm/./src/browser/decorations/OverviewRulerRenderer.ts","webpack://@xterm/xterm/./src/browser/input/CompositionHelper.ts","webpack://@xterm/xterm/./src/browser/input/Mouse.ts","webpack://@xterm/xterm/./src/browser/input/MoveToCell.ts","webpack://@xterm/xterm/./src/browser/renderer/dom/DomRenderer.ts","webpack://@xterm/xterm/./src/browser/renderer/dom/DomRendererRowFactory.ts","webpack://@xterm/xterm/./src/browser/renderer/dom/WidthCache.ts","webpack://@xterm/xterm/./src/browser/renderer/shared/Constants.ts","webpack://@xterm/xterm/./src/browser/renderer/shared/RendererUtils.ts","webpack://@xterm/xterm/./src/browser/renderer/shared/SelectionRenderModel.ts","webpack://@xterm/xterm/./src/browser/selection/SelectionModel.ts","webpack://@xterm/xterm/./src/browser/services/CharSizeService.ts","webpack://@xterm/xterm/./src/browser/services/CharacterJoinerService.ts","webpack://@xterm/xterm/./src/browser/services/CoreBrowserService.ts","webpack://@xterm/xterm/./src/browser/services/LinkProviderService.ts","webpack://@xterm/xterm/./src/browser/services/MouseService.ts","webpack://@xterm/xterm/./src/browser/services/RenderService.ts","webpack://@xterm/xterm/./src/browser/services/SelectionService.ts","webpack://@xterm/xterm/./src/browser/services/Services.ts","webpack://@xterm/xterm/./src/browser/services/ThemeService.ts","webpack://@xterm/xterm/./src/common/CircularList.ts","webpack://@xterm/xterm/./src/common/Clone.ts","webpack://@xterm/xterm/./src/common/Color.ts","webpack://@xterm/xterm/./src/common/CoreTerminal.ts","webpack://@xterm/xterm/./src/common/InputHandler.ts","webpack://@xterm/xterm/./src/common/MultiKeyMap.ts","webpack://@xterm/xterm/./src/common/Platform.ts","webpack://@xterm/xterm/./src/common/SortedList.ts","webpack://@xterm/xterm/./src/common/TaskQueue.ts","webpack://@xterm/xterm/./src/common/WindowsMode.ts","webpack://@xterm/xterm/./src/common/buffer/AttributeData.ts","webpack://@xterm/xterm/./src/common/buffer/Buffer.ts","webpack://@xterm/xterm/./src/common/buffer/BufferLine.ts","webpack://@xterm/xterm/./src/common/buffer/BufferRange.ts","webpack://@xterm/xterm/./src/common/buffer/BufferReflow.ts","webpack://@xterm/xterm/./src/common/buffer/BufferSet.ts","webpack://@xterm/xterm/./src/common/buffer/CellData.ts","webpack://@xterm/xterm/./src/common/buffer/Constants.ts","webpack://@xterm/xterm/./src/common/buffer/Marker.ts","webpack://@xterm/xterm/./src/common/data/Charsets.ts","webpack://@xterm/xterm/./src/common/data/EscapeSequences.ts","webpack://@xterm/xterm/./src/common/input/Keyboard.ts","webpack://@xterm/xterm/./src/common/input/TextDecoder.ts","webpack://@xterm/xterm/./src/common/input/UnicodeV6.ts","webpack://@xterm/xterm/./src/common/input/WriteBuffer.ts","webpack://@xterm/xterm/./src/common/input/XParseColor.ts","webpack://@xterm/xterm/./src/common/parser/Constants.ts","webpack://@xterm/xterm/./src/common/parser/DcsParser.ts","webpack://@xterm/xterm/./src/common/parser/EscapeSequenceParser.ts","webpack://@xterm/xterm/./src/common/parser/OscParser.ts","webpack://@xterm/xterm/./src/common/parser/Params.ts","webpack://@xterm/xterm/./src/common/public/AddonManager.ts","webpack://@xterm/xterm/./src/common/public/BufferApiView.ts","webpack://@xterm/xterm/./src/common/public/BufferLineApiView.ts","webpack://@xterm/xterm/./src/common/public/BufferNamespaceApi.ts","webpack://@xterm/xterm/./src/common/public/ParserApi.ts","webpack://@xterm/xterm/./src/common/public/UnicodeApi.ts","webpack://@xterm/xterm/./src/common/services/BufferService.ts","webpack://@xterm/xterm/./src/common/services/CharsetService.ts","webpack://@xterm/xterm/./src/common/services/CoreMouseService.ts","webpack://@xterm/xterm/./src/common/services/CoreService.ts","webpack://@xterm/xterm/./src/common/services/DecorationService.ts","webpack://@xterm/xterm/./src/common/services/InstantiationService.ts","webpack://@xterm/xterm/./src/common/services/LogService.ts","webpack://@xterm/xterm/./src/common/services/OptionsService.ts","webpack://@xterm/xterm/./src/common/services/OscLinkService.ts","webpack://@xterm/xterm/./src/common/services/ServiceRegistry.ts","webpack://@xterm/xterm/./src/common/services/Services.ts","webpack://@xterm/xterm/./src/common/services/UnicodeService.ts","webpack://@xterm/xterm/./out/vs/base/browser/browser.js","webpack://@xterm/xterm/./out/vs/base/browser/canIUse.js","webpack://@xterm/xterm/./out/vs/base/browser/dom.js","webpack://@xterm/xterm/./out/vs/base/browser/fastDomNode.js","webpack://@xterm/xterm/./out/vs/base/browser/globalPointerMoveMonitor.js","webpack://@xterm/xterm/./out/vs/base/browser/iframe.js","webpack://@xterm/xterm/./out/vs/base/browser/keyboardEvent.js","webpack://@xterm/xterm/./out/vs/base/browser/mouseEvent.js","webpack://@xterm/xterm/./out/vs/base/browser/touch.js","webpack://@xterm/xterm/./out/vs/base/browser/ui/scrollbar/abstractScrollbar.js","webpack://@xterm/xterm/./out/vs/base/browser/ui/scrollbar/horizontalScrollbar.js","webpack://@xterm/xterm/./out/vs/base/browser/ui/scrollbar/scrollableElement.js","webpack://@xterm/xterm/./out/vs/base/browser/ui/scrollbar/scrollbarArrow.js","webpack://@xterm/xterm/./out/vs/base/browser/ui/scrollbar/scrollbarState.js","webpack://@xterm/xterm/./out/vs/base/browser/ui/scrollbar/scrollbarVisibilityController.js","webpack://@xterm/xterm/./out/vs/base/browser/ui/scrollbar/verticalScrollbar.js","webpack://@xterm/xterm/./out/vs/base/browser/ui/widget.js","webpack://@xterm/xterm/./out/vs/base/browser/window.js","webpack://@xterm/xterm/./out/vs/base/common/arrays.js","webpack://@xterm/xterm/./out/vs/base/common/arraysFind.js","webpack://@xterm/xterm/./out/vs/base/common/async.js","webpack://@xterm/xterm/./out/vs/base/common/cancellation.js","webpack://@xterm/xterm/./out/vs/base/common/charCode.js","webpack://@xterm/xterm/./out/vs/base/common/collections.js","webpack://@xterm/xterm/./out/vs/base/common/decorators.js","webpack://@xterm/xterm/./out/vs/base/common/errors.js","webpack://@xterm/xterm/./out/vs/base/common/event.js","webpack://@xterm/xterm/./out/vs/base/common/functional.js","webpack://@xterm/xterm/./out/vs/base/common/hash.js","webpack://@xterm/xterm/./out/vs/base/common/iterator.js","webpack://@xterm/xterm/./out/vs/base/common/keyCodes.js","webpack://@xterm/xterm/./out/vs/base/common/keybindings.js","webpack://@xterm/xterm/./out/vs/base/common/lazy.js","webpack://@xterm/xterm/./out/vs/base/common/lifecycle.js","webpack://@xterm/xterm/./out/vs/base/common/linkedList.js","webpack://@xterm/xterm/./out/vs/base/common/map.js","webpack://@xterm/xterm/./out/vs/base/common/numbers.js","webpack://@xterm/xterm/./out/vs/base/common/platform.js","webpack://@xterm/xterm/./out/vs/base/common/scrollable.js","webpack://@xterm/xterm/./out/vs/base/common/stopwatch.js","webpack://@xterm/xterm/./out/vs/base/common/strings.js","webpack://@xterm/xterm/./out/vs/base/common/symbols.js","webpack://@xterm/xterm/./out/vs/base/common/uint.js","webpack://@xterm/xterm/webpack/bootstrap","webpack://@xterm/xterm/./src/browser/public/Terminal.ts"],"sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse {\n\t\tvar a = factory();\n\t\tfor(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];\n\t}\n})(globalThis, () => {\nreturn ","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport * as Strings from 'browser/LocalizableStrings';\nimport { ITerminal, IRenderDebouncer } from 'browser/Types';\nimport { TimeBasedDebouncer } from 'browser/TimeBasedDebouncer';\nimport { Disposable, toDisposable } from 'vs/base/common/lifecycle';\nimport { ICoreBrowserService, IRenderService } from 'browser/services/Services';\nimport { IBuffer } from 'common/buffer/Types';\nimport { IInstantiationService } from 'common/services/Services';\nimport { addDisposableListener } from 'vs/base/browser/dom';\n\nconst MAX_ROWS_TO_READ = 20;\n\nconst enum BoundaryPosition {\n TOP,\n BOTTOM\n}\n\n// Turn this on to unhide the accessibility tree and display it under\n// (instead of overlapping with) the terminal.\nconst DEBUG = false;\n\nexport class AccessibilityManager extends Disposable {\n private _debugRootContainer: HTMLElement | undefined;\n private _accessibilityContainer: HTMLElement;\n\n private _rowContainer: HTMLElement;\n private _rowElements: HTMLElement[];\n private _rowColumns: WeakMap = new WeakMap();\n\n private _liveRegion: HTMLElement;\n private _liveRegionLineCount: number = 0;\n private _liveRegionDebouncer: IRenderDebouncer;\n\n private _topBoundaryFocusListener: (e: FocusEvent) => void;\n private _bottomBoundaryFocusListener: (e: FocusEvent) => void;\n\n /**\n * This queue has a character pushed to it for keys that are pressed, if the\n * next character added to the terminal is equal to the key char then it is\n * not announced (added to live region) because it has already been announced\n * by the textarea event (which cannot be canceled). There are some race\n * condition cases if there is typing while data is streaming, but this covers\n * the main case of typing into the prompt and inputting the answer to a\n * question (Y/N, etc.).\n */\n private _charsToConsume: string[] = [];\n\n private _charsToAnnounce: string = '';\n\n constructor(\n private readonly _terminal: ITerminal,\n @IInstantiationService instantiationService: IInstantiationService,\n @ICoreBrowserService private readonly _coreBrowserService: ICoreBrowserService,\n @IRenderService private readonly _renderService: IRenderService\n ) {\n super();\n const doc = this._coreBrowserService.mainDocument;\n this._accessibilityContainer = doc.createElement('div');\n this._accessibilityContainer.classList.add('xterm-accessibility');\n\n this._rowContainer = doc.createElement('div');\n this._rowContainer.setAttribute('role', 'list');\n this._rowContainer.classList.add('xterm-accessibility-tree');\n this._rowElements = [];\n for (let i = 0; i < this._terminal.rows; i++) {\n this._rowElements[i] = this._createAccessibilityTreeNode();\n this._rowContainer.appendChild(this._rowElements[i]);\n }\n\n this._topBoundaryFocusListener = e => this._handleBoundaryFocus(e, BoundaryPosition.TOP);\n this._bottomBoundaryFocusListener = e => this._handleBoundaryFocus(e, BoundaryPosition.BOTTOM);\n this._rowElements[0].addEventListener('focus', this._topBoundaryFocusListener);\n this._rowElements[this._rowElements.length - 1].addEventListener('focus', this._bottomBoundaryFocusListener);\n\n this._accessibilityContainer.appendChild(this._rowContainer);\n\n this._liveRegion = doc.createElement('div');\n this._liveRegion.classList.add('live-region');\n this._liveRegion.setAttribute('aria-live', 'assertive');\n this._accessibilityContainer.appendChild(this._liveRegion);\n this._liveRegionDebouncer = this._register(new TimeBasedDebouncer(this._renderRows.bind(this)));\n\n if (!this._terminal.element) {\n throw new Error('Cannot enable accessibility before Terminal.open');\n }\n\n if (DEBUG) {\n this._accessibilityContainer.classList.add('debug');\n this._rowContainer.classList.add('debug');\n\n // Use a `
` container so that the css will still apply.\n this._debugRootContainer = doc.createElement('div');\n this._debugRootContainer.classList.add('xterm');\n\n this._debugRootContainer.appendChild(doc.createTextNode('------start a11y------'));\n this._debugRootContainer.appendChild(this._accessibilityContainer);\n this._debugRootContainer.appendChild(doc.createTextNode('------end a11y------'));\n\n this._terminal.element.insertAdjacentElement('afterend', this._debugRootContainer);\n } else {\n this._terminal.element.insertAdjacentElement('afterbegin', this._accessibilityContainer);\n }\n\n this._register(this._terminal.onResize(e => this._handleResize(e.rows)));\n this._register(this._terminal.onRender(e => this._refreshRows(e.start, e.end)));\n this._register(this._terminal.onScroll(() => this._refreshRows()));\n // Line feed is an issue as the prompt won't be read out after a command is run\n this._register(this._terminal.onA11yChar(char => this._handleChar(char)));\n this._register(this._terminal.onLineFeed(() => this._handleChar('\\n')));\n this._register(this._terminal.onA11yTab(spaceCount => this._handleTab(spaceCount)));\n this._register(this._terminal.onKey(e => this._handleKey(e.key)));\n this._register(this._terminal.onBlur(() => this._clearLiveRegion()));\n this._register(this._renderService.onDimensionsChange(() => this._refreshRowsDimensions()));\n this._register(addDisposableListener(doc, 'selectionchange', () => this._handleSelectionChange()));\n this._register(this._coreBrowserService.onDprChange(() => this._refreshRowsDimensions()));\n\n this._refreshRowsDimensions();\n this._refreshRows();\n this._register(toDisposable(() => {\n if (DEBUG) {\n this._debugRootContainer!.remove();\n } else {\n this._accessibilityContainer.remove();\n }\n this._rowElements.length = 0;\n }));\n }\n\n private _handleTab(spaceCount: number): void {\n for (let i = 0; i < spaceCount; i++) {\n this._handleChar(' ');\n }\n }\n\n private _handleChar(char: string): void {\n if (this._liveRegionLineCount < MAX_ROWS_TO_READ + 1) {\n if (this._charsToConsume.length > 0) {\n // Have the screen reader ignore the char if it was just input\n const shiftedChar = this._charsToConsume.shift();\n if (shiftedChar !== char) {\n this._charsToAnnounce += char;\n }\n } else {\n this._charsToAnnounce += char;\n }\n\n if (char === '\\n') {\n this._liveRegionLineCount++;\n if (this._liveRegionLineCount === MAX_ROWS_TO_READ + 1) {\n this._liveRegion.textContent += Strings.tooMuchOutput.get();\n }\n }\n }\n }\n\n private _clearLiveRegion(): void {\n this._liveRegion.textContent = '';\n this._liveRegionLineCount = 0;\n }\n\n private _handleKey(keyChar: string): void {\n this._clearLiveRegion();\n // Only add the char if there is no control character.\n if (!/\\p{Control}/u.test(keyChar)) {\n this._charsToConsume.push(keyChar);\n }\n }\n\n private _refreshRows(start?: number, end?: number): void {\n this._liveRegionDebouncer.refresh(start, end, this._terminal.rows);\n }\n\n private _renderRows(start: number, end: number): void {\n const buffer: IBuffer = this._terminal.buffer;\n const setSize = buffer.lines.length.toString();\n for (let i = start; i <= end; i++) {\n const line = buffer.lines.get(buffer.ydisp + i);\n const columns: number[] = [];\n const lineData = line?.translateToString(true, undefined, undefined, columns) || '';\n const posInSet = (buffer.ydisp + i + 1).toString();\n const element = this._rowElements[i];\n if (element) {\n if (lineData.length === 0) {\n element.textContent = '\\u00a0';\n this._rowColumns.set(element, [0, 1]);\n } else {\n element.textContent = lineData;\n this._rowColumns.set(element, columns);\n }\n element.setAttribute('aria-posinset', posInSet);\n element.setAttribute('aria-setsize', setSize);\n this._alignRowWidth(element);\n }\n }\n this._announceCharacters();\n }\n\n private _announceCharacters(): void {\n if (this._charsToAnnounce.length === 0) {\n return;\n }\n this._liveRegion.textContent += this._charsToAnnounce;\n this._charsToAnnounce = '';\n }\n\n private _handleBoundaryFocus(e: FocusEvent, position: BoundaryPosition): void {\n const boundaryElement = e.target as HTMLElement;\n const beforeBoundaryElement = this._rowElements[position === BoundaryPosition.TOP ? 1 : this._rowElements.length - 2];\n\n // Don't scroll if the buffer top has reached the end in that direction\n const posInSet = boundaryElement.getAttribute('aria-posinset');\n const lastRowPos = position === BoundaryPosition.TOP ? '1' : `${this._terminal.buffer.lines.length}`;\n if (posInSet === lastRowPos) {\n return;\n }\n\n // Don't scroll when the last focused item was not the second row (focus is going the other\n // direction)\n if (e.relatedTarget !== beforeBoundaryElement) {\n return;\n }\n\n // Remove old boundary element from array\n let topBoundaryElement: HTMLElement;\n let bottomBoundaryElement: HTMLElement;\n if (position === BoundaryPosition.TOP) {\n topBoundaryElement = boundaryElement;\n bottomBoundaryElement = this._rowElements.pop()!;\n this._rowContainer.removeChild(bottomBoundaryElement);\n } else {\n topBoundaryElement = this._rowElements.shift()!;\n bottomBoundaryElement = boundaryElement;\n this._rowContainer.removeChild(topBoundaryElement);\n }\n\n // Remove listeners from old boundary elements\n topBoundaryElement.removeEventListener('focus', this._topBoundaryFocusListener);\n bottomBoundaryElement.removeEventListener('focus', this._bottomBoundaryFocusListener);\n\n // Add new element to array/DOM\n if (position === BoundaryPosition.TOP) {\n const newElement = this._createAccessibilityTreeNode();\n this._rowElements.unshift(newElement);\n this._rowContainer.insertAdjacentElement('afterbegin', newElement);\n } else {\n const newElement = this._createAccessibilityTreeNode();\n this._rowElements.push(newElement);\n this._rowContainer.appendChild(newElement);\n }\n\n // Add listeners to new boundary elements\n this._rowElements[0].addEventListener('focus', this._topBoundaryFocusListener);\n this._rowElements[this._rowElements.length - 1].addEventListener('focus', this._bottomBoundaryFocusListener);\n\n // Scroll up\n this._terminal.scrollLines(position === BoundaryPosition.TOP ? -1 : 1);\n\n // Focus new boundary before element\n this._rowElements[position === BoundaryPosition.TOP ? 1 : this._rowElements.length - 2].focus();\n\n // Prevent the standard behavior\n e.preventDefault();\n e.stopImmediatePropagation();\n }\n\n private _handleSelectionChange(): void {\n if (this._rowElements.length === 0) {\n return;\n }\n\n const selection = this._coreBrowserService.mainDocument.getSelection();\n if (!selection) {\n return;\n }\n\n if (selection.isCollapsed) {\n // Only do something when the anchorNode is inside the row container. This\n // behavior mirrors what we do with mouse --- if the mouse clicks\n // somewhere outside of the terminal, we don't clear the selection.\n if (this._rowContainer.contains(selection.anchorNode)) {\n this._terminal.clearSelection();\n }\n return;\n }\n\n if (!selection.anchorNode || !selection.focusNode) {\n console.error('anchorNode and/or focusNode are null');\n return;\n }\n\n // Sort the two selection points in document order.\n let begin = { node: selection.anchorNode, offset: selection.anchorOffset };\n let end = { node: selection.focusNode, offset: selection.focusOffset };\n if ((begin.node.compareDocumentPosition(end.node) & Node.DOCUMENT_POSITION_PRECEDING) || (begin.node === end.node && begin.offset > end.offset) ) {\n [begin, end] = [end, begin];\n }\n\n // Clamp begin/end to the inside of the row container.\n if (begin.node.compareDocumentPosition(this._rowElements[0]) & (Node.DOCUMENT_POSITION_CONTAINED_BY | Node.DOCUMENT_POSITION_FOLLOWING)) {\n begin = { node: this._rowElements[0].childNodes[0], offset: 0 };\n }\n if (!this._rowContainer.contains(begin.node)) {\n // This happens when `begin` is below the last row.\n return;\n }\n const lastRowElement = this._rowElements.slice(-1)[0];\n if (end.node.compareDocumentPosition(lastRowElement) & (Node.DOCUMENT_POSITION_CONTAINED_BY | Node.DOCUMENT_POSITION_PRECEDING)) {\n end = {\n node: lastRowElement,\n offset: lastRowElement.textContent?.length ?? 0\n };\n }\n if (!this._rowContainer.contains(end.node)) {\n // This happens when `end` is above the first row.\n return;\n }\n\n const toRowColumn = ({ node, offset }: typeof begin): {row: number, column: number} | null => {\n // `node` is either the row element or the Text node inside it.\n const rowElement: any = node instanceof Text ? node.parentNode : node;\n let row = parseInt(rowElement?.getAttribute('aria-posinset'), 10) - 1;\n if (isNaN(row)) {\n console.warn('row is invalid. Race condition?');\n return null;\n }\n\n const columns = this._rowColumns.get(rowElement);\n if (!columns) {\n console.warn('columns is null. Race condition?');\n return null;\n }\n\n let column = offset < columns.length ? columns[offset] : columns.slice(-1)[0] + 1;\n if (column >= this._terminal.cols) {\n ++row;\n column = 0;\n }\n return {\n row,\n column\n };\n };\n\n const beginRowColumn = toRowColumn(begin);\n const endRowColumn = toRowColumn(end);\n\n if (!beginRowColumn || !endRowColumn) {\n return;\n }\n\n if (beginRowColumn.row > endRowColumn.row || (beginRowColumn.row === endRowColumn.row && beginRowColumn.column >= endRowColumn.column)) {\n // This should not happen unless we have some bugs.\n throw new Error('invalid range');\n }\n\n this._terminal.select(\n beginRowColumn.column,\n beginRowColumn.row,\n (endRowColumn.row - beginRowColumn.row) * this._terminal.cols - beginRowColumn.column + endRowColumn.column\n );\n }\n\n private _handleResize(rows: number): void {\n // Remove bottom boundary listener\n this._rowElements[this._rowElements.length - 1].removeEventListener('focus', this._bottomBoundaryFocusListener);\n\n // Grow rows as required\n for (let i = this._rowContainer.children.length; i < this._terminal.rows; i++) {\n this._rowElements[i] = this._createAccessibilityTreeNode();\n this._rowContainer.appendChild(this._rowElements[i]);\n }\n // Shrink rows as required\n while (this._rowElements.length > rows) {\n this._rowContainer.removeChild(this._rowElements.pop()!);\n }\n\n // Add bottom boundary listener\n this._rowElements[this._rowElements.length - 1].addEventListener('focus', this._bottomBoundaryFocusListener);\n\n this._refreshRowsDimensions();\n }\n\n private _createAccessibilityTreeNode(): HTMLElement {\n const element = this._coreBrowserService.mainDocument.createElement('div');\n element.setAttribute('role', 'listitem');\n element.tabIndex = -1;\n this._refreshRowDimensions(element);\n return element;\n }\n\n private _refreshRowsDimensions(): void {\n if (!this._renderService.dimensions.css.cell.height) {\n return;\n }\n Object.assign(this._accessibilityContainer.style, {\n width: `${this._renderService.dimensions.css.canvas.width}px`,\n fontSize: `${this._terminal.options.fontSize}px`\n });\n if (this._rowElements.length !== this._terminal.rows) {\n this._handleResize(this._terminal.rows);\n }\n for (let i = 0; i < this._terminal.rows; i++) {\n this._refreshRowDimensions(this._rowElements[i]);\n this._alignRowWidth(this._rowElements[i]);\n }\n }\n\n private _refreshRowDimensions(element: HTMLElement): void {\n element.style.height = `${this._renderService.dimensions.css.cell.height}px`;\n }\n\n /**\n * Scale the width of a row so that each of the character is (mostly) aligned\n * with the actual rendering. This will allow the screen reader to draw\n * selection outline at the correct position.\n *\n * On top of using the \"monospace\" font and correct font size, the scaling\n * here is necessary to handle characters that are not covered by the font\n * (e.g. CJK).\n */\n private _alignRowWidth(element: HTMLElement): void {\n element.style.transform = '';\n const width = element.getBoundingClientRect().width;\n const lastColumn = this._rowColumns.get(element)?.slice(-1)?.[0];\n if (!lastColumn) {\n return;\n }\n const targetWidth = lastColumn * this._renderService.dimensions.css.cell.width;\n element.style.transform = `scaleX(${targetWidth / width})`;\n }\n}\n","/**\n * Copyright (c) 2016 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { ISelectionService } from 'browser/services/Services';\nimport { ICoreService, IOptionsService } from 'common/services/Services';\n\n/**\n * Prepares text to be pasted into the terminal by normalizing the line endings\n * @param text The pasted text that needs processing before inserting into the terminal\n */\nexport function prepareTextForTerminal(text: string): string {\n return text.replace(/\\r?\\n/g, '\\r');\n}\n\n/**\n * Bracket text for paste, if necessary, as per https://cirw.in/blog/bracketed-paste\n * @param text The pasted text to bracket\n */\nexport function bracketTextForPaste(text: string, bracketedPasteMode: boolean): string {\n if (bracketedPasteMode) {\n return '\\x1b[200~' + text + '\\x1b[201~';\n }\n return text;\n}\n\n/**\n * Binds copy functionality to the given terminal.\n * @param ev The original copy event to be handled\n */\nexport function copyHandler(ev: ClipboardEvent, selectionService: ISelectionService): void {\n if (ev.clipboardData) {\n ev.clipboardData.setData('text/plain', selectionService.selectionText);\n }\n // Prevent or the original text will be copied.\n ev.preventDefault();\n}\n\n/**\n * Redirect the clipboard's data to the terminal's input handler.\n */\nexport function handlePasteEvent(ev: ClipboardEvent, textarea: HTMLTextAreaElement, coreService: ICoreService, optionsService: IOptionsService): void {\n ev.stopPropagation();\n if (ev.clipboardData) {\n const text = ev.clipboardData.getData('text/plain');\n paste(text, textarea, coreService, optionsService);\n }\n}\n\nexport function paste(text: string, textarea: HTMLTextAreaElement, coreService: ICoreService, optionsService: IOptionsService): void {\n text = prepareTextForTerminal(text);\n text = bracketTextForPaste(text, coreService.decPrivateModes.bracketedPasteMode && optionsService.rawOptions.ignoreBracketedPasteMode !== true);\n coreService.triggerDataEvent(text, true);\n textarea.value = '';\n}\n\n/**\n * Moves the textarea under the mouse cursor and focuses it.\n * @param ev The original right click event to be handled.\n * @param textarea The terminal's textarea.\n */\nexport function moveTextAreaUnderMouseCursor(ev: MouseEvent, textarea: HTMLTextAreaElement, screenElement: HTMLElement): void {\n\n // Calculate textarea position relative to the screen element\n const pos = screenElement.getBoundingClientRect();\n const left = ev.clientX - pos.left - 10;\n const top = ev.clientY - pos.top - 10;\n\n // Bring textarea at the cursor position\n textarea.style.width = '20px';\n textarea.style.height = '20px';\n textarea.style.left = `${left}px`;\n textarea.style.top = `${top}px`;\n textarea.style.zIndex = '1000';\n\n textarea.focus();\n}\n\n/**\n * Bind to right-click event and allow right-click copy and paste.\n */\nexport function rightClickHandler(ev: MouseEvent, textarea: HTMLTextAreaElement, screenElement: HTMLElement, selectionService: ISelectionService, shouldSelectWord: boolean): void {\n moveTextAreaUnderMouseCursor(ev, textarea, screenElement);\n\n if (shouldSelectWord) {\n selectionService.rightClickSelect(ev);\n }\n\n // Get textarea ready to copy from the context menu\n textarea.value = selectionService.selectionText;\n textarea.select();\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IColorContrastCache } from 'browser/Types';\nimport { IColor } from 'common/Types';\nimport { TwoKeyMap } from 'common/MultiKeyMap';\n\nexport class ColorContrastCache implements IColorContrastCache {\n private _color: TwoKeyMap = new TwoKeyMap();\n private _css: TwoKeyMap = new TwoKeyMap();\n\n public setCss(bg: number, fg: number, value: string | null): void {\n this._css.set(bg, fg, value);\n }\n\n public getCss(bg: number, fg: number): string | null | undefined {\n return this._css.get(bg, fg);\n }\n\n public setColor(bg: number, fg: number, value: IColor | null): void {\n this._color.set(bg, fg, value);\n }\n\n public getColor(bg: number, fg: number): IColor | null | undefined {\n return this._color.get(bg, fg);\n }\n\n public clear(): void {\n this._color.clear();\n this._css.clear();\n }\n}\n","/**\n * Copyright (c) 2014 The xterm.js authors. All rights reserved.\n * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)\n * @license MIT\n *\n * Originally forked from (with the author's permission):\n * Fabrice Bellard's javascript vt100 for jslinux:\n * http://bellard.org/jslinux/\n * Copyright (c) 2011 Fabrice Bellard\n * The original design remains. The terminal itself\n * has been extended to include xterm CSI codes, among\n * other features.\n *\n * Terminal Emulation References:\n * http://vt100.net/\n * http://invisible-island.net/xterm/ctlseqs/ctlseqs.txt\n * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html\n * http://invisible-island.net/vttest/\n * http://www.inwap.com/pdp10/ansicode.txt\n * http://linux.die.net/man/4/console_codes\n * http://linux.die.net/man/7/urxvt\n */\n\nimport { IDecoration, IDecorationOptions, IDisposable, ILinkProvider, IMarker } from '@xterm/xterm';\nimport { copyHandler, handlePasteEvent, moveTextAreaUnderMouseCursor, paste, rightClickHandler } from 'browser/Clipboard';\nimport * as Strings from 'browser/LocalizableStrings';\nimport { OscLinkProvider } from 'browser/OscLinkProvider';\nimport { CharacterJoinerHandler, CustomKeyEventHandler, CustomWheelEventHandler, IBrowser, IBufferRange, ICompositionHelper, ILinkifier2, ITerminal } from 'browser/Types';\nimport { Viewport } from 'browser/Viewport';\nimport { BufferDecorationRenderer } from 'browser/decorations/BufferDecorationRenderer';\nimport { OverviewRulerRenderer } from 'browser/decorations/OverviewRulerRenderer';\nimport { CompositionHelper } from 'browser/input/CompositionHelper';\nimport { DomRenderer } from 'browser/renderer/dom/DomRenderer';\nimport { IRenderer } from 'browser/renderer/shared/Types';\nimport { CharSizeService } from 'browser/services/CharSizeService';\nimport { CharacterJoinerService } from 'browser/services/CharacterJoinerService';\nimport { CoreBrowserService } from 'browser/services/CoreBrowserService';\nimport { LinkProviderService } from 'browser/services/LinkProviderService';\nimport { MouseService } from 'browser/services/MouseService';\nimport { RenderService } from 'browser/services/RenderService';\nimport { SelectionService } from 'browser/services/SelectionService';\nimport { ICharSizeService, ICharacterJoinerService, ICoreBrowserService, ILinkProviderService, IMouseService, IRenderService, ISelectionService, IThemeService } from 'browser/services/Services';\nimport { ThemeService } from 'browser/services/ThemeService';\nimport { channels, color } from 'common/Color';\nimport { CoreTerminal } from 'common/CoreTerminal';\nimport * as Browser from 'common/Platform';\nimport { ColorRequestType, CoreMouseAction, CoreMouseButton, CoreMouseEventType, IColorEvent, ITerminalOptions, KeyboardResultType, SpecialColorIndex } from 'common/Types';\nimport { DEFAULT_ATTR_DATA } from 'common/buffer/BufferLine';\nimport { IBuffer } from 'common/buffer/Types';\nimport { C0, C1_ESCAPED } from 'common/data/EscapeSequences';\nimport { evaluateKeyboardEvent } from 'common/input/Keyboard';\nimport { toRgbString } from 'common/input/XParseColor';\nimport { DecorationService } from 'common/services/DecorationService';\nimport { IDecorationService } from 'common/services/Services';\nimport { WindowsOptionsReportType } from '../common/InputHandler';\nimport { AccessibilityManager } from './AccessibilityManager';\nimport { Linkifier } from './Linkifier';\nimport { Emitter, Event } from 'vs/base/common/event';\nimport { addDisposableListener } from 'vs/base/browser/dom';\nimport { MutableDisposable, toDisposable } from 'vs/base/common/lifecycle';\n\nexport class CoreBrowserTerminal extends CoreTerminal implements ITerminal {\n public textarea: HTMLTextAreaElement | undefined;\n public element: HTMLElement | undefined;\n public screenElement: HTMLElement | undefined;\n\n private _document: Document | undefined;\n private _viewportElement: HTMLElement | undefined;\n private _helperContainer: HTMLElement | undefined;\n private _compositionView: HTMLElement | undefined;\n\n private readonly _linkifier: MutableDisposable = this._register(new MutableDisposable());\n public get linkifier(): ILinkifier2 | undefined { return this._linkifier.value; }\n private _overviewRulerRenderer: OverviewRulerRenderer | undefined;\n private _viewport: Viewport | undefined;\n\n public browser: IBrowser = Browser as any;\n\n private _customKeyEventHandler: CustomKeyEventHandler | undefined;\n private _customWheelEventHandler: CustomWheelEventHandler | undefined;\n\n // Browser services\n private _decorationService: DecorationService;\n private _linkProviderService: ILinkProviderService;\n\n // Optional browser services\n private _charSizeService: ICharSizeService | undefined;\n private _coreBrowserService: ICoreBrowserService | undefined;\n private _mouseService: IMouseService | undefined;\n private _renderService: IRenderService | undefined;\n private _themeService: IThemeService | undefined;\n private _characterJoinerService: ICharacterJoinerService | undefined;\n private _selectionService: ISelectionService | undefined;\n\n /**\n * Records whether the keydown event has already been handled and triggered a data event, if so\n * the keypress event should not trigger a data event but should still print to the textarea so\n * screen readers will announce it.\n */\n private _keyDownHandled: boolean = false;\n\n /**\n * Records whether a keydown event has occured since the last keyup event, i.e. whether a key\n * is currently \"pressed\".\n */\n private _keyDownSeen: boolean = false;\n\n /**\n * Records whether the keypress event has already been handled and triggered a data event, if so\n * the input event should not trigger a data event but should still print to the textarea so\n * screen readers will announce it.\n */\n private _keyPressHandled: boolean = false;\n\n /**\n * Records whether there has been a keydown event for a dead key without a corresponding keydown\n * event for the composed/alternative character. If we cancel the keydown event for the dead key,\n * no events will be emitted for the final character.\n */\n private _unprocessedDeadKey: boolean = false;\n\n private _compositionHelper: ICompositionHelper | undefined;\n private _accessibilityManager: MutableDisposable = this._register(new MutableDisposable());\n\n private readonly _onCursorMove = this._register(new Emitter());\n public readonly onCursorMove = this._onCursorMove.event;\n private readonly _onKey = this._register(new Emitter<{ key: string, domEvent: KeyboardEvent }>());\n public readonly onKey = this._onKey.event;\n private readonly _onRender = this._register(new Emitter<{ start: number, end: number }>());\n public readonly onRender = this._onRender.event;\n private readonly _onSelectionChange = this._register(new Emitter());\n public readonly onSelectionChange = this._onSelectionChange.event;\n private readonly _onTitleChange = this._register(new Emitter());\n public readonly onTitleChange = this._onTitleChange.event;\n private readonly _onBell = this._register(new Emitter());\n public readonly onBell = this._onBell.event;\n\n private _onFocus = this._register(new Emitter());\n public get onFocus(): Event { return this._onFocus.event; }\n private _onBlur = this._register(new Emitter());\n public get onBlur(): Event { return this._onBlur.event; }\n private _onA11yCharEmitter = this._register(new Emitter());\n public get onA11yChar(): Event { return this._onA11yCharEmitter.event; }\n private _onA11yTabEmitter = this._register(new Emitter());\n public get onA11yTab(): Event { return this._onA11yTabEmitter.event; }\n private _onWillOpen = this._register(new Emitter());\n public get onWillOpen(): Event { return this._onWillOpen.event; }\n\n constructor(\n options: Partial = {}\n ) {\n super(options);\n\n this._setup();\n\n this._decorationService = this._instantiationService.createInstance(DecorationService);\n this._instantiationService.setService(IDecorationService, this._decorationService);\n this._linkProviderService = this._instantiationService.createInstance(LinkProviderService);\n this._instantiationService.setService(ILinkProviderService, this._linkProviderService);\n this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(OscLinkProvider));\n\n // Setup InputHandler listeners\n this._register(this._inputHandler.onRequestBell(() => this._onBell.fire()));\n this._register(this._inputHandler.onRequestRefreshRows((e) => this.refresh(e?.start ?? 0, e?.end ?? (this.rows - 1))));\n this._register(this._inputHandler.onRequestSendFocus(() => this._reportFocus()));\n this._register(this._inputHandler.onRequestReset(() => this.reset()));\n this._register(this._inputHandler.onRequestWindowsOptionsReport(type => this._reportWindowsOptions(type)));\n this._register(this._inputHandler.onColor((event) => this._handleColorEvent(event)));\n this._register(Event.forward(this._inputHandler.onCursorMove, this._onCursorMove));\n this._register(Event.forward(this._inputHandler.onTitleChange, this._onTitleChange));\n this._register(Event.forward(this._inputHandler.onA11yChar, this._onA11yCharEmitter));\n this._register(Event.forward(this._inputHandler.onA11yTab, this._onA11yTabEmitter));\n\n // Setup listeners\n this._register(this._bufferService.onResize(e => this._afterResize(e.cols, e.rows)));\n\n this._register(toDisposable(() => {\n this._customKeyEventHandler = undefined;\n this.element?.parentNode?.removeChild(this.element);\n }));\n }\n\n /**\n * Handle color event from inputhandler for OSC 4|104 | 10|110 | 11|111 | 12|112.\n * An event from OSC 4|104 may contain multiple set or report requests, and multiple\n * or none restore requests (resetting all),\n * while an event from OSC 10|110 | 11|111 | 12|112 always contains a single request.\n */\n private _handleColorEvent(event: IColorEvent): void {\n if (!this._themeService) return;\n for (const req of event) {\n let acc: 'foreground' | 'background' | 'cursor' | 'ansi';\n let ident = '';\n switch (req.index) {\n case SpecialColorIndex.FOREGROUND: // OSC 10 | 110\n acc = 'foreground';\n ident = '10';\n break;\n case SpecialColorIndex.BACKGROUND: // OSC 11 | 111\n acc = 'background';\n ident = '11';\n break;\n case SpecialColorIndex.CURSOR: // OSC 12 | 112\n acc = 'cursor';\n ident = '12';\n break;\n default: // OSC 4 | 104\n // we can skip the [0..255] range check here (already done in inputhandler)\n acc = 'ansi';\n ident = '4;' + req.index;\n }\n switch (req.type) {\n case ColorRequestType.REPORT:\n const colorRgb = color.toColorRGB(acc === 'ansi'\n ? this._themeService.colors.ansi[req.index]\n : this._themeService.colors[acc]);\n this.coreService.triggerDataEvent(`${C0.ESC}]${ident};${toRgbString(colorRgb)}${C1_ESCAPED.ST}`);\n break;\n case ColorRequestType.SET:\n if (acc === 'ansi') {\n this._themeService.modifyColors(colors => colors.ansi[req.index] = channels.toColor(...req.color));\n } else {\n const narrowedAcc = acc;\n this._themeService.modifyColors(colors => colors[narrowedAcc] = channels.toColor(...req.color));\n }\n break;\n case ColorRequestType.RESTORE:\n this._themeService.restoreColor(req.index);\n break;\n }\n }\n }\n\n protected _setup(): void {\n super._setup();\n\n this._customKeyEventHandler = undefined;\n }\n\n /**\n * Convenience property to active buffer.\n */\n public get buffer(): IBuffer {\n return this.buffers.active;\n }\n\n /**\n * Focus the terminal. Delegates focus handling to the terminal's DOM element.\n */\n public focus(): void {\n if (this.textarea) {\n this.textarea.focus({ preventScroll: true });\n }\n }\n\n private _handleScreenReaderModeOptionChange(value: boolean): void {\n if (value) {\n if (!this._accessibilityManager.value && this._renderService) {\n this._accessibilityManager.value = this._instantiationService.createInstance(AccessibilityManager, this);\n }\n } else {\n this._accessibilityManager.clear();\n }\n }\n\n /**\n * Binds the desired focus behavior on a given terminal object.\n */\n private _handleTextAreaFocus(ev: FocusEvent): void {\n if (this.coreService.decPrivateModes.sendFocus) {\n this.coreService.triggerDataEvent(C0.ESC + '[I');\n }\n this.element!.classList.add('focus');\n this._showCursor();\n this._onFocus.fire();\n }\n\n /**\n * Blur the terminal, calling the blur function on the terminal's underlying\n * textarea.\n */\n public blur(): void {\n return this.textarea?.blur();\n }\n\n /**\n * Binds the desired blur behavior on a given terminal object.\n */\n private _handleTextAreaBlur(): void {\n // Text can safely be removed on blur. Doing it earlier could interfere with\n // screen readers reading it out.\n this.textarea!.value = '';\n this.refresh(this.buffer.y, this.buffer.y);\n if (this.coreService.decPrivateModes.sendFocus) {\n this.coreService.triggerDataEvent(C0.ESC + '[O');\n }\n this.element!.classList.remove('focus');\n this._onBlur.fire();\n }\n\n private _syncTextArea(): void {\n if (!this.textarea || !this.buffer.isCursorInViewport || this._compositionHelper!.isComposing || !this._renderService) {\n return;\n }\n const cursorY = this.buffer.ybase + this.buffer.y;\n const bufferLine = this.buffer.lines.get(cursorY);\n if (!bufferLine) {\n return;\n }\n const cursorX = Math.min(this.buffer.x, this.cols - 1);\n const cellHeight = this._renderService.dimensions.css.cell.height;\n const width = bufferLine.getWidth(cursorX);\n const cellWidth = this._renderService.dimensions.css.cell.width * width;\n const cursorTop = this.buffer.y * this._renderService.dimensions.css.cell.height;\n const cursorLeft = cursorX * this._renderService.dimensions.css.cell.width;\n\n // Sync the textarea to the exact position of the composition view so the IME knows where the\n // text is.\n this.textarea.style.left = cursorLeft + 'px';\n this.textarea.style.top = cursorTop + 'px';\n this.textarea.style.width = cellWidth + 'px';\n this.textarea.style.height = cellHeight + 'px';\n this.textarea.style.lineHeight = cellHeight + 'px';\n this.textarea.style.zIndex = '-5';\n }\n\n /**\n * Initialize default behavior\n */\n private _initGlobal(): void {\n this._bindKeys();\n\n // Bind clipboard functionality\n this._register(addDisposableListener(this.element!, 'copy', (event: ClipboardEvent) => {\n // If mouse events are active it means the selection manager is disabled and\n // copy should be handled by the host program.\n if (!this.hasSelection()) {\n return;\n }\n copyHandler(event, this._selectionService!);\n }));\n const pasteHandlerWrapper = (event: ClipboardEvent): void => handlePasteEvent(event, this.textarea!, this.coreService, this.optionsService);\n this._register(addDisposableListener(this.textarea!, 'paste', pasteHandlerWrapper));\n this._register(addDisposableListener(this.element!, 'paste', pasteHandlerWrapper));\n\n // Handle right click context menus\n if (Browser.isFirefox) {\n // Firefox doesn't appear to fire the contextmenu event on right click\n this._register(addDisposableListener(this.element!, 'mousedown', (event: MouseEvent) => {\n if (event.button === 2) {\n rightClickHandler(event, this.textarea!, this.screenElement!, this._selectionService!, this.options.rightClickSelectsWord);\n }\n }));\n } else {\n this._register(addDisposableListener(this.element!, 'contextmenu', (event: MouseEvent) => {\n rightClickHandler(event, this.textarea!, this.screenElement!, this._selectionService!, this.options.rightClickSelectsWord);\n }));\n }\n\n // Move the textarea under the cursor when middle clicking on Linux to ensure\n // middle click to paste selection works. This only appears to work in Chrome\n // at the time is writing.\n if (Browser.isLinux) {\n // Use auxclick event over mousedown the latter doesn't seem to work. Note\n // that the regular click event doesn't fire for the middle mouse button.\n this._register(addDisposableListener(this.element!, 'auxclick', (event: MouseEvent) => {\n if (event.button === 1) {\n moveTextAreaUnderMouseCursor(event, this.textarea!, this.screenElement!);\n }\n }));\n }\n }\n\n /**\n * Apply key handling to the terminal\n */\n private _bindKeys(): void {\n this._register(addDisposableListener(this.textarea!, 'keyup', (ev: KeyboardEvent) => this._keyUp(ev), true));\n this._register(addDisposableListener(this.textarea!, 'keydown', (ev: KeyboardEvent) => this._keyDown(ev), true));\n this._register(addDisposableListener(this.textarea!, 'keypress', (ev: KeyboardEvent) => this._keyPress(ev), true));\n this._register(addDisposableListener(this.textarea!, 'compositionstart', () => this._compositionHelper!.compositionstart()));\n this._register(addDisposableListener(this.textarea!, 'compositionupdate', (e: CompositionEvent) => this._compositionHelper!.compositionupdate(e)));\n this._register(addDisposableListener(this.textarea!, 'compositionend', () => this._compositionHelper!.compositionend()));\n this._register(addDisposableListener(this.textarea!, 'input', (ev: InputEvent) => this._inputEvent(ev), true));\n this._register(this.onRender(() => this._compositionHelper!.updateCompositionElements()));\n }\n\n /**\n * Opens the terminal within an element.\n *\n * @param parent The element to create the terminal within.\n */\n public open(parent: HTMLElement): void {\n if (!parent) {\n throw new Error('Terminal requires a parent element.');\n }\n\n if (!parent.isConnected) {\n this._logService.debug('Terminal.open was called on an element that was not attached to the DOM');\n }\n\n // If the terminal is already opened\n if (this.element?.ownerDocument.defaultView && this._coreBrowserService) {\n // Adjust the window if needed\n if (this.element.ownerDocument.defaultView !== this._coreBrowserService.window) {\n this._coreBrowserService.window = this.element.ownerDocument.defaultView;\n }\n return;\n }\n\n this._document = parent.ownerDocument;\n if (this.options.documentOverride && this.options.documentOverride instanceof Document) {\n this._document = this.optionsService.rawOptions.documentOverride as Document;\n }\n\n // Create main element container\n this.element = this._document.createElement('div');\n this.element.dir = 'ltr'; // xterm.css assumes LTR\n this.element.classList.add('terminal');\n this.element.classList.add('xterm');\n parent.appendChild(this.element);\n\n // Performance: Use a document fragment to build the terminal\n // viewport and helper elements detached from the DOM\n const fragment = this._document.createDocumentFragment();\n this._viewportElement = this._document.createElement('div');\n this._viewportElement.classList.add('xterm-viewport');\n fragment.appendChild(this._viewportElement);\n\n this.screenElement = this._document.createElement('div');\n this.screenElement.classList.add('xterm-screen');\n this._register(addDisposableListener(this.screenElement, 'mousemove', (ev: MouseEvent) => this.updateCursorStyle(ev)));\n // Create the container that will hold helpers like the textarea for\n // capturing DOM Events. Then produce the helpers.\n this._helperContainer = this._document.createElement('div');\n this._helperContainer.classList.add('xterm-helpers');\n this.screenElement.appendChild(this._helperContainer);\n fragment.appendChild(this.screenElement);\n\n const textarea = this.textarea = this._document.createElement('textarea');\n this.textarea.classList.add('xterm-helper-textarea');\n this.textarea.setAttribute('aria-label', Strings.promptLabel.get());\n if (!Browser.isChromeOS) {\n // ChromeVox on ChromeOS does not like this. See\n // https://issuetracker.google.com/issues/260170397\n this.textarea.setAttribute('aria-multiline', 'false');\n }\n this.textarea.setAttribute('autocorrect', 'off');\n this.textarea.setAttribute('autocapitalize', 'off');\n this.textarea.setAttribute('spellcheck', 'false');\n this.textarea.tabIndex = 0;\n this._register(this.optionsService.onSpecificOptionChange('disableStdin', () => textarea.readOnly = this.optionsService.rawOptions.disableStdin));\n this.textarea.readOnly = this.optionsService.rawOptions.disableStdin;\n\n // Register the core browser service before the generic textarea handlers are registered so it\n // handles them first. Otherwise the renderers may use the wrong focus state.\n this._coreBrowserService = this._register(this._instantiationService.createInstance(CoreBrowserService,\n this.textarea,\n parent.ownerDocument.defaultView ?? window,\n // Force unsafe null in node.js environment for tests\n this._document ?? (typeof window !== 'undefined') ? window.document : null as any\n ));\n this._instantiationService.setService(ICoreBrowserService, this._coreBrowserService);\n\n this._register(addDisposableListener(this.textarea, 'focus', (ev: FocusEvent) => this._handleTextAreaFocus(ev)));\n this._register(addDisposableListener(this.textarea, 'blur', () => this._handleTextAreaBlur()));\n this._helperContainer.appendChild(this.textarea);\n\n this._charSizeService = this._instantiationService.createInstance(CharSizeService, this._document, this._helperContainer);\n this._instantiationService.setService(ICharSizeService, this._charSizeService);\n\n this._themeService = this._instantiationService.createInstance(ThemeService);\n this._instantiationService.setService(IThemeService, this._themeService);\n\n this._characterJoinerService = this._instantiationService.createInstance(CharacterJoinerService);\n this._instantiationService.setService(ICharacterJoinerService, this._characterJoinerService);\n\n this._renderService = this._register(this._instantiationService.createInstance(RenderService, this.rows, this.screenElement));\n this._instantiationService.setService(IRenderService, this._renderService);\n this._register(this._renderService.onRenderedViewportChange(e => this._onRender.fire(e)));\n this.onResize(e => this._renderService!.resize(e.cols, e.rows));\n\n this._compositionView = this._document.createElement('div');\n this._compositionView.classList.add('composition-view');\n this._compositionHelper = this._instantiationService.createInstance(CompositionHelper, this.textarea, this._compositionView);\n this._helperContainer.appendChild(this._compositionView);\n\n this._mouseService = this._instantiationService.createInstance(MouseService);\n this._instantiationService.setService(IMouseService, this._mouseService);\n\n const linkifier = this._linkifier.value = this._register(this._instantiationService.createInstance(Linkifier, this.screenElement));\n\n // Performance: Add viewport and helper elements from the fragment\n this.element.appendChild(fragment);\n\n try {\n this._onWillOpen.fire(this.element);\n }\n catch { /* fails to load addon for some reason */ }\n if (!this._renderService.hasRenderer()) {\n this._renderService.setRenderer(this._createRenderer());\n }\n\n this._register(this.onCursorMove(() => {\n this._renderService!.handleCursorMove();\n this._syncTextArea();\n }));\n this._register(this.onResize(() => this._renderService!.handleResize(this.cols, this.rows)));\n this._register(this.onBlur(() => this._renderService!.handleBlur()));\n this._register(this.onFocus(() => this._renderService!.handleFocus()));\n\n this._viewport = this._register(this._instantiationService.createInstance(Viewport, this.element, this.screenElement));\n this._register(this._viewport.onRequestScrollLines(e => {\n super.scrollLines(e, false);\n this.refresh(0, this.rows - 1);\n }));\n\n this._selectionService = this._register(this._instantiationService.createInstance(SelectionService,\n this.element,\n this.screenElement,\n linkifier\n ));\n this._instantiationService.setService(ISelectionService, this._selectionService);\n this._register(this._selectionService.onRequestScrollLines(e => this.scrollLines(e.amount, e.suppressScrollEvent)));\n this._register(this._selectionService.onSelectionChange(() => this._onSelectionChange.fire()));\n this._register(this._selectionService.onRequestRedraw(e => this._renderService!.handleSelectionChanged(e.start, e.end, e.columnSelectMode)));\n this._register(this._selectionService.onLinuxMouseSelection(text => {\n // If there's a new selection, put it into the textarea, focus and select it\n // in order to register it as a selection on the OS. This event is fired\n // only on Linux to enable middle click to paste selection.\n this.textarea!.value = text;\n this.textarea!.focus();\n this.textarea!.select();\n }));\n this._register(Event.any(\n this._onScroll.event,\n this._inputHandler.onScroll\n )(() => {\n this._selectionService!.refresh();\n this._viewport?.queueSync();\n }));\n\n this._register(this._instantiationService.createInstance(BufferDecorationRenderer, this.screenElement));\n this._register(addDisposableListener(this.element, 'mousedown', (e: MouseEvent) => this._selectionService!.handleMouseDown(e)));\n\n // apply mouse event classes set by escape codes before terminal was attached\n if (this.coreMouseService.areMouseEventsActive) {\n this._selectionService.disable();\n this.element.classList.add('enable-mouse-events');\n } else {\n this._selectionService.enable();\n }\n\n if (this.options.screenReaderMode) {\n // Note that this must be done *after* the renderer is created in order to\n // ensure the correct order of the dprchange event\n this._accessibilityManager.value = this._instantiationService.createInstance(AccessibilityManager, this);\n }\n this._register(this.optionsService.onSpecificOptionChange('screenReaderMode', e => this._handleScreenReaderModeOptionChange(e)));\n\n if (this.options.overviewRuler.width) {\n this._overviewRulerRenderer = this._register(this._instantiationService.createInstance(OverviewRulerRenderer, this._viewportElement, this.screenElement));\n }\n this.optionsService.onSpecificOptionChange('overviewRuler', value => {\n if (!this._overviewRulerRenderer && value && this._viewportElement && this.screenElement) {\n this._overviewRulerRenderer = this._register(this._instantiationService.createInstance(OverviewRulerRenderer, this._viewportElement, this.screenElement));\n }\n });\n // Measure the character size\n this._charSizeService.measure();\n\n // Setup loop that draws to screen\n this.refresh(0, this.rows - 1);\n\n // Initialize global actions that need to be taken on the document.\n this._initGlobal();\n\n // Listen for mouse events and translate\n // them into terminal mouse protocols.\n this.bindMouse();\n }\n\n private _createRenderer(): IRenderer {\n return this._instantiationService.createInstance(DomRenderer, this, this._document!, this.element!, this.screenElement!, this._viewportElement!, this._helperContainer!, this.linkifier!);\n }\n\n /**\n * Bind certain mouse events to the terminal.\n * By default only 3 button + wheel up/down is ativated. For higher buttons\n * no mouse report will be created. Typically the standard actions will be active.\n *\n * There are several reasons not to enable support for higher buttons/wheel:\n * - Button 4 and 5 are typically used for history back and forward navigation,\n * there is no straight forward way to supress/intercept those standard actions.\n * - Support for higher buttons does not work in some platform/browser combinations.\n * - Left/right wheel was not tested.\n * - Emulators vary in mouse button support, typically only 3 buttons and\n * wheel up/down work reliable.\n *\n * TODO: Move mouse event code into its own file.\n */\n public bindMouse(): void {\n const self = this;\n const el = this.element!;\n\n // send event to CoreMouseService\n function sendEvent(ev: MouseEvent | WheelEvent): boolean {\n // get mouse coordinates\n const pos = self._mouseService!.getMouseReportCoords(ev, self.screenElement!);\n if (!pos) {\n return false;\n }\n\n let but: CoreMouseButton;\n let action: CoreMouseAction | undefined;\n switch ((ev as any).overrideType || ev.type) {\n case 'mousemove':\n action = CoreMouseAction.MOVE;\n if (ev.buttons === undefined) {\n // buttons is not supported on macOS, try to get a value from button instead\n but = CoreMouseButton.NONE;\n if (ev.button !== undefined) {\n but = ev.button < 3 ? ev.button : CoreMouseButton.NONE;\n }\n } else {\n // according to MDN buttons only reports up to button 5 (AUX2)\n but = ev.buttons & 1 ? CoreMouseButton.LEFT :\n ev.buttons & 4 ? CoreMouseButton.MIDDLE :\n ev.buttons & 2 ? CoreMouseButton.RIGHT :\n CoreMouseButton.NONE; // fallback to NONE\n }\n break;\n case 'mouseup':\n action = CoreMouseAction.UP;\n but = ev.button < 3 ? ev.button : CoreMouseButton.NONE;\n break;\n case 'mousedown':\n action = CoreMouseAction.DOWN;\n but = ev.button < 3 ? ev.button : CoreMouseButton.NONE;\n break;\n case 'wheel':\n if (self._customWheelEventHandler && self._customWheelEventHandler(ev as WheelEvent) === false) {\n return false;\n }\n const deltaY = (ev as WheelEvent).deltaY;\n if (deltaY === 0) {\n return false;\n }\n const lines = self.coreMouseService.consumeWheelEvent(\n ev as WheelEvent,\n self._renderService?.dimensions?.device?.cell?.height,\n self._coreBrowserService?.dpr\n );\n if (lines === 0) {\n return false;\n }\n action = deltaY < 0 ? CoreMouseAction.UP : CoreMouseAction.DOWN;\n but = CoreMouseButton.WHEEL;\n break;\n default:\n // dont handle other event types by accident\n return false;\n }\n\n // exit if we cannot determine valid button/action values\n // do nothing for higher buttons than wheel\n if (action === undefined || but === undefined || but > CoreMouseButton.WHEEL) {\n return false;\n }\n\n return self.coreMouseService.triggerMouseEvent({\n col: pos.col,\n row: pos.row,\n x: pos.x,\n y: pos.y,\n button: but,\n action,\n ctrl: ev.ctrlKey,\n alt: ev.altKey,\n shift: ev.shiftKey\n });\n }\n\n /**\n * Event listener state handling.\n * We listen to the onProtocolChange event of CoreMouseService and put\n * requested listeners in `requestedEvents`. With this the listeners\n * have all bits to do the event listener juggling.\n * Note: 'mousedown' currently is \"always on\" and not managed\n * by onProtocolChange.\n */\n const requestedEvents: { [key: string]: ((ev: MouseEvent | WheelEvent) => void) | null } = {\n mouseup: null,\n wheel: null,\n mousedrag: null,\n mousemove: null\n };\n const eventListeners: { [key: string]: (ev: any) => void | boolean } = {\n mouseup: (ev: MouseEvent) => {\n sendEvent(ev);\n if (!ev.buttons) {\n // if no other button is held remove global handlers\n this._document!.removeEventListener('mouseup', requestedEvents.mouseup!);\n if (requestedEvents.mousedrag) {\n this._document!.removeEventListener('mousemove', requestedEvents.mousedrag);\n }\n }\n return this.cancel(ev);\n },\n wheel: (ev: WheelEvent) => {\n sendEvent(ev);\n return this.cancel(ev, true);\n },\n mousedrag: (ev: MouseEvent) => {\n // deal only with move while a button is held\n if (ev.buttons) {\n sendEvent(ev);\n }\n },\n mousemove: (ev: MouseEvent) => {\n // deal only with move without any button\n if (!ev.buttons) {\n sendEvent(ev);\n }\n }\n };\n this._register(this.coreMouseService.onProtocolChange(events => {\n // apply global changes on events\n if (events) {\n if (this.optionsService.rawOptions.logLevel === 'debug') {\n this._logService.debug('Binding to mouse events:', this.coreMouseService.explainEvents(events));\n }\n this.element!.classList.add('enable-mouse-events');\n this._selectionService!.disable();\n } else {\n this._logService.debug('Unbinding from mouse events.');\n this.element!.classList.remove('enable-mouse-events');\n this._selectionService!.enable();\n }\n\n // add/remove handlers from requestedEvents\n\n if (!(events & CoreMouseEventType.MOVE)) {\n el.removeEventListener('mousemove', requestedEvents.mousemove!);\n requestedEvents.mousemove = null;\n } else if (!requestedEvents.mousemove) {\n el.addEventListener('mousemove', eventListeners.mousemove);\n requestedEvents.mousemove = eventListeners.mousemove;\n }\n\n if (!(events & CoreMouseEventType.WHEEL)) {\n el.removeEventListener('wheel', requestedEvents.wheel!);\n requestedEvents.wheel = null;\n } else if (!requestedEvents.wheel) {\n el.addEventListener('wheel', eventListeners.wheel, { passive: false });\n requestedEvents.wheel = eventListeners.wheel;\n }\n\n if (!(events & CoreMouseEventType.UP)) {\n this._document!.removeEventListener('mouseup', requestedEvents.mouseup!);\n requestedEvents.mouseup = null;\n } else if (!requestedEvents.mouseup) {\n requestedEvents.mouseup = eventListeners.mouseup;\n }\n\n if (!(events & CoreMouseEventType.DRAG)) {\n this._document!.removeEventListener('mousemove', requestedEvents.mousedrag!);\n requestedEvents.mousedrag = null;\n } else if (!requestedEvents.mousedrag) {\n requestedEvents.mousedrag = eventListeners.mousedrag;\n }\n }));\n // force initial onProtocolChange so we dont miss early mouse requests\n this.coreMouseService.activeProtocol = this.coreMouseService.activeProtocol;\n\n /**\n * \"Always on\" event listeners.\n */\n this._register(addDisposableListener(el, 'mousedown', (ev: MouseEvent) => {\n ev.preventDefault();\n this.focus();\n\n // Don't send the mouse button to the pty if mouse events are disabled or\n // if the selection manager is having selection forced (ie. a modifier is\n // held).\n if (!this.coreMouseService.areMouseEventsActive || this._selectionService!.shouldForceSelection(ev)) {\n return;\n }\n\n sendEvent(ev);\n\n // Register additional global handlers which should keep reporting outside\n // of the terminal element.\n // Note: Other emulators also do this for 'mousedown' while a button\n // is held, we currently limit 'mousedown' to the terminal only.\n if (requestedEvents.mouseup) {\n this._document!.addEventListener('mouseup', requestedEvents.mouseup);\n }\n if (requestedEvents.mousedrag) {\n this._document!.addEventListener('mousemove', requestedEvents.mousedrag);\n }\n\n return this.cancel(ev);\n }));\n\n this._register(addDisposableListener(el, 'wheel', (ev: WheelEvent) => {\n // do nothing, if app side handles wheel itself\n if (requestedEvents.wheel) return;\n\n if (this._customWheelEventHandler && this._customWheelEventHandler(ev) === false) {\n return false;\n }\n\n if (!this.buffer.hasScrollback) {\n // Convert wheel events into up/down events when the buffer does not have scrollback, this\n // enables scrolling in apps hosted in the alt buffer such as vim or tmux even when mouse\n // events are not enabled.\n // This used implementation used get the actual lines/partial lines scrolled from the\n // viewport but since moving to the new viewport implementation has been simplified to\n // simply send a single up or down sequence.\n\n // Do nothing if there's no vertical scroll\n const deltaY = (ev as WheelEvent).deltaY;\n if (deltaY === 0) {\n return false;\n }\n\n const lines = self.coreMouseService.consumeWheelEvent(\n ev as WheelEvent,\n self._renderService?.dimensions?.device?.cell?.height,\n self._coreBrowserService?.dpr\n );\n if (lines === 0) {\n return this.cancel(ev, true);\n }\n\n // Construct and send sequences\n const sequence = C0.ESC + (this.coreService.decPrivateModes.applicationCursorKeys ? 'O' : '[') + (ev.deltaY < 0 ? 'A' : 'B');\n this.coreService.triggerDataEvent(sequence, true);\n return this.cancel(ev, true);\n }\n }, { passive: false }));\n }\n\n\n /**\n * Tells the renderer to refresh terminal content between two rows (inclusive) at the next\n * opportunity.\n * @param start The row to start from (between 0 and this.rows - 1).\n * @param end The row to end at (between start and this.rows - 1).\n */\n public refresh(start: number, end: number): void {\n this._renderService?.refreshRows(start, end);\n }\n\n /**\n * Change the cursor style for different selection modes\n */\n public updateCursorStyle(ev: KeyboardEvent | MouseEvent): void {\n if (this._selectionService?.shouldColumnSelect(ev)) {\n this.element!.classList.add('column-select');\n } else {\n this.element!.classList.remove('column-select');\n }\n }\n\n /**\n * Display the cursor element\n */\n private _showCursor(): void {\n if (!this.coreService.isCursorInitialized) {\n this.coreService.isCursorInitialized = true;\n this.refresh(this.buffer.y, this.buffer.y);\n }\n }\n\n public scrollLines(disp: number, suppressScrollEvent?: boolean): void {\n // All scrollLines methods need to go via the viewport in order to support smooth scroll\n if (this._viewport) {\n this._viewport.scrollLines(disp);\n } else {\n super.scrollLines(disp, suppressScrollEvent);\n }\n this.refresh(0, this.rows - 1);\n }\n\n public scrollPages(pageCount: number): void {\n this.scrollLines(pageCount * (this.rows - 1));\n }\n\n public scrollToTop(): void {\n this.scrollLines(-this._bufferService.buffer.ydisp);\n }\n\n public scrollToBottom(disableSmoothScroll?: boolean): void {\n if (disableSmoothScroll && this._viewport) {\n this._viewport.scrollToLine(this.buffer.ybase, true);\n } else {\n this.scrollLines(this._bufferService.buffer.ybase - this._bufferService.buffer.ydisp);\n }\n }\n\n public scrollToLine(line: number): void {\n const scrollAmount = line - this._bufferService.buffer.ydisp;\n if (scrollAmount !== 0) {\n this.scrollLines(scrollAmount);\n }\n }\n\n public paste(data: string): void {\n paste(data, this.textarea!, this.coreService, this.optionsService);\n }\n\n public attachCustomKeyEventHandler(customKeyEventHandler: CustomKeyEventHandler): void {\n this._customKeyEventHandler = customKeyEventHandler;\n }\n\n public attachCustomWheelEventHandler(customWheelEventHandler: CustomWheelEventHandler): void {\n this._customWheelEventHandler = customWheelEventHandler;\n }\n\n public registerLinkProvider(linkProvider: ILinkProvider): IDisposable {\n return this._linkProviderService.registerLinkProvider(linkProvider);\n }\n\n public registerCharacterJoiner(handler: CharacterJoinerHandler): number {\n if (!this._characterJoinerService) {\n throw new Error('Terminal must be opened first');\n }\n const joinerId = this._characterJoinerService.register(handler);\n this.refresh(0, this.rows - 1);\n return joinerId;\n }\n\n public deregisterCharacterJoiner(joinerId: number): void {\n if (!this._characterJoinerService) {\n throw new Error('Terminal must be opened first');\n }\n if (this._characterJoinerService.deregister(joinerId)) {\n this.refresh(0, this.rows - 1);\n }\n }\n\n public get markers(): IMarker[] {\n return this.buffer.markers;\n }\n\n public registerMarker(cursorYOffset: number): IMarker {\n return this.buffer.addMarker(this.buffer.ybase + this.buffer.y + cursorYOffset);\n }\n\n public registerDecoration(decorationOptions: IDecorationOptions): IDecoration | undefined {\n return this._decorationService.registerDecoration(decorationOptions);\n }\n\n /**\n * Gets whether the terminal has an active selection.\n */\n public hasSelection(): boolean {\n return this._selectionService ? this._selectionService.hasSelection : false;\n }\n\n /**\n * Selects text within the terminal.\n * @param column The column the selection starts at..\n * @param row The row the selection starts at.\n * @param length The length of the selection.\n */\n public select(column: number, row: number, length: number): void {\n this._selectionService!.setSelection(column, row, length);\n }\n\n /**\n * Gets the terminal's current selection, this is useful for implementing copy\n * behavior outside of xterm.js.\n */\n public getSelection(): string {\n return this._selectionService ? this._selectionService.selectionText : '';\n }\n\n public getSelectionPosition(): IBufferRange | undefined {\n if (!this._selectionService || !this._selectionService.hasSelection) {\n return undefined;\n }\n\n return {\n start: {\n x: this._selectionService.selectionStart![0],\n y: this._selectionService.selectionStart![1]\n },\n end: {\n x: this._selectionService.selectionEnd![0],\n y: this._selectionService.selectionEnd![1]\n }\n };\n }\n\n /**\n * Clears the current terminal selection.\n */\n public clearSelection(): void {\n this._selectionService?.clearSelection();\n }\n\n /**\n * Selects all text within the terminal.\n */\n public selectAll(): void {\n this._selectionService?.selectAll();\n }\n\n public selectLines(start: number, end: number): void {\n this._selectionService?.selectLines(start, end);\n }\n\n /**\n * Handle a keydown [KeyboardEvent].\n *\n * [KeyboardEvent]: https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent\n */\n protected _keyDown(event: KeyboardEvent): boolean | undefined {\n this._keyDownHandled = false;\n this._keyDownSeen = true;\n\n if (this._customKeyEventHandler && this._customKeyEventHandler(event) === false) {\n return false;\n }\n\n // Ignore composing with Alt key on Mac when macOptionIsMeta is enabled\n const shouldIgnoreComposition = this.browser.isMac && this.options.macOptionIsMeta && event.altKey;\n\n if (!shouldIgnoreComposition && !this._compositionHelper!.keydown(event)) {\n if (this.options.scrollOnUserInput && this.buffer.ybase !== this.buffer.ydisp) {\n this.scrollToBottom(true);\n }\n return false;\n }\n\n if (!shouldIgnoreComposition && (event.key === 'Dead' || event.key === 'AltGraph')) {\n this._unprocessedDeadKey = true;\n }\n\n const result = evaluateKeyboardEvent(event, this.coreService.decPrivateModes.applicationCursorKeys, this.browser.isMac, this.options.macOptionIsMeta);\n\n this.updateCursorStyle(event);\n\n if (result.type === KeyboardResultType.PAGE_DOWN || result.type === KeyboardResultType.PAGE_UP) {\n const scrollCount = this.rows - 1;\n this.scrollLines(result.type === KeyboardResultType.PAGE_UP ? -scrollCount : scrollCount);\n return this.cancel(event, true);\n }\n\n if (result.type === KeyboardResultType.SELECT_ALL) {\n this.selectAll();\n }\n\n if (this._isThirdLevelShift(this.browser, event)) {\n return true;\n }\n\n if (result.cancel) {\n // The event is canceled at the end already, is this necessary?\n this.cancel(event, true);\n }\n\n if (!result.key) {\n return true;\n }\n\n // HACK: Process A-Z in the keypress event to fix an issue with macOS IMEs where lower case\n // letters cannot be input while caps lock is on.\n if (event.key && !event.ctrlKey && !event.altKey && !event.metaKey && event.key.length === 1) {\n if (event.key.charCodeAt(0) >= 65 && event.key.charCodeAt(0) <= 90) {\n return true;\n }\n }\n\n if (this._unprocessedDeadKey) {\n this._unprocessedDeadKey = false;\n return true;\n }\n\n // If ctrl+c or enter is being sent, clear out the textarea. This is done so that screen readers\n // will announce deleted characters. This will not work 100% of the time but it should cover\n // most scenarios.\n if (result.key === C0.ETX || result.key === C0.CR) {\n this.textarea!.value = '';\n }\n\n this._onKey.fire({ key: result.key, domEvent: event });\n this._showCursor();\n this.coreService.triggerDataEvent(result.key, true);\n\n // Cancel events when not in screen reader mode so events don't get bubbled up and handled by\n // other listeners. When screen reader mode is enabled, we don't cancel them (unless ctrl or alt\n // is also depressed) so that the cursor textarea can be updated, which triggers the screen\n // reader to read it.\n if (!this.optionsService.rawOptions.screenReaderMode || event.altKey || event.ctrlKey) {\n return this.cancel(event, true);\n }\n\n this._keyDownHandled = true;\n }\n\n private _isThirdLevelShift(browser: IBrowser, ev: KeyboardEvent): boolean {\n const thirdLevelKey =\n (browser.isMac && !this.options.macOptionIsMeta && ev.altKey && !ev.ctrlKey && !ev.metaKey) ||\n (browser.isWindows && ev.altKey && ev.ctrlKey && !ev.metaKey) ||\n (browser.isWindows && ev.getModifierState('AltGraph'));\n\n if (ev.type === 'keypress') {\n return thirdLevelKey;\n }\n\n // Don't invoke for arrows, pageDown, home, backspace, etc. (on non-keypress events)\n return thirdLevelKey && (!ev.keyCode || ev.keyCode > 47);\n }\n\n protected _keyUp(ev: KeyboardEvent): void {\n this._keyDownSeen = false;\n\n if (this._customKeyEventHandler && this._customKeyEventHandler(ev) === false) {\n return;\n }\n\n if (!wasModifierKeyOnlyEvent(ev)) {\n this.focus();\n }\n\n this.updateCursorStyle(ev);\n this._keyPressHandled = false;\n }\n\n /**\n * Handle a keypress event.\n * Key Resources:\n * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent\n * @param ev The keypress event to be handled.\n */\n protected _keyPress(ev: KeyboardEvent): boolean {\n let key;\n\n this._keyPressHandled = false;\n\n if (this._keyDownHandled) {\n return false;\n }\n\n if (this._customKeyEventHandler && this._customKeyEventHandler(ev) === false) {\n return false;\n }\n\n this.cancel(ev);\n\n if (ev.charCode) {\n key = ev.charCode;\n } else if (ev.which === null || ev.which === undefined) {\n key = ev.keyCode;\n } else if (ev.which !== 0 && ev.charCode !== 0) {\n key = ev.which;\n } else {\n return false;\n }\n\n if (!key || (\n (ev.altKey || ev.ctrlKey || ev.metaKey) && !this._isThirdLevelShift(this.browser, ev)\n )) {\n return false;\n }\n\n key = String.fromCharCode(key);\n\n this._onKey.fire({ key, domEvent: ev });\n this._showCursor();\n this.coreService.triggerDataEvent(key, true);\n\n this._keyPressHandled = true;\n\n // The key was handled so clear the dead key state, otherwise certain keystrokes like arrow\n // keys could be ignored\n this._unprocessedDeadKey = false;\n\n return true;\n }\n\n /**\n * Handle an input event.\n * Key Resources:\n * - https://developer.mozilla.org/en-US/docs/Web/API/InputEvent\n * @param ev The input event to be handled.\n */\n protected _inputEvent(ev: InputEvent): boolean {\n // Only support emoji IMEs when screen reader mode is disabled as the event must bubble up to\n // support reading out character input which can doubling up input characters\n // Based on these event traces: https://github.com/xtermjs/xterm.js/issues/3679\n if (ev.data && ev.inputType === 'insertText' && (!ev.composed || !this._keyDownSeen) && !this.optionsService.rawOptions.screenReaderMode) {\n if (this._keyPressHandled) {\n return false;\n }\n\n // The key was handled so clear the dead key state, otherwise certain keystrokes like arrow\n // keys could be ignored\n this._unprocessedDeadKey = false;\n\n const text = ev.data;\n this.coreService.triggerDataEvent(text, true);\n\n this.cancel(ev);\n return true;\n }\n\n return false;\n }\n\n /**\n * Resizes the terminal.\n *\n * @param x The number of columns to resize to.\n * @param y The number of rows to resize to.\n */\n public resize(x: number, y: number): void {\n if (x === this.cols && y === this.rows) {\n // Check if we still need to measure the char size (fixes #785).\n if (this._charSizeService && !this._charSizeService.hasValidSize) {\n this._charSizeService.measure();\n }\n return;\n }\n\n super.resize(x, y);\n }\n\n private _afterResize(x: number, y: number): void {\n this._charSizeService?.measure();\n }\n\n /**\n * Clear the entire buffer, making the prompt line the new first line.\n */\n public clear(): void {\n if (this.buffer.ybase === 0 && this.buffer.y === 0) {\n // Don't clear if it's already clear\n return;\n }\n this.buffer.clearAllMarkers();\n this.buffer.lines.set(0, this.buffer.lines.get(this.buffer.ybase + this.buffer.y)!);\n this.buffer.lines.length = 1;\n this.buffer.ydisp = 0;\n this.buffer.ybase = 0;\n this.buffer.y = 0;\n for (let i = 1; i < this.rows; i++) {\n this.buffer.lines.push(this.buffer.getBlankLine(DEFAULT_ATTR_DATA));\n }\n // IMPORTANT: Fire scroll event before viewport is reset. This ensures embedders get the clear\n // scroll event and that the viewport's state will be valid for immediate writes.\n this._onScroll.fire({ position: this.buffer.ydisp });\n this.refresh(0, this.rows - 1);\n }\n\n /**\n * Reset terminal.\n * Note: Calling this directly from JS is synchronous but does not clear\n * input buffers and does not reset the parser, thus the terminal will\n * continue to apply pending input data.\n * If you need in band reset (synchronous with input data) consider\n * using DECSTR (soft reset, CSI ! p) or RIS instead (hard reset, ESC c).\n */\n public reset(): void {\n /**\n * Since _setup handles a full terminal creation, we have to carry forward\n * a few things that should not reset.\n */\n this.options.rows = this.rows;\n this.options.cols = this.cols;\n const customKeyEventHandler = this._customKeyEventHandler;\n\n this._setup();\n super.reset();\n this._selectionService?.reset();\n this._decorationService.reset();\n\n // reattach\n this._customKeyEventHandler = customKeyEventHandler;\n\n // do a full screen refresh\n this.refresh(0, this.rows - 1);\n }\n\n public clearTextureAtlas(): void {\n this._renderService?.clearTextureAtlas();\n }\n\n private _reportFocus(): void {\n if (this.element?.classList.contains('focus')) {\n this.coreService.triggerDataEvent(C0.ESC + '[I');\n } else {\n this.coreService.triggerDataEvent(C0.ESC + '[O');\n }\n }\n\n private _reportWindowsOptions(type: WindowsOptionsReportType): void {\n if (!this._renderService) {\n return;\n }\n\n switch (type) {\n case WindowsOptionsReportType.GET_WIN_SIZE_PIXELS:\n const canvasWidth = this._renderService.dimensions.css.canvas.width.toFixed(0);\n const canvasHeight = this._renderService.dimensions.css.canvas.height.toFixed(0);\n this.coreService.triggerDataEvent(`${C0.ESC}[4;${canvasHeight};${canvasWidth}t`);\n break;\n case WindowsOptionsReportType.GET_CELL_SIZE_PIXELS:\n const cellWidth = this._renderService.dimensions.css.cell.width.toFixed(0);\n const cellHeight = this._renderService.dimensions.css.cell.height.toFixed(0);\n this.coreService.triggerDataEvent(`${C0.ESC}[6;${cellHeight};${cellWidth}t`);\n break;\n }\n }\n\n // TODO: Remove cancel function and cancelEvents option\n public cancel(ev: MouseEvent | WheelEvent | KeyboardEvent | InputEvent, force?: boolean): boolean | undefined {\n if (!this.options.cancelEvents && !force) {\n return;\n }\n ev.preventDefault();\n ev.stopPropagation();\n return false;\n }\n}\n\n/**\n * Helpers\n */\n\nfunction wasModifierKeyOnlyEvent(ev: KeyboardEvent): boolean {\n return ev.keyCode === 16 || // Shift\n ev.keyCode === 17 || // Ctrl\n ev.keyCode === 18; // Alt\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IBufferCellPosition, ILink, ILinkDecorations, ILinkWithState, ILinkifier2, ILinkifierEvent } from 'browser/Types';\nimport { Disposable, dispose, toDisposable } from 'vs/base/common/lifecycle';\nimport { IDisposable } from 'common/Types';\nimport { IBufferService } from 'common/services/Services';\nimport { ILinkProviderService, IMouseService, IRenderService } from './services/Services';\nimport { Emitter } from 'vs/base/common/event';\nimport { addDisposableListener } from 'vs/base/browser/dom';\n\nexport class Linkifier extends Disposable implements ILinkifier2 {\n public get currentLink(): ILinkWithState | undefined { return this._currentLink; }\n protected _currentLink: ILinkWithState | undefined;\n private _mouseDownLink: ILinkWithState | undefined;\n private _lastMouseEvent: MouseEvent | undefined;\n private _linkCacheDisposables: IDisposable[] = [];\n private _lastBufferCell: IBufferCellPosition | undefined;\n private _isMouseOut: boolean = true;\n private _wasResized: boolean = false;\n private _activeProviderReplies: Map | undefined;\n private _activeLine: number = -1;\n\n private readonly _onShowLinkUnderline = this._register(new Emitter());\n public readonly onShowLinkUnderline = this._onShowLinkUnderline.event;\n private readonly _onHideLinkUnderline = this._register(new Emitter());\n public readonly onHideLinkUnderline = this._onHideLinkUnderline.event;\n\n constructor(\n private readonly _element: HTMLElement,\n @IMouseService private readonly _mouseService: IMouseService,\n @IRenderService private readonly _renderService: IRenderService,\n @IBufferService private readonly _bufferService: IBufferService,\n @ILinkProviderService private readonly _linkProviderService: ILinkProviderService\n ) {\n super();\n this._register(toDisposable(() => {\n dispose(this._linkCacheDisposables);\n this._linkCacheDisposables.length = 0;\n this._lastMouseEvent = undefined;\n // Clear out link providers as they could easily cause an embedder memory leak\n this._activeProviderReplies?.clear();\n }));\n // Listen to resize to catch the case where it's resized and the cursor is out of the viewport.\n this._register(this._bufferService.onResize(() => {\n this._clearCurrentLink();\n this._wasResized = true;\n }));\n this._register(addDisposableListener(this._element, 'mouseleave', () => {\n this._isMouseOut = true;\n this._clearCurrentLink();\n }));\n this._register(addDisposableListener(this._element, 'mousemove', this._handleMouseMove.bind(this)));\n this._register(addDisposableListener(this._element, 'mousedown', this._handleMouseDown.bind(this)));\n this._register(addDisposableListener(this._element, 'mouseup', this._handleMouseUp.bind(this)));\n }\n\n private _handleMouseMove(event: MouseEvent): void {\n this._lastMouseEvent = event;\n\n const position = this._positionFromMouseEvent(event, this._element, this._mouseService);\n if (!position) {\n return;\n }\n this._isMouseOut = false;\n\n // Ignore the event if it's an embedder created hover widget\n const composedPath = event.composedPath() as HTMLElement[];\n for (let i = 0; i < composedPath.length; i++) {\n const target = composedPath[i];\n // Hit Terminal.element, break and continue\n if (target.classList.contains('xterm')) {\n break;\n }\n // It's a hover, don't respect hover event\n if (target.classList.contains('xterm-hover')) {\n return;\n }\n }\n\n if (!this._lastBufferCell || (position.x !== this._lastBufferCell.x || position.y !== this._lastBufferCell.y)) {\n this._handleHover(position);\n this._lastBufferCell = position;\n }\n }\n\n private _handleHover(position: IBufferCellPosition): void {\n // TODO: This currently does not cache link provider results across wrapped lines, activeLine\n // should be something like `activeRange: {startY, endY}`\n // Check if we need to clear the link\n if (this._activeLine !== position.y || this._wasResized) {\n this._clearCurrentLink();\n this._askForLink(position, false);\n this._wasResized = false;\n return;\n }\n\n // Check the if the link is in the mouse position\n const isCurrentLinkInPosition = this._currentLink && this._linkAtPosition(this._currentLink.link, position);\n if (!isCurrentLinkInPosition) {\n this._clearCurrentLink();\n this._askForLink(position, true);\n }\n }\n\n private _askForLink(position: IBufferCellPosition, useLineCache: boolean): void {\n if (!this._activeProviderReplies || !useLineCache) {\n this._activeProviderReplies?.forEach(reply => {\n reply?.forEach(linkWithState => {\n if (linkWithState.link.dispose) {\n linkWithState.link.dispose();\n }\n });\n });\n this._activeProviderReplies = new Map();\n this._activeLine = position.y;\n }\n let linkProvided = false;\n\n // There is no link cached, so ask for one\n for (const [i, linkProvider] of this._linkProviderService.linkProviders.entries()) {\n if (useLineCache) {\n const existingReply = this._activeProviderReplies?.get(i);\n // If there isn't a reply, the provider hasn't responded yet.\n\n // TODO: If there isn't a reply yet it means that the provider is still resolving. Ensuring\n // provideLinks isn't triggered again saves ILink.hover firing twice though. This probably\n // needs promises to get fixed\n if (existingReply) {\n linkProvided = this._checkLinkProviderResult(i, position, linkProvided);\n }\n } else {\n linkProvider.provideLinks(position.y, (links: ILink[] | undefined) => {\n if (this._isMouseOut) {\n return;\n }\n const linksWithState: ILinkWithState[] | undefined = links?.map(link => ({ link }));\n this._activeProviderReplies?.set(i, linksWithState);\n linkProvided = this._checkLinkProviderResult(i, position, linkProvided);\n\n // If all providers have responded, remove lower priority links that intersect ranges of\n // higher priority links\n if (this._activeProviderReplies?.size === this._linkProviderService.linkProviders.length) {\n this._removeIntersectingLinks(position.y, this._activeProviderReplies);\n }\n });\n }\n }\n }\n\n private _removeIntersectingLinks(y: number, replies: Map): void {\n const occupiedCells = new Set();\n for (let i = 0; i < replies.size; i++) {\n const providerReply = replies.get(i);\n if (!providerReply) {\n continue;\n }\n for (let i = 0; i < providerReply.length; i++) {\n const linkWithState = providerReply[i];\n const startX = linkWithState.link.range.start.y < y ? 0 : linkWithState.link.range.start.x;\n const endX = linkWithState.link.range.end.y > y ? this._bufferService.cols : linkWithState.link.range.end.x;\n for (let x = startX; x <= endX; x++) {\n if (occupiedCells.has(x)) {\n providerReply.splice(i--, 1);\n break;\n }\n occupiedCells.add(x);\n }\n }\n }\n }\n\n private _checkLinkProviderResult(index: number, position: IBufferCellPosition, linkProvided: boolean): boolean {\n if (!this._activeProviderReplies) {\n return linkProvided;\n }\n\n const links = this._activeProviderReplies.get(index);\n\n // Check if every provider before this one has come back undefined\n let hasLinkBefore = false;\n for (let j = 0; j < index; j++) {\n if (!this._activeProviderReplies.has(j) || this._activeProviderReplies.get(j)) {\n hasLinkBefore = true;\n }\n }\n\n // If all providers with higher priority came back undefined, then this provider's link for\n // the position should be used\n if (!hasLinkBefore && links) {\n const linkAtPosition = links.find(link => this._linkAtPosition(link.link, position));\n if (linkAtPosition) {\n linkProvided = true;\n this._handleNewLink(linkAtPosition);\n }\n }\n\n // Check if all the providers have responded\n if (this._activeProviderReplies.size === this._linkProviderService.linkProviders.length && !linkProvided) {\n // Respect the order of the link providers\n for (let j = 0; j < this._activeProviderReplies.size; j++) {\n const currentLink = this._activeProviderReplies.get(j)?.find(link => this._linkAtPosition(link.link, position));\n if (currentLink) {\n linkProvided = true;\n this._handleNewLink(currentLink);\n break;\n }\n }\n }\n\n return linkProvided;\n }\n\n private _handleMouseDown(): void {\n this._mouseDownLink = this._currentLink;\n }\n\n private _handleMouseUp(event: MouseEvent): void {\n if (!this._currentLink) {\n return;\n }\n\n const position = this._positionFromMouseEvent(event, this._element, this._mouseService);\n if (!position) {\n return;\n }\n\n if (this._mouseDownLink && linkEquals(this._mouseDownLink.link, this._currentLink.link) && this._linkAtPosition(this._currentLink.link, position)) {\n this._currentLink.link.activate(event, this._currentLink.link.text);\n }\n }\n\n private _clearCurrentLink(startRow?: number, endRow?: number): void {\n if (!this._currentLink || !this._lastMouseEvent) {\n return;\n }\n\n // If we have a start and end row, check that the link is within it\n if (!startRow || !endRow || (this._currentLink.link.range.start.y >= startRow && this._currentLink.link.range.end.y <= endRow)) {\n this._linkLeave(this._element, this._currentLink.link, this._lastMouseEvent);\n this._currentLink = undefined;\n dispose(this._linkCacheDisposables);\n this._linkCacheDisposables.length = 0;\n }\n }\n\n private _handleNewLink(linkWithState: ILinkWithState): void {\n if (!this._lastMouseEvent) {\n return;\n }\n\n const position = this._positionFromMouseEvent(this._lastMouseEvent, this._element, this._mouseService);\n\n if (!position) {\n return;\n }\n\n // Trigger hover if the we have a link at the position\n if (this._linkAtPosition(linkWithState.link, position)) {\n this._currentLink = linkWithState;\n this._currentLink.state = {\n decorations: {\n underline: linkWithState.link.decorations === undefined ? true : linkWithState.link.decorations.underline,\n pointerCursor: linkWithState.link.decorations === undefined ? true : linkWithState.link.decorations.pointerCursor\n },\n isHovered: true\n };\n this._linkHover(this._element, linkWithState.link, this._lastMouseEvent);\n\n // Add listener for tracking decorations changes\n linkWithState.link.decorations = {} as ILinkDecorations;\n Object.defineProperties(linkWithState.link.decorations, {\n pointerCursor: {\n get: () => this._currentLink?.state?.decorations.pointerCursor,\n set: v => {\n if (this._currentLink?.state && this._currentLink.state.decorations.pointerCursor !== v) {\n this._currentLink.state.decorations.pointerCursor = v;\n if (this._currentLink.state.isHovered) {\n this._element.classList.toggle('xterm-cursor-pointer', v);\n }\n }\n }\n },\n underline: {\n get: () => this._currentLink?.state?.decorations.underline,\n set: v => {\n if (this._currentLink?.state && this._currentLink?.state?.decorations.underline !== v) {\n this._currentLink.state.decorations.underline = v;\n if (this._currentLink.state.isHovered) {\n this._fireUnderlineEvent(linkWithState.link, v);\n }\n }\n }\n }\n });\n\n // Listen to viewport changes to re-render the link under the cursor (only when the line the\n // link is on changes)\n this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(e => {\n // Sanity check, this shouldn't happen in practice as this listener would be disposed\n if (!this._currentLink) {\n return;\n }\n // When start is 0 a scroll most likely occurred, make sure links above the fold also get\n // cleared.\n const start = e.start === 0 ? 0 : e.start + 1 + this._bufferService.buffer.ydisp;\n const end = this._bufferService.buffer.ydisp + 1 + e.end;\n // Only clear the link if the viewport change happened on this line\n if (this._currentLink.link.range.start.y >= start && this._currentLink.link.range.end.y <= end) {\n this._clearCurrentLink(start, end);\n if (this._lastMouseEvent) {\n // re-eval previously active link after changes\n const position = this._positionFromMouseEvent(this._lastMouseEvent, this._element, this._mouseService!);\n if (position) {\n this._askForLink(position, false);\n }\n }\n }\n }));\n }\n }\n\n protected _linkHover(element: HTMLElement, link: ILink, event: MouseEvent): void {\n if (this._currentLink?.state) {\n this._currentLink.state.isHovered = true;\n if (this._currentLink.state.decorations.underline) {\n this._fireUnderlineEvent(link, true);\n }\n if (this._currentLink.state.decorations.pointerCursor) {\n element.classList.add('xterm-cursor-pointer');\n }\n }\n\n if (link.hover) {\n link.hover(event, link.text);\n }\n }\n\n private _fireUnderlineEvent(link: ILink, showEvent: boolean): void {\n const range = link.range;\n const scrollOffset = this._bufferService.buffer.ydisp;\n const event = this._createLinkUnderlineEvent(range.start.x - 1, range.start.y - scrollOffset - 1, range.end.x, range.end.y - scrollOffset - 1, undefined);\n const emitter = showEvent ? this._onShowLinkUnderline : this._onHideLinkUnderline;\n emitter.fire(event);\n }\n\n protected _linkLeave(element: HTMLElement, link: ILink, event: MouseEvent): void {\n if (this._currentLink?.state) {\n this._currentLink.state.isHovered = false;\n if (this._currentLink.state.decorations.underline) {\n this._fireUnderlineEvent(link, false);\n }\n if (this._currentLink.state.decorations.pointerCursor) {\n element.classList.remove('xterm-cursor-pointer');\n }\n }\n\n if (link.leave) {\n link.leave(event, link.text);\n }\n }\n\n /**\n * Check if the buffer position is within the link\n * @param link\n * @param position\n */\n private _linkAtPosition(link: ILink, position: IBufferCellPosition): boolean {\n const lower = link.range.start.y * this._bufferService.cols + link.range.start.x;\n const upper = link.range.end.y * this._bufferService.cols + link.range.end.x;\n const current = position.y * this._bufferService.cols + position.x;\n return (lower <= current && current <= upper);\n }\n\n /**\n * Get the buffer position from a mouse event\n * @param event\n */\n private _positionFromMouseEvent(event: MouseEvent, element: HTMLElement, mouseService: IMouseService): IBufferCellPosition | undefined {\n const coords = mouseService.getCoords(event, element, this._bufferService.cols, this._bufferService.rows);\n if (!coords) {\n return;\n }\n\n return { x: coords[0], y: coords[1] + this._bufferService.buffer.ydisp };\n }\n\n private _createLinkUnderlineEvent(x1: number, y1: number, x2: number, y2: number, fg: number | undefined): ILinkifierEvent {\n return { x1, y1, x2, y2, cols: this._bufferService.cols, fg };\n }\n}\n\nfunction linkEquals(a: ILink, b: ILink): boolean {\n return (\n a.text === b.text &&\n a.range.start.x === b.range.start.x &&\n a.range.start.y === b.range.start.y &&\n a.range.end.x === b.range.end.x &&\n a.range.end.y === b.range.end.y\n );\n}\n","/**\n * Copyright (c) 2018 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\n// This file contains strings that get exported in the API so they can be localized\n\nlet promptLabelInternal = 'Terminal input';\nconst promptLabel = {\n get: () => promptLabelInternal,\n set: (value: string) => promptLabelInternal = value\n};\n\nlet tooMuchOutputInternal = 'Too much output to announce, navigate to rows manually to read';\nconst tooMuchOutput = {\n get: () => tooMuchOutputInternal,\n set: (value: string) => tooMuchOutputInternal = value\n};\n\nexport {\n promptLabel,\n tooMuchOutput\n};\n","/**\n * Copyright (c) 2022 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IBufferRange, ILink } from 'browser/Types';\nimport { ILinkProvider } from 'browser/services/Services';\nimport { CellData } from 'common/buffer/CellData';\nimport { IBufferService, IOptionsService, IOscLinkService } from 'common/services/Services';\n\nexport class OscLinkProvider implements ILinkProvider {\n constructor(\n @IBufferService private readonly _bufferService: IBufferService,\n @IOptionsService private readonly _optionsService: IOptionsService,\n @IOscLinkService private readonly _oscLinkService: IOscLinkService\n ) {\n }\n\n public provideLinks(y: number, callback: (links: ILink[] | undefined) => void): void {\n const line = this._bufferService.buffer.lines.get(y - 1);\n if (!line) {\n callback(undefined);\n return;\n }\n\n const result: ILink[] = [];\n const linkHandler = this._optionsService.rawOptions.linkHandler;\n const cell = new CellData();\n const lineLength = line.getTrimmedLength();\n let currentLinkId = -1;\n let currentStart = -1;\n let finishLink = false;\n for (let x = 0; x < lineLength; x++) {\n // Minor optimization, only check for content if there isn't a link in case the link ends with\n // a null cell\n if (currentStart === -1 && !line.hasContent(x)) {\n continue;\n }\n\n line.loadCell(x, cell);\n if (cell.hasExtendedAttrs() && cell.extended.urlId) {\n if (currentStart === -1) {\n currentStart = x;\n currentLinkId = cell.extended.urlId;\n continue;\n } else {\n finishLink = cell.extended.urlId !== currentLinkId;\n }\n } else {\n if (currentStart !== -1) {\n finishLink = true;\n }\n }\n\n if (finishLink || (currentStart !== -1 && x === lineLength - 1)) {\n const text = this._oscLinkService.getLinkData(currentLinkId)?.uri;\n if (text) {\n // These ranges are 1-based\n const range: IBufferRange = {\n start: {\n x: currentStart + 1,\n y\n },\n end: {\n // Offset end x if it's a link that ends on the last cell in the line\n x: x + (!finishLink && x === lineLength - 1 ? 1 : 0),\n y\n }\n };\n\n let ignoreLink = false;\n if (!linkHandler?.allowNonHttpProtocols) {\n try {\n const parsed = new URL(text);\n if (!['http:', 'https:'].includes(parsed.protocol)) {\n ignoreLink = true;\n }\n } catch (e) {\n // Ignore invalid URLs to prevent unexpected behaviors\n ignoreLink = true;\n }\n }\n\n if (!ignoreLink) {\n // OSC links always use underline and pointer decorations\n result.push({\n text,\n range,\n activate: (e, text) => (linkHandler ? linkHandler.activate(e, text, range) : defaultActivate(e, text)),\n hover: (e, text) => linkHandler?.hover?.(e, text, range),\n leave: (e, text) => linkHandler?.leave?.(e, text, range)\n });\n }\n }\n finishLink = false;\n\n // Clear link or start a new link if one starts immediately\n if (cell.hasExtendedAttrs() && cell.extended.urlId) {\n currentStart = x;\n currentLinkId = cell.extended.urlId;\n } else {\n currentStart = -1;\n currentLinkId = -1;\n }\n }\n }\n\n // TODO: Handle fetching and returning other link ranges to underline other links with the same\n // id\n callback(result);\n }\n}\n\nfunction defaultActivate(e: MouseEvent, uri: string): void {\n const answer = confirm(`Do you want to navigate to ${uri}?\\n\\nWARNING: This link could potentially be dangerous`);\n if (answer) {\n const newWindow = window.open();\n if (newWindow) {\n try {\n newWindow.opener = null;\n } catch {\n // no-op, Electron can throw\n }\n newWindow.location.href = uri;\n } else {\n console.warn('Opening link blocked as opener could not be cleared');\n }\n }\n}\n","/**\n * Copyright (c) 2018 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IRenderDebouncerWithCallback } from 'browser/Types';\nimport { ICoreBrowserService } from 'browser/services/Services';\n\n/**\n * Debounces calls to render terminal rows using animation frames.\n */\nexport class RenderDebouncer implements IRenderDebouncerWithCallback {\n private _rowStart: number | undefined;\n private _rowEnd: number | undefined;\n private _rowCount: number | undefined;\n private _animationFrame: number | undefined;\n private _refreshCallbacks: FrameRequestCallback[] = [];\n\n constructor(\n private _renderCallback: (start: number, end: number) => void,\n private readonly _coreBrowserService: ICoreBrowserService\n ) {\n }\n\n public dispose(): void {\n if (this._animationFrame) {\n this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame);\n this._animationFrame = undefined;\n }\n }\n\n public addRefreshCallback(callback: FrameRequestCallback): number {\n this._refreshCallbacks.push(callback);\n if (!this._animationFrame) {\n this._animationFrame = this._coreBrowserService.window.requestAnimationFrame(() => this._innerRefresh());\n }\n return this._animationFrame;\n }\n\n public refresh(rowStart: number | undefined, rowEnd: number | undefined, rowCount: number): void {\n this._rowCount = rowCount;\n // Get the min/max row start/end for the arg values\n rowStart = rowStart !== undefined ? rowStart : 0;\n rowEnd = rowEnd !== undefined ? rowEnd : this._rowCount - 1;\n // Set the properties to the updated values\n this._rowStart = this._rowStart !== undefined ? Math.min(this._rowStart, rowStart) : rowStart;\n this._rowEnd = this._rowEnd !== undefined ? Math.max(this._rowEnd, rowEnd) : rowEnd;\n\n if (this._animationFrame) {\n return;\n }\n\n this._animationFrame = this._coreBrowserService.window.requestAnimationFrame(() => this._innerRefresh());\n }\n\n private _innerRefresh(): void {\n this._animationFrame = undefined;\n\n // Make sure values are set\n if (this._rowStart === undefined || this._rowEnd === undefined || this._rowCount === undefined) {\n this._runRefreshCallbacks();\n return;\n }\n\n // Clamp values\n const start = Math.max(this._rowStart, 0);\n const end = Math.min(this._rowEnd, this._rowCount - 1);\n\n // Reset debouncer (this happens before render callback as the render could trigger it again)\n this._rowStart = undefined;\n this._rowEnd = undefined;\n\n // Run render callback\n this._renderCallback(start, end);\n this._runRefreshCallbacks();\n }\n\n private _runRefreshCallbacks(): void {\n for (const callback of this._refreshCallbacks) {\n callback(0);\n }\n this._refreshCallbacks = [];\n }\n}\n","/**\n * Copyright (c) 2018 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nconst RENDER_DEBOUNCE_THRESHOLD_MS = 1000; // 1 Second\n\nimport { IRenderDebouncer } from 'browser/Types';\n\n/**\n * Debounces calls to update screen readers to update at most once configurable interval of time.\n */\nexport class TimeBasedDebouncer implements IRenderDebouncer {\n private _rowStart: number | undefined;\n private _rowEnd: number | undefined;\n private _rowCount: number | undefined;\n\n // The last moment that the Terminal was refreshed at\n private _lastRefreshMs = 0;\n // Whether a trailing refresh should be triggered due to a refresh request that was throttled\n private _additionalRefreshRequested = false;\n\n private _refreshTimeoutID: number | undefined;\n\n constructor(\n private _renderCallback: (start: number, end: number) => void,\n private readonly _debounceThresholdMS = RENDER_DEBOUNCE_THRESHOLD_MS\n ) {\n }\n\n public dispose(): void {\n if (this._refreshTimeoutID) {\n clearTimeout(this._refreshTimeoutID);\n }\n }\n\n public refresh(rowStart: number | undefined, rowEnd: number | undefined, rowCount: number): void {\n this._rowCount = rowCount;\n // Get the min/max row start/end for the arg values\n rowStart = rowStart !== undefined ? rowStart : 0;\n rowEnd = rowEnd !== undefined ? rowEnd : this._rowCount - 1;\n // Set the properties to the updated values\n this._rowStart = this._rowStart !== undefined ? Math.min(this._rowStart, rowStart) : rowStart;\n this._rowEnd = this._rowEnd !== undefined ? Math.max(this._rowEnd, rowEnd) : rowEnd;\n\n // Only refresh if the time since last refresh is above a threshold, otherwise wait for\n // enough time to pass before refreshing again.\n const refreshRequestTime: number = performance.now();\n if (refreshRequestTime - this._lastRefreshMs >= this._debounceThresholdMS) {\n // Enough time has lapsed since the last refresh; refresh immediately\n this._lastRefreshMs = refreshRequestTime;\n this._innerRefresh();\n } else if (!this._additionalRefreshRequested) {\n // This is the first additional request throttled; set up trailing refresh\n const elapsed = refreshRequestTime - this._lastRefreshMs;\n const waitPeriodBeforeTrailingRefresh = this._debounceThresholdMS - elapsed;\n this._additionalRefreshRequested = true;\n\n this._refreshTimeoutID = window.setTimeout(() => {\n this._lastRefreshMs = performance.now();\n this._innerRefresh();\n this._additionalRefreshRequested = false;\n this._refreshTimeoutID = undefined; // No longer need to clear the timeout\n }, waitPeriodBeforeTrailingRefresh);\n }\n }\n\n private _innerRefresh(): void {\n // Make sure values are set\n if (this._rowStart === undefined || this._rowEnd === undefined || this._rowCount === undefined) {\n return;\n }\n\n // Clamp values\n const start = Math.max(this._rowStart, 0);\n const end = Math.min(this._rowEnd, this._rowCount - 1);\n\n // Reset debouncer (this happens before render callback as the render could trigger it again)\n this._rowStart = undefined;\n this._rowEnd = undefined;\n\n // Run render callback\n this._renderCallback(start, end);\n }\n}\n\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { CharData, IColor, ICoreTerminal, ITerminalOptions } from 'common/Types';\nimport { IBuffer } from 'common/buffer/Types';\nimport { IDisposable, Terminal as ITerminalApi } from '@xterm/xterm';\nimport { channels, css } from 'common/Color';\nimport type { Event } from 'vs/base/common/event';\n\n/**\n * A portion of the public API that are implemented identially internally and simply passed through.\n */\ntype InternalPassthroughApis = Omit;\n\nexport interface ITerminal extends InternalPassthroughApis, ICoreTerminal {\n screenElement: HTMLElement | undefined;\n browser: IBrowser;\n buffer: IBuffer;\n linkifier: ILinkifier2 | undefined;\n options: Required;\n\n onBlur: Event;\n onFocus: Event;\n onA11yChar: Event;\n onA11yTab: Event;\n onWillOpen: Event;\n\n cancel(ev: MouseEvent | WheelEvent | KeyboardEvent | InputEvent, force?: boolean): boolean | void;\n}\n\nexport type CustomKeyEventHandler = (event: KeyboardEvent) => boolean;\nexport type CustomWheelEventHandler = (event: WheelEvent) => boolean;\n\nexport type LineData = CharData[];\n\nexport interface ICompositionHelper {\n readonly isComposing: boolean;\n compositionstart(): void;\n compositionupdate(ev: CompositionEvent): void;\n compositionend(): void;\n updateCompositionElements(dontRecurse?: boolean): void;\n keydown(ev: KeyboardEvent): boolean;\n}\n\nexport interface IBrowser {\n isNode: boolean;\n userAgent: string;\n platform: string;\n isFirefox: boolean;\n isMac: boolean;\n isIpad: boolean;\n isIphone: boolean;\n isWindows: boolean;\n}\n\nexport interface IColorSet {\n foreground: IColor;\n background: IColor;\n cursor: IColor;\n cursorAccent: IColor;\n selectionForeground: IColor | undefined;\n selectionBackgroundTransparent: IColor;\n /** The selection blended on top of background. */\n selectionBackgroundOpaque: IColor;\n selectionInactiveBackgroundTransparent: IColor;\n selectionInactiveBackgroundOpaque: IColor;\n scrollbarSliderBackground: IColor;\n scrollbarSliderHoverBackground: IColor;\n scrollbarSliderActiveBackground: IColor;\n overviewRulerBorder: IColor;\n ansi: IColor[];\n /** Maps original colors to colors that respect minimum contrast ratio. */\n contrastCache: IColorContrastCache;\n /** Maps original colors to colors that respect _half_ of the minimum contrast ratio. */\n halfContrastCache: IColorContrastCache;\n}\n\nexport type ReadonlyColorSet = Readonly> & { ansi: Readonly['ansi']> };\n\nexport interface IColorContrastCache {\n clear(): void;\n setCss(bg: number, fg: number, value: string | null): void;\n getCss(bg: number, fg: number): string | null | undefined;\n setColor(bg: number, fg: number, value: IColor | null): void;\n getColor(bg: number, fg: number): IColor | null | undefined;\n}\n\nexport interface IPartialColorSet {\n foreground: IColor;\n background: IColor;\n cursor?: IColor;\n cursorAccent?: IColor;\n selectionBackground?: IColor;\n ansi: IColor[];\n}\n\nexport interface IViewport extends IDisposable {\n scrollBarWidth: number;\n readonly onRequestScrollLines: Event<{ amount: number, suppressScrollEvent: boolean }>;\n syncScrollArea(immediate?: boolean, force?: boolean): void;\n getLinesScrolled(ev: WheelEvent): number;\n getBufferElements(startLine: number, endLine?: number): { bufferElements: HTMLElement[], cursorElement?: HTMLElement };\n handleWheel(ev: WheelEvent): boolean;\n handleTouchStart(ev: TouchEvent): void;\n handleTouchMove(ev: TouchEvent): boolean;\n scrollLines(disp: number): void; // todo api name?\n reset(): void;\n}\n\nexport interface ILinkifierEvent {\n x1: number;\n y1: number;\n x2: number;\n y2: number;\n cols: number;\n fg: number | undefined;\n}\n\ninterface ILinkState {\n decorations: ILinkDecorations;\n isHovered: boolean;\n}\nexport interface ILinkWithState {\n link: ILink;\n state?: ILinkState;\n}\n\nexport interface ILinkifier2 extends IDisposable {\n onShowLinkUnderline: Event;\n onHideLinkUnderline: Event;\n readonly currentLink: ILinkWithState | undefined;\n}\n\nexport interface ILink {\n range: IBufferRange;\n text: string;\n decorations?: ILinkDecorations;\n activate(event: MouseEvent, text: string): void;\n hover?(event: MouseEvent, text: string): void;\n leave?(event: MouseEvent, text: string): void;\n dispose?(): void;\n}\n\nexport interface ILinkDecorations {\n pointerCursor: boolean;\n underline: boolean;\n}\n\nexport interface IBufferRange {\n start: IBufferCellPosition;\n end: IBufferCellPosition;\n}\n\nexport interface IBufferCellPosition {\n x: number;\n y: number;\n}\n\nexport type CharacterJoinerHandler = (text: string) => [number, number][];\n\nexport interface ICharacterJoiner {\n id: number;\n handler: CharacterJoinerHandler;\n}\n\nexport interface IRenderDebouncer extends IDisposable {\n refresh(rowStart: number | undefined, rowEnd: number | undefined, rowCount: number): void;\n}\n\nexport interface IRenderDebouncerWithCallback extends IRenderDebouncer {\n addRefreshCallback(callback: FrameRequestCallback): number;\n}\n\nexport interface IBufferElementProvider {\n provideBufferElements(): DocumentFragment | HTMLElement;\n}\n\n// An IIFE to generate DEFAULT_ANSI_COLORS.\nexport const DEFAULT_ANSI_COLORS = Object.freeze((() => {\n const colors = [\n // dark:\n css.toColor('#2e3436'),\n css.toColor('#cc0000'),\n css.toColor('#4e9a06'),\n css.toColor('#c4a000'),\n css.toColor('#3465a4'),\n css.toColor('#75507b'),\n css.toColor('#06989a'),\n css.toColor('#d3d7cf'),\n // bright:\n css.toColor('#555753'),\n css.toColor('#ef2929'),\n css.toColor('#8ae234'),\n css.toColor('#fce94f'),\n css.toColor('#729fcf'),\n css.toColor('#ad7fa8'),\n css.toColor('#34e2e2'),\n css.toColor('#eeeeec')\n ];\n\n // Fill in the remaining 240 ANSI colors.\n // Generate colors (16-231)\n const v = [0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff];\n for (let i = 0; i < 216; i++) {\n const r = v[(i / 36) % 6 | 0];\n const g = v[(i / 6) % 6 | 0];\n const b = v[i % 6];\n colors.push({\n css: channels.toCss(r, g, b),\n rgba: channels.toRgba(r, g, b)\n });\n }\n\n // Generate greys (232-255)\n for (let i = 0; i < 24; i++) {\n const c = 8 + i * 10;\n colors.push({\n css: channels.toCss(c, c, c),\n rgba: channels.toRgba(c, c, c)\n });\n }\n\n return colors;\n})());\n","/**\n * Copyright (c) 2024 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { ICoreBrowserService, IRenderService, IThemeService } from 'browser/services/Services';\nimport { ViewportConstants } from 'browser/shared/Constants';\nimport { Disposable, toDisposable } from 'vs/base/common/lifecycle';\nimport { IBufferService, ICoreMouseService, IOptionsService } from 'common/services/Services';\nimport { CoreMouseEventType } from 'common/Types';\nimport { scheduleAtNextAnimationFrame } from 'vs/base/browser/dom';\nimport { SmoothScrollableElement } from 'vs/base/browser/ui/scrollbar/scrollableElement';\nimport type { ScrollableElementChangeOptions } from 'vs/base/browser/ui/scrollbar/scrollableElementOptions';\nimport { Emitter, Event } from 'vs/base/common/event';\nimport { Scrollable, ScrollbarVisibility, type ScrollEvent } from 'vs/base/common/scrollable';\n\nexport class Viewport extends Disposable {\n\n protected _onRequestScrollLines = this._register(new Emitter());\n public readonly onRequestScrollLines = this._onRequestScrollLines.event;\n\n private _scrollableElement: SmoothScrollableElement;\n private _styleElement: HTMLStyleElement;\n\n private _queuedAnimationFrame?: number;\n private _latestYDisp?: number;\n private _isSyncing: boolean = false;\n private _isHandlingScroll: boolean = false;\n private _suppressOnScrollHandler: boolean = false;\n\n constructor(\n element: HTMLElement,\n screenElement: HTMLElement,\n @IBufferService private readonly _bufferService: IBufferService,\n @ICoreBrowserService coreBrowserService: ICoreBrowserService,\n @ICoreMouseService coreMouseService: ICoreMouseService,\n @IThemeService themeService: IThemeService,\n @IOptionsService private readonly _optionsService: IOptionsService,\n @IRenderService private readonly _renderService: IRenderService\n ) {\n super();\n\n const scrollable = this._register(new Scrollable({\n forceIntegerValues: false,\n smoothScrollDuration: this._optionsService.rawOptions.smoothScrollDuration,\n // This is used over `IRenderService.addRefreshCallback` since it can be canceled\n scheduleAtNextAnimationFrame: cb => scheduleAtNextAnimationFrame(coreBrowserService.window, cb)\n }));\n this._register(this._optionsService.onSpecificOptionChange('smoothScrollDuration', () => {\n scrollable.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration);\n }));\n\n this._scrollableElement = this._register(new SmoothScrollableElement(screenElement, {\n vertical: ScrollbarVisibility.Auto,\n horizontal: ScrollbarVisibility.Hidden,\n useShadows: false,\n mouseWheelSmoothScroll: true,\n ...this._getChangeOptions()\n }, scrollable));\n this._register(this._optionsService.onMultipleOptionChange([\n 'scrollSensitivity',\n 'fastScrollSensitivity',\n 'overviewRuler'\n ], () => this._scrollableElement.updateOptions(this._getChangeOptions())));\n // Don't handle mouse wheel if wheel events are supported by the current mouse prototcol\n this._register(coreMouseService.onProtocolChange(type => {\n this._scrollableElement.updateOptions({\n handleMouseWheel: !(type & CoreMouseEventType.WHEEL)\n });\n }));\n\n this._scrollableElement.setScrollDimensions({ height: 0, scrollHeight: 0 });\n this._register(Event.runAndSubscribe(themeService.onChangeColors, () => {\n this._scrollableElement.getDomNode().style.backgroundColor = themeService.colors.background.css;\n }));\n element.appendChild(this._scrollableElement.getDomNode());\n this._register(toDisposable(() => this._scrollableElement.getDomNode().remove()));\n\n this._styleElement = coreBrowserService.mainDocument.createElement('style');\n screenElement.appendChild(this._styleElement);\n this._register(toDisposable(() => this._styleElement.remove()));\n this._register(Event.runAndSubscribe(themeService.onChangeColors, () => {\n this._styleElement.textContent = [\n `.xterm .xterm-scrollable-element > .scrollbar > .slider {`,\n ` background: ${themeService.colors.scrollbarSliderBackground.css};`,\n `}`,\n `.xterm .xterm-scrollable-element > .scrollbar > .slider:hover {`,\n ` background: ${themeService.colors.scrollbarSliderHoverBackground.css};`,\n `}`,\n `.xterm .xterm-scrollable-element > .scrollbar > .slider.active {`,\n ` background: ${themeService.colors.scrollbarSliderActiveBackground.css};`,\n `}`\n ].join('\\n');\n }));\n\n this._register(this._bufferService.onResize(() => this.queueSync()));\n this._register(this._bufferService.buffers.onBufferActivate(() => {\n // Reset _latestYDisp when switching buffers to prevent stale scroll position\n // from alt buffer contaminating normal buffer scroll position\n this._latestYDisp = undefined;\n this.queueSync();\n }));\n this._register(this._bufferService.onScroll(() => this._sync()));\n\n this._register(this._scrollableElement.onScroll(e => this._handleScroll(e)));\n }\n\n public scrollLines(disp: number): void {\n const pos = this._scrollableElement.getScrollPosition();\n this._scrollableElement.setScrollPosition({\n reuseAnimation: true,\n scrollTop: pos.scrollTop + disp * this._renderService.dimensions.css.cell.height\n });\n }\n\n public scrollToLine(line: number, disableSmoothScroll?: boolean): void {\n if (disableSmoothScroll) {\n this._latestYDisp = line;\n }\n this._scrollableElement.setScrollPosition({\n reuseAnimation: !disableSmoothScroll,\n scrollTop: line * this._renderService.dimensions.css.cell.height\n });\n }\n\n private _getChangeOptions(): ScrollableElementChangeOptions {\n return {\n mouseWheelScrollSensitivity: this._optionsService.rawOptions.scrollSensitivity,\n fastScrollSensitivity: this._optionsService.rawOptions.fastScrollSensitivity,\n verticalScrollbarSize: this._optionsService.rawOptions.overviewRuler?.width || ViewportConstants.DEFAULT_SCROLL_BAR_WIDTH\n };\n }\n\n public queueSync(ydisp?: number): void {\n // Update state\n if (ydisp !== undefined) {\n this._latestYDisp = ydisp;\n }\n\n // Don't queue more than one callback\n if (this._queuedAnimationFrame !== undefined) {\n return;\n }\n this._queuedAnimationFrame = this._renderService.addRefreshCallback(() => {\n this._queuedAnimationFrame = undefined;\n this._sync(this._latestYDisp);\n });\n }\n\n private _sync(ydisp: number = this._bufferService.buffer.ydisp): void {\n if (!this._renderService || this._isSyncing) {\n return;\n }\n this._isSyncing = true;\n\n // Ignore any onScroll event that happens as a result of dimensions changing as this should\n // never cause a scrollLines call, only setScrollPosition can do that.\n this._suppressOnScrollHandler = true;\n this._scrollableElement.setScrollDimensions({\n height: this._renderService.dimensions.css.canvas.height,\n scrollHeight: this._renderService.dimensions.css.cell.height * this._bufferService.buffer.lines.length\n });\n this._suppressOnScrollHandler = false;\n\n // If ydisp has been changed by some other component (input/buffer), then stop animating smooth\n // scroll and scroll there immediately.\n if (ydisp !== this._latestYDisp) {\n this._scrollableElement.setScrollPosition({\n scrollTop: ydisp * this._renderService.dimensions.css.cell.height\n });\n }\n\n this._isSyncing = false;\n }\n\n private _handleScroll(e: ScrollEvent): void {\n if (!this._renderService) {\n return;\n }\n if (this._isHandlingScroll || this._suppressOnScrollHandler) {\n return;\n }\n this._isHandlingScroll = true;\n const newRow = Math.round(e.scrollTop / this._renderService.dimensions.css.cell.height);\n const diff = newRow - this._bufferService.buffer.ydisp;\n if (diff !== 0) {\n this._latestYDisp = newRow;\n this._onRequestScrollLines.fire(diff);\n }\n this._isHandlingScroll = false;\n }\n}\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\nimport { ICoreBrowserService, IRenderService } from 'browser/services/Services';\nimport { Disposable, toDisposable } from 'vs/base/common/lifecycle';\nimport { IBufferService, IDecorationService, IInternalDecoration } from 'common/services/Services';\n\nexport class BufferDecorationRenderer extends Disposable {\n private readonly _container: HTMLElement;\n private readonly _decorationElements: Map = new Map();\n\n private _animationFrame: number | undefined;\n private _altBufferIsActive: boolean = false;\n private _dimensionsChanged: boolean = false;\n\n constructor(\n private readonly _screenElement: HTMLElement,\n @IBufferService private readonly _bufferService: IBufferService,\n @ICoreBrowserService private readonly _coreBrowserService: ICoreBrowserService,\n @IDecorationService private readonly _decorationService: IDecorationService,\n @IRenderService private readonly _renderService: IRenderService\n ) {\n super();\n\n this._container = document.createElement('div');\n this._container.classList.add('xterm-decoration-container');\n this._screenElement.appendChild(this._container);\n\n this._register(this._renderService.onRenderedViewportChange(() => this._doRefreshDecorations()));\n this._register(this._renderService.onDimensionsChange(() => {\n this._dimensionsChanged = true;\n this._queueRefresh();\n }));\n this._register(this._coreBrowserService.onDprChange(() => this._queueRefresh()));\n this._register(this._bufferService.buffers.onBufferActivate(() => {\n this._altBufferIsActive = this._bufferService.buffer === this._bufferService.buffers.alt;\n }));\n this._register(this._decorationService.onDecorationRegistered(() => this._queueRefresh()));\n this._register(this._decorationService.onDecorationRemoved(decoration => this._removeDecoration(decoration)));\n this._register(toDisposable(() => {\n this._container.remove();\n this._decorationElements.clear();\n }));\n }\n\n private _queueRefresh(): void {\n if (this._animationFrame !== undefined) {\n return;\n }\n this._animationFrame = this._renderService.addRefreshCallback(() => {\n this._doRefreshDecorations();\n this._animationFrame = undefined;\n });\n }\n\n private _doRefreshDecorations(): void {\n for (const decoration of this._decorationService.decorations) {\n this._renderDecoration(decoration);\n }\n this._dimensionsChanged = false;\n }\n\n private _renderDecoration(decoration: IInternalDecoration): void {\n this._refreshStyle(decoration);\n if (this._dimensionsChanged) {\n this._refreshXPosition(decoration);\n }\n }\n\n private _createElement(decoration: IInternalDecoration): HTMLElement {\n const element = this._coreBrowserService.mainDocument.createElement('div');\n element.classList.add('xterm-decoration');\n element.classList.toggle('xterm-decoration-top-layer', decoration?.options?.layer === 'top');\n element.style.width = `${Math.round((decoration.options.width || 1) * this._renderService.dimensions.css.cell.width)}px`;\n element.style.height = `${(decoration.options.height || 1) * this._renderService.dimensions.css.cell.height}px`;\n element.style.top = `${(decoration.marker.line - this._bufferService.buffers.active.ydisp) * this._renderService.dimensions.css.cell.height}px`;\n element.style.lineHeight = `${this._renderService.dimensions.css.cell.height}px`;\n\n const x = decoration.options.x ?? 0;\n if (x && x > this._bufferService.cols) {\n // exceeded the container width, so hide\n element.style.display = 'none';\n }\n this._refreshXPosition(decoration, element);\n\n return element;\n }\n\n private _refreshStyle(decoration: IInternalDecoration): void {\n const line = decoration.marker.line - this._bufferService.buffers.active.ydisp;\n if (line < 0 || line >= this._bufferService.rows) {\n // outside of viewport\n if (decoration.element) {\n decoration.element.style.display = 'none';\n decoration.onRenderEmitter.fire(decoration.element);\n }\n } else {\n let element = this._decorationElements.get(decoration);\n if (!element) {\n element = this._createElement(decoration);\n decoration.element = element;\n this._decorationElements.set(decoration, element);\n this._container.appendChild(element);\n decoration.onDispose(() => {\n this._decorationElements.delete(decoration);\n element!.remove();\n });\n }\n element.style.display = this._altBufferIsActive ? 'none' : 'block';\n if (!this._altBufferIsActive) {\n element.style.width = `${Math.round((decoration.options.width || 1) * this._renderService.dimensions.css.cell.width)}px`;\n element.style.height = `${(decoration.options.height || 1) * this._renderService.dimensions.css.cell.height}px`;\n element.style.top = `${line * this._renderService.dimensions.css.cell.height}px`;\n element.style.lineHeight = `${this._renderService.dimensions.css.cell.height}px`;\n }\n decoration.onRenderEmitter.fire(element);\n }\n }\n\n private _refreshXPosition(decoration: IInternalDecoration, element: HTMLElement | undefined = decoration.element): void {\n if (!element) {\n return;\n }\n const x = decoration.options.x ?? 0;\n if ((decoration.options.anchor || 'left') === 'right') {\n element.style.right = x ? `${x * this._renderService.dimensions.css.cell.width}px` : '';\n } else {\n element.style.left = x ? `${x * this._renderService.dimensions.css.cell.width}px` : '';\n }\n }\n\n private _removeDecoration(decoration: IInternalDecoration): void {\n this._decorationElements.get(decoration)?.remove();\n this._decorationElements.delete(decoration);\n decoration.dispose();\n }\n}\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\nimport { IInternalDecoration } from 'common/services/Services';\n\nexport interface IColorZoneStore {\n readonly zones: IColorZone[];\n clear(): void;\n addDecoration(decoration: IInternalDecoration): void;\n /**\n * Sets the amount of padding in lines that will be added between zones, if new lines intersect\n * the padding they will be merged into the same zone.\n */\n setPadding(padding: { [position: string]: number }): void;\n}\n\nexport interface IColorZone {\n /** Color in a format supported by canvas' fillStyle. */\n color: string;\n position: 'full' | 'left' | 'center' | 'right' | undefined;\n startBufferLine: number;\n endBufferLine: number;\n}\n\ninterface IMinimalDecorationForColorZone {\n marker: Pick;\n options: Pick;\n}\n\nexport class ColorZoneStore implements IColorZoneStore {\n private _zones: IColorZone[] = [];\n\n // The zone pool is used to keep zone objects from being freed between clearing the color zone\n // store and fetching the zones. This helps reduce GC pressure since the color zones are\n // accumulated on potentially every scroll event.\n private _zonePool: IColorZone[] = [];\n private _zonePoolIndex = 0;\n\n private _linePadding: { [position: string]: number } = {\n full: 0,\n left: 0,\n center: 0,\n right: 0\n };\n\n public get zones(): IColorZone[] {\n // Trim the zone pool to free unused memory\n this._zonePool.length = Math.min(this._zonePool.length, this._zones.length);\n return this._zones;\n }\n\n public clear(): void {\n this._zones.length = 0;\n this._zonePoolIndex = 0;\n }\n\n public addDecoration(decoration: IMinimalDecorationForColorZone): void {\n if (!decoration.options.overviewRulerOptions) {\n return;\n }\n for (const z of this._zones) {\n if (z.color === decoration.options.overviewRulerOptions.color &&\n z.position === decoration.options.overviewRulerOptions.position) {\n if (this._lineIntersectsZone(z, decoration.marker.line)) {\n return;\n }\n if (this._lineAdjacentToZone(z, decoration.marker.line, decoration.options.overviewRulerOptions.position)) {\n this._addLineToZone(z, decoration.marker.line);\n return;\n }\n }\n }\n // Create using zone pool if possible\n if (this._zonePoolIndex < this._zonePool.length) {\n this._zonePool[this._zonePoolIndex].color = decoration.options.overviewRulerOptions.color;\n this._zonePool[this._zonePoolIndex].position = decoration.options.overviewRulerOptions.position;\n this._zonePool[this._zonePoolIndex].startBufferLine = decoration.marker.line;\n this._zonePool[this._zonePoolIndex].endBufferLine = decoration.marker.line;\n this._zones.push(this._zonePool[this._zonePoolIndex++]);\n return;\n }\n // Create\n this._zones.push({\n color: decoration.options.overviewRulerOptions.color,\n position: decoration.options.overviewRulerOptions.position,\n startBufferLine: decoration.marker.line,\n endBufferLine: decoration.marker.line\n });\n this._zonePool.push(this._zones[this._zones.length - 1]);\n this._zonePoolIndex++;\n }\n\n public setPadding(padding: { [position: string]: number }): void {\n this._linePadding = padding;\n }\n\n private _lineIntersectsZone(zone: IColorZone, line: number): boolean {\n return (\n line >= zone.startBufferLine &&\n line <= zone.endBufferLine\n );\n }\n\n private _lineAdjacentToZone(zone: IColorZone, line: number, position: IColorZone['position']): boolean {\n return (\n (line >= zone.startBufferLine - this._linePadding[position || 'full']) &&\n (line <= zone.endBufferLine + this._linePadding[position || 'full'])\n );\n }\n\n private _addLineToZone(zone: IColorZone, line: number): void {\n zone.startBufferLine = Math.min(zone.startBufferLine, line);\n zone.endBufferLine = Math.max(zone.endBufferLine, line);\n }\n}\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\nimport { ColorZoneStore, IColorZone, IColorZoneStore } from 'browser/decorations/ColorZoneStore';\nimport { ICoreBrowserService, IRenderService, IThemeService } from 'browser/services/Services';\nimport { Disposable, toDisposable } from 'vs/base/common/lifecycle';\nimport { IBufferService, IDecorationService, IOptionsService } from 'common/services/Services';\n\nconst enum Constants {\n OVERVIEW_RULER_BORDER_WIDTH = 1\n}\n\n// Helper objects to avoid excessive calculation and garbage collection during rendering. These are\n// static values for each render and can be accessed using the decoration position as the key.\nconst drawHeight = {\n full: 0,\n left: 0,\n center: 0,\n right: 0\n};\nconst drawWidth = {\n full: 0,\n left: 0,\n center: 0,\n right: 0\n};\nconst drawX = {\n full: 0,\n left: 0,\n center: 0,\n right: 0\n};\n\nexport class OverviewRulerRenderer extends Disposable {\n private readonly _canvas: HTMLCanvasElement;\n private readonly _ctx: CanvasRenderingContext2D;\n private readonly _colorZoneStore: IColorZoneStore = new ColorZoneStore();\n private get _width(): number {\n return this._optionsService.options.overviewRuler?.width || 0;\n }\n private _animationFrame: number | undefined;\n\n private _shouldUpdateDimensions: boolean | undefined = true;\n private _shouldUpdateAnchor: boolean | undefined = true;\n private _lastKnownBufferLength: number = 0;\n\n private _containerHeight: number | undefined;\n\n constructor(\n private readonly _viewportElement: HTMLElement,\n private readonly _screenElement: HTMLElement,\n @IBufferService private readonly _bufferService: IBufferService,\n @IDecorationService private readonly _decorationService: IDecorationService,\n @IRenderService private readonly _renderService: IRenderService,\n @IOptionsService private readonly _optionsService: IOptionsService,\n @IThemeService private readonly _themeService: IThemeService,\n @ICoreBrowserService private readonly _coreBrowserService: ICoreBrowserService\n ) {\n super();\n this._canvas = this._coreBrowserService.mainDocument.createElement('canvas');\n this._canvas.classList.add('xterm-decoration-overview-ruler');\n this._refreshCanvasDimensions();\n this._viewportElement.parentElement?.insertBefore(this._canvas, this._viewportElement);\n this._register(toDisposable(() => this._canvas?.remove()));\n\n const ctx = this._canvas.getContext('2d');\n if (!ctx) {\n throw new Error('Ctx cannot be null');\n } else {\n this._ctx = ctx;\n }\n\n this._register(this._decorationService.onDecorationRegistered(() => this._queueRefresh(undefined, true)));\n this._register(this._decorationService.onDecorationRemoved(() => this._queueRefresh(undefined, true)));\n\n this._register(this._renderService.onRenderedViewportChange(() => this._queueRefresh()));\n this._register(this._bufferService.buffers.onBufferActivate(() => {\n this._canvas!.style.display = this._bufferService.buffer === this._bufferService.buffers.alt ? 'none' : 'block';\n }));\n this._register(this._bufferService.onScroll(() => {\n if (this._lastKnownBufferLength !== this._bufferService.buffers.normal.lines.length) {\n this._refreshDrawHeightConstants();\n this._refreshColorZonePadding();\n }\n }));\n\n // Container height changed\n this._register(this._renderService.onRender((): void => {\n if (!this._containerHeight || this._containerHeight !== this._screenElement.clientHeight) {\n this._queueRefresh(true);\n this._containerHeight = this._screenElement.clientHeight;\n }\n }));\n\n this._register(this._coreBrowserService.onDprChange(() => this._queueRefresh(true)));\n this._register(this._optionsService.onSpecificOptionChange('overviewRuler', () => this._queueRefresh(true)));\n this._register(this._themeService.onChangeColors(() => this._queueRefresh()));\n this._queueRefresh(true);\n }\n\n private _refreshDrawConstants(): void {\n // width\n const outerWidth = Math.floor((this._canvas.width - Constants.OVERVIEW_RULER_BORDER_WIDTH) / 3);\n const innerWidth = Math.ceil((this._canvas.width - Constants.OVERVIEW_RULER_BORDER_WIDTH) / 3);\n drawWidth.full = this._canvas.width;\n drawWidth.left = outerWidth;\n drawWidth.center = innerWidth;\n drawWidth.right = outerWidth;\n // height\n this._refreshDrawHeightConstants();\n // x\n drawX.full = Constants.OVERVIEW_RULER_BORDER_WIDTH;\n drawX.left = Constants.OVERVIEW_RULER_BORDER_WIDTH;\n drawX.center = Constants.OVERVIEW_RULER_BORDER_WIDTH + drawWidth.left;\n drawX.right = Constants.OVERVIEW_RULER_BORDER_WIDTH + drawWidth.left + drawWidth.center;\n }\n\n private _refreshDrawHeightConstants(): void {\n drawHeight.full = Math.round(2 * this._coreBrowserService.dpr);\n // Calculate actual pixels per line\n const pixelsPerLine = this._canvas.height / this._bufferService.buffer.lines.length;\n // Clamp actual pixels within a range\n const nonFullHeight = Math.round(Math.max(Math.min(pixelsPerLine, 12), 6) * this._coreBrowserService.dpr);\n drawHeight.left = nonFullHeight;\n drawHeight.center = nonFullHeight;\n drawHeight.right = nonFullHeight;\n }\n\n private _refreshColorZonePadding(): void {\n this._colorZoneStore.setPadding({\n full: Math.floor(this._bufferService.buffers.active.lines.length / (this._canvas.height - 1) * drawHeight.full),\n left: Math.floor(this._bufferService.buffers.active.lines.length / (this._canvas.height - 1) * drawHeight.left),\n center: Math.floor(this._bufferService.buffers.active.lines.length / (this._canvas.height - 1) * drawHeight.center),\n right: Math.floor(this._bufferService.buffers.active.lines.length / (this._canvas.height - 1) * drawHeight.right)\n });\n this._lastKnownBufferLength = this._bufferService.buffers.normal.lines.length;\n }\n\n private _refreshCanvasDimensions(): void {\n this._canvas.style.width = `${this._width}px`;\n this._canvas.width = Math.round(this._width * this._coreBrowserService.dpr);\n this._canvas.style.height = `${this._screenElement.clientHeight}px`;\n this._canvas.height = Math.round(this._screenElement.clientHeight * this._coreBrowserService.dpr);\n this._refreshDrawConstants();\n this._refreshColorZonePadding();\n }\n\n private _refreshDecorations(): void {\n if (this._shouldUpdateDimensions) {\n this._refreshCanvasDimensions();\n }\n this._ctx.clearRect(0, 0, this._canvas.width, this._canvas.height);\n this._colorZoneStore.clear();\n for (const decoration of this._decorationService.decorations) {\n this._colorZoneStore.addDecoration(decoration);\n }\n this._ctx.lineWidth = 1;\n this._renderRulerOutline();\n const zones = this._colorZoneStore.zones;\n for (const zone of zones) {\n if (zone.position !== 'full') {\n this._renderColorZone(zone);\n }\n }\n for (const zone of zones) {\n if (zone.position === 'full') {\n this._renderColorZone(zone);\n }\n }\n this._shouldUpdateDimensions = false;\n this._shouldUpdateAnchor = false;\n }\n\n private _renderRulerOutline(): void {\n this._ctx.fillStyle = this._themeService.colors.overviewRulerBorder.css;\n this._ctx.fillRect(0, 0, Constants.OVERVIEW_RULER_BORDER_WIDTH, this._canvas.height);\n if (this._optionsService.rawOptions.overviewRuler.showTopBorder) {\n this._ctx.fillRect(Constants.OVERVIEW_RULER_BORDER_WIDTH, 0, this._canvas.width - Constants.OVERVIEW_RULER_BORDER_WIDTH, Constants.OVERVIEW_RULER_BORDER_WIDTH);\n }\n if (this._optionsService.rawOptions.overviewRuler.showBottomBorder) {\n this._ctx.fillRect(Constants.OVERVIEW_RULER_BORDER_WIDTH, this._canvas.height - Constants.OVERVIEW_RULER_BORDER_WIDTH, this._canvas.width - Constants.OVERVIEW_RULER_BORDER_WIDTH, this._canvas.height);\n }\n }\n\n private _renderColorZone(zone: IColorZone): void {\n this._ctx.fillStyle = zone.color;\n this._ctx.fillRect(\n /* x */ drawX[zone.position || 'full'],\n /* y */ Math.round(\n (this._canvas.height - 1) * // -1 to ensure at least 2px are allowed for decoration on last line\n (zone.startBufferLine / this._bufferService.buffers.active.lines.length) - drawHeight[zone.position || 'full'] / 2\n ),\n /* w */ drawWidth[zone.position || 'full'],\n /* h */ Math.round(\n (this._canvas.height - 1) * // -1 to ensure at least 2px are allowed for decoration on last line\n ((zone.endBufferLine - zone.startBufferLine) / this._bufferService.buffers.active.lines.length) + drawHeight[zone.position || 'full']\n )\n );\n }\n\n private _queueRefresh(updateCanvasDimensions?: boolean, updateAnchor?: boolean): void {\n this._shouldUpdateDimensions = updateCanvasDimensions || this._shouldUpdateDimensions;\n this._shouldUpdateAnchor = updateAnchor || this._shouldUpdateAnchor;\n if (this._animationFrame !== undefined) {\n return;\n }\n this._animationFrame = this._coreBrowserService.window.requestAnimationFrame(() => {\n this._refreshDecorations();\n this._animationFrame = undefined;\n });\n }\n}\n","/**\n * Copyright (c) 2016 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IRenderService } from 'browser/services/Services';\nimport { IBufferService, ICoreService, IOptionsService } from 'common/services/Services';\nimport { C0 } from 'common/data/EscapeSequences';\n\ninterface IPosition {\n start: number;\n end: number;\n}\n\n/**\n * Encapsulates the logic for handling compositionstart, compositionupdate and compositionend\n * events, displaying the in-progress composition to the UI and forwarding the final composition\n * to the handler.\n */\nexport class CompositionHelper {\n /**\n * Whether input composition is currently happening, eg. via a mobile keyboard, speech input or\n * IME. This variable determines whether the compositionText should be displayed on the UI.\n */\n private _isComposing: boolean;\n public get isComposing(): boolean { return this._isComposing; }\n\n /**\n * The position within the input textarea's value of the current composition.\n */\n private _compositionPosition: IPosition;\n\n /**\n * Whether a composition is in the process of being sent, setting this to false will cancel any\n * in-progress composition.\n */\n private _isSendingComposition: boolean;\n\n /**\n * Data already sent due to keydown event.\n */\n private _dataAlreadySent: string;\n\n constructor(\n private readonly _textarea: HTMLTextAreaElement,\n private readonly _compositionView: HTMLElement,\n @IBufferService private readonly _bufferService: IBufferService,\n @IOptionsService private readonly _optionsService: IOptionsService,\n @ICoreService private readonly _coreService: ICoreService,\n @IRenderService private readonly _renderService: IRenderService\n ) {\n this._isComposing = false;\n this._isSendingComposition = false;\n this._compositionPosition = { start: 0, end: 0 };\n this._dataAlreadySent = '';\n }\n\n /**\n * Handles the compositionstart event, activating the composition view.\n */\n public compositionstart(): void {\n this._isComposing = true;\n this._compositionPosition.start = this._textarea.value.length;\n this._compositionView.textContent = '';\n this._dataAlreadySent = '';\n this._compositionView.classList.add('active');\n }\n\n /**\n * Handles the compositionupdate event, updating the composition view.\n * @param ev The event.\n */\n public compositionupdate(ev: Pick): void {\n this._compositionView.textContent = ev.data;\n this.updateCompositionElements();\n setTimeout(() => {\n this._compositionPosition.end = this._textarea.value.length;\n }, 0);\n }\n\n /**\n * Handles the compositionend event, hiding the composition view and sending the composition to\n * the handler.\n */\n public compositionend(): void {\n this._finalizeComposition(true);\n }\n\n /**\n * Handles the keydown event, routing any necessary events to the CompositionHelper functions.\n * @param ev The keydown event.\n * @returns Whether the Terminal should continue processing the keydown event.\n */\n public keydown(ev: KeyboardEvent): boolean {\n if (this._isComposing || this._isSendingComposition) {\n if (ev.keyCode === 20 || ev.keyCode === 229) {\n // 20 is CapsLock, 229 is Enter\n // Continue composing if the keyCode is the \"composition character\"\n return false;\n }\n if (ev.keyCode === 16 || ev.keyCode === 17 || ev.keyCode === 18) {\n // Continue composing if the keyCode is a modifier key\n return false;\n }\n // Finish composition immediately. This is mainly here for the case where enter is\n // pressed and the handler needs to be triggered before the command is executed.\n this._finalizeComposition(false);\n }\n\n if (ev.keyCode === 229) {\n // If the \"composition character\" is used but gets to this point it means a non-composition\n // character (eg. numbers and punctuation) was pressed when the IME was active.\n this._handleAnyTextareaChanges();\n return false;\n }\n\n return true;\n }\n\n /**\n * Finalizes the composition, resuming regular input actions. This is called when a composition\n * is ending.\n * @param waitForPropagation Whether to wait for events to propagate before sending\n * the input. This should be false if a non-composition keystroke is entered before the\n * compositionend event is triggered, such as enter, so that the composition is sent before\n * the command is executed.\n */\n private _finalizeComposition(waitForPropagation: boolean): void {\n this._compositionView.classList.remove('active');\n this._isComposing = false;\n\n if (!waitForPropagation) {\n // Cancel any delayed composition send requests and send the input immediately.\n this._isSendingComposition = false;\n const input = this._textarea.value.substring(this._compositionPosition.start, this._compositionPosition.end);\n this._coreService.triggerDataEvent(input, true);\n } else {\n // Make a deep copy of the composition position here as a new compositionstart event may\n // fire before the setTimeout executes.\n const currentCompositionPosition = {\n start: this._compositionPosition.start,\n end: this._compositionPosition.end\n };\n\n // Since composition* events happen before the changes take place in the textarea on most\n // browsers, use a setTimeout with 0ms time to allow the native compositionend event to\n // complete. This ensures the correct character is retrieved.\n // This solution was used because:\n // - The compositionend event's data property is unreliable, at least on Chromium\n // - The last compositionupdate event's data property does not always accurately describe\n // the character, a counter example being Korean where an ending consonsant can move to\n // the following character if the following input is a vowel.\n this._isSendingComposition = true;\n setTimeout(() => {\n // Ensure that the input has not already been sent\n if (this._isSendingComposition) {\n this._isSendingComposition = false;\n let input;\n // Add length of data already sent due to keydown event,\n // otherwise input characters can be duplicated. (Issue #3191)\n currentCompositionPosition.start += this._dataAlreadySent.length;\n if (this._isComposing) {\n // Use the start position of the new composition to get the string\n // if a new composition has started.\n input = this._textarea.value.substring(currentCompositionPosition.start, this._compositionPosition.start);\n } else {\n // Don't use the end position here in order to pick up any characters after the\n // composition has finished, for example when typing a non-composition character\n // (eg. 2) after a composition character.\n input = this._textarea.value.substring(currentCompositionPosition.start);\n }\n if (input.length > 0) {\n this._coreService.triggerDataEvent(input, true);\n }\n }\n }, 0);\n }\n }\n\n /**\n * Apply any changes made to the textarea after the current event chain is allowed to complete.\n * This should be called when not currently composing but a keydown event with the \"composition\n * character\" (229) is triggered, in order to allow non-composition text to be entered when an\n * IME is active.\n */\n private _handleAnyTextareaChanges(): void {\n const oldValue = this._textarea.value;\n setTimeout(() => {\n // Ignore if a composition has started since the timeout\n if (!this._isComposing) {\n const newValue = this._textarea.value;\n\n const diff = newValue.replace(oldValue, '');\n\n this._dataAlreadySent = diff;\n\n if (newValue.length > oldValue.length) {\n this._coreService.triggerDataEvent(diff, true);\n } else if (newValue.length < oldValue.length) {\n this._coreService.triggerDataEvent(`${C0.DEL}`, true);\n } else if ((newValue.length === oldValue.length) && (newValue !== oldValue)) {\n this._coreService.triggerDataEvent(newValue, true);\n }\n\n }\n }, 0);\n }\n\n /**\n * Positions the composition view on top of the cursor and the textarea just below it (so the\n * IME helper dialog is positioned correctly).\n * @param dontRecurse Whether to use setTimeout to recursively trigger another update, this is\n * necessary as the IME events across browsers are not consistently triggered.\n */\n public updateCompositionElements(dontRecurse?: boolean): void {\n if (!this._isComposing) {\n return;\n }\n\n if (this._bufferService.buffer.isCursorInViewport) {\n const cursorX = Math.min(this._bufferService.buffer.x, this._bufferService.cols - 1);\n\n const cellHeight = this._renderService.dimensions.css.cell.height;\n const cursorTop = this._bufferService.buffer.y * this._renderService.dimensions.css.cell.height;\n const cursorLeft = cursorX * this._renderService.dimensions.css.cell.width;\n\n this._compositionView.style.left = cursorLeft + 'px';\n this._compositionView.style.top = cursorTop + 'px';\n this._compositionView.style.height = cellHeight + 'px';\n this._compositionView.style.lineHeight = cellHeight + 'px';\n this._compositionView.style.fontFamily = this._optionsService.rawOptions.fontFamily;\n this._compositionView.style.fontSize = this._optionsService.rawOptions.fontSize + 'px';\n // Sync the textarea to the exact position of the composition view so the IME knows where the\n // text is.\n const compositionViewBounds = this._compositionView.getBoundingClientRect();\n this._textarea.style.left = cursorLeft + 'px';\n this._textarea.style.top = cursorTop + 'px';\n // Ensure the text area is at least 1x1, otherwise certain IMEs may break\n this._textarea.style.width = Math.max(compositionViewBounds.width, 1) + 'px';\n this._textarea.style.height = Math.max(compositionViewBounds.height, 1) + 'px';\n this._textarea.style.lineHeight = compositionViewBounds.height + 'px';\n }\n\n if (!dontRecurse) {\n setTimeout(() => this.updateCompositionElements(true), 0);\n }\n }\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nexport function getCoordsRelativeToElement(window: Pick, event: {clientX: number, clientY: number}, element: HTMLElement): [number, number] {\n const rect = element.getBoundingClientRect();\n const elementStyle = window.getComputedStyle(element);\n const leftPadding = parseInt(elementStyle.getPropertyValue('padding-left'));\n const topPadding = parseInt(elementStyle.getPropertyValue('padding-top'));\n return [\n event.clientX - rect.left - leftPadding,\n event.clientY - rect.top - topPadding\n ];\n}\n\n/**\n * Gets coordinates within the terminal for a particular mouse event. The result\n * is returned as an array in the form [x, y] instead of an object as it's a\n * little faster and this function is used in some low level code.\n * @param window The window object the element belongs to.\n * @param event The mouse event.\n * @param element The terminal's container element.\n * @param colCount The number of columns in the terminal.\n * @param rowCount The number of rows n the terminal.\n * @param hasValidCharSize Whether there is a valid character size available.\n * @param cssCellWidth The cell width device pixel render dimensions.\n * @param cssCellHeight The cell height device pixel render dimensions.\n * @param isSelection Whether the request is for the selection or not. This will\n * apply an offset to the x value such that the left half of the cell will\n * select that cell and the right half will select the next cell.\n */\nexport function getCoords(window: Pick, event: Pick, element: HTMLElement, colCount: number, rowCount: number, hasValidCharSize: boolean, cssCellWidth: number, cssCellHeight: number, isSelection?: boolean): [number, number] | undefined {\n // Coordinates cannot be measured if there are no valid\n if (!hasValidCharSize) {\n return undefined;\n }\n\n const coords = getCoordsRelativeToElement(window, event, element);\n if (!coords) {\n return undefined;\n }\n\n coords[0] = Math.ceil((coords[0] + (isSelection ? cssCellWidth / 2 : 0)) / cssCellWidth);\n coords[1] = Math.ceil(coords[1] / cssCellHeight);\n\n // Ensure coordinates are within the terminal viewport. Note that selections\n // need an addition point of precision to cover the end point (as characters\n // cover half of one char and half of the next).\n coords[0] = Math.min(Math.max(coords[0], 1), colCount + (isSelection ? 1 : 0));\n coords[1] = Math.min(Math.max(coords[1], 1), rowCount);\n\n return coords;\n}\n","/**\n * Copyright (c) 2018 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { C0 } from 'common/data/EscapeSequences';\nimport { IBufferService } from 'common/services/Services';\n\nconst enum Direction {\n UP = 'A',\n DOWN = 'B',\n RIGHT = 'C',\n LEFT = 'D'\n}\n\n/**\n * Concatenates all the arrow sequences together.\n * Resets the starting row to an unwrapped row, moves to the requested row,\n * then moves to requested col.\n */\nexport function moveToCellSequence(targetX: number, targetY: number, bufferService: IBufferService, applicationCursor: boolean): string {\n const startX = bufferService.buffer.x;\n const startY = bufferService.buffer.y;\n\n // The alt buffer should try to navigate between rows\n if (!bufferService.buffer.hasScrollback) {\n return resetStartingRow(startX, startY, targetX, targetY, bufferService, applicationCursor) +\n moveToRequestedRow(startY, targetY, bufferService, applicationCursor) +\n moveToRequestedCol(startX, startY, targetX, targetY, bufferService, applicationCursor);\n }\n\n // Only move horizontally for the normal buffer\n let direction;\n if (startY === targetY) {\n direction = startX > targetX ? Direction.LEFT : Direction.RIGHT;\n return repeat(Math.abs(startX - targetX), sequence(direction, applicationCursor));\n }\n direction = startY > targetY ? Direction.LEFT : Direction.RIGHT;\n const rowDifference = Math.abs(startY - targetY);\n const cellsToMove = colsFromRowEnd(startY > targetY ? targetX : startX, bufferService) +\n (rowDifference - 1) * bufferService.cols + 1 /* wrap around 1 row */ +\n colsFromRowBeginning(startY > targetY ? startX : targetX, bufferService);\n return repeat(cellsToMove, sequence(direction, applicationCursor));\n}\n\n/**\n * Find the number of cols from a row beginning to a col.\n */\nfunction colsFromRowBeginning(currX: number, bufferService: IBufferService): number {\n return currX - 1;\n}\n\n/**\n * Find the number of cols from a col to row end.\n */\nfunction colsFromRowEnd(currX: number, bufferService: IBufferService): number {\n return bufferService.cols - currX;\n}\n\n/**\n * If the initial position of the cursor is on a row that is wrapped, move the\n * cursor up to the first row that is not wrapped to have accurate vertical\n * positioning.\n */\nfunction resetStartingRow(startX: number, startY: number, targetX: number, targetY: number, bufferService: IBufferService, applicationCursor: boolean): string {\n if (moveToRequestedRow(startY, targetY, bufferService, applicationCursor).length === 0) {\n return '';\n }\n return repeat(bufferLine(\n startX, startY, startX,\n startY - wrappedRowsForRow(startY, bufferService), false, bufferService\n ).length, sequence(Direction.LEFT, applicationCursor));\n}\n\n/**\n * Using the reset starting and ending row, move to the requested row,\n * ignoring wrapped rows\n */\nfunction moveToRequestedRow(startY: number, targetY: number, bufferService: IBufferService, applicationCursor: boolean): string {\n const startRow = startY - wrappedRowsForRow(startY, bufferService);\n const endRow = targetY - wrappedRowsForRow(targetY, bufferService);\n\n const rowsToMove = Math.abs(startRow - endRow) - wrappedRowsCount(startY, targetY, bufferService);\n\n return repeat(rowsToMove, sequence(verticalDirection(startY, targetY), applicationCursor));\n}\n\n/**\n * Move to the requested col on the ending row\n */\nfunction moveToRequestedCol(startX: number, startY: number, targetX: number, targetY: number, bufferService: IBufferService, applicationCursor: boolean): string {\n let startRow;\n if (moveToRequestedRow(startY, targetY, bufferService, applicationCursor).length > 0) {\n startRow = targetY - wrappedRowsForRow(targetY, bufferService);\n } else {\n startRow = startY;\n }\n\n const endRow = targetY;\n const direction = horizontalDirection(startX, startY, targetX, targetY, bufferService, applicationCursor);\n\n return repeat(bufferLine(\n startX, startRow, targetX, endRow,\n direction === Direction.RIGHT, bufferService\n ).length, sequence(direction, applicationCursor));\n}\n\n/**\n * Utility functions\n */\n\n/**\n * Calculates the number of wrapped rows between the unwrapped starting and\n * ending rows. These rows need to ignored since the cursor skips over them.\n */\nfunction wrappedRowsCount(startY: number, targetY: number, bufferService: IBufferService): number {\n let wrappedRows = 0;\n const startRow = startY - wrappedRowsForRow(startY, bufferService);\n const endRow = targetY - wrappedRowsForRow(targetY, bufferService);\n\n for (let i = 0; i < Math.abs(startRow - endRow); i++) {\n const direction = verticalDirection(startY, targetY) === Direction.UP ? -1 : 1;\n const line = bufferService.buffer.lines.get(startRow + (direction * i));\n if (line?.isWrapped) {\n wrappedRows++;\n }\n }\n\n return wrappedRows;\n}\n\n/**\n * Calculates the number of wrapped rows that make up a given row.\n * @param currentRow The row to determine how many wrapped rows make it up\n */\nfunction wrappedRowsForRow(currentRow: number, bufferService: IBufferService): number {\n let rowCount = 0;\n let line = bufferService.buffer.lines.get(currentRow);\n let lineWraps = line?.isWrapped;\n\n while (lineWraps && currentRow >= 0 && currentRow < bufferService.rows) {\n rowCount++;\n line = bufferService.buffer.lines.get(--currentRow);\n lineWraps = line?.isWrapped;\n }\n\n return rowCount;\n}\n\n/**\n * Direction determiners\n */\n\n/**\n * Determines if the right or left arrow is needed\n */\nfunction horizontalDirection(startX: number, startY: number, targetX: number, targetY: number, bufferService: IBufferService, applicationCursor: boolean): Direction {\n let startRow;\n if (moveToRequestedRow(targetX, targetY, bufferService, applicationCursor).length > 0) {\n startRow = targetY - wrappedRowsForRow(targetY, bufferService);\n } else {\n startRow = startY;\n }\n\n if ((startX < targetX &&\n startRow <= targetY) || // down/right or same y/right\n (startX >= targetX &&\n startRow < targetY)) { // down/left or same y/left\n return Direction.RIGHT;\n }\n return Direction.LEFT;\n}\n\n/**\n * Determines if the up or down arrow is needed\n */\nfunction verticalDirection(startY: number, targetY: number): Direction {\n return startY > targetY ? Direction.UP : Direction.DOWN;\n}\n\n/**\n * Constructs the string of chars in the buffer from a starting row and col\n * to an ending row and col\n * @param startCol The starting column position\n * @param startRow The starting row position\n * @param endCol The ending column position\n * @param endRow The ending row position\n * @param forward Direction to move\n */\nfunction bufferLine(\n startCol: number,\n startRow: number,\n endCol: number,\n endRow: number,\n forward: boolean,\n bufferService: IBufferService\n): string {\n let currentCol = startCol;\n let currentRow = startRow;\n let bufferStr = '';\n\n while ((currentCol !== endCol || currentRow !== endRow) &&\n currentRow >= 0 &&\n currentRow < bufferService.buffer.lines.length) {\n currentCol += forward ? 1 : -1;\n\n if (forward && currentCol > bufferService.cols - 1) {\n bufferStr += bufferService.buffer.translateBufferLineToString(\n currentRow, false, startCol, currentCol\n );\n currentCol = 0;\n startCol = 0;\n currentRow++;\n } else if (!forward && currentCol < 0) {\n bufferStr += bufferService.buffer.translateBufferLineToString(\n currentRow, false, 0, startCol + 1\n );\n currentCol = bufferService.cols - 1;\n startCol = currentCol;\n currentRow--;\n }\n }\n\n return bufferStr + bufferService.buffer.translateBufferLineToString(\n currentRow, false, startCol, currentCol\n );\n}\n\n/**\n * Constructs the escape sequence for clicking an arrow\n * @param direction The direction to move\n */\nfunction sequence(direction: Direction, applicationCursor: boolean): string {\n const mod = applicationCursor ? 'O' : '[';\n return C0.ESC + mod + direction;\n}\n\n/**\n * Returns a string repeated a given number of times\n * Polyfill from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat\n * @param count The number of times to repeat the string\n * @param str The string that is to be repeated\n */\nfunction repeat(count: number, str: string): string {\n count = Math.floor(count);\n let rpt = '';\n for (let i = 0; i < count; i++) {\n rpt += str;\n }\n return rpt;\n}\n","/**\n * Copyright (c) 2018 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { DomRendererRowFactory, RowCss } from 'browser/renderer/dom/DomRendererRowFactory';\nimport { WidthCache } from 'browser/renderer/dom/WidthCache';\nimport { INVERTED_DEFAULT_COLOR } from 'browser/renderer/shared/Constants';\nimport { createRenderDimensions } from 'browser/renderer/shared/RendererUtils';\nimport { createSelectionRenderModel } from 'browser/renderer/shared/SelectionRenderModel';\nimport { IRenderDimensions, IRenderer, IRequestRedrawEvent, ISelectionRenderModel } from 'browser/renderer/shared/Types';\nimport { ICharSizeService, ICoreBrowserService, IThemeService } from 'browser/services/Services';\nimport { ILinkifier2, ILinkifierEvent, ITerminal, ReadonlyColorSet } from 'browser/Types';\nimport { color } from 'common/Color';\nimport { Disposable, toDisposable } from 'vs/base/common/lifecycle';\nimport { IBufferService, ICoreService, IInstantiationService, IOptionsService } from 'common/services/Services';\nimport { Emitter } from 'vs/base/common/event';\n\n\nconst TERMINAL_CLASS_PREFIX = 'xterm-dom-renderer-owner-';\nconst ROW_CONTAINER_CLASS = 'xterm-rows';\nconst FG_CLASS_PREFIX = 'xterm-fg-';\nconst BG_CLASS_PREFIX = 'xterm-bg-';\nconst FOCUS_CLASS = 'xterm-focus';\nconst SELECTION_CLASS = 'xterm-selection';\n\nlet nextTerminalId = 1;\n\n/**\n * The standard renderer and fallback for when the webgl addon is slow. This is not meant to be\n * particularly fast and will even lack some features such as custom glyphs, hoever this is more\n * reliable as webgl may not work on some machines.\n */\nexport class DomRenderer extends Disposable implements IRenderer {\n private _rowFactory: DomRendererRowFactory;\n private _terminalClass: number = nextTerminalId++;\n\n private _themeStyleElement!: HTMLStyleElement;\n private _dimensionsStyleElement!: HTMLStyleElement;\n private _rowContainer: HTMLElement;\n private _rowElements: HTMLElement[] = [];\n private _selectionContainer: HTMLElement;\n private _widthCache: WidthCache;\n private _selectionRenderModel: ISelectionRenderModel = createSelectionRenderModel();\n\n public dimensions: IRenderDimensions;\n\n public readonly onRequestRedraw = this._register(new Emitter()).event;\n\n constructor(\n private readonly _terminal: ITerminal,\n private readonly _document: Document,\n private readonly _element: HTMLElement,\n private readonly _screenElement: HTMLElement,\n private readonly _viewportElement: HTMLElement,\n private readonly _helperContainer: HTMLElement,\n private readonly _linkifier2: ILinkifier2,\n @IInstantiationService instantiationService: IInstantiationService,\n @ICharSizeService private readonly _charSizeService: ICharSizeService,\n @IOptionsService private readonly _optionsService: IOptionsService,\n @IBufferService private readonly _bufferService: IBufferService,\n @ICoreService private readonly _coreService: ICoreService,\n @ICoreBrowserService private readonly _coreBrowserService: ICoreBrowserService,\n @IThemeService private readonly _themeService: IThemeService\n ) {\n super();\n this._rowContainer = this._document.createElement('div');\n this._rowContainer.classList.add(ROW_CONTAINER_CLASS);\n this._rowContainer.style.lineHeight = 'normal';\n this._rowContainer.setAttribute('aria-hidden', 'true');\n this._refreshRowElements(this._bufferService.cols, this._bufferService.rows);\n this._selectionContainer = this._document.createElement('div');\n this._selectionContainer.classList.add(SELECTION_CLASS);\n this._selectionContainer.setAttribute('aria-hidden', 'true');\n\n this.dimensions = createRenderDimensions();\n this._updateDimensions();\n this._register(this._optionsService.onOptionChange(() => this._handleOptionsChanged()));\n\n this._register(this._themeService.onChangeColors(e => this._injectCss(e)));\n this._injectCss(this._themeService.colors);\n\n this._rowFactory = instantiationService.createInstance(DomRendererRowFactory, document);\n\n this._element.classList.add(TERMINAL_CLASS_PREFIX + this._terminalClass);\n this._screenElement.appendChild(this._rowContainer);\n this._screenElement.appendChild(this._selectionContainer);\n\n this._register(this._linkifier2.onShowLinkUnderline(e => this._handleLinkHover(e)));\n this._register(this._linkifier2.onHideLinkUnderline(e => this._handleLinkLeave(e)));\n\n this._register(toDisposable(() => {\n this._element.classList.remove(TERMINAL_CLASS_PREFIX + this._terminalClass);\n\n // Outside influences such as React unmounts may manipulate the DOM before our disposal.\n // https://github.com/xtermjs/xterm.js/issues/2960\n this._rowContainer.remove();\n this._selectionContainer.remove();\n this._widthCache.dispose();\n this._themeStyleElement.remove();\n this._dimensionsStyleElement.remove();\n }));\n\n this._widthCache = new WidthCache(this._document, this._helperContainer);\n this._widthCache.setFont(\n this._optionsService.rawOptions.fontFamily,\n this._optionsService.rawOptions.fontSize,\n this._optionsService.rawOptions.fontWeight,\n this._optionsService.rawOptions.fontWeightBold\n );\n this._setDefaultSpacing();\n }\n\n private _updateDimensions(): void {\n const dpr = this._coreBrowserService.dpr;\n this.dimensions.device.char.width = this._charSizeService.width * dpr;\n this.dimensions.device.char.height = Math.ceil(this._charSizeService.height * dpr);\n this.dimensions.device.cell.width = this.dimensions.device.char.width + Math.round(this._optionsService.rawOptions.letterSpacing);\n this.dimensions.device.cell.height = Math.floor(this.dimensions.device.char.height * this._optionsService.rawOptions.lineHeight);\n this.dimensions.device.char.left = 0;\n this.dimensions.device.char.top = 0;\n this.dimensions.device.canvas.width = this.dimensions.device.cell.width * this._bufferService.cols;\n this.dimensions.device.canvas.height = this.dimensions.device.cell.height * this._bufferService.rows;\n this.dimensions.css.canvas.width = Math.round(this.dimensions.device.canvas.width / dpr);\n this.dimensions.css.canvas.height = Math.round(this.dimensions.device.canvas.height / dpr);\n this.dimensions.css.cell.width = this.dimensions.css.canvas.width / this._bufferService.cols;\n this.dimensions.css.cell.height = this.dimensions.css.canvas.height / this._bufferService.rows;\n\n for (const element of this._rowElements) {\n element.style.width = `${this.dimensions.css.canvas.width}px`;\n element.style.height = `${this.dimensions.css.cell.height}px`;\n element.style.lineHeight = `${this.dimensions.css.cell.height}px`;\n // Make sure rows don't overflow onto following row\n element.style.overflow = 'hidden';\n }\n\n if (!this._dimensionsStyleElement) {\n this._dimensionsStyleElement = this._document.createElement('style');\n this._screenElement.appendChild(this._dimensionsStyleElement);\n }\n\n const styles =\n `${this._terminalSelector} .${ROW_CONTAINER_CLASS} span {` +\n ` display: inline-block;` + // TODO: find workaround for inline-block (creates ~20% render penalty)\n ` height: 100%;` +\n ` vertical-align: top;` +\n `}`;\n\n this._dimensionsStyleElement.textContent = styles;\n\n this._selectionContainer.style.height = this._viewportElement.style.height;\n this._screenElement.style.width = `${this.dimensions.css.canvas.width}px`;\n this._screenElement.style.height = `${this.dimensions.css.canvas.height}px`;\n }\n\n private _injectCss(colors: ReadonlyColorSet): void {\n if (!this._themeStyleElement) {\n this._themeStyleElement = this._document.createElement('style');\n this._screenElement.appendChild(this._themeStyleElement);\n }\n\n // Base CSS\n let styles =\n `${this._terminalSelector} .${ROW_CONTAINER_CLASS} {` +\n // Disabling pointer events circumvents a browser behavior that prevents `click` events from\n // being delivered if the target element is replaced during the click. This happened due to\n // refresh() being called during the mousedown handler to start a selection.\n ` pointer-events: none;` +\n ` color: ${colors.foreground.css};` +\n ` font-family: ${this._optionsService.rawOptions.fontFamily};` +\n ` font-size: ${this._optionsService.rawOptions.fontSize}px;` +\n ` font-kerning: none;` +\n ` white-space: pre` +\n `}`;\n styles +=\n `${this._terminalSelector} .${ROW_CONTAINER_CLASS} .xterm-dim {` +\n ` color: ${color.multiplyOpacity(colors.foreground, 0.5).css};` +\n `}`;\n // Text styles\n styles +=\n `${this._terminalSelector} span:not(.${RowCss.BOLD_CLASS}) {` +\n ` font-weight: ${this._optionsService.rawOptions.fontWeight};` +\n `}` +\n `${this._terminalSelector} span.${RowCss.BOLD_CLASS} {` +\n ` font-weight: ${this._optionsService.rawOptions.fontWeightBold};` +\n `}` +\n `${this._terminalSelector} span.${RowCss.ITALIC_CLASS} {` +\n ` font-style: italic;` +\n `}`;\n // Blink animation\n const blinkAnimationUnderlineId = `blink_underline_${this._terminalClass}`;\n const blinkAnimationBarId = `blink_bar_${this._terminalClass}`;\n const blinkAnimationBlockId = `blink_block_${this._terminalClass}`;\n styles +=\n `@keyframes ${blinkAnimationUnderlineId} {` +\n ` 50% {` +\n ` border-bottom-style: hidden;` +\n ` }` +\n `}`;\n styles +=\n `@keyframes ${blinkAnimationBarId} {` +\n ` 50% {` +\n ` box-shadow: none;` +\n ` }` +\n `}`;\n styles +=\n `@keyframes ${blinkAnimationBlockId} {` +\n ` 0% {` +\n ` background-color: ${colors.cursor.css};` +\n ` color: ${colors.cursorAccent.css};` +\n ` }` +\n ` 50% {` +\n ` background-color: inherit;` +\n ` color: ${colors.cursor.css};` +\n ` }` +\n `}`;\n // Cursor\n styles +=\n `${this._terminalSelector} .${ROW_CONTAINER_CLASS}.${FOCUS_CLASS} .${RowCss.CURSOR_CLASS}.${RowCss.CURSOR_BLINK_CLASS}.${RowCss.CURSOR_STYLE_UNDERLINE_CLASS} {` +\n ` animation: ${blinkAnimationUnderlineId} 1s step-end infinite;` +\n `}` +\n `${this._terminalSelector} .${ROW_CONTAINER_CLASS}.${FOCUS_CLASS} .${RowCss.CURSOR_CLASS}.${RowCss.CURSOR_BLINK_CLASS}.${RowCss.CURSOR_STYLE_BAR_CLASS} {` +\n ` animation: ${blinkAnimationBarId} 1s step-end infinite;` +\n `}` +\n `${this._terminalSelector} .${ROW_CONTAINER_CLASS}.${FOCUS_CLASS} .${RowCss.CURSOR_CLASS}.${RowCss.CURSOR_BLINK_CLASS}.${RowCss.CURSOR_STYLE_BLOCK_CLASS} {` +\n ` animation: ${blinkAnimationBlockId} 1s step-end infinite;` +\n `}` +\n // !important helps fix an issue where the cursor will not render on top of the selection,\n // however it's very hard to fix this issue and retain the blink animation without the use of\n // !important. So this edge case fails when cursor blink is on.\n `${this._terminalSelector} .${ROW_CONTAINER_CLASS} .${RowCss.CURSOR_CLASS}.${RowCss.CURSOR_STYLE_BLOCK_CLASS} {` +\n ` background-color: ${colors.cursor.css};` +\n ` color: ${colors.cursorAccent.css};` +\n `}` +\n `${this._terminalSelector} .${ROW_CONTAINER_CLASS} .${RowCss.CURSOR_CLASS}.${RowCss.CURSOR_STYLE_BLOCK_CLASS}:not(.${RowCss.CURSOR_BLINK_CLASS}) {` +\n ` background-color: ${colors.cursor.css} !important;` +\n ` color: ${colors.cursorAccent.css} !important;` +\n `}` +\n `${this._terminalSelector} .${ROW_CONTAINER_CLASS} .${RowCss.CURSOR_CLASS}.${RowCss.CURSOR_STYLE_OUTLINE_CLASS} {` +\n ` outline: 1px solid ${colors.cursor.css};` +\n ` outline-offset: -1px;` +\n `}` +\n `${this._terminalSelector} .${ROW_CONTAINER_CLASS} .${RowCss.CURSOR_CLASS}.${RowCss.CURSOR_STYLE_BAR_CLASS} {` +\n ` box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${colors.cursor.css} inset;` +\n `}` +\n `${this._terminalSelector} .${ROW_CONTAINER_CLASS} .${RowCss.CURSOR_CLASS}.${RowCss.CURSOR_STYLE_UNDERLINE_CLASS} {` +\n ` border-bottom: 1px ${colors.cursor.css};` +\n ` border-bottom-style: solid;` +\n ` height: calc(100% - 1px);` +\n `}`;\n // Selection\n styles +=\n `${this._terminalSelector} .${SELECTION_CLASS} {` +\n ` position: absolute;` +\n ` top: 0;` +\n ` left: 0;` +\n ` z-index: 1;` +\n ` pointer-events: none;` +\n `}` +\n `${this._terminalSelector}.focus .${SELECTION_CLASS} div {` +\n ` position: absolute;` +\n ` background-color: ${colors.selectionBackgroundOpaque.css};` +\n `}` +\n `${this._terminalSelector} .${SELECTION_CLASS} div {` +\n ` position: absolute;` +\n ` background-color: ${colors.selectionInactiveBackgroundOpaque.css};` +\n `}`;\n // Colors\n for (const [i, c] of colors.ansi.entries()) {\n styles +=\n `${this._terminalSelector} .${FG_CLASS_PREFIX}${i} { color: ${c.css}; }` +\n `${this._terminalSelector} .${FG_CLASS_PREFIX}${i}.${RowCss.DIM_CLASS} { color: ${color.multiplyOpacity(c, 0.5).css}; }` +\n `${this._terminalSelector} .${BG_CLASS_PREFIX}${i} { background-color: ${c.css}; }`;\n }\n styles +=\n `${this._terminalSelector} .${FG_CLASS_PREFIX}${INVERTED_DEFAULT_COLOR} { color: ${color.opaque(colors.background).css}; }` +\n `${this._terminalSelector} .${FG_CLASS_PREFIX}${INVERTED_DEFAULT_COLOR}.${RowCss.DIM_CLASS} { color: ${color.multiplyOpacity(color.opaque(colors.background), 0.5).css}; }` +\n `${this._terminalSelector} .${BG_CLASS_PREFIX}${INVERTED_DEFAULT_COLOR} { background-color: ${colors.foreground.css}; }`;\n\n this._themeStyleElement.textContent = styles;\n }\n\n /**\n * default letter spacing\n * Due to rounding issues in dimensions dpr calc glyph might render\n * slightly too wide or too narrow. The method corrects the stacking offsets\n * by applying a default letter-spacing for all chars.\n * The value gets passed to the row factory to avoid setting this value again\n * (render speedup is roughly 10%).\n */\n private _setDefaultSpacing(): void {\n // measure same char as in CharSizeService to get the base deviation\n const spacing = this.dimensions.css.cell.width - this._widthCache.get('W', false, false);\n this._rowContainer.style.letterSpacing = `${spacing}px`;\n this._rowFactory.defaultSpacing = spacing;\n }\n\n public handleDevicePixelRatioChange(): void {\n this._updateDimensions();\n this._widthCache.clear();\n this._setDefaultSpacing();\n }\n\n private _refreshRowElements(cols: number, rows: number): void {\n // Add missing elements\n for (let i = this._rowElements.length; i <= rows; i++) {\n const row = this._document.createElement('div');\n this._rowContainer.appendChild(row);\n this._rowElements.push(row);\n }\n // Remove excess elements\n while (this._rowElements.length > rows) {\n this._rowContainer.removeChild(this._rowElements.pop()!);\n }\n }\n\n public handleResize(cols: number, rows: number): void {\n this._refreshRowElements(cols, rows);\n this._updateDimensions();\n this.handleSelectionChanged(this._selectionRenderModel.selectionStart, this._selectionRenderModel.selectionEnd, this._selectionRenderModel.columnSelectMode);\n }\n\n public handleCharSizeChanged(): void {\n this._updateDimensions();\n this._widthCache.clear();\n this._setDefaultSpacing();\n }\n\n public handleBlur(): void {\n this._rowContainer.classList.remove(FOCUS_CLASS);\n this.renderRows(0, this._bufferService.rows - 1);\n }\n\n public handleFocus(): void {\n this._rowContainer.classList.add(FOCUS_CLASS);\n this.renderRows(this._bufferService.buffer.y, this._bufferService.buffer.y);\n }\n\n public handleSelectionChanged(start: [number, number] | undefined, end: [number, number] | undefined, columnSelectMode: boolean): void {\n // Remove all selections\n this._selectionContainer.replaceChildren();\n this._rowFactory.handleSelectionChanged(start, end, columnSelectMode);\n this.renderRows(0, this._bufferService.rows - 1);\n\n // Selection does not exist\n if (!start || !end) {\n return;\n }\n\n this._selectionRenderModel.update(this._terminal, start, end, columnSelectMode);\n if (!this._selectionRenderModel.hasSelection) {\n return;\n }\n\n // Translate from buffer position to viewport position\n const viewportStartRow = this._selectionRenderModel.viewportStartRow;\n const viewportEndRow = this._selectionRenderModel.viewportEndRow;\n const viewportCappedStartRow = this._selectionRenderModel.viewportCappedStartRow;\n const viewportCappedEndRow = this._selectionRenderModel.viewportCappedEndRow;\n\n // Create the selections\n const documentFragment = this._document.createDocumentFragment();\n\n if (columnSelectMode) {\n const isXFlipped = start[0] > end[0];\n documentFragment.appendChild(\n this._createSelectionElement(viewportCappedStartRow, isXFlipped ? end[0] : start[0], isXFlipped ? start[0] : end[0], viewportCappedEndRow - viewportCappedStartRow + 1)\n );\n } else {\n // Draw first row\n const startCol = viewportStartRow === viewportCappedStartRow ? start[0] : 0;\n const endCol = viewportCappedStartRow === viewportEndRow ? end[0] : this._bufferService.cols;\n documentFragment.appendChild(this._createSelectionElement(viewportCappedStartRow, startCol, endCol));\n // Draw middle rows\n const middleRowsCount = viewportCappedEndRow - viewportCappedStartRow - 1;\n documentFragment.appendChild(this._createSelectionElement(viewportCappedStartRow + 1, 0, this._bufferService.cols, middleRowsCount));\n // Draw final row\n if (viewportCappedStartRow !== viewportCappedEndRow) {\n // Only draw viewportEndRow if it's not the same as viewporttartRow\n const endCol = viewportEndRow === viewportCappedEndRow ? end[0] : this._bufferService.cols;\n documentFragment.appendChild(this._createSelectionElement(viewportCappedEndRow, 0, endCol));\n }\n }\n this._selectionContainer.appendChild(documentFragment);\n }\n\n /**\n * Creates a selection element at the specified position.\n * @param row The row of the selection.\n * @param colStart The start column.\n * @param colEnd The end columns.\n */\n private _createSelectionElement(row: number, colStart: number, colEnd: number, rowCount: number = 1): HTMLElement {\n const element = this._document.createElement('div');\n const left = colStart * this.dimensions.css.cell.width;\n let width = this.dimensions.css.cell.width * (colEnd - colStart);\n if (left + width > this.dimensions.css.canvas.width) {\n width = this.dimensions.css.canvas.width - left;\n }\n\n element.style.height = `${rowCount * this.dimensions.css.cell.height}px`;\n element.style.top = `${row * this.dimensions.css.cell.height}px`;\n element.style.left = `${left}px`;\n element.style.width = `${width}px`;\n return element;\n }\n\n public handleCursorMove(): void {\n // No-op, the cursor is drawn when rows are drawn\n }\n\n private _handleOptionsChanged(): void {\n // Force a refresh\n this._updateDimensions();\n // Refresh CSS\n this._injectCss(this._themeService.colors);\n // update spacing cache\n this._widthCache.setFont(\n this._optionsService.rawOptions.fontFamily,\n this._optionsService.rawOptions.fontSize,\n this._optionsService.rawOptions.fontWeight,\n this._optionsService.rawOptions.fontWeightBold\n );\n this._setDefaultSpacing();\n }\n\n public clear(): void {\n for (const e of this._rowElements) {\n /**\n * NOTE: This used to be `e.innerText = '';` but that doesn't work when using `jsdom` and\n * `@testing-library/react`\n *\n * references:\n * - https://github.com/testing-library/react-testing-library/issues/1146\n * - https://github.com/jsdom/jsdom/issues/1245\n */\n e.replaceChildren();\n }\n }\n\n public renderRows(start: number, end: number): void {\n const buffer = this._bufferService.buffer;\n const cursorAbsoluteY = buffer.ybase + buffer.y;\n const cursorX = Math.min(buffer.x, this._bufferService.cols - 1);\n const cursorBlink = this._coreService.decPrivateModes.cursorBlink ?? this._optionsService.rawOptions.cursorBlink;\n const cursorStyle = this._coreService.decPrivateModes.cursorStyle ?? this._optionsService.rawOptions.cursorStyle;\n const cursorInactiveStyle = this._optionsService.rawOptions.cursorInactiveStyle;\n\n for (let y = start; y <= end; y++) {\n const row = y + buffer.ydisp;\n const rowElement = this._rowElements[y];\n const lineData = buffer.lines.get(row);\n if (!rowElement || !lineData) {\n break;\n }\n rowElement.replaceChildren(\n ...this._rowFactory.createRow(\n lineData,\n row,\n row === cursorAbsoluteY,\n cursorStyle,\n cursorInactiveStyle,\n cursorX,\n cursorBlink,\n this.dimensions.css.cell.width,\n this._widthCache,\n -1,\n -1\n )\n );\n }\n }\n\n private get _terminalSelector(): string {\n return `.${TERMINAL_CLASS_PREFIX}${this._terminalClass}`;\n }\n\n private _handleLinkHover(e: ILinkifierEvent): void {\n this._setCellUnderline(e.x1, e.x2, e.y1, e.y2, e.cols, true);\n }\n\n private _handleLinkLeave(e: ILinkifierEvent): void {\n this._setCellUnderline(e.x1, e.x2, e.y1, e.y2, e.cols, false);\n }\n\n private _setCellUnderline(x: number, x2: number, y: number, y2: number, cols: number, enabled: boolean): void {\n /**\n * NOTE: The linkifier may send out of viewport y-values if:\n * - negative y-value: the link started at a higher line\n * - y-value >= maxY: the link ends at a line below viewport\n *\n * For negative y-values we can simply adjust x = 0,\n * as higher up link start means, that everything from\n * (0,0) is a link under top-down-left-right char progression\n *\n * Additionally there might be a small chance of out-of-sync x|y-values\n * from a race condition of render updates vs. link event handler execution:\n * - (sync) resize: chances terminal buffer in sync, schedules render update async\n * - (async) link handler race condition: new buffer metrics, but still on old render state\n * - (async) render update: brings term metrics and render state back in sync\n */\n // clip coords into viewport\n if (y < 0) x = 0;\n if (y2 < 0) x2 = 0;\n const maxY = this._bufferService.rows - 1;\n y = Math.max(Math.min(y, maxY), 0);\n y2 = Math.max(Math.min(y2, maxY), 0);\n\n cols = Math.min(cols, this._bufferService.cols);\n const buffer = this._bufferService.buffer;\n const cursorAbsoluteY = buffer.ybase + buffer.y;\n const cursorX = Math.min(buffer.x, cols - 1);\n const cursorBlink = this._optionsService.rawOptions.cursorBlink;\n const cursorStyle = this._optionsService.rawOptions.cursorStyle;\n const cursorInactiveStyle = this._optionsService.rawOptions.cursorInactiveStyle;\n\n // refresh rows within link range\n for (let i = y; i <= y2; ++i) {\n const row = i + buffer.ydisp;\n const rowElement = this._rowElements[i];\n const bufferline = buffer.lines.get(row);\n if (!rowElement || !bufferline) {\n break;\n }\n rowElement.replaceChildren(\n ...this._rowFactory.createRow(\n bufferline,\n row,\n row === cursorAbsoluteY,\n cursorStyle,\n cursorInactiveStyle,\n cursorX,\n cursorBlink,\n this.dimensions.css.cell.width,\n this._widthCache,\n enabled ? (i === y ? x : 0) : -1,\n enabled ? ((i === y2 ? x2 : cols) - 1) : -1\n )\n );\n }\n }\n}\n","/**\n * Copyright (c) 2018, 2023 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IBufferLine, ICellData, IColor } from 'common/Types';\nimport { INVERTED_DEFAULT_COLOR } from 'browser/renderer/shared/Constants';\nimport { WHITESPACE_CELL_CHAR, Attributes } from 'common/buffer/Constants';\nimport { CellData } from 'common/buffer/CellData';\nimport { ICoreService, IDecorationService, IOptionsService } from 'common/services/Services';\nimport { channels, color } from 'common/Color';\nimport { ICharacterJoinerService, ICoreBrowserService, IThemeService } from 'browser/services/Services';\nimport { JoinedCellData } from 'browser/services/CharacterJoinerService';\nimport { treatGlyphAsBackgroundColor } from 'browser/renderer/shared/RendererUtils';\nimport { AttributeData } from 'common/buffer/AttributeData';\nimport { WidthCache } from 'browser/renderer/dom/WidthCache';\nimport { IColorContrastCache } from 'browser/Types';\n\n\nexport const enum RowCss {\n BOLD_CLASS = 'xterm-bold',\n DIM_CLASS = 'xterm-dim',\n ITALIC_CLASS = 'xterm-italic',\n UNDERLINE_CLASS = 'xterm-underline',\n OVERLINE_CLASS = 'xterm-overline',\n STRIKETHROUGH_CLASS = 'xterm-strikethrough',\n CURSOR_CLASS = 'xterm-cursor',\n CURSOR_BLINK_CLASS = 'xterm-cursor-blink',\n CURSOR_STYLE_BLOCK_CLASS = 'xterm-cursor-block',\n CURSOR_STYLE_OUTLINE_CLASS = 'xterm-cursor-outline',\n CURSOR_STYLE_BAR_CLASS = 'xterm-cursor-bar',\n CURSOR_STYLE_UNDERLINE_CLASS = 'xterm-cursor-underline'\n}\n\n\nexport class DomRendererRowFactory {\n private _workCell: CellData = new CellData();\n\n private _selectionStart: [number, number] | undefined;\n private _selectionEnd: [number, number] | undefined;\n private _columnSelectMode: boolean = false;\n\n public defaultSpacing = 0;\n\n constructor(\n private readonly _document: Document,\n @ICharacterJoinerService private readonly _characterJoinerService: ICharacterJoinerService,\n @IOptionsService private readonly _optionsService: IOptionsService,\n @ICoreBrowserService private readonly _coreBrowserService: ICoreBrowserService,\n @ICoreService private readonly _coreService: ICoreService,\n @IDecorationService private readonly _decorationService: IDecorationService,\n @IThemeService private readonly _themeService: IThemeService\n ) {}\n\n public handleSelectionChanged(start: [number, number] | undefined, end: [number, number] | undefined, columnSelectMode: boolean): void {\n this._selectionStart = start;\n this._selectionEnd = end;\n this._columnSelectMode = columnSelectMode;\n }\n\n public createRow(\n lineData: IBufferLine,\n row: number,\n isCursorRow: boolean,\n cursorStyle: string | undefined,\n cursorInactiveStyle: string | undefined,\n cursorX: number,\n cursorBlink: boolean,\n cellWidth: number,\n widthCache: WidthCache,\n linkStart: number,\n linkEnd: number\n ): HTMLSpanElement[] {\n\n const elements: HTMLSpanElement[] = [];\n const joinedRanges = this._characterJoinerService.getJoinedCharacters(row);\n const colors = this._themeService.colors;\n\n let lineLength = lineData.getNoBgTrimmedLength();\n if (isCursorRow && lineLength < cursorX + 1) {\n lineLength = cursorX + 1;\n }\n\n let charElement: HTMLSpanElement | undefined;\n let cellAmount = 0;\n let text = '';\n let i = 0;\n let oldBg = 0;\n let oldFg = 0;\n let oldExt = 0;\n let oldLinkHover: number | boolean = false;\n let oldSpacing = 0;\n let oldIsInSelection: boolean = false;\n let spacing = 0;\n let skipJoinedCheckUntilX = 0;\n const classes: string[] = [];\n\n const hasHover = linkStart !== -1 && linkEnd !== -1;\n\n for (let x = 0; x < lineLength; x++) {\n lineData.loadCell(x, this._workCell);\n let width = this._workCell.getWidth();\n\n // The character to the left is a wide character, drawing is owned by the char at x-1\n if (width === 0) {\n continue;\n }\n\n // If true, indicates that the current character(s) to draw were joined.\n let isJoined = false;\n\n // Indicates whether this cell is part of a joined range that should be ignored as it cannot\n // be rendered entirely, like the selection state differs across the range.\n let isValidJoinRange = (x >= skipJoinedCheckUntilX);\n\n let lastCharX = x;\n\n // Process any joined character ranges as needed. Because of how the\n // ranges are produced, we know that they are valid for the characters\n // and attributes of our input.\n let cell = this._workCell;\n if (joinedRanges.length > 0 && x === joinedRanges[0][0] && isValidJoinRange) {\n const range = joinedRanges.shift()!;\n // If the ligature's selection state is not consistent, don't join it. This helps the\n // selection render correctly regardless whether they should be joined.\n const firstSelectionState = this._isCellInSelection(range[0], row);\n for (i = range[0] + 1; i < range[1]; i++) {\n isValidJoinRange &&= (firstSelectionState === this._isCellInSelection(i, row));\n }\n // Similarly, if the cursor is in the ligature, don't join it.\n isValidJoinRange &&= !isCursorRow || cursorX < range[0] || cursorX >= range[1];\n if (!isValidJoinRange) {\n skipJoinedCheckUntilX = range[1];\n } else {\n isJoined = true;\n\n // We already know the exact start and end column of the joined range,\n // so we get the string and width representing it directly\n cell = new JoinedCellData(\n this._workCell,\n lineData.translateToString(true, range[0], range[1]),\n range[1] - range[0]\n );\n\n // Skip over the cells occupied by this range in the loop\n lastCharX = range[1] - 1;\n\n // Recalculate width\n width = cell.getWidth();\n }\n }\n\n const isInSelection = this._isCellInSelection(x, row);\n const isCursorCell = isCursorRow && x === cursorX;\n const isLinkHover = hasHover && x >= linkStart && x <= linkEnd;\n\n let isDecorated = false;\n this._decorationService.forEachDecorationAtCell(x, row, undefined, d => {\n isDecorated = true;\n });\n\n // get chars to render for this cell\n let chars = cell.getChars() || WHITESPACE_CELL_CHAR;\n if (chars === ' ' && (cell.isUnderline() || cell.isOverline())) {\n chars = '\\xa0';\n }\n\n // lookup char render width and calc spacing\n spacing = width * cellWidth - widthCache.get(chars, cell.isBold(), cell.isItalic());\n\n if (!charElement) {\n charElement = this._document.createElement('span');\n } else {\n /**\n * chars can only be merged on existing span if:\n * - existing span only contains mergeable chars (cellAmount != 0)\n * - bg did not change (or both are in selection)\n * - fg did not change (or both are in selection and selection fg is set)\n * - ext did not change\n * - underline from hover state did not change\n * - cell content renders to same letter-spacing\n * - cell is not cursor\n */\n if (\n cellAmount\n && (\n (isInSelection && oldIsInSelection)\n || (!isInSelection && !oldIsInSelection && cell.bg === oldBg)\n )\n && (\n (isInSelection && oldIsInSelection && colors.selectionForeground)\n || cell.fg === oldFg\n )\n && cell.extended.ext === oldExt\n && isLinkHover === oldLinkHover\n && spacing === oldSpacing\n && !isCursorCell\n && !isJoined\n && !isDecorated\n && isValidJoinRange\n ) {\n // no span alterations, thus only account chars skipping all code below\n if (cell.isInvisible()) {\n text += WHITESPACE_CELL_CHAR;\n } else {\n text += chars;\n }\n cellAmount++;\n continue;\n } else {\n /**\n * cannot merge:\n * - apply left-over text to old span\n * - create new span, reset state holders cellAmount & text\n */\n if (cellAmount) {\n charElement.textContent = text;\n }\n charElement = this._document.createElement('span');\n cellAmount = 0;\n text = '';\n }\n }\n // preserve conditions for next merger eval round\n oldBg = cell.bg;\n oldFg = cell.fg;\n oldExt = cell.extended.ext;\n oldLinkHover = isLinkHover;\n oldSpacing = spacing;\n oldIsInSelection = isInSelection;\n\n if (isJoined) {\n // The DOM renderer colors the background of the cursor but for ligatures all cells are\n // joined. The workaround here is to show a cursor around the whole ligature so it shows up,\n // the cursor looks the same when on any character of the ligature though\n if (cursorX >= x && cursorX <= lastCharX) {\n cursorX = x;\n }\n }\n\n if (!this._coreService.isCursorHidden && isCursorCell && this._coreService.isCursorInitialized) {\n classes.push(RowCss.CURSOR_CLASS);\n if (this._coreBrowserService.isFocused) {\n if (cursorBlink) {\n classes.push(RowCss.CURSOR_BLINK_CLASS);\n }\n classes.push(\n cursorStyle === 'bar'\n ? RowCss.CURSOR_STYLE_BAR_CLASS\n : cursorStyle === 'underline'\n ? RowCss.CURSOR_STYLE_UNDERLINE_CLASS\n : RowCss.CURSOR_STYLE_BLOCK_CLASS\n );\n } else {\n if (cursorInactiveStyle) {\n switch (cursorInactiveStyle) {\n case 'outline':\n classes.push(RowCss.CURSOR_STYLE_OUTLINE_CLASS);\n break;\n case 'block':\n classes.push(RowCss.CURSOR_STYLE_BLOCK_CLASS);\n break;\n case 'bar':\n classes.push(RowCss.CURSOR_STYLE_BAR_CLASS);\n break;\n case 'underline':\n classes.push(RowCss.CURSOR_STYLE_UNDERLINE_CLASS);\n break;\n default:\n break;\n }\n }\n }\n }\n\n if (cell.isBold()) {\n classes.push(RowCss.BOLD_CLASS);\n }\n\n if (cell.isItalic()) {\n classes.push(RowCss.ITALIC_CLASS);\n }\n\n if (cell.isDim()) {\n classes.push(RowCss.DIM_CLASS);\n }\n\n if (cell.isInvisible()) {\n text = WHITESPACE_CELL_CHAR;\n } else {\n text = cell.getChars() || WHITESPACE_CELL_CHAR;\n }\n\n if (cell.isUnderline()) {\n classes.push(`${RowCss.UNDERLINE_CLASS}-${cell.extended.underlineStyle}`);\n if (text === ' ') {\n text = '\\xa0'; // =  \n }\n if (!cell.isUnderlineColorDefault()) {\n if (cell.isUnderlineColorRGB()) {\n charElement.style.textDecorationColor = `rgb(${AttributeData.toColorRGB(cell.getUnderlineColor()).join(',')})`;\n } else {\n let fg = cell.getUnderlineColor();\n if (this._optionsService.rawOptions.drawBoldTextInBrightColors && cell.isBold() && fg < 8) {\n fg += 8;\n }\n charElement.style.textDecorationColor = colors.ansi[fg].css;\n }\n }\n }\n\n if (cell.isOverline()) {\n classes.push(RowCss.OVERLINE_CLASS);\n if (text === ' ') {\n text = '\\xa0'; // =  \n }\n }\n\n if (cell.isStrikethrough()) {\n classes.push(RowCss.STRIKETHROUGH_CLASS);\n }\n\n // apply link hover underline late, effectively overrides any previous text-decoration\n // settings\n if (isLinkHover) {\n charElement.style.textDecoration = 'underline';\n }\n\n let fg = cell.getFgColor();\n let fgColorMode = cell.getFgColorMode();\n let bg = cell.getBgColor();\n let bgColorMode = cell.getBgColorMode();\n const isInverse = !!cell.isInverse();\n if (isInverse) {\n const temp = fg;\n fg = bg;\n bg = temp;\n const temp2 = fgColorMode;\n fgColorMode = bgColorMode;\n bgColorMode = temp2;\n }\n\n // Apply any decoration foreground/background overrides, this must happen after inverse has\n // been applied\n let bgOverride: IColor | undefined;\n let fgOverride: IColor | undefined;\n let isTop = false;\n this._decorationService.forEachDecorationAtCell(x, row, undefined, d => {\n if (d.options.layer !== 'top' && isTop) {\n return;\n }\n if (d.backgroundColorRGB) {\n bgColorMode = Attributes.CM_RGB;\n bg = d.backgroundColorRGB.rgba >> 8 & 0xFFFFFF;\n bgOverride = d.backgroundColorRGB;\n }\n if (d.foregroundColorRGB) {\n fgColorMode = Attributes.CM_RGB;\n fg = d.foregroundColorRGB.rgba >> 8 & 0xFFFFFF;\n fgOverride = d.foregroundColorRGB;\n }\n isTop = d.options.layer === 'top';\n });\n\n // Apply selection\n if (!isTop && isInSelection) {\n // If in the selection, force the element to be above the selection to improve contrast and\n // support opaque selections. The applies background is not actually needed here as\n // selection is drawn in a seperate container, the main purpose of this to ensuring minimum\n // contrast ratio\n bgOverride = this._coreBrowserService.isFocused ? colors.selectionBackgroundOpaque : colors.selectionInactiveBackgroundOpaque;\n bg = bgOverride.rgba >> 8 & 0xFFFFFF;\n bgColorMode = Attributes.CM_RGB;\n // Since an opaque selection is being rendered, the selection pretends to be a decoration to\n // ensure text is drawn above the selection.\n isTop = true;\n // Apply selection foreground if applicable\n if (colors.selectionForeground) {\n fgColorMode = Attributes.CM_RGB;\n fg = colors.selectionForeground.rgba >> 8 & 0xFFFFFF;\n fgOverride = colors.selectionForeground;\n }\n }\n\n // If it's a top decoration, render above the selection\n if (isTop) {\n classes.push('xterm-decoration-top');\n }\n\n // Background\n let resolvedBg: IColor;\n switch (bgColorMode) {\n case Attributes.CM_P16:\n case Attributes.CM_P256:\n resolvedBg = colors.ansi[bg];\n classes.push(`xterm-bg-${bg}`);\n break;\n case Attributes.CM_RGB:\n resolvedBg = channels.toColor(bg >> 16, bg >> 8 & 0xFF, bg & 0xFF);\n this._addStyle(charElement, `background-color:#${padStart((bg >>> 0).toString(16), '0', 6)}`);\n break;\n case Attributes.CM_DEFAULT:\n default:\n if (isInverse) {\n resolvedBg = colors.foreground;\n classes.push(`xterm-bg-${INVERTED_DEFAULT_COLOR}`);\n } else {\n resolvedBg = colors.background;\n }\n }\n\n // If there is no background override by now it's the original color, so apply dim if needed\n if (!bgOverride) {\n if (cell.isDim()) {\n bgOverride = color.multiplyOpacity(resolvedBg, 0.5);\n }\n }\n\n // Foreground\n switch (fgColorMode) {\n case Attributes.CM_P16:\n case Attributes.CM_P256:\n if (cell.isBold() && fg < 8 && this._optionsService.rawOptions.drawBoldTextInBrightColors) {\n fg += 8;\n }\n if (!this._applyMinimumContrast(charElement, resolvedBg, colors.ansi[fg], cell, bgOverride, undefined)) {\n classes.push(`xterm-fg-${fg}`);\n }\n break;\n case Attributes.CM_RGB:\n const color = channels.toColor(\n (fg >> 16) & 0xFF,\n (fg >> 8) & 0xFF,\n (fg ) & 0xFF\n );\n if (!this._applyMinimumContrast(charElement, resolvedBg, color, cell, bgOverride, fgOverride)) {\n this._addStyle(charElement, `color:#${padStart(fg.toString(16), '0', 6)}`);\n }\n break;\n case Attributes.CM_DEFAULT:\n default:\n if (!this._applyMinimumContrast(charElement, resolvedBg, colors.foreground, cell, bgOverride, fgOverride)) {\n if (isInverse) {\n classes.push(`xterm-fg-${INVERTED_DEFAULT_COLOR}`);\n }\n }\n }\n\n // apply CSS classes\n // slightly faster than using classList by omitting\n // checks for doubled entries (code above should not have doublets)\n if (classes.length) {\n charElement.className = classes.join(' ');\n classes.length = 0;\n }\n\n // exclude conditions for cell merging - never merge these\n if (!isCursorCell && !isJoined && !isDecorated && isValidJoinRange) {\n cellAmount++;\n } else {\n charElement.textContent = text;\n }\n // apply letter-spacing rule\n if (spacing !== this.defaultSpacing) {\n charElement.style.letterSpacing = `${spacing}px`;\n }\n\n elements.push(charElement);\n x = lastCharX;\n }\n\n // postfix text of last merged span\n if (charElement && cellAmount) {\n charElement.textContent = text;\n }\n\n return elements;\n }\n\n private _applyMinimumContrast(element: HTMLElement, bg: IColor, fg: IColor, cell: ICellData, bgOverride: IColor | undefined, fgOverride: IColor | undefined): boolean {\n if (this._optionsService.rawOptions.minimumContrastRatio === 1 || treatGlyphAsBackgroundColor(cell.getCode())) {\n return false;\n }\n\n // Try get from cache first, only use the cache when there are no decoration overrides\n const cache = this._getContrastCache(cell);\n let adjustedColor: IColor | undefined | null = undefined;\n if (!bgOverride && !fgOverride) {\n adjustedColor = cache.getColor(bg.rgba, fg.rgba);\n }\n\n // Calculate and store in cache\n if (adjustedColor === undefined) {\n // Dim cells only require half the contrast, otherwise they wouldn't be distinguishable from\n // non-dim cells\n const ratio = this._optionsService.rawOptions.minimumContrastRatio / (cell.isDim() ? 2 : 1);\n adjustedColor = color.ensureContrastRatio(bgOverride || bg, fgOverride || fg, ratio);\n cache.setColor((bgOverride || bg).rgba, (fgOverride || fg).rgba, adjustedColor ?? null);\n }\n\n if (adjustedColor) {\n this._addStyle(element, `color:${adjustedColor.css}`);\n return true;\n }\n\n return false;\n }\n\n private _getContrastCache(cell: ICellData): IColorContrastCache {\n if (cell.isDim()) {\n return this._themeService.colors.halfContrastCache;\n }\n return this._themeService.colors.contrastCache;\n }\n\n private _addStyle(element: HTMLElement, style: string): void {\n element.setAttribute('style', `${element.getAttribute('style') || ''}${style};`);\n }\n\n private _isCellInSelection(x: number, y: number): boolean {\n const start = this._selectionStart;\n const end = this._selectionEnd;\n if (!start || !end) {\n return false;\n }\n if (this._columnSelectMode) {\n if (start[0] <= end[0]) {\n return x >= start[0] && y >= start[1] &&\n x < end[0] && y <= end[1];\n }\n return x < start[0] && y >= start[1] &&\n x >= end[0] && y <= end[1];\n }\n return (y > start[1] && y < end[1]) ||\n (start[1] === end[1] && y === start[1] && x >= start[0] && x < end[0]) ||\n (start[1] < end[1] && y === end[1] && x < end[0]) ||\n (start[1] < end[1] && y === start[1] && x >= start[0]);\n }\n}\n\nfunction padStart(text: string, padChar: string, length: number): string {\n while (text.length < length) {\n text = padChar + text;\n }\n return text;\n}\n","/**\n * Copyright (c) 2023 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IDisposable } from 'common/Types';\nimport { FontWeight } from 'common/services/Services';\n\n\nexport const enum WidthCacheSettings {\n /** sentinel for unset values in flat cache */\n FLAT_UNSET = -9999,\n /** size of flat cache, size-1 equals highest codepoint handled by flat */\n FLAT_SIZE = 256,\n /** char repeat for measuring */\n REPEAT = 32\n}\n\n\nconst enum FontVariant {\n REGULAR = 0,\n BOLD = 1,\n ITALIC = 2,\n BOLD_ITALIC = 3\n}\n\n\nexport class WidthCache implements IDisposable {\n // flat cache for regular variant up to CacheSettings.FLAT_SIZE\n // NOTE: ~4x faster access than holey (serving >>80% of terminal content)\n // It has a small memory footprint (only 1MB for full BMP caching),\n // still the sweet spot is not reached before touching 32k different codepoints,\n // thus we store the remaining <<20% of terminal data in a holey structure.\n protected _flat = new Float32Array(WidthCacheSettings.FLAT_SIZE);\n\n // holey cache for bold, italic and bold&italic for any string\n // FIXME: can grow really big over time (~8.5 MB for full BMP caching),\n // so a shared API across terminals is needed\n protected _holey: Map | undefined;\n\n private _font = '';\n private _fontSize = 0;\n private _weight: FontWeight = 'normal';\n private _weightBold: FontWeight = 'bold';\n private _container: HTMLDivElement;\n private _measureElements: HTMLSpanElement[] = [];\n\n constructor(_document: Document, _helperContainer: HTMLElement) {\n this._container = _document.createElement('div');\n this._container.classList.add('xterm-width-cache-measure-container');\n this._container.setAttribute('aria-hidden', 'true');\n // SP should stack in spans\n this._container.style.whiteSpace = 'pre';\n // avoid undercuts in non-monospace fonts from kerning\n this._container.style.fontKerning = 'none';\n\n const regular = _document.createElement('span');\n regular.classList.add('xterm-char-measure-element');\n\n const bold = _document.createElement('span');\n bold.classList.add('xterm-char-measure-element');\n bold.style.fontWeight = 'bold';\n\n const italic = _document.createElement('span');\n italic.classList.add('xterm-char-measure-element');\n italic.style.fontStyle = 'italic';\n\n const boldItalic = _document.createElement('span');\n boldItalic.classList.add('xterm-char-measure-element');\n boldItalic.style.fontWeight = 'bold';\n boldItalic.style.fontStyle = 'italic';\n\n // NOTE: must be in order of FontVariant\n this._measureElements = [regular, bold, italic, boldItalic];\n this._container.appendChild(regular);\n this._container.appendChild(bold);\n this._container.appendChild(italic);\n this._container.appendChild(boldItalic);\n\n _helperContainer.appendChild(this._container);\n\n this.clear();\n }\n\n public dispose(): void {\n this._container.remove(); // remove elements from DOM\n this._measureElements.length = 0; // release element refs\n this._holey = undefined; // free cache memory via GC\n }\n\n /**\n * Clear the width cache.\n */\n public clear(): void {\n this._flat.fill(WidthCacheSettings.FLAT_UNSET);\n // .clear() has some overhead, re-assign instead (>3 times faster)\n this._holey = new Map();\n }\n\n /**\n * Set the font for measuring.\n * Must be called for any changes on font settings.\n * Also clears the cache.\n */\n public setFont(font: string, fontSize: number, weight: FontWeight, weightBold: FontWeight): void {\n // skip if nothing changed\n if (font === this._font\n && fontSize === this._fontSize\n && weight === this._weight\n && weightBold === this._weightBold\n ) {\n return;\n }\n\n this._font = font;\n this._fontSize = fontSize;\n this._weight = weight;\n this._weightBold = weightBold;\n\n this._container.style.fontFamily = this._font;\n this._container.style.fontSize = `${this._fontSize}px`;\n this._measureElements[FontVariant.REGULAR].style.fontWeight = `${weight}`;\n this._measureElements[FontVariant.BOLD].style.fontWeight = `${weightBold}`;\n this._measureElements[FontVariant.ITALIC].style.fontWeight = `${weight}`;\n this._measureElements[FontVariant.BOLD_ITALIC].style.fontWeight = `${weightBold}`;\n\n this.clear();\n }\n\n /**\n * Get the render width for cell content `c` with current font settings.\n * `variant` denotes the font variant to be used.\n */\n public get(c: string, bold: boolean | number, italic: boolean | number): number {\n let cp = 0;\n if (!bold && !italic && c.length === 1 && (cp = c.charCodeAt(0)) < WidthCacheSettings.FLAT_SIZE) {\n if (this._flat[cp] !== WidthCacheSettings.FLAT_UNSET) {\n return this._flat[cp];\n }\n const width = this._measure(c, 0);\n if (width > 0) {\n this._flat[cp] = width;\n }\n return width;\n }\n let key = c;\n if (bold) key += 'B';\n if (italic) key += 'I';\n let width = this._holey!.get(key);\n if (width === undefined) {\n let variant = 0;\n if (bold) variant |= FontVariant.BOLD;\n if (italic) variant |= FontVariant.ITALIC;\n width = this._measure(c, variant);\n if (width > 0) {\n this._holey!.set(key, width);\n }\n }\n return width;\n }\n\n protected _measure(c: string, variant: FontVariant): number {\n const el = this._measureElements[variant];\n el.textContent = c.repeat(WidthCacheSettings.REPEAT);\n return el.offsetWidth / WidthCacheSettings.REPEAT;\n }\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nexport const INVERTED_DEFAULT_COLOR = 257;\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IDimensions, IRenderDimensions } from 'browser/renderer/shared/Types';\n\nexport function throwIfFalsy(value: T | undefined | null): T {\n if (!value) {\n throw new Error('value must not be falsy');\n }\n return value;\n}\n\nexport function isPowerlineGlyph(codepoint: number): boolean {\n // Only return true for Powerline symbols which require\n // different padding and should be excluded from minimum contrast\n // ratio standards\n return 0xE0A4 <= codepoint && codepoint <= 0xE0D6;\n}\n\nexport function isRestrictedPowerlineGlyph(codepoint: number): boolean {\n return 0xE0B0 <= codepoint && codepoint <= 0xE0B7;\n}\n\nfunction isNerdFontGlyph(codepoint: number): boolean {\n return 0xE000 <= codepoint && codepoint <= 0xF8FF;\n}\n\nfunction isBoxOrBlockGlyph(codepoint: number): boolean {\n return 0x2500 <= codepoint && codepoint <= 0x259F;\n}\n\nexport function isEmoji(codepoint: number): boolean {\n return (\n codepoint >= 0x1F600 && codepoint <= 0x1F64F || // Emoticons\n codepoint >= 0x1F300 && codepoint <= 0x1F5FF || // Misc Symbols and Pictographs\n codepoint >= 0x1F680 && codepoint <= 0x1F6FF || // Transport and Map\n codepoint >= 0x2600 && codepoint <= 0x26FF || // Misc symbols\n codepoint >= 0x2700 && codepoint <= 0x27BF || // Dingbats\n codepoint >= 0xFE00 && codepoint <= 0xFE0F || // Variation Selectors\n codepoint >= 0x1F900 && codepoint <= 0x1F9FF || // Supplemental Symbols and Pictographs\n codepoint >= 0x1F1E6 && codepoint <= 0x1F1FF\n );\n}\n\nexport function allowRescaling(codepoint: number | undefined, width: number, glyphSizeX: number, deviceCellWidth: number): boolean {\n return (\n // Is single cell width\n width === 1 &&\n // Glyph exceeds cell bounds, add 50% to avoid hurting readability by rescaling glyphs that\n // barely overlap\n glyphSizeX > Math.ceil(deviceCellWidth * 1.5) &&\n // Never rescale ascii\n codepoint !== undefined && codepoint > 0xFF &&\n // Never rescale emoji\n !isEmoji(codepoint) &&\n // Never rescale powerline or nerd fonts\n !isPowerlineGlyph(codepoint) && !isNerdFontGlyph(codepoint)\n );\n}\n\nexport function treatGlyphAsBackgroundColor(codepoint: number): boolean {\n return isPowerlineGlyph(codepoint) || isBoxOrBlockGlyph(codepoint);\n}\n\nexport function createRenderDimensions(): IRenderDimensions {\n return {\n css: {\n canvas: createDimension(),\n cell: createDimension()\n },\n device: {\n canvas: createDimension(),\n cell: createDimension(),\n char: {\n width: 0,\n height: 0,\n left: 0,\n top: 0\n }\n }\n };\n}\n\nfunction createDimension(): IDimensions {\n return {\n width: 0,\n height: 0\n };\n}\n\nexport function computeNextVariantOffset(cellWidth: number, lineWidth: number, currentOffset: number = 0): number {\n return (cellWidth - (Math.round(lineWidth) * 2 - currentOffset)) % (Math.round(lineWidth) * 2);\n}\n","/**\n * Copyright (c) 2022 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { ITerminal } from 'browser/Types';\nimport { ISelectionRenderModel } from 'browser/renderer/shared/Types';\nimport { Terminal } from '@xterm/xterm';\n\nclass SelectionRenderModel implements ISelectionRenderModel {\n public hasSelection!: boolean;\n public columnSelectMode!: boolean;\n public viewportStartRow!: number;\n public viewportEndRow!: number;\n public viewportCappedStartRow!: number;\n public viewportCappedEndRow!: number;\n public startCol!: number;\n public endCol!: number;\n public selectionStart: [number, number] | undefined;\n public selectionEnd: [number, number] | undefined;\n\n constructor() {\n this.clear();\n }\n\n public clear(): void {\n this.hasSelection = false;\n this.columnSelectMode = false;\n this.viewportStartRow = 0;\n this.viewportEndRow = 0;\n this.viewportCappedStartRow = 0;\n this.viewportCappedEndRow = 0;\n this.startCol = 0;\n this.endCol = 0;\n this.selectionStart = undefined;\n this.selectionEnd = undefined;\n }\n\n public update(terminal: ITerminal, start: [number, number] | undefined, end: [number, number] | undefined, columnSelectMode: boolean = false): void {\n this.selectionStart = start;\n this.selectionEnd = end;\n // Selection does not exist\n if (!start || !end || (start[0] === end[0] && start[1] === end[1])) {\n this.clear();\n return;\n }\n\n // Translate from buffer position to viewport position\n const viewportY = terminal.buffers.active.ydisp;\n const viewportStartRow = start[1] - viewportY;\n const viewportEndRow = end[1] - viewportY;\n const viewportCappedStartRow = Math.max(viewportStartRow, 0);\n const viewportCappedEndRow = Math.min(viewportEndRow, terminal.rows - 1);\n\n // No need to draw the selection\n if (viewportCappedStartRow >= terminal.rows || viewportCappedEndRow < 0) {\n this.clear();\n return;\n }\n\n this.hasSelection = true;\n this.columnSelectMode = columnSelectMode;\n this.viewportStartRow = viewportStartRow;\n this.viewportEndRow = viewportEndRow;\n this.viewportCappedStartRow = viewportCappedStartRow;\n this.viewportCappedEndRow = viewportCappedEndRow;\n this.startCol = start[0];\n this.endCol = end[0];\n }\n\n public isCellSelected(terminal: Terminal, x: number, y: number): boolean {\n if (!this.hasSelection) {\n return false;\n }\n y -= terminal.buffer.active.viewportY;\n if (this.columnSelectMode) {\n if (this.startCol <= this.endCol) {\n return x >= this.startCol && y >= this.viewportCappedStartRow &&\n x < this.endCol && y <= this.viewportCappedEndRow;\n }\n return x < this.startCol && y >= this.viewportCappedStartRow &&\n x >= this.endCol && y <= this.viewportCappedEndRow;\n }\n return (y > this.viewportStartRow && y < this.viewportEndRow) ||\n (this.viewportStartRow === this.viewportEndRow && y === this.viewportStartRow && x >= this.startCol && x < this.endCol) ||\n (this.viewportStartRow < this.viewportEndRow && y === this.viewportEndRow && x < this.endCol) ||\n (this.viewportStartRow < this.viewportEndRow && y === this.viewportStartRow && x >= this.startCol);\n }\n}\n\nexport function createSelectionRenderModel(): ISelectionRenderModel {\n return new SelectionRenderModel();\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IBufferService } from 'common/services/Services';\n\n/**\n * Represents a selection within the buffer. This model only cares about column\n * and row coordinates, not wide characters.\n */\nexport class SelectionModel {\n /**\n * Whether select all is currently active.\n */\n public isSelectAllActive: boolean = false;\n\n /**\n * The minimal length of the selection from the start position. When double\n * clicking on a word, the word will be selected which makes the selection\n * start at the start of the word and makes this variable the length.\n */\n public selectionStartLength: number = 0;\n\n /**\n * The [x, y] position the selection starts at.\n */\n public selectionStart: [number, number] | undefined;\n\n /**\n * The [x, y] position the selection ends at.\n */\n public selectionEnd: [number, number] | undefined;\n\n constructor(\n private _bufferService: IBufferService\n ) {\n }\n\n /**\n * Clears the current selection.\n */\n public clearSelection(): void {\n this.selectionStart = undefined;\n this.selectionEnd = undefined;\n this.isSelectAllActive = false;\n this.selectionStartLength = 0;\n }\n\n /**\n * The final selection start, taking into consideration select all.\n */\n public get finalSelectionStart(): [number, number] | undefined {\n if (this.isSelectAllActive) {\n return [0, 0];\n }\n\n if (!this.selectionEnd || !this.selectionStart) {\n return this.selectionStart;\n }\n\n return this.areSelectionValuesReversed() ? this.selectionEnd : this.selectionStart;\n }\n\n /**\n * The final selection end, taking into consideration select all, double click\n * word selection and triple click line selection.\n */\n public get finalSelectionEnd(): [number, number] | undefined {\n if (this.isSelectAllActive) {\n return [this._bufferService.cols, this._bufferService.buffer.ybase + this._bufferService.rows - 1];\n }\n\n if (!this.selectionStart) {\n return undefined;\n }\n\n // Use the selection start + length if the end doesn't exist or they're reversed\n if (!this.selectionEnd || this.areSelectionValuesReversed()) {\n const startPlusLength = this.selectionStart[0] + this.selectionStartLength;\n if (startPlusLength > this._bufferService.cols) {\n // Ensure the trailing EOL isn't included when the selection ends on the right edge\n if (startPlusLength % this._bufferService.cols === 0) {\n return [this._bufferService.cols, this.selectionStart[1] + Math.floor(startPlusLength / this._bufferService.cols) - 1];\n }\n return [startPlusLength % this._bufferService.cols, this.selectionStart[1] + Math.floor(startPlusLength / this._bufferService.cols)];\n }\n return [startPlusLength, this.selectionStart[1]];\n }\n\n // Ensure the the word/line is selected after a double/triple click\n if (this.selectionStartLength) {\n // Select the larger of the two when start and end are on the same line\n if (this.selectionEnd[1] === this.selectionStart[1]) {\n // Keep the whole wrapped word/line selected if the content wraps multiple lines\n const startPlusLength = this.selectionStart[0] + this.selectionStartLength;\n if (startPlusLength > this._bufferService.cols) {\n return [startPlusLength % this._bufferService.cols, this.selectionStart[1] + Math.floor(startPlusLength / this._bufferService.cols)];\n }\n return [Math.max(startPlusLength, this.selectionEnd[0]), this.selectionEnd[1]];\n }\n }\n return this.selectionEnd;\n }\n\n /**\n * Returns whether the selection start and end are reversed.\n */\n public areSelectionValuesReversed(): boolean {\n const start = this.selectionStart;\n const end = this.selectionEnd;\n if (!start || !end) {\n return false;\n }\n return start[1] > end[1] || (start[1] === end[1] && start[0] > end[0]);\n }\n\n /**\n * Handle the buffer being trimmed, adjust the selection position.\n * @param amount The amount the buffer is being trimmed.\n * @returns Whether a refresh is necessary.\n */\n public handleTrim(amount: number): boolean {\n // Adjust the selection position based on the trimmed amount.\n if (this.selectionStart) {\n this.selectionStart[1] -= amount;\n }\n if (this.selectionEnd) {\n this.selectionEnd[1] -= amount;\n }\n\n // The selection has moved off the buffer, clear it.\n if (this.selectionEnd && this.selectionEnd[1] < 0) {\n this.clearSelection();\n return true;\n }\n\n // If the selection start is trimmed, ensure the start column is 0.\n if (this.selectionStart && this.selectionStart[1] < 0) {\n this.selectionStart[1] = 0;\n }\n return false;\n }\n}\n","/**\n * Copyright (c) 2016 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IOptionsService } from 'common/services/Services';\nimport { ICharSizeService } from 'browser/services/Services';\nimport { Disposable } from 'vs/base/common/lifecycle';\nimport { Emitter } from 'vs/base/common/event';\n\nexport class CharSizeService extends Disposable implements ICharSizeService {\n public serviceBrand: undefined;\n\n public width: number = 0;\n public height: number = 0;\n private _measureStrategy: IMeasureStrategy;\n\n public get hasValidSize(): boolean { return this.width > 0 && this.height > 0; }\n\n private readonly _onCharSizeChange = this._register(new Emitter());\n public readonly onCharSizeChange = this._onCharSizeChange.event;\n\n constructor(\n document: Document,\n parentElement: HTMLElement,\n @IOptionsService private readonly _optionsService: IOptionsService\n ) {\n super();\n try {\n this._measureStrategy = this._register(new TextMetricsMeasureStrategy(this._optionsService));\n } catch {\n this._measureStrategy = this._register(new DomMeasureStrategy(document, parentElement, this._optionsService));\n }\n this._register(this._optionsService.onMultipleOptionChange(['fontFamily', 'fontSize'], () => this.measure()));\n }\n\n public measure(): void {\n const result = this._measureStrategy.measure();\n if (result.width !== this.width || result.height !== this.height) {\n this.width = result.width;\n this.height = result.height;\n this._onCharSizeChange.fire();\n }\n }\n}\n\ninterface IMeasureStrategy {\n measure(): Readonly;\n}\n\ninterface IMeasureResult {\n width: number;\n height: number;\n}\n\nconst enum DomMeasureStrategyConstants {\n REPEAT = 32\n}\n\nabstract class BaseMeasureStategy extends Disposable implements IMeasureStrategy {\n protected _result: IMeasureResult = { width: 0, height: 0 };\n\n protected _validateAndSet(width: number | undefined, height: number | undefined): void {\n // If values are 0 then the element is likely currently display:none, in which case we should\n // retain the previous value.\n if (width !== undefined && width > 0 && height !== undefined && height > 0) {\n this._result.width = width;\n this._result.height = height;\n }\n }\n\n public abstract measure(): Readonly;\n}\n\nclass DomMeasureStrategy extends BaseMeasureStategy {\n private _measureElement: HTMLElement;\n\n constructor(\n private _document: Document,\n private _parentElement: HTMLElement,\n private _optionsService: IOptionsService\n ) {\n super();\n this._measureElement = this._document.createElement('span');\n this._measureElement.classList.add('xterm-char-measure-element');\n this._measureElement.textContent = 'W'.repeat(DomMeasureStrategyConstants.REPEAT);\n this._measureElement.setAttribute('aria-hidden', 'true');\n this._measureElement.style.whiteSpace = 'pre';\n this._measureElement.style.fontKerning = 'none';\n this._parentElement.appendChild(this._measureElement);\n }\n\n public measure(): Readonly {\n this._measureElement.style.fontFamily = this._optionsService.rawOptions.fontFamily;\n this._measureElement.style.fontSize = `${this._optionsService.rawOptions.fontSize}px`;\n\n // Note that this triggers a synchronous layout\n this._validateAndSet(Number(this._measureElement.offsetWidth) / DomMeasureStrategyConstants.REPEAT, Number(this._measureElement.offsetHeight));\n\n return this._result;\n }\n}\n\nclass TextMetricsMeasureStrategy extends BaseMeasureStategy {\n private _canvas: OffscreenCanvas;\n private _ctx: OffscreenCanvasRenderingContext2D;\n\n constructor(\n private _optionsService: IOptionsService\n ) {\n super();\n // This will throw if any required API is not supported\n this._canvas = new OffscreenCanvas(100, 100);\n this._ctx = this._canvas.getContext('2d')!;\n const a = this._ctx.measureText('W');\n if (!('width' in a && 'fontBoundingBoxAscent' in a && 'fontBoundingBoxDescent' in a)) {\n throw new Error('Required font metrics not supported');\n }\n }\n\n public measure(): Readonly {\n this._ctx.font = `${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`;\n const metrics = this._ctx.measureText('W');\n this._validateAndSet(metrics.width, metrics.fontBoundingBoxAscent + metrics.fontBoundingBoxDescent);\n return this._result;\n }\n}\n","/**\n * Copyright (c) 2018 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IBufferLine, ICellData, CharData } from 'common/Types';\nimport { ICharacterJoiner } from 'browser/Types';\nimport { AttributeData } from 'common/buffer/AttributeData';\nimport { WHITESPACE_CELL_CHAR, Content } from 'common/buffer/Constants';\nimport { CellData } from 'common/buffer/CellData';\nimport { IBufferService } from 'common/services/Services';\nimport { ICharacterJoinerService } from 'browser/services/Services';\n\nexport class JoinedCellData extends AttributeData implements ICellData {\n private _width: number;\n // .content carries no meaning for joined CellData, simply nullify it\n // thus we have to overload all other .content accessors\n public content: number = 0;\n public fg: number;\n public bg: number;\n public combinedData: string = '';\n\n constructor(firstCell: ICellData, chars: string, width: number) {\n super();\n this.fg = firstCell.fg;\n this.bg = firstCell.bg;\n this.combinedData = chars;\n this._width = width;\n }\n\n public isCombined(): number {\n // always mark joined cell data as combined\n return Content.IS_COMBINED_MASK;\n }\n\n public getWidth(): number {\n return this._width;\n }\n\n public getChars(): string {\n return this.combinedData;\n }\n\n public getCode(): number {\n // code always gets the highest possible fake codepoint (read as -1)\n // this is needed as code is used by caches as identifier\n return 0x1FFFFF;\n }\n\n public setFromCharData(value: CharData): void {\n throw new Error('not implemented');\n }\n\n public getAsCharData(): CharData {\n return [this.fg, this.getChars(), this.getWidth(), this.getCode()];\n }\n}\n\nexport class CharacterJoinerService implements ICharacterJoinerService {\n public serviceBrand: undefined;\n\n private _characterJoiners: ICharacterJoiner[] = [];\n private _nextCharacterJoinerId: number = 0;\n private _workCell: CellData = new CellData();\n\n constructor(\n @IBufferService private _bufferService: IBufferService\n ) { }\n\n public register(handler: (text: string) => [number, number][]): number {\n const joiner: ICharacterJoiner = {\n id: this._nextCharacterJoinerId++,\n handler\n };\n\n this._characterJoiners.push(joiner);\n return joiner.id;\n }\n\n public deregister(joinerId: number): boolean {\n for (let i = 0; i < this._characterJoiners.length; i++) {\n if (this._characterJoiners[i].id === joinerId) {\n this._characterJoiners.splice(i, 1);\n return true;\n }\n }\n\n return false;\n }\n\n public getJoinedCharacters(row: number): [number, number][] {\n if (this._characterJoiners.length === 0) {\n return [];\n }\n\n const line = this._bufferService.buffer.lines.get(row);\n if (!line || line.length === 0) {\n return [];\n }\n\n const ranges: [number, number][] = [];\n const lineStr = line.translateToString(true);\n\n // Because some cells can be represented by multiple javascript characters,\n // we track the cell and the string indexes separately. This allows us to\n // translate the string ranges we get from the joiners back into cell ranges\n // for use when rendering\n let rangeStartColumn = 0;\n let currentStringIndex = 0;\n let rangeStartStringIndex = 0;\n let rangeAttrFG = line.getFg(0);\n let rangeAttrBG = line.getBg(0);\n\n for (let x = 0; x < line.getTrimmedLength(); x++) {\n line.loadCell(x, this._workCell);\n\n if (this._workCell.getWidth() === 0) {\n // If this character is of width 0, skip it.\n continue;\n }\n\n // End of range\n if (this._workCell.fg !== rangeAttrFG || this._workCell.bg !== rangeAttrBG) {\n // If we ended up with a sequence of more than one character,\n // look for ranges to join.\n if (x - rangeStartColumn > 1) {\n const joinedRanges = this._getJoinedRanges(\n lineStr,\n rangeStartStringIndex,\n currentStringIndex,\n line,\n rangeStartColumn\n );\n for (let i = 0; i < joinedRanges.length; i++) {\n ranges.push(joinedRanges[i]);\n }\n }\n\n // Reset our markers for a new range.\n rangeStartColumn = x;\n rangeStartStringIndex = currentStringIndex;\n rangeAttrFG = this._workCell.fg;\n rangeAttrBG = this._workCell.bg;\n }\n\n currentStringIndex += this._workCell.getChars().length || WHITESPACE_CELL_CHAR.length;\n }\n\n // Process any trailing ranges.\n if (this._bufferService.cols - rangeStartColumn > 1) {\n const joinedRanges = this._getJoinedRanges(\n lineStr,\n rangeStartStringIndex,\n currentStringIndex,\n line,\n rangeStartColumn\n );\n for (let i = 0; i < joinedRanges.length; i++) {\n ranges.push(joinedRanges[i]);\n }\n }\n\n return ranges;\n }\n\n /**\n * Given a segment of a line of text, find all ranges of text that should be\n * joined in a single rendering unit. Ranges are internally converted to\n * column ranges, rather than string ranges.\n * @param line String representation of the full line of text\n * @param startIndex Start position of the range to search in the string (inclusive)\n * @param endIndex End position of the range to search in the string (exclusive)\n */\n private _getJoinedRanges(line: string, startIndex: number, endIndex: number, lineData: IBufferLine, startCol: number): [number, number][] {\n const text = line.substring(startIndex, endIndex);\n // At this point we already know that there is at least one joiner so\n // we can just pull its value and assign it directly rather than\n // merging it into an empty array, which incurs unnecessary writes.\n let allJoinedRanges: [number, number][] = [];\n try {\n allJoinedRanges = this._characterJoiners[0].handler(text);\n } catch (error) {\n console.error(error);\n }\n for (let i = 1; i < this._characterJoiners.length; i++) {\n // We merge any overlapping ranges across the different joiners\n try {\n const joinerRanges = this._characterJoiners[i].handler(text);\n for (let j = 0; j < joinerRanges.length; j++) {\n CharacterJoinerService._mergeRanges(allJoinedRanges, joinerRanges[j]);\n }\n } catch (error) {\n console.error(error);\n }\n }\n this._stringRangesToCellRanges(allJoinedRanges, lineData, startCol);\n return allJoinedRanges;\n }\n\n /**\n * Modifies the provided ranges in-place to adjust for variations between\n * string length and cell width so that the range represents a cell range,\n * rather than the string range the joiner provides.\n * @param ranges String ranges containing start (inclusive) and end (exclusive) index\n * @param line Cell data for the relevant line in the terminal\n * @param startCol Offset within the line to start from\n */\n private _stringRangesToCellRanges(ranges: [number, number][], line: IBufferLine, startCol: number): void {\n let currentRangeIndex = 0;\n let currentRangeStarted = false;\n let currentStringIndex = 0;\n let currentRange = ranges[currentRangeIndex];\n\n // If we got through all of the ranges, stop searching\n if (!currentRange) {\n return;\n }\n\n for (let x = startCol; x < this._bufferService.cols; x++) {\n const width = line.getWidth(x);\n const length = line.getString(x).length || WHITESPACE_CELL_CHAR.length;\n\n // We skip zero-width characters when creating the string to join the text\n // so we do the same here\n if (width === 0) {\n continue;\n }\n\n // Adjust the start of the range\n if (!currentRangeStarted && currentRange[0] <= currentStringIndex) {\n currentRange[0] = x;\n currentRangeStarted = true;\n }\n\n // Adjust the end of the range\n if (currentRange[1] <= currentStringIndex) {\n currentRange[1] = x;\n\n // We're finished with this range, so we move to the next one\n currentRange = ranges[++currentRangeIndex];\n\n // If there are no more ranges left, stop searching\n if (!currentRange) {\n break;\n }\n\n // Ranges can be on adjacent characters. Because the end index of the\n // ranges are exclusive, this means that the index for the start of a\n // range can be the same as the end index of the previous range. To\n // account for the start of the next range, we check here just in case.\n if (currentRange[0] <= currentStringIndex) {\n currentRange[0] = x;\n currentRangeStarted = true;\n } else {\n currentRangeStarted = false;\n }\n }\n\n // Adjust the string index based on the character length to line up with\n // the column adjustment\n currentStringIndex += length;\n }\n\n // If there is still a range left at the end, it must extend all the way to\n // the end of the line.\n if (currentRange) {\n currentRange[1] = this._bufferService.cols;\n }\n }\n\n /**\n * Merges the range defined by the provided start and end into the list of\n * existing ranges. The merge is done in place on the existing range for\n * performance and is also returned.\n * @param ranges Existing range list\n * @param newRange Tuple of two numbers representing the new range to merge in.\n * @returns The ranges input with the new range merged in place\n */\n private static _mergeRanges(ranges: [number, number][], newRange: [number, number]): [number, number][] {\n let inRange = false;\n for (let i = 0; i < ranges.length; i++) {\n const range = ranges[i];\n if (!inRange) {\n if (newRange[1] <= range[0]) {\n // Case 1: New range is before the search range\n ranges.splice(i, 0, newRange);\n return ranges;\n }\n\n if (newRange[1] <= range[1]) {\n // Case 2: New range is either wholly contained within the\n // search range or overlaps with the front of it\n range[0] = Math.min(newRange[0], range[0]);\n return ranges;\n }\n\n if (newRange[0] < range[1]) {\n // Case 3: New range either wholly contains the search range\n // or overlaps with the end of it\n range[0] = Math.min(newRange[0], range[0]);\n inRange = true;\n }\n\n // Case 4: New range starts after the search range\n continue;\n } else {\n if (newRange[1] <= range[0]) {\n // Case 5: New range extends from previous range but doesn't\n // reach the current one\n ranges[i - 1][1] = newRange[1];\n return ranges;\n }\n\n if (newRange[1] <= range[1]) {\n // Case 6: New range extends from prvious range into the\n // current range\n ranges[i - 1][1] = Math.max(newRange[1], range[1]);\n ranges.splice(i, 1);\n return ranges;\n }\n\n // Case 7: New range extends from previous range past the\n // end of the current range\n ranges.splice(i, 1);\n i--;\n }\n }\n\n if (inRange) {\n // Case 8: New range extends past the last existing range\n ranges[ranges.length - 1][1] = newRange[1];\n } else {\n // Case 9: New range starts after the last existing range\n ranges.push(newRange);\n }\n\n return ranges;\n }\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { ICoreBrowserService } from './Services';\nimport { Emitter, Event } from 'vs/base/common/event';\nimport { addDisposableListener } from 'vs/base/browser/dom';\nimport { Disposable, MutableDisposable, toDisposable } from 'vs/base/common/lifecycle';\n\nexport class CoreBrowserService extends Disposable implements ICoreBrowserService {\n public serviceBrand: undefined;\n\n private _isFocused = false;\n private _cachedIsFocused: boolean | undefined = undefined;\n private _screenDprMonitor = this._register(new ScreenDprMonitor(this._window));\n\n private readonly _onDprChange = this._register(new Emitter());\n public readonly onDprChange = this._onDprChange.event;\n private readonly _onWindowChange = this._register(new Emitter());\n public readonly onWindowChange = this._onWindowChange.event;\n\n constructor(\n private _textarea: HTMLTextAreaElement,\n private _window: Window & typeof globalThis,\n public readonly mainDocument: Document\n ) {\n super();\n\n // Monitor device pixel ratio\n this._register(this.onWindowChange(w => this._screenDprMonitor.setWindow(w)));\n this._register(Event.forward(this._screenDprMonitor.onDprChange, this._onDprChange));\n\n this._register(addDisposableListener(this._textarea, 'focus', () => this._isFocused = true));\n this._register(addDisposableListener(this._textarea, 'blur', () => this._isFocused = false));\n }\n\n public get window(): Window & typeof globalThis {\n return this._window;\n }\n\n public set window(value: Window & typeof globalThis) {\n if (this._window !== value) {\n this._window = value;\n this._onWindowChange.fire(this._window);\n }\n }\n\n public get dpr(): number {\n return this.window.devicePixelRatio;\n }\n\n public get isFocused(): boolean {\n if (this._cachedIsFocused === undefined) {\n this._cachedIsFocused = this._isFocused && this._textarea.ownerDocument.hasFocus();\n queueMicrotask(() => this._cachedIsFocused = undefined);\n }\n return this._cachedIsFocused;\n }\n}\n\n\n/**\n * The screen device pixel ratio monitor allows listening for when the\n * window.devicePixelRatio value changes. This is done not with polling but with\n * the use of window.matchMedia to watch media queries. When the event fires,\n * the listener will be reattached using a different media query to ensure that\n * any further changes will _register.\n *\n * The listener should fire on both window zoom changes and switching to a\n * monitor with a different DPI.\n */\nclass ScreenDprMonitor extends Disposable {\n private _currentDevicePixelRatio: number;\n private _outerListener: ((this: MediaQueryList, ev: MediaQueryListEvent) => any) | undefined;\n private _resolutionMediaMatchList: MediaQueryList | undefined;\n private _windowResizeListener = this._register(new MutableDisposable());\n\n private readonly _onDprChange = this._register(new Emitter());\n public readonly onDprChange = this._onDprChange.event;\n\n constructor(private _parentWindow: Window) {\n super();\n\n // Initialize listener and dpr value\n this._outerListener = () => this._setDprAndFireIfDiffers();\n this._currentDevicePixelRatio = this._parentWindow.devicePixelRatio;\n this._updateDpr();\n\n // Monitor active window resize\n this._setWindowResizeListener();\n\n // Setup additional disposables\n this._register(toDisposable(() => this.clearListener()));\n }\n\n\n public setWindow(parentWindow: Window): void {\n this._parentWindow = parentWindow;\n this._setWindowResizeListener();\n this._setDprAndFireIfDiffers();\n }\n\n private _setWindowResizeListener(): void {\n this._windowResizeListener.value = addDisposableListener(this._parentWindow, 'resize', () => this._setDprAndFireIfDiffers());\n }\n\n private _setDprAndFireIfDiffers(): void {\n if (this._parentWindow.devicePixelRatio !== this._currentDevicePixelRatio) {\n this._onDprChange.fire(this._parentWindow.devicePixelRatio);\n }\n this._updateDpr();\n }\n\n private _updateDpr(): void {\n if (!this._outerListener) {\n return;\n }\n\n // Clear listeners for old DPR\n this._resolutionMediaMatchList?.removeListener(this._outerListener);\n\n // Add listeners for new DPR\n this._currentDevicePixelRatio = this._parentWindow.devicePixelRatio;\n this._resolutionMediaMatchList = this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`);\n this._resolutionMediaMatchList.addListener(this._outerListener);\n }\n\n public clearListener(): void {\n if (!this._resolutionMediaMatchList || !this._outerListener) {\n return;\n }\n this._resolutionMediaMatchList.removeListener(this._outerListener);\n this._resolutionMediaMatchList = undefined;\n this._outerListener = undefined;\n }\n}\n","import { ILinkProvider, ILinkProviderService } from 'browser/services/Services';\nimport { Disposable, toDisposable } from 'vs/base/common/lifecycle';\nimport { IDisposable } from 'common/Types';\n\nexport class LinkProviderService extends Disposable implements ILinkProviderService {\n declare public serviceBrand: undefined;\n\n public readonly linkProviders: ILinkProvider[] = [];\n\n constructor() {\n super();\n this._register(toDisposable(() => this.linkProviders.length = 0));\n }\n\n public registerLinkProvider(linkProvider: ILinkProvider): IDisposable {\n this.linkProviders.push(linkProvider);\n return {\n dispose: () => {\n // Remove the link provider from the list\n const providerIndex = this.linkProviders.indexOf(linkProvider);\n\n if (providerIndex !== -1) {\n this.linkProviders.splice(providerIndex, 1);\n }\n }\n };\n }\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { ICharSizeService, IRenderService, IMouseService } from './Services';\nimport { getCoords, getCoordsRelativeToElement } from 'browser/input/Mouse';\n\nexport class MouseService implements IMouseService {\n public serviceBrand: undefined;\n\n constructor(\n @IRenderService private readonly _renderService: IRenderService,\n @ICharSizeService private readonly _charSizeService: ICharSizeService\n ) {\n }\n\n public getCoords(event: {clientX: number, clientY: number}, element: HTMLElement, colCount: number, rowCount: number, isSelection?: boolean): [number, number] | undefined {\n return getCoords(\n window,\n event,\n element,\n colCount,\n rowCount,\n this._charSizeService.hasValidSize,\n this._renderService.dimensions.css.cell.width,\n this._renderService.dimensions.css.cell.height,\n isSelection\n );\n }\n\n public getMouseReportCoords(event: MouseEvent, element: HTMLElement): { col: number, row: number, x: number, y: number } | undefined {\n const coords = getCoordsRelativeToElement(window, event, element);\n if (!this._charSizeService.hasValidSize) {\n return undefined;\n }\n coords[0] = Math.min(Math.max(coords[0], 0), this._renderService.dimensions.css.canvas.width - 1);\n coords[1] = Math.min(Math.max(coords[1], 0), this._renderService.dimensions.css.canvas.height - 1);\n return {\n col: Math.floor(coords[0] / this._renderService.dimensions.css.cell.width),\n row: Math.floor(coords[1] / this._renderService.dimensions.css.cell.height),\n x: Math.floor(coords[0]),\n y: Math.floor(coords[1])\n };\n }\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { RenderDebouncer } from 'browser/RenderDebouncer';\nimport { IRenderDebouncerWithCallback } from 'browser/Types';\nimport { IRenderDimensions, IRenderer } from 'browser/renderer/shared/Types';\nimport { ICharSizeService, ICoreBrowserService, IRenderService, IThemeService } from 'browser/services/Services';\nimport { Disposable, MutableDisposable, toDisposable } from 'vs/base/common/lifecycle';\nimport { DebouncedIdleTask } from 'common/TaskQueue';\nimport { IBufferService, ICoreService, IDecorationService, IOptionsService } from 'common/services/Services';\nimport { Emitter } from 'vs/base/common/event';\n\ninterface ISelectionState {\n start: [number, number] | undefined;\n end: [number, number] | undefined;\n columnSelectMode: boolean;\n}\n\nconst enum Constants {\n SYNCHRONIZED_OUTPUT_TIMEOUT_MS = 1000\n}\n\nexport class RenderService extends Disposable implements IRenderService {\n public serviceBrand: undefined;\n\n private _renderer: MutableDisposable = this._register(new MutableDisposable());\n private _renderDebouncer: IRenderDebouncerWithCallback;\n private _pausedResizeTask = new DebouncedIdleTask();\n private _observerDisposable = this._register(new MutableDisposable());\n\n private _isPaused: boolean = false;\n private _needsFullRefresh: boolean = false;\n private _isNextRenderRedrawOnly: boolean = true;\n private _needsSelectionRefresh: boolean = false;\n private _canvasWidth: number = 0;\n private _canvasHeight: number = 0;\n private _syncOutputHandler: SynchronizedOutputHandler;\n private _selectionState: ISelectionState = {\n start: undefined,\n end: undefined,\n columnSelectMode: false\n };\n\n private readonly _onDimensionsChange = this._register(new Emitter());\n public readonly onDimensionsChange = this._onDimensionsChange.event;\n private readonly _onRenderedViewportChange = this._register(new Emitter<{ start: number, end: number }>());\n public readonly onRenderedViewportChange = this._onRenderedViewportChange.event;\n private readonly _onRender = this._register(new Emitter<{ start: number, end: number }>());\n public readonly onRender = this._onRender.event;\n private readonly _onRefreshRequest = this._register(new Emitter<{ start: number, end: number }>());\n public readonly onRefreshRequest = this._onRefreshRequest.event;\n\n public get dimensions(): IRenderDimensions { return this._renderer.value!.dimensions; }\n\n constructor(\n private _rowCount: number,\n screenElement: HTMLElement,\n @IOptionsService private readonly _optionsService: IOptionsService,\n @ICharSizeService private readonly _charSizeService: ICharSizeService,\n @ICoreService private readonly _coreService: ICoreService,\n @IDecorationService decorationService: IDecorationService,\n @IBufferService bufferService: IBufferService,\n @ICoreBrowserService private readonly _coreBrowserService: ICoreBrowserService,\n @IThemeService themeService: IThemeService\n ) {\n super();\n\n this._renderDebouncer = new RenderDebouncer((start, end) => this._renderRows(start, end), this._coreBrowserService);\n this._register(this._renderDebouncer);\n\n this._syncOutputHandler = new SynchronizedOutputHandler(\n this._coreBrowserService,\n this._coreService,\n () => this._fullRefresh()\n );\n this._register(toDisposable(() => this._syncOutputHandler.dispose()));\n\n this._register(this._coreBrowserService.onDprChange(() => this.handleDevicePixelRatioChange()));\n\n this._register(bufferService.onResize(() => this._fullRefresh()));\n this._register(bufferService.buffers.onBufferActivate(() => this._renderer.value?.clear()));\n this._register(this._optionsService.onOptionChange(() => this._handleOptionsChanged()));\n this._register(this._charSizeService.onCharSizeChange(() => this.handleCharSizeChanged()));\n\n // Do a full refresh whenever any decoration is added or removed. This may not actually result\n // in changes but since decorations should be used sparingly or added/removed all in the same\n // frame this should have minimal performance impact.\n this._register(decorationService.onDecorationRegistered(() => this._fullRefresh()));\n this._register(decorationService.onDecorationRemoved(() => this._fullRefresh()));\n\n // Clear the renderer when the a change that could affect glyphs occurs\n this._register(this._optionsService.onMultipleOptionChange([\n 'customGlyphs',\n 'drawBoldTextInBrightColors',\n 'letterSpacing',\n 'lineHeight',\n 'fontFamily',\n 'fontSize',\n 'fontWeight',\n 'fontWeightBold',\n 'minimumContrastRatio',\n 'rescaleOverlappingGlyphs'\n ], () => {\n this.clear();\n this.handleResize(bufferService.cols, bufferService.rows);\n this._fullRefresh();\n }));\n\n // Refresh the cursor line when the cursor changes\n this._register(this._optionsService.onMultipleOptionChange([\n 'cursorBlink',\n 'cursorStyle'\n ], () => this.refreshRows(bufferService.buffer.y, bufferService.buffer.y, true)));\n\n this._register(themeService.onChangeColors(() => this._fullRefresh()));\n\n this._registerIntersectionObserver(this._coreBrowserService.window, screenElement);\n this._register(this._coreBrowserService.onWindowChange((w) => this._registerIntersectionObserver(w, screenElement)));\n }\n\n private _registerIntersectionObserver(w: Window & typeof globalThis, screenElement: HTMLElement): void {\n // Detect whether IntersectionObserver is detected and enable renderer pause\n // and resume based on terminal visibility if so\n if ('IntersectionObserver' in w) {\n const observer = new w.IntersectionObserver(e => this._handleIntersectionChange(e[e.length - 1]), { threshold: 0 });\n observer.observe(screenElement);\n this._observerDisposable.value = toDisposable(() => observer.disconnect());\n }\n }\n\n private _handleIntersectionChange(entry: IntersectionObserverEntry): void {\n this._isPaused = entry.isIntersecting === undefined ? (entry.intersectionRatio === 0) : !entry.isIntersecting;\n\n // Terminal was hidden on open\n if (!this._isPaused && !this._charSizeService.hasValidSize) {\n this._charSizeService.measure();\n }\n\n if (!this._isPaused && this._needsFullRefresh) {\n this._pausedResizeTask.flush();\n this.refreshRows(0, this._rowCount - 1);\n this._needsFullRefresh = false;\n }\n }\n\n public refreshRows(start: number, end: number, isRedrawOnly: boolean = false): void {\n if (this._isPaused) {\n this._needsFullRefresh = true;\n return;\n }\n\n if (this._coreService.decPrivateModes.synchronizedOutput) {\n this._syncOutputHandler.bufferRows(start, end);\n return;\n }\n\n const buffered = this._syncOutputHandler.flush();\n if (buffered) {\n start = Math.min(start, buffered.start);\n end = Math.max(end, buffered.end);\n }\n\n if (!isRedrawOnly) {\n this._isNextRenderRedrawOnly = false;\n }\n this._renderDebouncer.refresh(start, end, this._rowCount);\n }\n\n private _renderRows(start: number, end: number): void {\n if (!this._renderer.value) {\n return;\n }\n\n // Skip rendering if synchronized output mode is enabled. This check must happen here\n // (in addition to refreshRows) to handle renders that were queued before the mode was enabled.\n if (this._coreService.decPrivateModes.synchronizedOutput) {\n this._syncOutputHandler.bufferRows(start, end);\n return;\n }\n\n // Since this is debounced, a resize event could have happened between the time a refresh was\n // requested and when this triggers. Clamp the values of start and end to ensure they're valid\n // given the current viewport state.\n start = Math.min(start, this._rowCount - 1);\n end = Math.min(end, this._rowCount - 1);\n\n // Render\n this._renderer.value.renderRows(start, end);\n\n // Update selection if needed\n if (this._needsSelectionRefresh) {\n this._renderer.value.handleSelectionChanged(this._selectionState.start, this._selectionState.end, this._selectionState.columnSelectMode);\n this._needsSelectionRefresh = false;\n }\n\n // Fire render event only if it was not a redraw\n if (!this._isNextRenderRedrawOnly) {\n this._onRenderedViewportChange.fire({ start, end });\n }\n this._onRender.fire({ start, end });\n this._isNextRenderRedrawOnly = true;\n }\n\n public resize(cols: number, rows: number): void {\n this._rowCount = rows;\n this._fireOnCanvasResize();\n }\n\n private _handleOptionsChanged(): void {\n if (!this._renderer.value) {\n return;\n }\n this.refreshRows(0, this._rowCount - 1);\n this._fireOnCanvasResize();\n }\n\n private _fireOnCanvasResize(): void {\n if (!this._renderer.value) {\n return;\n }\n // Don't fire the event if the dimensions haven't changed\n if (this._renderer.value.dimensions.css.canvas.width === this._canvasWidth && this._renderer.value.dimensions.css.canvas.height === this._canvasHeight) {\n return;\n }\n this._onDimensionsChange.fire(this._renderer.value.dimensions);\n }\n\n public hasRenderer(): boolean {\n return !!this._renderer.value;\n }\n\n public setRenderer(renderer: IRenderer): void {\n this._renderer.value = renderer;\n // If the value was not set, the terminal is being disposed so ignore it\n if (this._renderer.value) {\n this._renderer.value.onRequestRedraw(e => this.refreshRows(e.start, e.end, true));\n\n // Force a refresh\n this._needsSelectionRefresh = true;\n this._fullRefresh();\n }\n }\n\n public addRefreshCallback(callback: FrameRequestCallback): number {\n return this._renderDebouncer.addRefreshCallback(callback);\n }\n\n private _fullRefresh(): void {\n if (this._isPaused) {\n this._needsFullRefresh = true;\n } else {\n this.refreshRows(0, this._rowCount - 1);\n }\n }\n\n public clearTextureAtlas(): void {\n if (!this._renderer.value) {\n return;\n }\n this._renderer.value.clearTextureAtlas?.();\n this._fullRefresh();\n }\n\n public handleDevicePixelRatioChange(): void {\n // Force char size measurement as DomMeasureStrategy(getBoundingClientRect) is not stable\n // when devicePixelRatio changes\n this._charSizeService.measure();\n\n if (!this._renderer.value) {\n return;\n }\n this._renderer.value.handleDevicePixelRatioChange();\n this.refreshRows(0, this._rowCount - 1);\n }\n\n public handleResize(cols: number, rows: number): void {\n if (!this._renderer.value) {\n return;\n }\n if (this._isPaused) {\n this._pausedResizeTask.set(() => this._renderer.value?.handleResize(cols, rows));\n } else {\n this._renderer.value.handleResize(cols, rows);\n }\n this._fullRefresh();\n }\n\n // TODO: Is this useful when we have onResize?\n public handleCharSizeChanged(): void {\n this._renderer.value?.handleCharSizeChanged();\n }\n\n public handleBlur(): void {\n this._renderer.value?.handleBlur();\n }\n\n public handleFocus(): void {\n this._renderer.value?.handleFocus();\n }\n\n public handleSelectionChanged(start: [number, number] | undefined, end: [number, number] | undefined, columnSelectMode: boolean): void {\n this._selectionState.start = start;\n this._selectionState.end = end;\n this._selectionState.columnSelectMode = columnSelectMode;\n this._renderer.value?.handleSelectionChanged(start, end, columnSelectMode);\n }\n\n public handleCursorMove(): void {\n this._renderer.value?.handleCursorMove();\n }\n\n public clear(): void {\n this._renderer.value?.clear();\n }\n}\n\n/**\n * Buffers row refresh requests during synchronized output mode (DEC mode 2026).\n * When the mode is disabled, the accumulated row range is flushed for rendering.\n * A safety timeout ensures rendering occurs even if the end sequence is not received.\n */\nclass SynchronizedOutputHandler {\n private _start: number = 0;\n private _end: number = 0;\n private _timeout: number | undefined;\n private _isBuffering: boolean = false;\n\n constructor(\n private readonly _coreBrowserService: ICoreBrowserService,\n private readonly _coreService: ICoreService,\n private readonly _onTimeout: () => void\n ) {}\n\n public bufferRows(start: number, end: number): void {\n if (!this._isBuffering) {\n this._start = start;\n this._end = end;\n this._isBuffering = true;\n } else {\n this._start = Math.min(this._start, start);\n this._end = Math.max(this._end, end);\n }\n\n if (this._timeout === undefined) {\n this._timeout = this._coreBrowserService.window.setTimeout(() => {\n this._timeout = undefined;\n this._coreService.decPrivateModes.synchronizedOutput = false;\n this._onTimeout();\n }, Constants.SYNCHRONIZED_OUTPUT_TIMEOUT_MS);\n }\n }\n\n public flush(): { start: number, end: number } | undefined {\n if (this._timeout !== undefined) {\n this._coreBrowserService.window.clearTimeout(this._timeout);\n this._timeout = undefined;\n }\n\n if (!this._isBuffering) {\n return undefined;\n }\n\n const result = { start: this._start, end: this._end };\n this._isBuffering = false;\n return result;\n }\n\n public dispose(): void {\n if (this._timeout !== undefined) {\n this._coreBrowserService.window.clearTimeout(this._timeout);\n this._timeout = undefined;\n }\n }\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IBufferRange, ILinkifier2 } from 'browser/Types';\nimport { getCoordsRelativeToElement } from 'browser/input/Mouse';\nimport { moveToCellSequence } from 'browser/input/MoveToCell';\nimport { SelectionModel } from 'browser/selection/SelectionModel';\nimport { ISelectionRedrawRequestEvent, ISelectionRequestScrollLinesEvent } from 'browser/selection/Types';\nimport { ICoreBrowserService, IMouseService, IRenderService, ISelectionService } from 'browser/services/Services';\nimport { Disposable, toDisposable } from 'vs/base/common/lifecycle';\nimport * as Browser from 'common/Platform';\nimport { IBufferLine, IDisposable } from 'common/Types';\nimport { getRangeLength } from 'common/buffer/BufferRange';\nimport { CellData } from 'common/buffer/CellData';\nimport { IBuffer } from 'common/buffer/Types';\nimport { IBufferService, ICoreService, IOptionsService } from 'common/services/Services';\nimport { Emitter } from 'vs/base/common/event';\n\n/**\n * The number of pixels the mouse needs to be above or below the viewport in\n * order to scroll at the maximum speed.\n */\nconst DRAG_SCROLL_MAX_THRESHOLD = 50;\n\n/**\n * The maximum scrolling speed\n */\nconst DRAG_SCROLL_MAX_SPEED = 15;\n\n/**\n * The number of milliseconds between drag scroll updates.\n */\nconst DRAG_SCROLL_INTERVAL = 50;\n\n/**\n * The maximum amount of time that can have elapsed for an alt click to move the\n * cursor.\n */\nconst ALT_CLICK_MOVE_CURSOR_TIME = 500;\n\nconst NON_BREAKING_SPACE_CHAR = String.fromCharCode(160);\nconst ALL_NON_BREAKING_SPACE_REGEX = new RegExp(NON_BREAKING_SPACE_CHAR, 'g');\n\n/**\n * Represents a position of a word on a line.\n */\ninterface IWordPosition {\n start: number;\n length: number;\n}\n\n/**\n * A selection mode, this drives how the selection behaves on mouse move.\n */\nexport const enum SelectionMode {\n NORMAL,\n WORD,\n LINE,\n COLUMN\n}\n\n/**\n * A class that manages the selection of the terminal. With help from\n * SelectionModel, SelectionService handles with all logic associated with\n * dealing with the selection, including handling mouse interaction, wide\n * characters and fetching the actual text within the selection. Rendering is\n * not handled by the SelectionService but the onRedrawRequest event is fired\n * when the selection is ready to be redrawn (on an animation frame).\n */\nexport class SelectionService extends Disposable implements ISelectionService {\n public serviceBrand: undefined;\n\n protected _model: SelectionModel;\n\n /**\n * The amount to scroll every drag scroll update (depends on how far the mouse\n * drag is above or below the terminal).\n */\n private _dragScrollAmount: number = 0;\n\n /**\n * The current selection mode.\n */\n protected _activeSelectionMode: SelectionMode;\n\n /**\n * A setInterval timer that is active while the mouse is down whose callback\n * scrolls the viewport when necessary.\n */\n private _dragScrollIntervalTimer: number | undefined;\n\n /**\n * The animation frame ID used for refreshing the selection.\n */\n private _refreshAnimationFrame: number | undefined;\n\n /**\n * Whether selection is enabled.\n */\n private _enabled = true;\n\n private _mouseMoveListener: EventListener;\n private _mouseUpListener: EventListener;\n private _trimListener: IDisposable;\n private _workCell: CellData = new CellData();\n\n private _mouseDownTimeStamp: number = 0;\n private _oldHasSelection: boolean = false;\n private _oldSelectionStart: [number, number] | undefined = undefined;\n private _oldSelectionEnd: [number, number] | undefined = undefined;\n\n private readonly _onLinuxMouseSelection = this._register(new Emitter());\n public readonly onLinuxMouseSelection = this._onLinuxMouseSelection.event;\n private readonly _onRedrawRequest = this._register(new Emitter());\n public readonly onRequestRedraw = this._onRedrawRequest.event;\n private readonly _onSelectionChange = this._register(new Emitter());\n public readonly onSelectionChange = this._onSelectionChange.event;\n private readonly _onRequestScrollLines = this._register(new Emitter());\n public readonly onRequestScrollLines = this._onRequestScrollLines.event;\n\n constructor(\n private readonly _element: HTMLElement,\n private readonly _screenElement: HTMLElement,\n private readonly _linkifier: ILinkifier2,\n @IBufferService private readonly _bufferService: IBufferService,\n @ICoreService private readonly _coreService: ICoreService,\n @IMouseService private readonly _mouseService: IMouseService,\n @IOptionsService private readonly _optionsService: IOptionsService,\n @IRenderService private readonly _renderService: IRenderService,\n @ICoreBrowserService private readonly _coreBrowserService: ICoreBrowserService\n ) {\n super();\n\n // Init listeners\n this._mouseMoveListener = event => this._handleMouseMove(event as MouseEvent);\n this._mouseUpListener = event => this._handleMouseUp(event as MouseEvent);\n this._coreService.onUserInput(() => {\n if (this.hasSelection) {\n this.clearSelection();\n }\n });\n this._trimListener = this._bufferService.buffer.lines.onTrim(amount => this._handleTrim(amount));\n this._register(this._bufferService.buffers.onBufferActivate(e => this._handleBufferActivate(e)));\n\n this.enable();\n\n this._model = new SelectionModel(this._bufferService);\n this._activeSelectionMode = SelectionMode.NORMAL;\n\n this._register(toDisposable(() => {\n this._removeMouseDownListeners();\n }));\n\n // Clear selection when resizing vertically. This experience could be improved, this is the\n // simple option to fix the buggy behavior. https://github.com/xtermjs/xterm.js/issues/5300\n this._register(this._bufferService.onResize(e => {\n if (e.rowsChanged) {\n this.clearSelection();\n }\n }));\n }\n\n public reset(): void {\n this.clearSelection();\n }\n\n /**\n * Disables the selection manager. This is useful for when terminal mouse\n * are enabled.\n */\n public disable(): void {\n this.clearSelection();\n this._enabled = false;\n }\n\n /**\n * Enable the selection manager.\n */\n public enable(): void {\n this._enabled = true;\n }\n\n public get selectionStart(): [number, number] | undefined { return this._model.finalSelectionStart; }\n public get selectionEnd(): [number, number] | undefined { return this._model.finalSelectionEnd; }\n\n /**\n * Gets whether there is an active text selection.\n */\n public get hasSelection(): boolean {\n const start = this._model.finalSelectionStart;\n const end = this._model.finalSelectionEnd;\n if (!start || !end) {\n return false;\n }\n return start[0] !== end[0] || start[1] !== end[1];\n }\n\n /**\n * Gets the text currently selected.\n */\n public get selectionText(): string {\n const start = this._model.finalSelectionStart;\n const end = this._model.finalSelectionEnd;\n if (!start || !end) {\n return '';\n }\n\n const buffer = this._bufferService.buffer;\n const result: string[] = [];\n\n if (this._activeSelectionMode === SelectionMode.COLUMN) {\n // Ignore zero width selections\n if (start[0] === end[0]) {\n return '';\n }\n\n // For column selection it's not enough to rely on final selection's swapping of reversed\n // values, it also needs the x coordinates to swap independently of the y coordinate is needed\n const startCol = start[0] < end[0] ? start[0] : end[0];\n const endCol = start[0] < end[0] ? end[0] : start[0];\n for (let i = start[1]; i <= end[1]; i++) {\n const lineText = buffer.translateBufferLineToString(i, true, startCol, endCol);\n result.push(lineText);\n }\n } else {\n // Get first row\n const startRowEndCol = start[1] === end[1] ? end[0] : undefined;\n result.push(buffer.translateBufferLineToString(start[1], true, start[0], startRowEndCol));\n\n // Get middle rows\n for (let i = start[1] + 1; i <= end[1] - 1; i++) {\n const bufferLine = buffer.lines.get(i);\n const lineText = buffer.translateBufferLineToString(i, true);\n if (bufferLine?.isWrapped) {\n result[result.length - 1] += lineText;\n } else {\n result.push(lineText);\n }\n }\n\n // Get final row\n if (start[1] !== end[1]) {\n const bufferLine = buffer.lines.get(end[1]);\n const lineText = buffer.translateBufferLineToString(end[1], true, 0, end[0]);\n if (bufferLine && bufferLine!.isWrapped) {\n result[result.length - 1] += lineText;\n } else {\n result.push(lineText);\n }\n }\n }\n\n // Format string by replacing non-breaking space chars with regular spaces\n // and joining the array into a multi-line string.\n const formattedResult = result.map(line => {\n return line.replace(ALL_NON_BREAKING_SPACE_REGEX, ' ');\n }).join(Browser.isWindows ? '\\r\\n' : '\\n');\n\n return formattedResult;\n }\n\n /**\n * Clears the current terminal selection.\n */\n public clearSelection(): void {\n this._model.clearSelection();\n this._removeMouseDownListeners();\n this.refresh();\n this._onSelectionChange.fire();\n }\n\n /**\n * Queues a refresh, redrawing the selection on the next opportunity.\n * @param isLinuxMouseSelection Whether the selection should be registered as a new\n * selection on Linux.\n */\n public refresh(isLinuxMouseSelection?: boolean): void {\n // Queue the refresh for the renderer\n if (!this._refreshAnimationFrame) {\n this._refreshAnimationFrame = this._coreBrowserService.window.requestAnimationFrame(() => this._refresh());\n }\n\n // If the platform is Linux and the refresh call comes from a mouse event,\n // we need to update the selection for middle click to paste selection.\n if (Browser.isLinux && isLinuxMouseSelection) {\n const selectionText = this.selectionText;\n if (selectionText.length) {\n this._onLinuxMouseSelection.fire(this.selectionText);\n }\n }\n }\n\n /**\n * Fires the refresh event, causing consumers to pick it up and redraw the\n * selection state.\n */\n private _refresh(): void {\n this._refreshAnimationFrame = undefined;\n this._onRedrawRequest.fire({\n start: this._model.finalSelectionStart,\n end: this._model.finalSelectionEnd,\n columnSelectMode: this._activeSelectionMode === SelectionMode.COLUMN\n });\n }\n\n /**\n * Checks if the current click was inside the current selection\n * @param event The mouse event\n */\n private _isClickInSelection(event: MouseEvent): boolean {\n const coords = this._getMouseBufferCoords(event);\n const start = this._model.finalSelectionStart;\n const end = this._model.finalSelectionEnd;\n\n if (!start || !end || !coords) {\n return false;\n }\n\n return this._areCoordsInSelection(coords, start, end);\n }\n\n public isCellInSelection(x: number, y: number): boolean {\n const start = this._model.finalSelectionStart;\n const end = this._model.finalSelectionEnd;\n if (!start || !end) {\n return false;\n }\n return this._areCoordsInSelection([x, y], start, end);\n }\n\n protected _areCoordsInSelection(coords: [number, number], start: [number, number], end: [number, number]): boolean {\n return (coords[1] > start[1] && coords[1] < end[1]) ||\n (start[1] === end[1] && coords[1] === start[1] && coords[0] >= start[0] && coords[0] < end[0]) ||\n (start[1] < end[1] && coords[1] === end[1] && coords[0] < end[0]) ||\n (start[1] < end[1] && coords[1] === start[1] && coords[0] >= start[0]);\n }\n\n /**\n * Selects word at the current mouse event coordinates.\n * @param event The mouse event.\n */\n private _selectWordAtCursor(event: MouseEvent, allowWhitespaceOnlySelection: boolean): boolean {\n // Check if there is a link under the cursor first and select that if so\n const range = this._linkifier.currentLink?.link?.range;\n if (range) {\n this._model.selectionStart = [range.start.x - 1, range.start.y - 1];\n this._model.selectionStartLength = getRangeLength(range, this._bufferService.cols);\n this._model.selectionEnd = undefined;\n return true;\n }\n\n const coords = this._getMouseBufferCoords(event);\n if (coords) {\n this._selectWordAt(coords, allowWhitespaceOnlySelection);\n this._model.selectionEnd = undefined;\n return true;\n }\n return false;\n }\n\n /**\n * Selects all text within the terminal.\n */\n public selectAll(): void {\n this._model.isSelectAllActive = true;\n this.refresh();\n this._onSelectionChange.fire();\n }\n\n public selectLines(start: number, end: number): void {\n this._model.clearSelection();\n start = Math.max(start, 0);\n end = Math.min(end, this._bufferService.buffer.lines.length - 1);\n this._model.selectionStart = [0, start];\n this._model.selectionEnd = [this._bufferService.cols, end];\n this.refresh();\n this._onSelectionChange.fire();\n }\n\n /**\n * Handle the buffer being trimmed, adjust the selection position.\n * @param amount The amount the buffer is being trimmed.\n */\n private _handleTrim(amount: number): void {\n const needsRefresh = this._model.handleTrim(amount);\n if (needsRefresh) {\n this.refresh();\n }\n }\n\n /**\n * Gets the 0-based [x, y] buffer coordinates of the current mouse event.\n * @param event The mouse event.\n */\n private _getMouseBufferCoords(event: MouseEvent): [number, number] | undefined {\n const coords = this._mouseService.getCoords(event, this._screenElement, this._bufferService.cols, this._bufferService.rows, true);\n if (!coords) {\n return undefined;\n }\n\n // Convert to 0-based\n coords[0]--;\n coords[1]--;\n\n // Convert viewport coords to buffer coords\n coords[1] += this._bufferService.buffer.ydisp;\n return coords;\n }\n\n /**\n * Gets the amount the viewport should be scrolled based on how far out of the\n * terminal the mouse is.\n * @param event The mouse event.\n */\n private _getMouseEventScrollAmount(event: MouseEvent): number {\n let offset = getCoordsRelativeToElement(this._coreBrowserService.window, event, this._screenElement)[1];\n const terminalHeight = this._renderService.dimensions.css.canvas.height;\n if (offset >= 0 && offset <= terminalHeight) {\n return 0;\n }\n if (offset > terminalHeight) {\n offset -= terminalHeight;\n }\n\n offset = Math.min(Math.max(offset, -DRAG_SCROLL_MAX_THRESHOLD), DRAG_SCROLL_MAX_THRESHOLD);\n offset /= DRAG_SCROLL_MAX_THRESHOLD;\n return (offset / Math.abs(offset)) + Math.round(offset * (DRAG_SCROLL_MAX_SPEED - 1));\n }\n\n /**\n * Returns whether the selection manager should force selection, regardless of\n * whether the terminal is in mouse events mode.\n * @param event The mouse event.\n */\n public shouldForceSelection(event: MouseEvent): boolean {\n if (Browser.isMac) {\n return event.altKey && this._optionsService.rawOptions.macOptionClickForcesSelection;\n }\n\n return event.shiftKey;\n }\n\n /**\n * Handles te mousedown event, setting up for a new selection.\n * @param event The mousedown event.\n */\n public handleMouseDown(event: MouseEvent): void {\n this._mouseDownTimeStamp = event.timeStamp;\n // If we have selection, we want the context menu on right click even if the\n // terminal is in mouse mode.\n if (event.button === 2 && this.hasSelection) {\n return;\n }\n\n // Only action the primary button\n if (event.button !== 0) {\n return;\n }\n\n // Allow selection when using a specific modifier key, even when disabled\n if (!this._enabled) {\n if (!this.shouldForceSelection(event)) {\n return;\n }\n\n // Don't send the mouse down event to the current process, we want to select\n event.stopPropagation();\n }\n\n // Tell the browser not to start a regular selection\n event.preventDefault();\n\n // Reset drag scroll state\n this._dragScrollAmount = 0;\n\n if (this._enabled && event.shiftKey) {\n this._handleIncrementalClick(event);\n } else {\n if (event.detail === 1) {\n this._handleSingleClick(event);\n } else if (event.detail === 2) {\n this._handleDoubleClick(event);\n } else if (event.detail === 3) {\n this._handleTripleClick(event);\n }\n }\n\n this._addMouseDownListeners();\n this.refresh(true);\n }\n\n /**\n * Adds listeners when mousedown is triggered.\n */\n private _addMouseDownListeners(): void {\n // Listen on the document so that dragging outside of viewport works\n if (this._screenElement.ownerDocument) {\n this._screenElement.ownerDocument.addEventListener('mousemove', this._mouseMoveListener);\n this._screenElement.ownerDocument.addEventListener('mouseup', this._mouseUpListener);\n }\n this._dragScrollIntervalTimer = this._coreBrowserService.window.setInterval(() => this._dragScroll(), DRAG_SCROLL_INTERVAL);\n }\n\n /**\n * Removes the listeners that are registered when mousedown is triggered.\n */\n private _removeMouseDownListeners(): void {\n if (this._screenElement.ownerDocument) {\n this._screenElement.ownerDocument.removeEventListener('mousemove', this._mouseMoveListener);\n this._screenElement.ownerDocument.removeEventListener('mouseup', this._mouseUpListener);\n }\n this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer);\n this._dragScrollIntervalTimer = undefined;\n }\n\n /**\n * Performs an incremental click, setting the selection end position to the mouse\n * position.\n * @param event The mouse event.\n */\n private _handleIncrementalClick(event: MouseEvent): void {\n if (this._model.selectionStart) {\n this._model.selectionEnd = this._getMouseBufferCoords(event);\n }\n }\n\n /**\n * Performs a single click, resetting relevant state and setting the selection\n * start position.\n * @param event The mouse event.\n */\n private _handleSingleClick(event: MouseEvent): void {\n this._model.selectionStartLength = 0;\n this._model.isSelectAllActive = false;\n this._activeSelectionMode = this.shouldColumnSelect(event) ? SelectionMode.COLUMN : SelectionMode.NORMAL;\n\n // Initialize the new selection\n this._model.selectionStart = this._getMouseBufferCoords(event);\n if (!this._model.selectionStart) {\n return;\n }\n this._model.selectionEnd = undefined;\n\n // Ensure the line exists\n const line = this._bufferService.buffer.lines.get(this._model.selectionStart[1]);\n if (!line) {\n return;\n }\n\n // Return early if the click event is not in the buffer (eg. in scroll bar)\n if (line.length === this._model.selectionStart[0]) {\n return;\n }\n\n // If the mouse is over the second half of a wide character, adjust the\n // selection to cover the whole character\n if (line.hasWidth(this._model.selectionStart[0]) === 0) {\n this._model.selectionStart[0]++;\n }\n }\n\n /**\n * Performs a double click, selecting the current word.\n * @param event The mouse event.\n */\n private _handleDoubleClick(event: MouseEvent): void {\n if (this._selectWordAtCursor(event, true)) {\n this._activeSelectionMode = SelectionMode.WORD;\n }\n }\n\n /**\n * Performs a triple click, selecting the current line and activating line\n * select mode.\n * @param event The mouse event.\n */\n private _handleTripleClick(event: MouseEvent): void {\n const coords = this._getMouseBufferCoords(event);\n if (coords) {\n this._activeSelectionMode = SelectionMode.LINE;\n this._selectLineAt(coords[1]);\n }\n }\n\n /**\n * Returns whether the selection manager should operate in column select mode\n * @param event the mouse or keyboard event\n */\n public shouldColumnSelect(event: KeyboardEvent | MouseEvent): boolean {\n return event.altKey && !(Browser.isMac && this._optionsService.rawOptions.macOptionClickForcesSelection);\n }\n\n /**\n * Handles the mousemove event when the mouse button is down, recording the\n * end of the selection and refreshing the selection.\n * @param event The mousemove event.\n */\n private _handleMouseMove(event: MouseEvent): void {\n // If the mousemove listener is active it means that a selection is\n // currently being made, we should stop propagation to prevent mouse events\n // to be sent to the pty.\n event.stopImmediatePropagation();\n\n // Do nothing if there is no selection start, this can happen if the first\n // click in the terminal is an incremental click\n if (!this._model.selectionStart) {\n return;\n }\n\n // Record the previous position so we know whether to redraw the selection\n // at the end.\n const previousSelectionEnd = this._model.selectionEnd ? [this._model.selectionEnd[0], this._model.selectionEnd[1]] : null;\n\n // Set the initial selection end based on the mouse coordinates\n this._model.selectionEnd = this._getMouseBufferCoords(event);\n if (!this._model.selectionEnd) {\n this.refresh(true);\n return;\n }\n\n // Select the entire line if line select mode is active.\n if (this._activeSelectionMode === SelectionMode.LINE) {\n if (this._model.selectionEnd[1] < this._model.selectionStart[1]) {\n this._model.selectionEnd[0] = 0;\n } else {\n this._model.selectionEnd[0] = this._bufferService.cols;\n }\n } else if (this._activeSelectionMode === SelectionMode.WORD) {\n this._selectToWordAt(this._model.selectionEnd);\n }\n\n // Determine the amount of scrolling that will happen.\n this._dragScrollAmount = this._getMouseEventScrollAmount(event);\n\n // If the cursor was above or below the viewport, make sure it's at the\n // start or end of the viewport respectively. This should only happen when\n // NOT in column select mode.\n if (this._activeSelectionMode !== SelectionMode.COLUMN) {\n if (this._dragScrollAmount > 0) {\n this._model.selectionEnd[0] = this._bufferService.cols;\n } else if (this._dragScrollAmount < 0) {\n this._model.selectionEnd[0] = 0;\n }\n }\n\n // If the character is a wide character include the cell to the right in the\n // selection. Note that selections at the very end of the line will never\n // have a character.\n const buffer = this._bufferService.buffer;\n if (this._model.selectionEnd[1] < buffer.lines.length) {\n const line = buffer.lines.get(this._model.selectionEnd[1]);\n if (line && line.hasWidth(this._model.selectionEnd[0]) === 0) {\n if (this._model.selectionEnd[0] < this._bufferService.cols) {\n this._model.selectionEnd[0]++;\n }\n }\n }\n\n // Only draw here if the selection changes.\n if (!previousSelectionEnd ||\n previousSelectionEnd[0] !== this._model.selectionEnd[0] ||\n previousSelectionEnd[1] !== this._model.selectionEnd[1]) {\n this.refresh(true);\n }\n }\n\n /**\n * The callback that occurs every DRAG_SCROLL_INTERVAL ms that does the\n * scrolling of the viewport.\n */\n private _dragScroll(): void {\n if (!this._model.selectionEnd || !this._model.selectionStart) {\n return;\n }\n if (this._dragScrollAmount) {\n this._onRequestScrollLines.fire({ amount: this._dragScrollAmount, suppressScrollEvent: false });\n // Re-evaluate selection\n // If the cursor was above or below the viewport, make sure it's at the\n // start or end of the viewport respectively. This should only happen when\n // NOT in column select mode.\n const buffer = this._bufferService.buffer;\n if (this._dragScrollAmount > 0) {\n if (this._activeSelectionMode !== SelectionMode.COLUMN) {\n this._model.selectionEnd[0] = this._bufferService.cols;\n }\n this._model.selectionEnd[1] = Math.min(buffer.ydisp + this._bufferService.rows, buffer.lines.length - 1);\n } else {\n if (this._activeSelectionMode !== SelectionMode.COLUMN) {\n this._model.selectionEnd[0] = 0;\n }\n this._model.selectionEnd[1] = buffer.ydisp;\n }\n this.refresh();\n }\n }\n\n /**\n * Handles the mouseup event, removing the mousedown listeners.\n * @param event The mouseup event.\n */\n private _handleMouseUp(event: MouseEvent): void {\n const timeElapsed = event.timeStamp - this._mouseDownTimeStamp;\n\n this._removeMouseDownListeners();\n\n if (this.selectionText.length <= 1 && timeElapsed < ALT_CLICK_MOVE_CURSOR_TIME && event.altKey && this._optionsService.rawOptions.altClickMovesCursor) {\n if (this._bufferService.buffer.ybase === this._bufferService.buffer.ydisp) {\n const coordinates = this._mouseService.getCoords(\n event,\n this._element,\n this._bufferService.cols,\n this._bufferService.rows,\n false\n );\n if (coordinates && coordinates[0] !== undefined && coordinates[1] !== undefined) {\n const sequence = moveToCellSequence(coordinates[0] - 1, coordinates[1] - 1, this._bufferService, this._coreService.decPrivateModes.applicationCursorKeys);\n this._coreService.triggerDataEvent(sequence, true);\n }\n }\n } else {\n this._fireEventIfSelectionChanged();\n }\n }\n\n private _fireEventIfSelectionChanged(): void {\n const start = this._model.finalSelectionStart;\n const end = this._model.finalSelectionEnd;\n const hasSelection = !!start && !!end && (start[0] !== end[0] || start[1] !== end[1]);\n\n if (!hasSelection) {\n if (this._oldHasSelection) {\n this._fireOnSelectionChange(start, end, hasSelection);\n }\n return;\n }\n\n // Sanity check, these should not be undefined as there is a selection\n if (!start || !end) {\n return;\n }\n\n if (!this._oldSelectionStart || !this._oldSelectionEnd || (\n start[0] !== this._oldSelectionStart[0] || start[1] !== this._oldSelectionStart[1] ||\n end[0] !== this._oldSelectionEnd[0] || end[1] !== this._oldSelectionEnd[1])) {\n\n this._fireOnSelectionChange(start, end, hasSelection);\n }\n }\n\n private _fireOnSelectionChange(start: [number, number] | undefined, end: [number, number] | undefined, hasSelection: boolean): void {\n this._oldSelectionStart = start;\n this._oldSelectionEnd = end;\n this._oldHasSelection = hasSelection;\n this._onSelectionChange.fire();\n }\n\n private _handleBufferActivate(e: {activeBuffer: IBuffer, inactiveBuffer: IBuffer}): void {\n this.clearSelection();\n // Only adjust the selection on trim, shiftElements is rarely used (only in\n // reverseIndex) and delete in a splice is only ever used when the same\n // number of elements was just added. Given this is could actually be\n // beneficial to leave the selection as is for these cases.\n this._trimListener.dispose();\n this._trimListener = e.activeBuffer.lines.onTrim(amount => this._handleTrim(amount));\n }\n\n /**\n * Converts a viewport column (0 to cols - 1) to the character index on the\n * buffer line, the latter takes into account wide and null characters.\n * @param bufferLine The buffer line to use.\n * @param x The x index in the buffer line to convert.\n */\n private _convertViewportColToCharacterIndex(bufferLine: IBufferLine, x: number): number {\n let charIndex = x;\n for (let i = 0; x >= i; i++) {\n const length = bufferLine.loadCell(i, this._workCell).getChars().length;\n if (this._workCell.getWidth() === 0) {\n // Wide characters aren't included in the line string so decrement the\n // index so the index is back on the wide character.\n charIndex--;\n } else if (length > 1 && x !== i) {\n // Emojis take up multiple characters, so adjust accordingly. For these\n // we don't want ot include the character at the column as we're\n // returning the start index in the string, not the end index.\n charIndex += length - 1;\n }\n }\n return charIndex;\n }\n\n public setSelection(col: number, row: number, length: number): void {\n this._model.clearSelection();\n this._removeMouseDownListeners();\n this._model.selectionStart = [col, row];\n this._model.selectionStartLength = length;\n this.refresh();\n this._fireEventIfSelectionChanged();\n }\n\n public rightClickSelect(ev: MouseEvent): void {\n if (!this._isClickInSelection(ev)) {\n if (this._selectWordAtCursor(ev, false)) {\n this.refresh(true);\n }\n this._fireEventIfSelectionChanged();\n }\n }\n\n /**\n * Gets positional information for the word at the coordinated specified.\n * @param coords The coordinates to get the word at.\n */\n private _getWordAt(coords: [number, number], allowWhitespaceOnlySelection: boolean, followWrappedLinesAbove: boolean = true, followWrappedLinesBelow: boolean = true): IWordPosition | undefined {\n // Ensure coords are within viewport (eg. not within scroll bar)\n if (coords[0] >= this._bufferService.cols) {\n return undefined;\n }\n\n const buffer = this._bufferService.buffer;\n const bufferLine = buffer.lines.get(coords[1]);\n if (!bufferLine) {\n return undefined;\n }\n\n const line = buffer.translateBufferLineToString(coords[1], false);\n\n // Get actual index, taking into consideration wide characters\n let startIndex = this._convertViewportColToCharacterIndex(bufferLine, coords[0]);\n let endIndex = startIndex;\n\n // Record offset to be used later\n const charOffset = coords[0] - startIndex;\n let leftWideCharCount = 0;\n let rightWideCharCount = 0;\n let leftLongCharOffset = 0;\n let rightLongCharOffset = 0;\n\n if (line.charAt(startIndex) === ' ') {\n // Expand until non-whitespace is hit\n while (startIndex > 0 && line.charAt(startIndex - 1) === ' ') {\n startIndex--;\n }\n while (endIndex < line.length && line.charAt(endIndex + 1) === ' ') {\n endIndex++;\n }\n } else {\n // Expand until whitespace is hit. This algorithm works by scanning left\n // and right from the starting position, keeping both the index format\n // (line) and the column format (bufferLine) in sync. When a wide\n // character is hit, it is recorded and the column index is adjusted.\n let startCol = coords[0];\n let endCol = coords[0];\n\n // Consider the initial position, skip it and increment the wide char\n // variable\n if (bufferLine.getWidth(startCol) === 0) {\n leftWideCharCount++;\n startCol--;\n }\n if (bufferLine.getWidth(endCol) === 2) {\n rightWideCharCount++;\n endCol++;\n }\n\n // Adjust the end index for characters whose length are > 1 (emojis)\n const length = bufferLine.getString(endCol).length;\n if (length > 1) {\n rightLongCharOffset += length - 1;\n endIndex += length - 1;\n }\n\n // Expand the string in both directions until a space is hit\n while (startCol > 0 && startIndex > 0 && !this._isCharWordSeparator(bufferLine.loadCell(startCol - 1, this._workCell))) {\n bufferLine.loadCell(startCol - 1, this._workCell);\n const length = this._workCell.getChars().length;\n if (this._workCell.getWidth() === 0) {\n // If the next character is a wide char, record it and skip the column\n leftWideCharCount++;\n startCol--;\n } else if (length > 1) {\n // If the next character's string is longer than 1 char (eg. emoji),\n // adjust the index\n leftLongCharOffset += length - 1;\n startIndex -= length - 1;\n }\n startIndex--;\n startCol--;\n }\n while (endCol < bufferLine.length && endIndex + 1 < line.length && !this._isCharWordSeparator(bufferLine.loadCell(endCol + 1, this._workCell))) {\n bufferLine.loadCell(endCol + 1, this._workCell);\n const length = this._workCell.getChars().length;\n if (this._workCell.getWidth() === 2) {\n // If the next character is a wide char, record it and skip the column\n rightWideCharCount++;\n endCol++;\n } else if (length > 1) {\n // If the next character's string is longer than 1 char (eg. emoji),\n // adjust the index\n rightLongCharOffset += length - 1;\n endIndex += length - 1;\n }\n endIndex++;\n endCol++;\n }\n }\n\n // Incremenet the end index so it is at the start of the next character\n endIndex++;\n\n // Calculate the start _column_, converting the the string indexes back to\n // column coordinates.\n let start =\n startIndex // The index of the selection's start char in the line string\n + charOffset // The difference between the initial char's column and index\n - leftWideCharCount // The number of wide chars left of the initial char\n + leftLongCharOffset; // The number of additional chars left of the initial char added by columns with strings longer than 1 (emojis)\n\n // Calculate the length in _columns_, converting the the string indexes back\n // to column coordinates.\n let length = Math.min(this._bufferService.cols, // Disallow lengths larger than the terminal cols\n endIndex // The index of the selection's end char in the line string\n - startIndex // The index of the selection's start char in the line string\n + leftWideCharCount // The number of wide chars left of the initial char\n + rightWideCharCount // The number of wide chars right of the initial char (inclusive)\n - leftLongCharOffset // The number of additional chars left of the initial char added by columns with strings longer than 1 (emojis)\n - rightLongCharOffset); // The number of additional chars right of the initial char (inclusive) added by columns with strings longer than 1 (emojis)\n\n if (!allowWhitespaceOnlySelection && line.slice(startIndex, endIndex).trim() === '') {\n return undefined;\n }\n\n // Recurse upwards if the line is wrapped and the word wraps to the above line\n if (followWrappedLinesAbove) {\n if (start === 0 && bufferLine.getCodePoint(0) !== 32 /* ' ' */) {\n const previousBufferLine = buffer.lines.get(coords[1] - 1);\n if (previousBufferLine && bufferLine.isWrapped && previousBufferLine.getCodePoint(this._bufferService.cols - 1) !== 32 /* ' ' */) {\n const previousLineWordPosition = this._getWordAt([this._bufferService.cols - 1, coords[1] - 1], false, true, false);\n if (previousLineWordPosition) {\n const offset = this._bufferService.cols - previousLineWordPosition.start;\n start -= offset;\n length += offset;\n }\n }\n }\n }\n\n // Recurse downwards if the line is wrapped and the word wraps to the next line\n if (followWrappedLinesBelow) {\n if (start + length === this._bufferService.cols && bufferLine.getCodePoint(this._bufferService.cols - 1) !== 32 /* ' ' */) {\n const nextBufferLine = buffer.lines.get(coords[1] + 1);\n if (nextBufferLine?.isWrapped && nextBufferLine.getCodePoint(0) !== 32 /* ' ' */) {\n const nextLineWordPosition = this._getWordAt([0, coords[1] + 1], false, false, true);\n if (nextLineWordPosition) {\n length += nextLineWordPosition.length;\n }\n }\n }\n }\n\n return { start, length };\n }\n\n /**\n * Selects the word at the coordinates specified.\n * @param coords The coordinates to get the word at.\n * @param allowWhitespaceOnlySelection If whitespace should be selected\n */\n protected _selectWordAt(coords: [number, number], allowWhitespaceOnlySelection: boolean): void {\n const wordPosition = this._getWordAt(coords, allowWhitespaceOnlySelection);\n if (wordPosition) {\n // Adjust negative start value\n while (wordPosition.start < 0) {\n wordPosition.start += this._bufferService.cols;\n coords[1]--;\n }\n this._model.selectionStart = [wordPosition.start, coords[1]];\n this._model.selectionStartLength = wordPosition.length;\n }\n }\n\n /**\n * Sets the selection end to the word at the coordinated specified.\n * @param coords The coordinates to get the word at.\n */\n private _selectToWordAt(coords: [number, number]): void {\n const wordPosition = this._getWordAt(coords, true);\n if (wordPosition) {\n let endRow = coords[1];\n\n // Adjust negative start value\n while (wordPosition.start < 0) {\n wordPosition.start += this._bufferService.cols;\n endRow--;\n }\n\n // Adjust wrapped length value, this only needs to happen when values are reversed as in that\n // case we're interested in the start of the word, not the end\n if (!this._model.areSelectionValuesReversed()) {\n while (wordPosition.start + wordPosition.length > this._bufferService.cols) {\n wordPosition.length -= this._bufferService.cols;\n endRow++;\n }\n }\n\n this._model.selectionEnd = [this._model.areSelectionValuesReversed() ? wordPosition.start : wordPosition.start + wordPosition.length, endRow];\n }\n }\n\n /**\n * Gets whether the character is considered a word separator by the select\n * word logic.\n * @param cell The cell to check.\n */\n private _isCharWordSeparator(cell: CellData): boolean {\n // Zero width characters are never separators as they are always to the\n // right of wide characters\n if (cell.getWidth() === 0) {\n return false;\n }\n return this._optionsService.rawOptions.wordSeparator.indexOf(cell.getChars()) >= 0;\n }\n\n /**\n * Selects the line specified.\n * @param line The line index.\n */\n protected _selectLineAt(line: number): void {\n const wrappedRange = this._bufferService.buffer.getWrappedRangeForLine(line);\n const range: IBufferRange = {\n start: { x: 0, y: wrappedRange.first },\n end: { x: this._bufferService.cols - 1, y: wrappedRange.last }\n };\n this._model.selectionStart = [0, wrappedRange.first];\n this._model.selectionEnd = undefined;\n this._model.selectionStartLength = getRangeLength(range, this._bufferService.cols);\n }\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IRenderDimensions, IRenderer } from 'browser/renderer/shared/Types';\nimport { IColorSet, ILink, ReadonlyColorSet } from 'browser/Types';\nimport { ISelectionRedrawRequestEvent as ISelectionRequestRedrawEvent, ISelectionRequestScrollLinesEvent } from 'browser/selection/Types';\nimport { createDecorator } from 'common/services/ServiceRegistry';\nimport { AllColorIndex, IDisposable } from 'common/Types';\nimport type { Event } from 'vs/base/common/event';\n\nexport const ICharSizeService = createDecorator('CharSizeService');\nexport interface ICharSizeService {\n serviceBrand: undefined;\n\n readonly width: number;\n readonly height: number;\n readonly hasValidSize: boolean;\n\n readonly onCharSizeChange: Event;\n\n measure(): void;\n}\n\nexport const ICoreBrowserService = createDecorator('CoreBrowserService');\nexport interface ICoreBrowserService {\n serviceBrand: undefined;\n\n readonly isFocused: boolean;\n\n readonly onDprChange: Event;\n readonly onWindowChange: Event;\n\n /**\n * Gets or sets the parent window that the terminal is rendered into. DOM and rendering APIs (e.g.\n * requestAnimationFrame) should be invoked in the context of this window. This should be set when\n * the window hosting the xterm.js instance changes.\n */\n window: Window & typeof globalThis;\n /**\n * The document of the primary window to be used to create elements when working with multiple\n * windows. This is defined by the documentOverride setting.\n */\n readonly mainDocument: Document;\n /**\n * Helper for getting the devicePixelRatio of the parent window.\n */\n readonly dpr: number;\n}\n\nexport const IMouseService = createDecorator('MouseService');\nexport interface IMouseService {\n serviceBrand: undefined;\n\n getCoords(event: {clientX: number, clientY: number}, element: HTMLElement, colCount: number, rowCount: number, isSelection?: boolean): [number, number] | undefined;\n getMouseReportCoords(event: MouseEvent, element: HTMLElement): { col: number, row: number, x: number, y: number } | undefined;\n}\n\nexport const IRenderService = createDecorator('RenderService');\nexport interface IRenderService extends IDisposable {\n serviceBrand: undefined;\n\n onDimensionsChange: Event;\n /**\n * Fires when buffer changes are rendered. This does not fire when only cursor\n * or selections are rendered.\n */\n onRenderedViewportChange: Event<{ start: number, end: number }>;\n /**\n * Fires on render\n */\n onRender: Event<{ start: number, end: number }>;\n onRefreshRequest: Event<{ start: number, end: number }>;\n\n dimensions: IRenderDimensions;\n\n addRefreshCallback(callback: FrameRequestCallback): number;\n\n refreshRows(start: number, end: number): void;\n clearTextureAtlas(): void;\n resize(cols: number, rows: number): void;\n hasRenderer(): boolean;\n setRenderer(renderer: IRenderer): void;\n handleDevicePixelRatioChange(): void;\n handleResize(cols: number, rows: number): void;\n handleCharSizeChanged(): void;\n handleBlur(): void;\n handleFocus(): void;\n handleSelectionChanged(start: [number, number] | undefined, end: [number, number] | undefined, columnSelectMode: boolean): void;\n handleCursorMove(): void;\n clear(): void;\n}\n\nexport const ISelectionService = createDecorator('SelectionService');\nexport interface ISelectionService {\n serviceBrand: undefined;\n\n readonly selectionText: string;\n readonly hasSelection: boolean;\n readonly selectionStart: [number, number] | undefined;\n readonly selectionEnd: [number, number] | undefined;\n\n readonly onLinuxMouseSelection: Event;\n readonly onRequestRedraw: Event;\n readonly onRequestScrollLines: Event;\n readonly onSelectionChange: Event;\n\n disable(): void;\n enable(): void;\n reset(): void;\n setSelection(row: number, col: number, length: number): void;\n selectAll(): void;\n selectLines(start: number, end: number): void;\n clearSelection(): void;\n rightClickSelect(event: MouseEvent): void;\n shouldColumnSelect(event: KeyboardEvent | MouseEvent): boolean;\n shouldForceSelection(event: MouseEvent): boolean;\n refresh(isLinuxMouseSelection?: boolean): void;\n handleMouseDown(event: MouseEvent): void;\n isCellInSelection(x: number, y: number): boolean;\n}\n\nexport const ICharacterJoinerService = createDecorator('CharacterJoinerService');\nexport interface ICharacterJoinerService {\n serviceBrand: undefined;\n\n register(handler: (text: string) => [number, number][]): number;\n deregister(joinerId: number): boolean;\n getJoinedCharacters(row: number): [number, number][];\n}\n\nexport const IThemeService = createDecorator('ThemeService');\nexport interface IThemeService {\n serviceBrand: undefined;\n\n readonly colors: ReadonlyColorSet;\n\n readonly onChangeColors: Event;\n\n restoreColor(slot?: AllColorIndex): void;\n /**\n * Allows external modifying of colors in the theme, this is used instead of {@link colors} to\n * prevent accidental writes.\n */\n modifyColors(callback: (colors: IColorSet) => void): void;\n}\n\n\nexport const ILinkProviderService = createDecorator('LinkProviderService');\nexport interface ILinkProviderService extends IDisposable {\n serviceBrand: undefined;\n readonly linkProviders: ReadonlyArray;\n registerLinkProvider(linkProvider: ILinkProvider): IDisposable;\n}\nexport interface ILinkProvider {\n provideLinks(y: number, callback: (links: ILink[] | undefined) => void): void;\n}\n","/**\n * Copyright (c) 2022 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { ColorContrastCache } from 'browser/ColorContrastCache';\nimport { IThemeService } from 'browser/services/Services';\nimport { DEFAULT_ANSI_COLORS, IColorContrastCache, IColorSet, ReadonlyColorSet } from 'browser/Types';\nimport { color, css, NULL_COLOR } from 'common/Color';\nimport { Disposable } from 'vs/base/common/lifecycle';\nimport { IOptionsService, ITheme } from 'common/services/Services';\nimport { AllColorIndex, IColor, SpecialColorIndex } from 'common/Types';\nimport { Emitter } from 'vs/base/common/event';\n\ninterface IRestoreColorSet {\n foreground: IColor;\n background: IColor;\n cursor: IColor;\n ansi: IColor[];\n}\n\n\nconst DEFAULT_FOREGROUND = css.toColor('#ffffff');\nconst DEFAULT_BACKGROUND = css.toColor('#000000');\nconst DEFAULT_CURSOR = css.toColor('#ffffff');\nconst DEFAULT_CURSOR_ACCENT = DEFAULT_BACKGROUND;\nconst DEFAULT_SELECTION = {\n css: 'rgba(255, 255, 255, 0.3)',\n rgba: 0xFFFFFF4D\n};\nconst DEFAULT_OVERVIEW_RULER_BORDER = DEFAULT_FOREGROUND;\n\nexport class ThemeService extends Disposable implements IThemeService {\n public serviceBrand: undefined;\n\n private _colors: IColorSet;\n private _contrastCache: IColorContrastCache = new ColorContrastCache();\n private _halfContrastCache: IColorContrastCache = new ColorContrastCache();\n private _restoreColors!: IRestoreColorSet;\n\n public get colors(): ReadonlyColorSet { return this._colors; }\n\n private readonly _onChangeColors = this._register(new Emitter());\n public readonly onChangeColors = this._onChangeColors.event;\n\n constructor(\n @IOptionsService private readonly _optionsService: IOptionsService\n ) {\n super();\n\n this._colors = {\n foreground: DEFAULT_FOREGROUND,\n background: DEFAULT_BACKGROUND,\n cursor: DEFAULT_CURSOR,\n cursorAccent: DEFAULT_CURSOR_ACCENT,\n selectionForeground: undefined,\n selectionBackgroundTransparent: DEFAULT_SELECTION,\n selectionBackgroundOpaque: color.blend(DEFAULT_BACKGROUND, DEFAULT_SELECTION),\n selectionInactiveBackgroundTransparent: DEFAULT_SELECTION,\n selectionInactiveBackgroundOpaque: color.blend(DEFAULT_BACKGROUND, DEFAULT_SELECTION),\n scrollbarSliderBackground: color.opacity(DEFAULT_FOREGROUND, 0.2),\n scrollbarSliderHoverBackground: color.opacity(DEFAULT_FOREGROUND, 0.4),\n scrollbarSliderActiveBackground: color.opacity(DEFAULT_FOREGROUND, 0.5),\n overviewRulerBorder: DEFAULT_FOREGROUND,\n ansi: DEFAULT_ANSI_COLORS.slice(),\n contrastCache: this._contrastCache,\n halfContrastCache: this._halfContrastCache\n };\n this._updateRestoreColors();\n this._setTheme(this._optionsService.rawOptions.theme);\n\n this._register(this._optionsService.onSpecificOptionChange('minimumContrastRatio', () => this._contrastCache.clear()));\n this._register(this._optionsService.onSpecificOptionChange('theme', () => this._setTheme(this._optionsService.rawOptions.theme)));\n }\n\n /**\n * Sets the terminal's theme.\n * @param theme The theme to use. If a partial theme is provided then default\n * colors will be used where colors are not defined.\n */\n private _setTheme(theme: ITheme = {}): void {\n const colors = this._colors;\n colors.foreground = parseColor(theme.foreground, DEFAULT_FOREGROUND);\n colors.background = parseColor(theme.background, DEFAULT_BACKGROUND);\n colors.cursor = color.blend(colors.background, parseColor(theme.cursor, DEFAULT_CURSOR));\n colors.cursorAccent = color.blend(colors.background, parseColor(theme.cursorAccent, DEFAULT_CURSOR_ACCENT));\n colors.selectionBackgroundTransparent = parseColor(theme.selectionBackground, DEFAULT_SELECTION);\n colors.selectionBackgroundOpaque = color.blend(colors.background, colors.selectionBackgroundTransparent);\n colors.selectionInactiveBackgroundTransparent = parseColor(theme.selectionInactiveBackground, colors.selectionBackgroundTransparent);\n colors.selectionInactiveBackgroundOpaque = color.blend(colors.background, colors.selectionInactiveBackgroundTransparent);\n colors.selectionForeground = theme.selectionForeground ? parseColor(theme.selectionForeground, NULL_COLOR) : undefined;\n if (colors.selectionForeground === NULL_COLOR) {\n colors.selectionForeground = undefined;\n }\n\n /**\n * If selection color is opaque, blend it with background with 0.3 opacity\n * Issue #2737\n */\n if (color.isOpaque(colors.selectionBackgroundTransparent)) {\n const opacity = 0.3;\n colors.selectionBackgroundTransparent = color.opacity(colors.selectionBackgroundTransparent, opacity);\n }\n if (color.isOpaque(colors.selectionInactiveBackgroundTransparent)) {\n const opacity = 0.3;\n colors.selectionInactiveBackgroundTransparent = color.opacity(colors.selectionInactiveBackgroundTransparent, opacity);\n }\n colors.scrollbarSliderBackground = parseColor(theme.scrollbarSliderBackground, color.opacity(colors.foreground, 0.2));\n colors.scrollbarSliderHoverBackground = parseColor(theme.scrollbarSliderHoverBackground, color.opacity(colors.foreground, 0.4));\n colors.scrollbarSliderActiveBackground = parseColor(theme.scrollbarSliderActiveBackground, color.opacity(colors.foreground, 0.5));\n colors.overviewRulerBorder = parseColor(theme.overviewRulerBorder, DEFAULT_OVERVIEW_RULER_BORDER);\n colors.ansi = DEFAULT_ANSI_COLORS.slice();\n colors.ansi[0] = parseColor(theme.black, DEFAULT_ANSI_COLORS[0]);\n colors.ansi[1] = parseColor(theme.red, DEFAULT_ANSI_COLORS[1]);\n colors.ansi[2] = parseColor(theme.green, DEFAULT_ANSI_COLORS[2]);\n colors.ansi[3] = parseColor(theme.yellow, DEFAULT_ANSI_COLORS[3]);\n colors.ansi[4] = parseColor(theme.blue, DEFAULT_ANSI_COLORS[4]);\n colors.ansi[5] = parseColor(theme.magenta, DEFAULT_ANSI_COLORS[5]);\n colors.ansi[6] = parseColor(theme.cyan, DEFAULT_ANSI_COLORS[6]);\n colors.ansi[7] = parseColor(theme.white, DEFAULT_ANSI_COLORS[7]);\n colors.ansi[8] = parseColor(theme.brightBlack, DEFAULT_ANSI_COLORS[8]);\n colors.ansi[9] = parseColor(theme.brightRed, DEFAULT_ANSI_COLORS[9]);\n colors.ansi[10] = parseColor(theme.brightGreen, DEFAULT_ANSI_COLORS[10]);\n colors.ansi[11] = parseColor(theme.brightYellow, DEFAULT_ANSI_COLORS[11]);\n colors.ansi[12] = parseColor(theme.brightBlue, DEFAULT_ANSI_COLORS[12]);\n colors.ansi[13] = parseColor(theme.brightMagenta, DEFAULT_ANSI_COLORS[13]);\n colors.ansi[14] = parseColor(theme.brightCyan, DEFAULT_ANSI_COLORS[14]);\n colors.ansi[15] = parseColor(theme.brightWhite, DEFAULT_ANSI_COLORS[15]);\n if (theme.extendedAnsi) {\n const colorCount = Math.min(colors.ansi.length - 16, theme.extendedAnsi.length);\n for (let i = 0; i < colorCount; i++) {\n colors.ansi[i + 16] = parseColor(theme.extendedAnsi[i], DEFAULT_ANSI_COLORS[i + 16]);\n }\n }\n // Clear our the cache\n this._contrastCache.clear();\n this._halfContrastCache.clear();\n this._updateRestoreColors();\n this._onChangeColors.fire(this.colors);\n }\n\n public restoreColor(slot?: AllColorIndex): void {\n this._restoreColor(slot);\n this._onChangeColors.fire(this.colors);\n }\n\n private _restoreColor(slot: AllColorIndex | undefined): void {\n // unset slot restores all ansi colors\n if (slot === undefined) {\n for (let i = 0; i < this._restoreColors.ansi.length; ++i) {\n this._colors.ansi[i] = this._restoreColors.ansi[i];\n }\n return;\n }\n switch (slot) {\n case SpecialColorIndex.FOREGROUND:\n this._colors.foreground = this._restoreColors.foreground;\n break;\n case SpecialColorIndex.BACKGROUND:\n this._colors.background = this._restoreColors.background;\n break;\n case SpecialColorIndex.CURSOR:\n this._colors.cursor = this._restoreColors.cursor;\n break;\n default:\n this._colors.ansi[slot] = this._restoreColors.ansi[slot];\n }\n }\n\n public modifyColors(callback: (colors: IColorSet) => void): void {\n callback(this._colors);\n // Assume the change happened\n this._onChangeColors.fire(this.colors);\n }\n\n private _updateRestoreColors(): void {\n this._restoreColors = {\n foreground: this._colors.foreground,\n background: this._colors.background,\n cursor: this._colors.cursor,\n ansi: this._colors.ansi.slice()\n };\n }\n}\n\nfunction parseColor(\n cssString: string | undefined,\n fallback: IColor\n): IColor {\n if (cssString !== undefined) {\n try {\n return css.toColor(cssString);\n } catch {\n // no-op\n }\n }\n return fallback;\n}\n","/**\n * Copyright (c) 2016 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { ICircularList } from 'common/Types';\nimport { Disposable } from 'vs/base/common/lifecycle';\nimport { Emitter } from 'vs/base/common/event';\n\nexport interface IInsertEvent {\n index: number;\n amount: number;\n}\n\nexport interface IDeleteEvent {\n index: number;\n amount: number;\n}\n\n/**\n * Represents a circular list; a list with a maximum size that wraps around when push is called,\n * overriding values at the start of the list.\n */\nexport class CircularList extends Disposable implements ICircularList {\n protected _array: (T | undefined)[];\n private _startIndex: number;\n private _length: number;\n\n public readonly onDeleteEmitter = this._register(new Emitter());\n public readonly onDelete = this.onDeleteEmitter.event;\n public readonly onInsertEmitter = this._register(new Emitter());\n public readonly onInsert = this.onInsertEmitter.event;\n public readonly onTrimEmitter = this._register(new Emitter());\n public readonly onTrim = this.onTrimEmitter.event;\n\n constructor(\n private _maxLength: number\n ) {\n super();\n this._array = new Array(this._maxLength);\n this._startIndex = 0;\n this._length = 0;\n }\n\n public get maxLength(): number {\n return this._maxLength;\n }\n\n public set maxLength(newMaxLength: number) {\n // There was no change in maxLength, return early.\n if (this._maxLength === newMaxLength) {\n return;\n }\n\n // Reconstruct array, starting at index 0. Only transfer values from the\n // indexes 0 to length.\n const newArray = new Array(newMaxLength);\n for (let i = 0; i < Math.min(newMaxLength, this.length); i++) {\n newArray[i] = this._array[this._getCyclicIndex(i)];\n }\n this._array = newArray;\n this._maxLength = newMaxLength;\n this._startIndex = 0;\n }\n\n public get length(): number {\n return this._length;\n }\n\n public set length(newLength: number) {\n if (newLength > this._length) {\n for (let i = this._length; i < newLength; i++) {\n this._array[i] = undefined;\n }\n }\n this._length = newLength;\n }\n\n /**\n * Gets the value at an index.\n *\n * Note that for performance reasons there is no bounds checking here, the index reference is\n * circular so this should always return a value and never throw.\n * @param index The index of the value to get.\n * @returns The value corresponding to the index.\n */\n public get(index: number): T | undefined {\n return this._array[this._getCyclicIndex(index)];\n }\n\n /**\n * Sets the value at an index.\n *\n * Note that for performance reasons there is no bounds checking here, the index reference is\n * circular so this should always return a value and never throw.\n * @param index The index to set.\n * @param value The value to set.\n */\n public set(index: number, value: T | undefined): void {\n this._array[this._getCyclicIndex(index)] = value;\n }\n\n /**\n * Pushes a new value onto the list, wrapping around to the start of the array, overriding index 0\n * if the maximum length is reached.\n * @param value The value to push onto the list.\n */\n public push(value: T): void {\n this._array[this._getCyclicIndex(this._length)] = value;\n if (this._length === this._maxLength) {\n this._startIndex = ++this._startIndex % this._maxLength;\n this.onTrimEmitter.fire(1);\n } else {\n this._length++;\n }\n }\n\n /**\n * Advance ringbuffer index and return current element for recycling.\n * Note: The buffer must be full for this method to work.\n * @throws When the buffer is not full.\n */\n public recycle(): T {\n if (this._length !== this._maxLength) {\n throw new Error('Can only recycle when the buffer is full');\n }\n this._startIndex = ++this._startIndex % this._maxLength;\n this.onTrimEmitter.fire(1);\n return this._array[this._getCyclicIndex(this._length - 1)]!;\n }\n\n /**\n * Ringbuffer is at max length.\n */\n public get isFull(): boolean {\n return this._length === this._maxLength;\n }\n\n /**\n * Removes and returns the last value on the list.\n * @returns The popped value.\n */\n public pop(): T | undefined {\n return this._array[this._getCyclicIndex(this._length-- - 1)];\n }\n\n /**\n * Deletes and/or inserts items at a particular index (in that order). Unlike\n * Array.prototype.splice, this operation does not return the deleted items as a new array in\n * order to save creating a new array. Note that this operation may shift all values in the list\n * in the worst case.\n * @param start The index to delete and/or insert.\n * @param deleteCount The number of elements to delete.\n * @param items The items to insert.\n */\n public splice(start: number, deleteCount: number, ...items: T[]): void {\n // Delete items\n if (deleteCount) {\n for (let i = start; i < this._length - deleteCount; i++) {\n this._array[this._getCyclicIndex(i)] = this._array[this._getCyclicIndex(i + deleteCount)];\n }\n this._length -= deleteCount;\n this.onDeleteEmitter.fire({ index: start, amount: deleteCount });\n }\n\n // Add items\n for (let i = this._length - 1; i >= start; i--) {\n this._array[this._getCyclicIndex(i + items.length)] = this._array[this._getCyclicIndex(i)];\n }\n for (let i = 0; i < items.length; i++) {\n this._array[this._getCyclicIndex(start + i)] = items[i];\n }\n if (items.length) {\n this.onInsertEmitter.fire({ index: start, amount: items.length });\n }\n\n // Adjust length as needed\n if (this._length + items.length > this._maxLength) {\n const countToTrim = (this._length + items.length) - this._maxLength;\n this._startIndex += countToTrim;\n this._length = this._maxLength;\n this.onTrimEmitter.fire(countToTrim);\n } else {\n this._length += items.length;\n }\n }\n\n /**\n * Trims a number of items from the start of the list.\n * @param count The number of items to remove.\n */\n public trimStart(count: number): void {\n if (count > this._length) {\n count = this._length;\n }\n this._startIndex += count;\n this._length -= count;\n this.onTrimEmitter.fire(count);\n }\n\n public shiftElements(start: number, count: number, offset: number): void {\n if (count <= 0) {\n return;\n }\n if (start < 0 || start >= this._length) {\n throw new Error('start argument out of range');\n }\n if (start + offset < 0) {\n throw new Error('Cannot shift elements in list beyond index 0');\n }\n\n if (offset > 0) {\n for (let i = count - 1; i >= 0; i--) {\n this.set(start + i + offset, this.get(start + i));\n }\n const expandListBy = (start + count + offset) - this._length;\n if (expandListBy > 0) {\n this._length += expandListBy;\n while (this._length > this._maxLength) {\n this._length--;\n this._startIndex++;\n this.onTrimEmitter.fire(1);\n }\n }\n } else {\n for (let i = 0; i < count; i++) {\n this.set(start + i + offset, this.get(start + i));\n }\n }\n }\n\n /**\n * Gets the cyclic index for the specified regular index. The cyclic index can then be used on the\n * backing array to get the element associated with the regular index.\n * @param index The regular index.\n * @returns The cyclic index.\n */\n private _getCyclicIndex(index: number): number {\n return (this._startIndex + index) % this._maxLength;\n }\n}\n","/**\n * Copyright (c) 2016 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\n/*\n * A simple utility for cloning values\n */\nexport function clone(val: T, depth: number = 5): T {\n if (typeof val !== 'object') {\n return val;\n }\n\n // If we're cloning an array, use an array as the base, otherwise use an object\n const clonedObject: any = Array.isArray(val) ? [] : {};\n\n for (const key in val) {\n // Recursively clone eack item unless we're at the maximum depth\n clonedObject[key] = depth <= 1 ? val[key] : (val[key] && clone(val[key], depth - 1));\n }\n\n return clonedObject as T;\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IColor, IColorRGB } from 'common/Types';\n\nlet $r = 0;\nlet $g = 0;\nlet $b = 0;\nlet $a = 0;\n\nexport const NULL_COLOR: IColor = {\n css: '#00000000',\n rgba: 0\n};\n\n/**\n * Helper functions where the source type is \"channels\" (individual color channels as numbers).\n */\nexport namespace channels {\n export function toCss(r: number, g: number, b: number, a?: number): string {\n if (a !== undefined) {\n return `#${toPaddedHex(r)}${toPaddedHex(g)}${toPaddedHex(b)}${toPaddedHex(a)}`;\n }\n return `#${toPaddedHex(r)}${toPaddedHex(g)}${toPaddedHex(b)}`;\n }\n\n export function toRgba(r: number, g: number, b: number, a: number = 0xFF): number {\n // Note: The aggregated number is RGBA32 (BE), thus needs to be converted to ABGR32\n // on LE systems, before it can be used for direct 32-bit buffer writes.\n // >>> 0 forces an unsigned int\n return (r << 24 | g << 16 | b << 8 | a) >>> 0;\n }\n\n export function toColor(r: number, g: number, b: number, a?: number): IColor {\n return {\n css: channels.toCss(r, g, b, a),\n rgba: channels.toRgba(r, g, b, a)\n };\n }\n}\n\n/**\n * Helper functions where the source type is `IColor`.\n */\nexport namespace color {\n export function blend(bg: IColor, fg: IColor): IColor {\n $a = (fg.rgba & 0xFF) / 255;\n if ($a === 1) {\n return {\n css: fg.css,\n rgba: fg.rgba\n };\n }\n const fgR = (fg.rgba >> 24) & 0xFF;\n const fgG = (fg.rgba >> 16) & 0xFF;\n const fgB = (fg.rgba >> 8) & 0xFF;\n const bgR = (bg.rgba >> 24) & 0xFF;\n const bgG = (bg.rgba >> 16) & 0xFF;\n const bgB = (bg.rgba >> 8) & 0xFF;\n $r = bgR + Math.round((fgR - bgR) * $a);\n $g = bgG + Math.round((fgG - bgG) * $a);\n $b = bgB + Math.round((fgB - bgB) * $a);\n const css = channels.toCss($r, $g, $b);\n const rgba = channels.toRgba($r, $g, $b);\n return { css, rgba };\n }\n\n export function isOpaque(color: IColor): boolean {\n return (color.rgba & 0xFF) === 0xFF;\n }\n\n export function ensureContrastRatio(bg: IColor, fg: IColor, ratio: number): IColor | undefined {\n const result = rgba.ensureContrastRatio(bg.rgba, fg.rgba, ratio);\n if (!result) {\n return undefined;\n }\n return channels.toColor(\n (result >> 24 & 0xFF),\n (result >> 16 & 0xFF),\n (result >> 8 & 0xFF)\n );\n }\n\n export function opaque(color: IColor): IColor {\n const rgbaColor = (color.rgba | 0xFF) >>> 0;\n [$r, $g, $b] = rgba.toChannels(rgbaColor);\n return {\n css: channels.toCss($r, $g, $b),\n rgba: rgbaColor\n };\n }\n\n export function opacity(color: IColor, opacity: number): IColor {\n $a = Math.round(opacity * 0xFF);\n [$r, $g, $b] = rgba.toChannels(color.rgba);\n return {\n css: channels.toCss($r, $g, $b, $a),\n rgba: channels.toRgba($r, $g, $b, $a)\n };\n }\n\n export function multiplyOpacity(color: IColor, factor: number): IColor {\n $a = color.rgba & 0xFF;\n return opacity(color, ($a * factor) / 0xFF);\n }\n\n export function toColorRGB(color: IColor): IColorRGB {\n return [(color.rgba >> 24) & 0xFF, (color.rgba >> 16) & 0xFF, (color.rgba >> 8) & 0xFF];\n }\n}\n\n/**\n * Helper functions where the source type is \"css\" (string: '#rgb', '#rgba', '#rrggbb',\n * '#rrggbbaa').\n */\nexport namespace css {\n // Attempt to set get the shared canvas context\n let $ctx: CanvasRenderingContext2D | undefined;\n let $litmusColor: CanvasGradient | undefined;\n try {\n // This is guaranteed to run in the first window, so document should be correct\n const canvas = document.createElement('canvas');\n canvas.width = 1;\n canvas.height = 1;\n const ctx = canvas.getContext('2d', {\n willReadFrequently: true\n });\n if (ctx) {\n $ctx = ctx;\n $ctx.globalCompositeOperation = 'copy';\n $litmusColor = $ctx.createLinearGradient(0, 0, 1, 1);\n }\n }\n catch {\n // noop\n }\n\n /**\n * Converts a css string to an IColor, this should handle all valid CSS color strings and will\n * throw if it's invalid. The ideal format to use is `#rrggbb[aa]` as it's the fastest to parse.\n *\n * Only `#rgb[a]`, `#rrggbb[aa]`, `rgb()` and `rgba()` formats are supported when run in a Node\n * environment.\n */\n export function toColor(css: string): IColor {\n // Formats: #rgb[a] and #rrggbb[aa]\n if (css.match(/#[\\da-f]{3,8}/i)) {\n switch (css.length) {\n case 4: { // #rgb\n $r = parseInt(css.slice(1, 2).repeat(2), 16);\n $g = parseInt(css.slice(2, 3).repeat(2), 16);\n $b = parseInt(css.slice(3, 4).repeat(2), 16);\n return channels.toColor($r, $g, $b);\n }\n case 5: { // #rgba\n $r = parseInt(css.slice(1, 2).repeat(2), 16);\n $g = parseInt(css.slice(2, 3).repeat(2), 16);\n $b = parseInt(css.slice(3, 4).repeat(2), 16);\n $a = parseInt(css.slice(4, 5).repeat(2), 16);\n return channels.toColor($r, $g, $b, $a);\n }\n case 7: // #rrggbb\n return {\n css,\n rgba: (parseInt(css.slice(1), 16) << 8 | 0xFF) >>> 0\n };\n case 9: // #rrggbbaa\n return {\n css,\n rgba: parseInt(css.slice(1), 16) >>> 0\n };\n }\n }\n\n // Formats: rgb() or rgba()\n const rgbaMatch = css.match(/rgba?\\(\\s*(\\d{1,3})\\s*,\\s*(\\d{1,3})\\s*,\\s*(\\d{1,3})\\s*(,\\s*(0|1|\\d?\\.(\\d+))\\s*)?\\)/);\n if (rgbaMatch) {\n $r = parseInt(rgbaMatch[1]);\n $g = parseInt(rgbaMatch[2]);\n $b = parseInt(rgbaMatch[3]);\n $a = Math.round((rgbaMatch[5] === undefined ? 1 : parseFloat(rgbaMatch[5])) * 0xFF);\n return channels.toColor($r, $g, $b, $a);\n }\n\n // Validate the context is available for canvas-based color parsing\n if (!$ctx || !$litmusColor) {\n throw new Error('css.toColor: Unsupported css format');\n }\n\n // Validate the color using canvas fillStyle\n // See https://html.spec.whatwg.org/multipage/canvas.html#fill-and-stroke-styles\n $ctx.fillStyle = $litmusColor;\n $ctx.fillStyle = css;\n if (typeof $ctx.fillStyle !== 'string') {\n throw new Error('css.toColor: Unsupported css format');\n }\n\n $ctx.fillRect(0, 0, 1, 1);\n [$r, $g, $b, $a] = $ctx.getImageData(0, 0, 1, 1).data;\n\n // Validate the color is non-transparent as color hue gets lost when drawn to the canvas\n if ($a !== 0xFF) {\n throw new Error('css.toColor: Unsupported css format');\n }\n\n // Extract the color from the canvas' fillStyle property which exposes the color value in rgba()\n // format\n // See https://html.spec.whatwg.org/multipage/canvas.html#serialisation-of-a-color\n return {\n rgba: channels.toRgba($r, $g, $b, $a),\n css\n };\n }\n}\n\n/**\n * Helper functions where the source type is \"rgb\" (number: 0xrrggbb).\n */\nexport namespace rgb {\n /**\n * Gets the relative luminance of an RGB color, this is useful in determining the contrast ratio\n * between two colors.\n * @param rgb The color to use.\n * @see https://www.w3.org/TR/WCAG20/#relativeluminancedef\n */\n export function relativeLuminance(rgb: number): number {\n return relativeLuminance2(\n (rgb >> 16) & 0xFF,\n (rgb >> 8 ) & 0xFF,\n (rgb ) & 0xFF);\n }\n\n /**\n * Gets the relative luminance of an RGB color, this is useful in determining the contrast ratio\n * between two colors.\n * @param r The red channel (0x00 to 0xFF).\n * @param g The green channel (0x00 to 0xFF).\n * @param b The blue channel (0x00 to 0xFF).\n * @see https://www.w3.org/TR/WCAG20/#relativeluminancedef\n */\n export function relativeLuminance2(r: number, g: number, b: number): number {\n const rs = r / 255;\n const gs = g / 255;\n const bs = b / 255;\n const rr = rs <= 0.03928 ? rs / 12.92 : Math.pow((rs + 0.055) / 1.055, 2.4);\n const rg = gs <= 0.03928 ? gs / 12.92 : Math.pow((gs + 0.055) / 1.055, 2.4);\n const rb = bs <= 0.03928 ? bs / 12.92 : Math.pow((bs + 0.055) / 1.055, 2.4);\n return rr * 0.2126 + rg * 0.7152 + rb * 0.0722;\n }\n}\n\n/**\n * Helper functions where the source type is \"rgba\" (number: 0xrrggbbaa).\n */\nexport namespace rgba {\n export function blend(bg: number, fg: number): number {\n $a = (fg & 0xFF) / 0xFF;\n if ($a === 1) {\n return fg;\n }\n const fgR = (fg >> 24) & 0xFF;\n const fgG = (fg >> 16) & 0xFF;\n const fgB = (fg >> 8) & 0xFF;\n const bgR = (bg >> 24) & 0xFF;\n const bgG = (bg >> 16) & 0xFF;\n const bgB = (bg >> 8) & 0xFF;\n $r = bgR + Math.round((fgR - bgR) * $a);\n $g = bgG + Math.round((fgG - bgG) * $a);\n $b = bgB + Math.round((fgB - bgB) * $a);\n return channels.toRgba($r, $g, $b);\n }\n\n /**\n * Given a foreground color and a background color, either increase or reduce the luminance of the\n * foreground color until the specified contrast ratio is met. If pure white or black is hit\n * without the contrast ratio being met, go the other direction using the background color as the\n * foreground color and take either the first or second result depending on which has the higher\n * contrast ratio.\n *\n * `undefined` will be returned if the contrast ratio is already met.\n *\n * @param bgRgba The background color in rgba format.\n * @param fgRgba The foreground color in rgba format.\n * @param ratio The contrast ratio to achieve.\n */\n export function ensureContrastRatio(bgRgba: number, fgRgba: number, ratio: number): number | undefined {\n const bgL = rgb.relativeLuminance(bgRgba >> 8);\n const fgL = rgb.relativeLuminance(fgRgba >> 8);\n const cr = contrastRatio(bgL, fgL);\n if (cr < ratio) {\n if (fgL < bgL) {\n const resultA = reduceLuminance(bgRgba, fgRgba, ratio);\n const resultARatio = contrastRatio(bgL, rgb.relativeLuminance(resultA >> 8));\n if (resultARatio < ratio) {\n const resultB = increaseLuminance(bgRgba, fgRgba, ratio);\n const resultBRatio = contrastRatio(bgL, rgb.relativeLuminance(resultB >> 8));\n return resultARatio > resultBRatio ? resultA : resultB;\n }\n return resultA;\n }\n const resultA = increaseLuminance(bgRgba, fgRgba, ratio);\n const resultARatio = contrastRatio(bgL, rgb.relativeLuminance(resultA >> 8));\n if (resultARatio < ratio) {\n const resultB = reduceLuminance(bgRgba, fgRgba, ratio);\n const resultBRatio = contrastRatio(bgL, rgb.relativeLuminance(resultB >> 8));\n return resultARatio > resultBRatio ? resultA : resultB;\n }\n return resultA;\n }\n return undefined;\n }\n\n export function reduceLuminance(bgRgba: number, fgRgba: number, ratio: number): number {\n // This is a naive but fast approach to reducing luminance as converting to\n // HSL and back is expensive\n const bgR = (bgRgba >> 24) & 0xFF;\n const bgG = (bgRgba >> 16) & 0xFF;\n const bgB = (bgRgba >> 8) & 0xFF;\n let fgR = (fgRgba >> 24) & 0xFF;\n let fgG = (fgRgba >> 16) & 0xFF;\n let fgB = (fgRgba >> 8) & 0xFF;\n let cr = contrastRatio(rgb.relativeLuminance2(fgR, fgG, fgB), rgb.relativeLuminance2(bgR, bgG, bgB));\n while (cr < ratio && (fgR > 0 || fgG > 0 || fgB > 0)) {\n // Reduce by 10% until the ratio is hit\n fgR -= Math.max(0, Math.ceil(fgR * 0.1));\n fgG -= Math.max(0, Math.ceil(fgG * 0.1));\n fgB -= Math.max(0, Math.ceil(fgB * 0.1));\n cr = contrastRatio(rgb.relativeLuminance2(fgR, fgG, fgB), rgb.relativeLuminance2(bgR, bgG, bgB));\n }\n return (fgR << 24 | fgG << 16 | fgB << 8 | 0xFF) >>> 0;\n }\n\n export function increaseLuminance(bgRgba: number, fgRgba: number, ratio: number): number {\n // This is a naive but fast approach to increasing luminance as converting to\n // HSL and back is expensive\n const bgR = (bgRgba >> 24) & 0xFF;\n const bgG = (bgRgba >> 16) & 0xFF;\n const bgB = (bgRgba >> 8) & 0xFF;\n let fgR = (fgRgba >> 24) & 0xFF;\n let fgG = (fgRgba >> 16) & 0xFF;\n let fgB = (fgRgba >> 8) & 0xFF;\n let cr = contrastRatio(rgb.relativeLuminance2(fgR, fgG, fgB), rgb.relativeLuminance2(bgR, bgG, bgB));\n while (cr < ratio && (fgR < 0xFF || fgG < 0xFF || fgB < 0xFF)) {\n // Increase by 10% until the ratio is hit\n fgR = Math.min(0xFF, fgR + Math.ceil((255 - fgR) * 0.1));\n fgG = Math.min(0xFF, fgG + Math.ceil((255 - fgG) * 0.1));\n fgB = Math.min(0xFF, fgB + Math.ceil((255 - fgB) * 0.1));\n cr = contrastRatio(rgb.relativeLuminance2(fgR, fgG, fgB), rgb.relativeLuminance2(bgR, bgG, bgB));\n }\n return (fgR << 24 | fgG << 16 | fgB << 8 | 0xFF) >>> 0;\n }\n\n export function toChannels(value: number): [number, number, number, number] {\n return [(value >> 24) & 0xFF, (value >> 16) & 0xFF, (value >> 8) & 0xFF, value & 0xFF];\n }\n}\n\nexport function toPaddedHex(c: number): string {\n const s = c.toString(16);\n return s.length < 2 ? '0' + s : s;\n}\n\n/**\n * Gets the contrast ratio between two relative luminance values.\n * @param l1 The first relative luminance.\n * @param l2 The first relative luminance.\n * @see https://www.w3.org/TR/WCAG20/#contrast-ratiodef\n */\nexport function contrastRatio(l1: number, l2: number): number {\n if (l1 < l2) {\n return (l2 + 0.05) / (l1 + 0.05);\n }\n return (l1 + 0.05) / (l2 + 0.05);\n}\n","/**\n * Copyright (c) 2014-2020 The xterm.js authors. All rights reserved.\n * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)\n * @license MIT\n *\n * Originally forked from (with the author's permission):\n * Fabrice Bellard's javascript vt100 for jslinux:\n * http://bellard.org/jslinux/\n * Copyright (c) 2011 Fabrice Bellard\n * The original design remains. The terminal itself\n * has been extended to include xterm CSI codes, among\n * other features.\n *\n * Terminal Emulation References:\n * http://vt100.net/\n * http://invisible-island.net/xterm/ctlseqs/ctlseqs.txt\n * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html\n * http://invisible-island.net/vttest/\n * http://www.inwap.com/pdp10/ansicode.txt\n * http://linux.die.net/man/4/console_codes\n * http://linux.die.net/man/7/urxvt\n */\n\nimport { IInstantiationService, IOptionsService, IBufferService, ILogService, ICharsetService, ICoreService, ICoreMouseService, IUnicodeService, LogLevelEnum, ITerminalOptions, IOscLinkService } from 'common/services/Services';\nimport { InstantiationService } from 'common/services/InstantiationService';\nimport { LogService } from 'common/services/LogService';\nimport { BufferService, MINIMUM_COLS, MINIMUM_ROWS } from 'common/services/BufferService';\nimport { OptionsService } from 'common/services/OptionsService';\nimport { IDisposable, IAttributeData, ICoreTerminal, IScrollEvent } from 'common/Types';\nimport { CoreService } from 'common/services/CoreService';\nimport { CoreMouseService } from 'common/services/CoreMouseService';\nimport { UnicodeService } from 'common/services/UnicodeService';\nimport { CharsetService } from 'common/services/CharsetService';\nimport { updateWindowsModeWrappedState } from 'common/WindowsMode';\nimport { IFunctionIdentifier, IParams } from 'common/parser/Types';\nimport { IBufferSet } from 'common/buffer/Types';\nimport { InputHandler } from 'common/InputHandler';\nimport { WriteBuffer } from 'common/input/WriteBuffer';\nimport { OscLinkService } from 'common/services/OscLinkService';\nimport { Emitter, Event } from 'vs/base/common/event';\nimport { Disposable, MutableDisposable, toDisposable } from 'vs/base/common/lifecycle';\n\n// Only trigger this warning a single time per session\nlet hasWriteSyncWarnHappened = false;\n\nexport abstract class CoreTerminal extends Disposable implements ICoreTerminal {\n protected readonly _instantiationService: IInstantiationService;\n protected readonly _bufferService: IBufferService;\n protected readonly _logService: ILogService;\n protected readonly _charsetService: ICharsetService;\n protected readonly _oscLinkService: IOscLinkService;\n\n public readonly coreMouseService: ICoreMouseService;\n public readonly coreService: ICoreService;\n public readonly unicodeService: IUnicodeService;\n public readonly optionsService: IOptionsService;\n\n protected _inputHandler: InputHandler;\n private _writeBuffer: WriteBuffer;\n private _windowsWrappingHeuristics = this._register(new MutableDisposable());\n\n private readonly _onBinary = this._register(new Emitter());\n public readonly onBinary = this._onBinary.event;\n private readonly _onData = this._register(new Emitter());\n public readonly onData = this._onData.event;\n protected _onLineFeed = this._register(new Emitter());\n public readonly onLineFeed = this._onLineFeed.event;\n private readonly _onResize = this._register(new Emitter<{ cols: number, rows: number }>());\n public readonly onResize = this._onResize.event;\n protected readonly _onWriteParsed = this._register(new Emitter());\n public readonly onWriteParsed = this._onWriteParsed.event;\n\n /**\n * Internally we track the source of the scroll but this is meaningless outside the library so\n * it's filtered out.\n */\n protected _onScrollApi?: Emitter;\n protected _onScroll = this._register(new Emitter());\n public get onScroll(): Event {\n if (!this._onScrollApi) {\n this._onScrollApi = this._register(new Emitter());\n this._onScroll.event(ev => {\n this._onScrollApi?.fire(ev.position);\n });\n }\n return this._onScrollApi.event;\n }\n\n public get cols(): number { return this._bufferService.cols; }\n public get rows(): number { return this._bufferService.rows; }\n public get buffers(): IBufferSet { return this._bufferService.buffers; }\n public get options(): Required { return this.optionsService.options; }\n public set options(options: ITerminalOptions) {\n for (const key in options) {\n this.optionsService.options[key] = options[key];\n }\n }\n\n constructor(\n options: Partial\n ) {\n super();\n\n // Setup and initialize services\n this._instantiationService = new InstantiationService();\n this.optionsService = this._register(new OptionsService(options));\n this._instantiationService.setService(IOptionsService, this.optionsService);\n this._bufferService = this._register(this._instantiationService.createInstance(BufferService));\n this._instantiationService.setService(IBufferService, this._bufferService);\n this._logService = this._register(this._instantiationService.createInstance(LogService));\n this._instantiationService.setService(ILogService, this._logService);\n this.coreService = this._register(this._instantiationService.createInstance(CoreService));\n this._instantiationService.setService(ICoreService, this.coreService);\n this.coreMouseService = this._register(this._instantiationService.createInstance(CoreMouseService));\n this._instantiationService.setService(ICoreMouseService, this.coreMouseService);\n this.unicodeService = this._register(this._instantiationService.createInstance(UnicodeService));\n this._instantiationService.setService(IUnicodeService, this.unicodeService);\n this._charsetService = this._instantiationService.createInstance(CharsetService);\n this._instantiationService.setService(ICharsetService, this._charsetService);\n this._oscLinkService = this._instantiationService.createInstance(OscLinkService);\n this._instantiationService.setService(IOscLinkService, this._oscLinkService);\n\n\n // Register input handler and handle/forward events\n this._inputHandler = this._register(new InputHandler(this._bufferService, this._charsetService, this.coreService, this._logService, this.optionsService, this._oscLinkService, this.coreMouseService, this.unicodeService));\n this._register(Event.forward(this._inputHandler.onLineFeed, this._onLineFeed));\n this._register(this._inputHandler);\n\n // Setup listeners\n this._register(Event.forward(this._bufferService.onResize, this._onResize));\n this._register(Event.forward(this.coreService.onData, this._onData));\n this._register(Event.forward(this.coreService.onBinary, this._onBinary));\n this._register(this.coreService.onRequestScrollToBottom(() => this.scrollToBottom(true)));\n this._register(this.coreService.onUserInput(() => this._writeBuffer.handleUserInput()));\n this._register(this.optionsService.onMultipleOptionChange(['windowsMode', 'windowsPty'], () => this._handleWindowsPtyOptionChange()));\n this._register(this._bufferService.onScroll(() => {\n this._onScroll.fire({ position: this._bufferService.buffer.ydisp });\n this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop, this._bufferService.buffer.scrollBottom);\n }));\n // Setup WriteBuffer\n this._writeBuffer = this._register(new WriteBuffer((data, promiseResult) => this._inputHandler.parse(data, promiseResult)));\n this._register(Event.forward(this._writeBuffer.onWriteParsed, this._onWriteParsed));\n }\n\n public write(data: string | Uint8Array, callback?: () => void): void {\n this._writeBuffer.write(data, callback);\n }\n\n /**\n * Write data to terminal synchonously.\n *\n * This method is unreliable with async parser handlers, thus should not\n * be used anymore. If you need blocking semantics on data input consider\n * `write` with a callback instead.\n *\n * @deprecated Unreliable, will be removed soon.\n */\n public writeSync(data: string | Uint8Array, maxSubsequentCalls?: number): void {\n if (this._logService.logLevel <= LogLevelEnum.WARN && !hasWriteSyncWarnHappened) {\n this._logService.warn('writeSync is unreliable and will be removed soon.');\n hasWriteSyncWarnHappened = true;\n }\n this._writeBuffer.writeSync(data, maxSubsequentCalls);\n }\n\n public input(data: string, wasUserInput: boolean = true): void {\n this.coreService.triggerDataEvent(data, wasUserInput);\n }\n\n public resize(x: number, y: number): void {\n if (isNaN(x) || isNaN(y)) {\n return;\n }\n\n x = Math.max(x, MINIMUM_COLS);\n y = Math.max(y, MINIMUM_ROWS);\n\n this._bufferService.resize(x, y);\n }\n\n /**\n * Scroll the terminal down 1 row, creating a blank line.\n * @param eraseAttr The attribute data to use the for blank line.\n * @param isWrapped Whether the new line is wrapped from the previous line.\n */\n public scroll(eraseAttr: IAttributeData, isWrapped: boolean = false): void {\n this._bufferService.scroll(eraseAttr, isWrapped);\n }\n\n /**\n * Scroll the display of the terminal\n * @param disp The number of lines to scroll down (negative scroll up).\n * @param suppressScrollEvent Don't emit the scroll event as scrollLines. This is used to avoid\n * unwanted events being handled by the viewport when the event was triggered from the viewport\n * originally.\n */\n public scrollLines(disp: number, suppressScrollEvent?: boolean): void {\n this._bufferService.scrollLines(disp, suppressScrollEvent);\n }\n\n public scrollPages(pageCount: number): void {\n this.scrollLines(pageCount * (this.rows - 1));\n }\n\n public scrollToTop(): void {\n this.scrollLines(-this._bufferService.buffer.ydisp);\n }\n\n public scrollToBottom(disableSmoothScroll?: boolean): void {\n this.scrollLines(this._bufferService.buffer.ybase - this._bufferService.buffer.ydisp);\n }\n\n public scrollToLine(line: number): void {\n const scrollAmount = line - this._bufferService.buffer.ydisp;\n if (scrollAmount !== 0) {\n this.scrollLines(scrollAmount);\n }\n }\n\n /** Add handler for ESC escape sequence. See xterm.d.ts for details. */\n public registerEscHandler(id: IFunctionIdentifier, callback: () => boolean | Promise): IDisposable {\n return this._inputHandler.registerEscHandler(id, callback);\n }\n\n /** Add handler for DCS escape sequence. See xterm.d.ts for details. */\n public registerDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: IParams) => boolean | Promise): IDisposable {\n return this._inputHandler.registerDcsHandler(id, callback);\n }\n\n /** Add handler for CSI escape sequence. See xterm.d.ts for details. */\n public registerCsiHandler(id: IFunctionIdentifier, callback: (params: IParams) => boolean | Promise): IDisposable {\n return this._inputHandler.registerCsiHandler(id, callback);\n }\n\n /** Add handler for OSC escape sequence. See xterm.d.ts for details. */\n public registerOscHandler(ident: number, callback: (data: string) => boolean | Promise): IDisposable {\n return this._inputHandler.registerOscHandler(ident, callback);\n }\n\n protected _setup(): void {\n this._handleWindowsPtyOptionChange();\n }\n\n public reset(): void {\n this._inputHandler.reset();\n this._bufferService.reset();\n this._charsetService.reset();\n this.coreService.reset();\n this.coreMouseService.reset();\n }\n\n\n private _handleWindowsPtyOptionChange(): void {\n let value = false;\n const windowsPty = this.optionsService.rawOptions.windowsPty;\n if (windowsPty && windowsPty.buildNumber !== undefined && windowsPty.buildNumber !== undefined) {\n value = !!(windowsPty.backend === 'conpty' && windowsPty.buildNumber < 21376);\n } else if (this.optionsService.rawOptions.windowsMode) {\n value = true;\n }\n if (value) {\n this._enableWindowsWrappingHeuristics();\n } else {\n this._windowsWrappingHeuristics.clear();\n }\n }\n\n protected _enableWindowsWrappingHeuristics(): void {\n if (!this._windowsWrappingHeuristics.value) {\n const disposables: IDisposable[] = [];\n disposables.push(this.onLineFeed(updateWindowsModeWrappedState.bind(null, this._bufferService)));\n disposables.push(this.registerCsiHandler({ final: 'H' }, () => {\n updateWindowsModeWrappedState(this._bufferService);\n return false;\n }));\n this._windowsWrappingHeuristics.value = toDisposable(() => {\n for (const d of disposables) {\n d.dispose();\n }\n });\n }\n }\n}\n","/**\n * Copyright (c) 2014 The xterm.js authors. All rights reserved.\n * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)\n * @license MIT\n */\n\nimport { IInputHandler, IAttributeData, IDisposable, IWindowOptions, IColorEvent, IParseStack, ColorIndex, ColorRequestType, SpecialColorIndex } from 'common/Types';\nimport { C0, C1 } from 'common/data/EscapeSequences';\nimport { CHARSETS, DEFAULT_CHARSET } from 'common/data/Charsets';\nimport { EscapeSequenceParser } from 'common/parser/EscapeSequenceParser';\nimport { Disposable } from 'vs/base/common/lifecycle';\nimport { StringToUtf32, stringFromCodePoint, Utf8ToUtf32 } from 'common/input/TextDecoder';\nimport { BufferLine, DEFAULT_ATTR_DATA } from 'common/buffer/BufferLine';\nimport { IParsingState, IEscapeSequenceParser, IParams, IFunctionIdentifier } from 'common/parser/Types';\nimport { NULL_CELL_CODE, NULL_CELL_WIDTH, Attributes, FgFlags, BgFlags, Content, UnderlineStyle } from 'common/buffer/Constants';\nimport { CellData } from 'common/buffer/CellData';\nimport { AttributeData } from 'common/buffer/AttributeData';\nimport { ICoreService, IBufferService, IOptionsService, ILogService, ICoreMouseService, ICharsetService, IUnicodeService, LogLevelEnum, IOscLinkService } from 'common/services/Services';\nimport { UnicodeService } from 'common/services/UnicodeService';\nimport { OscHandler } from 'common/parser/OscParser';\nimport { DcsHandler } from 'common/parser/DcsParser';\nimport { IBuffer } from 'common/buffer/Types';\nimport { parseColor } from 'common/input/XParseColor';\nimport { Emitter } from 'vs/base/common/event';\n\n/**\n * Map collect to glevel. Used in `selectCharset`.\n */\nconst GLEVEL: { [key: string]: number } = { '(': 0, ')': 1, '*': 2, '+': 3, '-': 1, '.': 2 };\n\n/**\n * VT commands done by the parser - FIXME: move this to the parser?\n */\n// @vt: #Y ESC CSI \"Control Sequence Introducer\" \"ESC [\" \"Start of a CSI sequence.\"\n// @vt: #Y ESC OSC \"Operating System Command\" \"ESC ]\" \"Start of an OSC sequence.\"\n// @vt: #Y ESC DCS \"Device Control String\" \"ESC P\" \"Start of a DCS sequence.\"\n// @vt: #Y ESC ST \"String Terminator\" \"ESC \\\" \"Terminator used for string type sequences.\"\n// @vt: #Y ESC PM \"Privacy Message\" \"ESC ^\" \"Start of a privacy message.\"\n// @vt: #Y ESC APC \"Application Program Command\" \"ESC _\" \"Start of an APC sequence.\"\n// @vt: #Y C1 CSI \"Control Sequence Introducer\" \"\\x9B\" \"Start of a CSI sequence.\"\n// @vt: #Y C1 OSC \"Operating System Command\" \"\\x9D\" \"Start of an OSC sequence.\"\n// @vt: #Y C1 DCS \"Device Control String\" \"\\x90\" \"Start of a DCS sequence.\"\n// @vt: #Y C1 ST \"String Terminator\" \"\\x9C\" \"Terminator used for string type sequences.\"\n// @vt: #Y C1 PM \"Privacy Message\" \"\\x9E\" \"Start of a privacy message.\"\n// @vt: #Y C1 APC \"Application Program Command\" \"\\x9F\" \"Start of an APC sequence.\"\n// @vt: #Y C0 NUL \"Null\" \"\\0, \\x00\" \"NUL is ignored.\"\n// @vt: #Y C0 ESC \"Escape\" \"\\e, \\x1B\" \"Start of a sequence. Cancels any other sequence.\"\n\n/**\n * Document xterm VT features here that are currently unsupported\n */\n// @vt: #E[Supported via @xterm/addon-image.] DCS SIXEL \"SIXEL Graphics\" \"DCS Ps ; Ps ; Ps ; q \tPt ST\" \"Draw SIXEL image.\"\n// @vt: #N DCS DECUDK \"User Defined Keys\" \"DCS Ps ; Ps \\| Pt ST\" \"Definitions for user-defined keys.\"\n// @vt: #N DCS XTGETTCAP \"Request Terminfo String\" \"DCS + q Pt ST\" \"Request Terminfo String.\"\n// @vt: #N DCS XTSETTCAP \"Set Terminfo Data\" \"DCS + p Pt ST\" \"Set Terminfo Data.\"\n// @vt: #N OSC 1 \"Set Icon Name\" \"OSC 1 ; Pt BEL\" \"Set icon name.\"\n\n/**\n * Max length of the UTF32 input buffer. Real memory consumption is 4 times higher.\n */\nconst MAX_PARSEBUFFER_LENGTH = 131072;\n\n/**\n * Limit length of title and icon name stacks.\n */\nconst STACK_LIMIT = 10;\n\n// map params to window option\nfunction paramToWindowOption(n: number, opts: IWindowOptions): boolean {\n if (n > 24) {\n return opts.setWinLines || false;\n }\n switch (n) {\n case 1: return !!opts.restoreWin;\n case 2: return !!opts.minimizeWin;\n case 3: return !!opts.setWinPosition;\n case 4: return !!opts.setWinSizePixels;\n case 5: return !!opts.raiseWin;\n case 6: return !!opts.lowerWin;\n case 7: return !!opts.refreshWin;\n case 8: return !!opts.setWinSizeChars;\n case 9: return !!opts.maximizeWin;\n case 10: return !!opts.fullscreenWin;\n case 11: return !!opts.getWinState;\n case 13: return !!opts.getWinPosition;\n case 14: return !!opts.getWinSizePixels;\n case 15: return !!opts.getScreenSizePixels;\n case 16: return !!opts.getCellSizePixels;\n case 18: return !!opts.getWinSizeChars;\n case 19: return !!opts.getScreenSizeChars;\n case 20: return !!opts.getIconTitle;\n case 21: return !!opts.getWinTitle;\n case 22: return !!opts.pushTitle;\n case 23: return !!opts.popTitle;\n case 24: return !!opts.setWinLines;\n }\n return false;\n}\n\nexport enum WindowsOptionsReportType {\n GET_WIN_SIZE_PIXELS = 0,\n GET_CELL_SIZE_PIXELS = 1\n}\n\n// create a warning log if an async handler takes longer than the limit (in ms)\nconst SLOW_ASYNC_LIMIT = 5000;\n\n// Work variables to avoid garbage collection\nlet $temp = 0;\n\n/**\n * The terminal's standard implementation of IInputHandler, this handles all\n * input from the Parser.\n *\n * Refer to http://invisible-island.net/xterm/ctlseqs/ctlseqs.html to understand\n * each function's header comment.\n */\nexport class InputHandler extends Disposable implements IInputHandler {\n private _parseBuffer: Uint32Array = new Uint32Array(4096);\n private _stringDecoder: StringToUtf32 = new StringToUtf32();\n private _utf8Decoder: Utf8ToUtf32 = new Utf8ToUtf32();\n private _windowTitle = '';\n private _iconName = '';\n private _dirtyRowTracker: IDirtyRowTracker;\n protected _windowTitleStack: string[] = [];\n protected _iconNameStack: string[] = [];\n\n private _curAttrData: IAttributeData = DEFAULT_ATTR_DATA.clone();\n public getAttrData(): IAttributeData { return this._curAttrData; }\n private _eraseAttrDataInternal: IAttributeData = DEFAULT_ATTR_DATA.clone();\n\n private _activeBuffer: IBuffer;\n\n private readonly _onRequestBell = this._register(new Emitter());\n public readonly onRequestBell = this._onRequestBell.event;\n private readonly _onRequestRefreshRows = this._register(new Emitter<{ start: number, end: number } | undefined>());\n public readonly onRequestRefreshRows = this._onRequestRefreshRows.event;\n private readonly _onRequestReset = this._register(new Emitter());\n public readonly onRequestReset = this._onRequestReset.event;\n private readonly _onRequestSendFocus = this._register(new Emitter());\n public readonly onRequestSendFocus = this._onRequestSendFocus.event;\n private readonly _onRequestSyncScrollBar = this._register(new Emitter());\n public readonly onRequestSyncScrollBar = this._onRequestSyncScrollBar.event;\n private readonly _onRequestWindowsOptionsReport = this._register(new Emitter());\n public readonly onRequestWindowsOptionsReport = this._onRequestWindowsOptionsReport.event;\n\n private readonly _onA11yChar = this._register(new Emitter());\n public readonly onA11yChar = this._onA11yChar.event;\n private readonly _onA11yTab = this._register(new Emitter());\n public readonly onA11yTab = this._onA11yTab.event;\n private readonly _onCursorMove = this._register(new Emitter());\n public readonly onCursorMove = this._onCursorMove.event;\n private readonly _onLineFeed = this._register(new Emitter());\n public readonly onLineFeed = this._onLineFeed.event;\n private readonly _onScroll = this._register(new Emitter());\n public readonly onScroll = this._onScroll.event;\n private readonly _onTitleChange = this._register(new Emitter());\n public readonly onTitleChange = this._onTitleChange.event;\n private readonly _onColor = this._register(new Emitter());\n public readonly onColor = this._onColor.event;\n\n private _parseStack: IParseStack = {\n paused: false,\n cursorStartX: 0,\n cursorStartY: 0,\n decodedLength: 0,\n position: 0\n };\n\n constructor(\n private readonly _bufferService: IBufferService,\n private readonly _charsetService: ICharsetService,\n private readonly _coreService: ICoreService,\n private readonly _logService: ILogService,\n private readonly _optionsService: IOptionsService,\n private readonly _oscLinkService: IOscLinkService,\n private readonly _coreMouseService: ICoreMouseService,\n private readonly _unicodeService: IUnicodeService,\n private readonly _parser: IEscapeSequenceParser = new EscapeSequenceParser()\n ) {\n super();\n this._register(this._parser);\n this._dirtyRowTracker = new DirtyRowTracker(this._bufferService);\n\n // Track properties used in performance critical code manually to avoid using slow getters\n this._activeBuffer = this._bufferService.buffer;\n this._register(this._bufferService.buffers.onBufferActivate(e => this._activeBuffer = e.activeBuffer));\n\n /**\n * custom fallback handlers\n */\n this._parser.setCsiHandlerFallback((ident, params) => {\n this._logService.debug('Unknown CSI code: ', { identifier: this._parser.identToString(ident), params: params.toArray() });\n });\n this._parser.setEscHandlerFallback(ident => {\n this._logService.debug('Unknown ESC code: ', { identifier: this._parser.identToString(ident) });\n });\n this._parser.setExecuteHandlerFallback(code => {\n this._logService.debug('Unknown EXECUTE code: ', { code });\n });\n this._parser.setOscHandlerFallback((identifier, action, data) => {\n this._logService.debug('Unknown OSC code: ', { identifier, action, data });\n });\n this._parser.setDcsHandlerFallback((ident, action, payload) => {\n if (action === 'HOOK') {\n payload = payload.toArray();\n }\n this._logService.debug('Unknown DCS code: ', { identifier: this._parser.identToString(ident), action, payload });\n });\n\n /**\n * print handler\n */\n this._parser.setPrintHandler((data, start, end) => this.print(data, start, end));\n\n /**\n * CSI handler\n */\n this._parser.registerCsiHandler({ final: '@' }, params => this.insertChars(params));\n this._parser.registerCsiHandler({ intermediates: ' ', final: '@' }, params => this.scrollLeft(params));\n this._parser.registerCsiHandler({ final: 'A' }, params => this.cursorUp(params));\n this._parser.registerCsiHandler({ intermediates: ' ', final: 'A' }, params => this.scrollRight(params));\n this._parser.registerCsiHandler({ final: 'B' }, params => this.cursorDown(params));\n this._parser.registerCsiHandler({ final: 'C' }, params => this.cursorForward(params));\n this._parser.registerCsiHandler({ final: 'D' }, params => this.cursorBackward(params));\n this._parser.registerCsiHandler({ final: 'E' }, params => this.cursorNextLine(params));\n this._parser.registerCsiHandler({ final: 'F' }, params => this.cursorPrecedingLine(params));\n this._parser.registerCsiHandler({ final: 'G' }, params => this.cursorCharAbsolute(params));\n this._parser.registerCsiHandler({ final: 'H' }, params => this.cursorPosition(params));\n this._parser.registerCsiHandler({ final: 'I' }, params => this.cursorForwardTab(params));\n this._parser.registerCsiHandler({ final: 'J' }, params => this.eraseInDisplay(params, false));\n this._parser.registerCsiHandler({ prefix: '?', final: 'J' }, params => this.eraseInDisplay(params, true));\n this._parser.registerCsiHandler({ final: 'K' }, params => this.eraseInLine(params, false));\n this._parser.registerCsiHandler({ prefix: '?', final: 'K' }, params => this.eraseInLine(params, true));\n this._parser.registerCsiHandler({ final: 'L' }, params => this.insertLines(params));\n this._parser.registerCsiHandler({ final: 'M' }, params => this.deleteLines(params));\n this._parser.registerCsiHandler({ final: 'P' }, params => this.deleteChars(params));\n this._parser.registerCsiHandler({ final: 'S' }, params => this.scrollUp(params));\n this._parser.registerCsiHandler({ final: 'T' }, params => this.scrollDown(params));\n this._parser.registerCsiHandler({ final: 'X' }, params => this.eraseChars(params));\n this._parser.registerCsiHandler({ final: 'Z' }, params => this.cursorBackwardTab(params));\n this._parser.registerCsiHandler({ final: '`' }, params => this.charPosAbsolute(params));\n this._parser.registerCsiHandler({ final: 'a' }, params => this.hPositionRelative(params));\n this._parser.registerCsiHandler({ final: 'b' }, params => this.repeatPrecedingCharacter(params));\n this._parser.registerCsiHandler({ final: 'c' }, params => this.sendDeviceAttributesPrimary(params));\n this._parser.registerCsiHandler({ prefix: '>', final: 'c' }, params => this.sendDeviceAttributesSecondary(params));\n this._parser.registerCsiHandler({ final: 'd' }, params => this.linePosAbsolute(params));\n this._parser.registerCsiHandler({ final: 'e' }, params => this.vPositionRelative(params));\n this._parser.registerCsiHandler({ final: 'f' }, params => this.hVPosition(params));\n this._parser.registerCsiHandler({ final: 'g' }, params => this.tabClear(params));\n this._parser.registerCsiHandler({ final: 'h' }, params => this.setMode(params));\n this._parser.registerCsiHandler({ prefix: '?', final: 'h' }, params => this.setModePrivate(params));\n this._parser.registerCsiHandler({ final: 'l' }, params => this.resetMode(params));\n this._parser.registerCsiHandler({ prefix: '?', final: 'l' }, params => this.resetModePrivate(params));\n this._parser.registerCsiHandler({ final: 'm' }, params => this.charAttributes(params));\n this._parser.registerCsiHandler({ final: 'n' }, params => this.deviceStatus(params));\n this._parser.registerCsiHandler({ prefix: '?', final: 'n' }, params => this.deviceStatusPrivate(params));\n this._parser.registerCsiHandler({ intermediates: '!', final: 'p' }, params => this.softReset(params));\n this._parser.registerCsiHandler({ intermediates: ' ', final: 'q' }, params => this.setCursorStyle(params));\n this._parser.registerCsiHandler({ final: 'r' }, params => this.setScrollRegion(params));\n this._parser.registerCsiHandler({ final: 's' }, params => this.saveCursor(params));\n this._parser.registerCsiHandler({ final: 't' }, params => this.windowOptions(params));\n this._parser.registerCsiHandler({ final: 'u' }, params => this.restoreCursor(params));\n this._parser.registerCsiHandler({ intermediates: '\\'', final: '}' }, params => this.insertColumns(params));\n this._parser.registerCsiHandler({ intermediates: '\\'', final: '~' }, params => this.deleteColumns(params));\n this._parser.registerCsiHandler({ intermediates: '\"', final: 'q' }, params => this.selectProtected(params));\n this._parser.registerCsiHandler({ intermediates: '$', final: 'p' }, params => this.requestMode(params, true));\n this._parser.registerCsiHandler({ prefix: '?', intermediates: '$', final: 'p' }, params => this.requestMode(params, false));\n\n /**\n * execute handler\n */\n this._parser.setExecuteHandler(C0.BEL, () => this.bell());\n this._parser.setExecuteHandler(C0.LF, () => this.lineFeed());\n this._parser.setExecuteHandler(C0.VT, () => this.lineFeed());\n this._parser.setExecuteHandler(C0.FF, () => this.lineFeed());\n this._parser.setExecuteHandler(C0.CR, () => this.carriageReturn());\n this._parser.setExecuteHandler(C0.BS, () => this.backspace());\n this._parser.setExecuteHandler(C0.HT, () => this.tab());\n this._parser.setExecuteHandler(C0.SO, () => this.shiftOut());\n this._parser.setExecuteHandler(C0.SI, () => this.shiftIn());\n // FIXME: What do to with missing? Old code just added those to print.\n\n this._parser.setExecuteHandler(C1.IND, () => this.index());\n this._parser.setExecuteHandler(C1.NEL, () => this.nextLine());\n this._parser.setExecuteHandler(C1.HTS, () => this.tabSet());\n\n /**\n * OSC handler\n */\n // 0 - icon name + title\n this._parser.registerOscHandler(0, new OscHandler(data => { this.setTitle(data); this.setIconName(data); return true; }));\n // 1 - icon name\n this._parser.registerOscHandler(1, new OscHandler(data => this.setIconName(data)));\n // 2 - title\n this._parser.registerOscHandler(2, new OscHandler(data => this.setTitle(data)));\n // 3 - set property X in the form \"prop=value\"\n // 4 - Change Color Number\n this._parser.registerOscHandler(4, new OscHandler(data => this.setOrReportIndexedColor(data)));\n // 5 - Change Special Color Number\n // 6 - Enable/disable Special Color Number c\n // 7 - current directory? (not in xterm spec, see https://gitlab.com/gnachman/iterm2/issues/3939)\n // 8 - create hyperlink (not in xterm spec, see https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda)\n this._parser.registerOscHandler(8, new OscHandler(data => this.setHyperlink(data)));\n // 10 - Change VT100 text foreground color to Pt.\n this._parser.registerOscHandler(10, new OscHandler(data => this.setOrReportFgColor(data)));\n // 11 - Change VT100 text background color to Pt.\n this._parser.registerOscHandler(11, new OscHandler(data => this.setOrReportBgColor(data)));\n // 12 - Change text cursor color to Pt.\n this._parser.registerOscHandler(12, new OscHandler(data => this.setOrReportCursorColor(data)));\n // 13 - Change mouse foreground color to Pt.\n // 14 - Change mouse background color to Pt.\n // 15 - Change Tektronix foreground color to Pt.\n // 16 - Change Tektronix background color to Pt.\n // 17 - Change highlight background color to Pt.\n // 18 - Change Tektronix cursor color to Pt.\n // 19 - Change highlight foreground color to Pt.\n // 46 - Change Log File to Pt.\n // 50 - Set Font to Pt.\n // 51 - reserved for Emacs shell.\n // 52 - Manipulate Selection Data.\n // 104 ; c - Reset Color Number c.\n this._parser.registerOscHandler(104, new OscHandler(data => this.restoreIndexedColor(data)));\n // 105 ; c - Reset Special Color Number c.\n // 106 ; c; f - Enable/disable Special Color Number c.\n // 110 - Reset VT100 text foreground color.\n this._parser.registerOscHandler(110, new OscHandler(data => this.restoreFgColor(data)));\n // 111 - Reset VT100 text background color.\n this._parser.registerOscHandler(111, new OscHandler(data => this.restoreBgColor(data)));\n // 112 - Reset text cursor color.\n this._parser.registerOscHandler(112, new OscHandler(data => this.restoreCursorColor(data)));\n // 113 - Reset mouse foreground color.\n // 114 - Reset mouse background color.\n // 115 - Reset Tektronix foreground color.\n // 116 - Reset Tektronix background color.\n // 117 - Reset highlight color.\n // 118 - Reset Tektronix cursor color.\n // 119 - Reset highlight foreground color.\n\n /**\n * ESC handlers\n */\n this._parser.registerEscHandler({ final: '7' }, () => this.saveCursor());\n this._parser.registerEscHandler({ final: '8' }, () => this.restoreCursor());\n this._parser.registerEscHandler({ final: 'D' }, () => this.index());\n this._parser.registerEscHandler({ final: 'E' }, () => this.nextLine());\n this._parser.registerEscHandler({ final: 'H' }, () => this.tabSet());\n this._parser.registerEscHandler({ final: 'M' }, () => this.reverseIndex());\n this._parser.registerEscHandler({ final: '=' }, () => this.keypadApplicationMode());\n this._parser.registerEscHandler({ final: '>' }, () => this.keypadNumericMode());\n this._parser.registerEscHandler({ final: 'c' }, () => this.fullReset());\n this._parser.registerEscHandler({ final: 'n' }, () => this.setgLevel(2));\n this._parser.registerEscHandler({ final: 'o' }, () => this.setgLevel(3));\n this._parser.registerEscHandler({ final: '|' }, () => this.setgLevel(3));\n this._parser.registerEscHandler({ final: '}' }, () => this.setgLevel(2));\n this._parser.registerEscHandler({ final: '~' }, () => this.setgLevel(1));\n this._parser.registerEscHandler({ intermediates: '%', final: '@' }, () => this.selectDefaultCharset());\n this._parser.registerEscHandler({ intermediates: '%', final: 'G' }, () => this.selectDefaultCharset());\n for (const flag in CHARSETS) {\n this._parser.registerEscHandler({ intermediates: '(', final: flag }, () => this.selectCharset('(' + flag));\n this._parser.registerEscHandler({ intermediates: ')', final: flag }, () => this.selectCharset(')' + flag));\n this._parser.registerEscHandler({ intermediates: '*', final: flag }, () => this.selectCharset('*' + flag));\n this._parser.registerEscHandler({ intermediates: '+', final: flag }, () => this.selectCharset('+' + flag));\n this._parser.registerEscHandler({ intermediates: '-', final: flag }, () => this.selectCharset('-' + flag));\n this._parser.registerEscHandler({ intermediates: '.', final: flag }, () => this.selectCharset('.' + flag));\n this._parser.registerEscHandler({ intermediates: '/', final: flag }, () => this.selectCharset('/' + flag)); // TODO: supported?\n }\n this._parser.registerEscHandler({ intermediates: '#', final: '8' }, () => this.screenAlignmentPattern());\n\n /**\n * error handler\n */\n this._parser.setErrorHandler((state: IParsingState) => {\n this._logService.error('Parsing error: ', state);\n return state;\n });\n\n /**\n * DCS handler\n */\n this._parser.registerDcsHandler({ intermediates: '$', final: 'q' }, new DcsHandler((data, params) => this.requestStatusString(data, params)));\n }\n\n /**\n * Async parse support.\n */\n private _preserveStack(cursorStartX: number, cursorStartY: number, decodedLength: number, position: number): void {\n this._parseStack.paused = true;\n this._parseStack.cursorStartX = cursorStartX;\n this._parseStack.cursorStartY = cursorStartY;\n this._parseStack.decodedLength = decodedLength;\n this._parseStack.position = position;\n }\n\n private _logSlowResolvingAsync(p: Promise): void {\n // log a limited warning about an async handler taking too long\n if (this._logService.logLevel <= LogLevelEnum.WARN) {\n Promise.race([p, new Promise((res, rej) => setTimeout(() => rej('#SLOW_TIMEOUT'), SLOW_ASYNC_LIMIT))])\n .catch(err => {\n if (err !== '#SLOW_TIMEOUT') {\n throw err;\n }\n console.warn(`async parser handler taking longer than ${SLOW_ASYNC_LIMIT} ms`);\n });\n }\n }\n\n private _getCurrentLinkId(): number {\n return this._curAttrData.extended.urlId;\n }\n\n /**\n * Parse call with async handler support.\n *\n * Whether the stack state got preserved for the next call, is indicated by the return value:\n * - undefined (void):\n * all handlers were sync, no stack save, continue normally with next chunk\n * - Promise\\:\n * execution stopped at async handler, stack saved, continue with same chunk and the promise\n * resolve value as `promiseResult` until the method returns `undefined`\n *\n * Note: This method should only be called by `Terminal.write` to ensure correct execution order\n * and proper continuation of async parser handlers.\n */\n public parse(data: string | Uint8Array, promiseResult?: boolean): void | Promise {\n let result: void | Promise;\n let cursorStartX = this._activeBuffer.x;\n let cursorStartY = this._activeBuffer.y;\n let start = 0;\n const wasPaused = this._parseStack.paused;\n\n if (wasPaused) {\n // assumption: _parseBuffer never mutates between async calls\n if (result = this._parser.parse(this._parseBuffer, this._parseStack.decodedLength, promiseResult)) {\n this._logSlowResolvingAsync(result);\n return result;\n }\n cursorStartX = this._parseStack.cursorStartX;\n cursorStartY = this._parseStack.cursorStartY;\n this._parseStack.paused = false;\n if (data.length > MAX_PARSEBUFFER_LENGTH) {\n start = this._parseStack.position + MAX_PARSEBUFFER_LENGTH;\n }\n }\n\n // Log debug data, the log level gate is to prevent extra work in this hot path\n if (this._logService.logLevel <= LogLevelEnum.DEBUG) {\n this._logService.debug(`parsing data ${typeof data === 'string' ? ` \"${data}\"` : ` \"${Array.prototype.map.call(data, e => String.fromCharCode(e)).join('')}\"`}`);\n }\n if (this._logService.logLevel === LogLevelEnum.TRACE) {\n this._logService.trace(`parsing data (codes)`, typeof data === 'string'\n ? data.split('').map(e => e.charCodeAt(0))\n : data\n );\n }\n\n // resize input buffer if needed\n if (this._parseBuffer.length < data.length) {\n if (this._parseBuffer.length < MAX_PARSEBUFFER_LENGTH) {\n this._parseBuffer = new Uint32Array(Math.min(data.length, MAX_PARSEBUFFER_LENGTH));\n }\n }\n\n // Clear the dirty row service so we know which lines changed as a result of parsing\n // Important: do not clear between async calls, otherwise we lost pending update information.\n if (!wasPaused) {\n this._dirtyRowTracker.clearRange();\n }\n\n // process big data in smaller chunks\n if (data.length > MAX_PARSEBUFFER_LENGTH) {\n for (let i = start; i < data.length; i += MAX_PARSEBUFFER_LENGTH) {\n const end = i + MAX_PARSEBUFFER_LENGTH < data.length ? i + MAX_PARSEBUFFER_LENGTH : data.length;\n const len = (typeof data === 'string')\n ? this._stringDecoder.decode(data.substring(i, end), this._parseBuffer)\n : this._utf8Decoder.decode(data.subarray(i, end), this._parseBuffer);\n if (result = this._parser.parse(this._parseBuffer, len)) {\n this._preserveStack(cursorStartX, cursorStartY, len, i);\n this._logSlowResolvingAsync(result);\n return result;\n }\n }\n } else {\n if (!wasPaused) {\n const len = (typeof data === 'string')\n ? this._stringDecoder.decode(data, this._parseBuffer)\n : this._utf8Decoder.decode(data, this._parseBuffer);\n if (result = this._parser.parse(this._parseBuffer, len)) {\n this._preserveStack(cursorStartX, cursorStartY, len, 0);\n this._logSlowResolvingAsync(result);\n return result;\n }\n }\n }\n\n if (this._activeBuffer.x !== cursorStartX || this._activeBuffer.y !== cursorStartY) {\n this._onCursorMove.fire();\n }\n\n // Refresh any dirty rows accumulated as part of parsing, fire only for rows within the\n // _viewport_ which is relative to ydisp, not relative to ybase.\n const viewportEnd = this._dirtyRowTracker.end + (this._bufferService.buffer.ybase - this._bufferService.buffer.ydisp);\n const viewportStart = this._dirtyRowTracker.start + (this._bufferService.buffer.ybase - this._bufferService.buffer.ydisp);\n if (viewportStart < this._bufferService.rows) {\n this._onRequestRefreshRows.fire({\n start: Math.min(viewportStart, this._bufferService.rows - 1),\n end: Math.min(viewportEnd, this._bufferService.rows - 1)\n });\n }\n }\n\n public print(data: Uint32Array, start: number, end: number): void {\n let code: number;\n let chWidth: number;\n const charset = this._charsetService.charset;\n const screenReaderMode = this._optionsService.rawOptions.screenReaderMode;\n const cols = this._bufferService.cols;\n const wraparoundMode = this._coreService.decPrivateModes.wraparound;\n const insertMode = this._coreService.modes.insertMode;\n const curAttr = this._curAttrData;\n let bufferRow = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y)!;\n\n this._dirtyRowTracker.markDirty(this._activeBuffer.y);\n\n // handle wide chars: reset start_cell-1 if we would overwrite the second cell of a wide char\n if (this._activeBuffer.x && end - start > 0 && bufferRow.getWidth(this._activeBuffer.x - 1) === 2) {\n bufferRow.setCellFromCodepoint(this._activeBuffer.x - 1, 0, 1, curAttr);\n }\n\n let precedingJoinState = this._parser.precedingJoinState;\n for (let pos = start; pos < end; ++pos) {\n code = data[pos];\n\n // get charset replacement character\n // charset is only defined for ASCII, therefore we only\n // search for an replacement char if code < 127\n if (code < 127 && charset) {\n const ch = charset[String.fromCharCode(code)];\n if (ch) {\n code = ch.charCodeAt(0);\n }\n }\n\n const currentInfo = this._unicodeService.charProperties(code, precedingJoinState);\n chWidth = UnicodeService.extractWidth(currentInfo);\n const shouldJoin = UnicodeService.extractShouldJoin(currentInfo);\n const oldWidth = shouldJoin ? UnicodeService.extractWidth(precedingJoinState) : 0;\n precedingJoinState = currentInfo;\n\n if (screenReaderMode) {\n this._onA11yChar.fire(stringFromCodePoint(code));\n }\n if (this._getCurrentLinkId()) {\n this._oscLinkService.addLineToLink(this._getCurrentLinkId(), this._activeBuffer.ybase + this._activeBuffer.y);\n }\n\n // goto next line if ch would overflow\n // NOTE: To avoid costly width checks here,\n // the terminal does not allow a cols < 2.\n if (this._activeBuffer.x + chWidth - oldWidth > cols) {\n // autowrap - DECAWM\n // automatically wraps to the beginning of the next line\n if (wraparoundMode) {\n const oldRow = bufferRow;\n let oldCol = this._activeBuffer.x - oldWidth;\n this._activeBuffer.x = oldWidth;\n this._activeBuffer.y++;\n if (this._activeBuffer.y === this._activeBuffer.scrollBottom + 1) {\n this._activeBuffer.y--;\n this._bufferService.scroll(this._eraseAttrData(), true);\n } else {\n if (this._activeBuffer.y >= this._bufferService.rows) {\n this._activeBuffer.y = this._bufferService.rows - 1;\n }\n // The line already exists (eg. the initial viewport), mark it as a\n // wrapped line\n this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y)!.isWrapped = true;\n }\n // row changed, get it again\n bufferRow = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y)!;\n if (oldWidth > 0 && bufferRow instanceof BufferLine) {\n // Combining character widens 1 column to 2.\n // Move old character to next line.\n bufferRow.copyCellsFrom(oldRow as BufferLine,\n oldCol, 0, oldWidth, false);\n }\n // clear left over cells to the right\n while (oldCol < cols) {\n oldRow.setCellFromCodepoint(oldCol++, 0, 1, curAttr);\n }\n } else {\n this._activeBuffer.x = cols - 1;\n if (chWidth === 2) {\n // FIXME: check for xterm behavior\n // What to do here? We got a wide char that does not fit into last cell\n continue;\n }\n }\n }\n\n // insert combining char at last cursor position\n // this._activeBuffer.x should never be 0 for a combining char\n // since they always follow a cell consuming char\n // therefore we can test for this._activeBuffer.x to avoid overflow left\n if (shouldJoin && this._activeBuffer.x) {\n const offset = bufferRow.getWidth(this._activeBuffer.x - 1) ? 1 : 2;\n // if empty cell after fullwidth, need to go 2 cells back\n // it is save to step 2 cells back here\n // since an empty cell is only set by fullwidth chars\n bufferRow.addCodepointToCell(this._activeBuffer.x - offset,\n code, chWidth);\n for (let delta = chWidth - oldWidth; --delta >= 0;) {\n bufferRow.setCellFromCodepoint(this._activeBuffer.x++, 0, 0, curAttr);\n }\n continue;\n }\n\n // insert mode: move characters to right\n if (insertMode) {\n // right shift cells according to the width\n bufferRow.insertCells(this._activeBuffer.x, chWidth - oldWidth, this._activeBuffer.getNullCell(curAttr));\n // test last cell - since the last cell has only room for\n // a halfwidth char any fullwidth shifted there is lost\n // and will be set to empty cell\n if (bufferRow.getWidth(cols - 1) === 2) {\n bufferRow.setCellFromCodepoint(cols - 1, NULL_CELL_CODE, NULL_CELL_WIDTH, curAttr);\n }\n }\n\n // write current char to buffer and advance cursor\n bufferRow.setCellFromCodepoint(this._activeBuffer.x++, code, chWidth, curAttr);\n\n // fullwidth char - also set next cell to placeholder stub and advance cursor\n // for graphemes bigger than fullwidth we can simply loop to zero\n // we already made sure above, that this._activeBuffer.x + chWidth will not overflow right\n if (chWidth > 0) {\n while (--chWidth) {\n // other than a regular empty cell a cell following a wide char has no width\n bufferRow.setCellFromCodepoint(this._activeBuffer.x++, 0, 0, curAttr);\n }\n }\n }\n\n this._parser.precedingJoinState = precedingJoinState;\n\n // handle wide chars: reset cell to the right if it is second cell of a wide char\n if (this._activeBuffer.x < cols && end - start > 0 && bufferRow.getWidth(this._activeBuffer.x) === 0 && !bufferRow.hasContent(this._activeBuffer.x)) {\n bufferRow.setCellFromCodepoint(this._activeBuffer.x, 0, 1, curAttr);\n }\n\n this._dirtyRowTracker.markDirty(this._activeBuffer.y);\n }\n\n /**\n * Forward registerCsiHandler from parser.\n */\n public registerCsiHandler(id: IFunctionIdentifier, callback: (params: IParams) => boolean | Promise): IDisposable {\n if (id.final === 't' && !id.prefix && !id.intermediates) {\n // security: always check whether window option is allowed\n return this._parser.registerCsiHandler(id, params => {\n if (!paramToWindowOption(params.params[0], this._optionsService.rawOptions.windowOptions)) {\n return true;\n }\n return callback(params);\n });\n }\n return this._parser.registerCsiHandler(id, callback);\n }\n\n /**\n * Forward registerDcsHandler from parser.\n */\n public registerDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: IParams) => boolean | Promise): IDisposable {\n return this._parser.registerDcsHandler(id, new DcsHandler(callback));\n }\n\n /**\n * Forward registerEscHandler from parser.\n */\n public registerEscHandler(id: IFunctionIdentifier, callback: () => boolean | Promise): IDisposable {\n return this._parser.registerEscHandler(id, callback);\n }\n\n /**\n * Forward registerOscHandler from parser.\n */\n public registerOscHandler(ident: number, callback: (data: string) => boolean | Promise): IDisposable {\n return this._parser.registerOscHandler(ident, new OscHandler(callback));\n }\n\n /**\n * BEL\n * Bell (Ctrl-G).\n *\n * @vt: #Y C0 BEL \"Bell\" \"\\a, \\x07\" \"Ring the bell.\"\n * The behavior of the bell is further customizable with `ITerminalOptions.bellStyle`\n * and `ITerminalOptions.bellSound`.\n */\n public bell(): boolean {\n this._onRequestBell.fire();\n return true;\n }\n\n /**\n * LF\n * Line Feed or New Line (NL). (LF is Ctrl-J).\n *\n * @vt: #Y C0 LF \"Line Feed\" \"\\n, \\x0A\" \"Move the cursor one row down, scrolling if needed.\"\n * Scrolling is restricted to scroll margins and will only happen on the bottom line.\n *\n * @vt: #Y C0 VT \"Vertical Tabulation\" \"\\v, \\x0B\" \"Treated as LF.\"\n * @vt: #Y C0 FF \"Form Feed\" \"\\f, \\x0C\" \"Treated as LF.\"\n */\n public lineFeed(): boolean {\n this._dirtyRowTracker.markDirty(this._activeBuffer.y);\n if (this._optionsService.rawOptions.convertEol) {\n this._activeBuffer.x = 0;\n }\n this._activeBuffer.y++;\n if (this._activeBuffer.y === this._activeBuffer.scrollBottom + 1) {\n this._activeBuffer.y--;\n this._bufferService.scroll(this._eraseAttrData());\n } else if (this._activeBuffer.y >= this._bufferService.rows) {\n this._activeBuffer.y = this._bufferService.rows - 1;\n } else {\n // There was an explicit line feed (not just a carriage return), so clear the wrapped state of\n // the line. This is particularly important on conpty/Windows where revisiting lines to\n // reprint is common, especially on resize. Note that the windowsMode wrapped line heuristics\n // can mess with this so windowsMode should be disabled, which is recommended on Windows build\n // 21376 and above.\n this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y)!.isWrapped = false;\n }\n // If the end of the line is hit, prevent this action from wrapping around to the next line.\n if (this._activeBuffer.x >= this._bufferService.cols) {\n this._activeBuffer.x--;\n }\n this._dirtyRowTracker.markDirty(this._activeBuffer.y);\n\n this._onLineFeed.fire();\n return true;\n }\n\n /**\n * CR\n * Carriage Return (Ctrl-M).\n *\n * @vt: #Y C0 CR \"Carriage Return\" \"\\r, \\x0D\" \"Move the cursor to the beginning of the row.\"\n */\n public carriageReturn(): boolean {\n this._activeBuffer.x = 0;\n return true;\n }\n\n /**\n * BS\n * Backspace (Ctrl-H).\n *\n * @vt: #Y C0 BS \"Backspace\" \"\\b, \\x08\" \"Move the cursor one position to the left.\"\n * By default it is not possible to move the cursor past the leftmost position.\n * If `reverse wrap-around` (`CSI ? 45 h`) is set, a previous soft line wrap (DECAWM)\n * can be undone with BS within the scroll margins. In that case the cursor will wrap back\n * to the end of the previous row. Note that it is not possible to peek back into the scrollbuffer\n * with the cursor, thus at the home position (top-leftmost cell) this has no effect.\n */\n public backspace(): boolean {\n // reverse wrap-around is disabled\n if (!this._coreService.decPrivateModes.reverseWraparound) {\n this._restrictCursor();\n if (this._activeBuffer.x > 0) {\n this._activeBuffer.x--;\n }\n return true;\n }\n\n // reverse wrap-around is enabled\n // other than for normal operation mode, reverse wrap-around allows the cursor\n // to be at x=cols to be able to address the last cell of a row by BS\n this._restrictCursor(this._bufferService.cols);\n\n if (this._activeBuffer.x > 0) {\n this._activeBuffer.x--;\n } else {\n /**\n * reverse wrap-around handling:\n * Our implementation deviates from xterm on purpose. Details:\n * - only previous soft NLs can be reversed (isWrapped=true)\n * - only works within scrollborders (top/bottom, left/right not yet supported)\n * - cannot peek into scrollbuffer\n * - any cursor movement sequence keeps working as expected\n */\n if (this._activeBuffer.x === 0\n && this._activeBuffer.y > this._activeBuffer.scrollTop\n && this._activeBuffer.y <= this._activeBuffer.scrollBottom\n && this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y)?.isWrapped) {\n this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y)!.isWrapped = false;\n this._activeBuffer.y--;\n this._activeBuffer.x = this._bufferService.cols - 1;\n // find last taken cell - last cell can have 3 different states:\n // - hasContent(true) + hasWidth(1): narrow char - we are done\n // - hasWidth(0): second part of wide char - we are done\n // - hasContent(false) + hasWidth(1): empty cell due to early wrapping wide char, go one\n // cell further back\n const line = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y)!;\n if (line.hasWidth(this._activeBuffer.x) && !line.hasContent(this._activeBuffer.x)) {\n this._activeBuffer.x--;\n // We do this only once, since width=1 + hasContent=false currently happens only once\n // before early wrapping of a wide char.\n // This needs to be fixed once we support graphemes taking more than 2 cells.\n }\n }\n }\n this._restrictCursor();\n return true;\n }\n\n /**\n * TAB\n * Horizontal Tab (HT) (Ctrl-I).\n *\n * @vt: #Y C0 HT \"Horizontal Tabulation\" \"\\t, \\x09\" \"Move the cursor to the next character tab stop.\"\n */\n public tab(): boolean {\n if (this._activeBuffer.x >= this._bufferService.cols) {\n return true;\n }\n const originalX = this._activeBuffer.x;\n this._activeBuffer.x = this._activeBuffer.nextStop();\n if (this._optionsService.rawOptions.screenReaderMode) {\n this._onA11yTab.fire(this._activeBuffer.x - originalX);\n }\n return true;\n }\n\n /**\n * SO\n * Shift Out (Ctrl-N) -> Switch to Alternate Character Set. This invokes the\n * G1 character set.\n *\n * @vt: #P[Only limited ISO-2022 charset support.] C0 SO \"Shift Out\" \"\\x0E\" \"Switch to an alternative character set.\"\n */\n public shiftOut(): boolean {\n this._charsetService.setgLevel(1);\n return true;\n }\n\n /**\n * SI\n * Shift In (Ctrl-O) -> Switch to Standard Character Set. This invokes the G0\n * character set (the default).\n *\n * @vt: #Y C0 SI \"Shift In\" \"\\x0F\" \"Return to regular character set after Shift Out.\"\n */\n public shiftIn(): boolean {\n this._charsetService.setgLevel(0);\n return true;\n }\n\n /**\n * Restrict cursor to viewport size / scroll margin (origin mode).\n */\n private _restrictCursor(maxCol: number = this._bufferService.cols - 1): void {\n this._activeBuffer.x = Math.min(maxCol, Math.max(0, this._activeBuffer.x));\n this._activeBuffer.y = this._coreService.decPrivateModes.origin\n ? Math.min(this._activeBuffer.scrollBottom, Math.max(this._activeBuffer.scrollTop, this._activeBuffer.y))\n : Math.min(this._bufferService.rows - 1, Math.max(0, this._activeBuffer.y));\n this._dirtyRowTracker.markDirty(this._activeBuffer.y);\n }\n\n /**\n * Set absolute cursor position.\n */\n private _setCursor(x: number, y: number): void {\n this._dirtyRowTracker.markDirty(this._activeBuffer.y);\n if (this._coreService.decPrivateModes.origin) {\n this._activeBuffer.x = x;\n this._activeBuffer.y = this._activeBuffer.scrollTop + y;\n } else {\n this._activeBuffer.x = x;\n this._activeBuffer.y = y;\n }\n this._restrictCursor();\n this._dirtyRowTracker.markDirty(this._activeBuffer.y);\n }\n\n /**\n * Set relative cursor position.\n */\n private _moveCursor(x: number, y: number): void {\n // for relative changes we have to make sure we are within 0 .. cols/rows - 1\n // before calculating the new position\n this._restrictCursor();\n this._setCursor(this._activeBuffer.x + x, this._activeBuffer.y + y);\n }\n\n /**\n * CSI Ps A\n * Cursor Up Ps Times (default = 1) (CUU).\n *\n * @vt: #Y CSI CUU \"Cursor Up\" \"CSI Ps A\" \"Move cursor `Ps` times up (default=1).\"\n * If the cursor would pass the top scroll margin, it will stop there.\n */\n public cursorUp(params: IParams): boolean {\n // stop at scrollTop\n const diffToTop = this._activeBuffer.y - this._activeBuffer.scrollTop;\n if (diffToTop >= 0) {\n this._moveCursor(0, -Math.min(diffToTop, params.params[0] || 1));\n } else {\n this._moveCursor(0, -(params.params[0] || 1));\n }\n return true;\n }\n\n /**\n * CSI Ps B\n * Cursor Down Ps Times (default = 1) (CUD).\n *\n * @vt: #Y CSI CUD \"Cursor Down\" \"CSI Ps B\" \"Move cursor `Ps` times down (default=1).\"\n * If the cursor would pass the bottom scroll margin, it will stop there.\n */\n public cursorDown(params: IParams): boolean {\n // stop at scrollBottom\n const diffToBottom = this._activeBuffer.scrollBottom - this._activeBuffer.y;\n if (diffToBottom >= 0) {\n this._moveCursor(0, Math.min(diffToBottom, params.params[0] || 1));\n } else {\n this._moveCursor(0, params.params[0] || 1);\n }\n return true;\n }\n\n /**\n * CSI Ps C\n * Cursor Forward Ps Times (default = 1) (CUF).\n *\n * @vt: #Y CSI CUF \"Cursor Forward\" \"CSI Ps C\" \"Move cursor `Ps` times forward (default=1).\"\n */\n public cursorForward(params: IParams): boolean {\n this._moveCursor(params.params[0] || 1, 0);\n return true;\n }\n\n /**\n * CSI Ps D\n * Cursor Backward Ps Times (default = 1) (CUB).\n *\n * @vt: #Y CSI CUB \"Cursor Backward\" \"CSI Ps D\" \"Move cursor `Ps` times backward (default=1).\"\n */\n public cursorBackward(params: IParams): boolean {\n this._moveCursor(-(params.params[0] || 1), 0);\n return true;\n }\n\n /**\n * CSI Ps E\n * Cursor Next Line Ps Times (default = 1) (CNL).\n * Other than cursorDown (CUD) also set the cursor to first column.\n *\n * @vt: #Y CSI CNL \"Cursor Next Line\" \"CSI Ps E\" \"Move cursor `Ps` times down (default=1) and to the first column.\"\n * Same as CUD, additionally places the cursor at the first column.\n */\n public cursorNextLine(params: IParams): boolean {\n this.cursorDown(params);\n this._activeBuffer.x = 0;\n return true;\n }\n\n /**\n * CSI Ps F\n * Cursor Previous Line Ps Times (default = 1) (CPL).\n * Other than cursorUp (CUU) also set the cursor to first column.\n *\n * @vt: #Y CSI CPL \"Cursor Backward\" \"CSI Ps F\" \"Move cursor `Ps` times up (default=1) and to the first column.\"\n * Same as CUU, additionally places the cursor at the first column.\n */\n public cursorPrecedingLine(params: IParams): boolean {\n this.cursorUp(params);\n this._activeBuffer.x = 0;\n return true;\n }\n\n /**\n * CSI Ps G\n * Cursor Character Absolute [column] (default = [row,1]) (CHA).\n *\n * @vt: #Y CSI CHA \"Cursor Horizontal Absolute\" \"CSI Ps G\" \"Move cursor to `Ps`-th column of the active row (default=1).\"\n */\n public cursorCharAbsolute(params: IParams): boolean {\n this._setCursor((params.params[0] || 1) - 1, this._activeBuffer.y);\n return true;\n }\n\n /**\n * CSI Ps ; Ps H\n * Cursor Position [row;column] (default = [1,1]) (CUP).\n *\n * @vt: #Y CSI CUP \"Cursor Position\" \"CSI Ps ; Ps H\" \"Set cursor to position [`Ps`, `Ps`] (default = [1, 1]).\"\n * If ORIGIN mode is set, places the cursor to the absolute position within the scroll margins.\n * If ORIGIN mode is not set, places the cursor to the absolute position within the viewport.\n * Note that the coordinates are 1-based, thus the top left position starts at `1 ; 1`.\n */\n public cursorPosition(params: IParams): boolean {\n this._setCursor(\n // col\n (params.length >= 2) ? (params.params[1] || 1) - 1 : 0,\n // row\n (params.params[0] || 1) - 1\n );\n return true;\n }\n\n /**\n * CSI Pm ` Character Position Absolute\n * [column] (default = [row,1]) (HPA).\n * Currently same functionality as CHA.\n *\n * @vt: #Y CSI HPA \"Horizontal Position Absolute\" \"CSI Ps ` \" \"Same as CHA.\"\n */\n public charPosAbsolute(params: IParams): boolean {\n this._setCursor((params.params[0] || 1) - 1, this._activeBuffer.y);\n return true;\n }\n\n /**\n * CSI Pm a Character Position Relative\n * [columns] (default = [row,col+1]) (HPR)\n *\n * @vt: #Y CSI HPR \"Horizontal Position Relative\" \"CSI Ps a\" \"Same as CUF.\"\n */\n public hPositionRelative(params: IParams): boolean {\n this._moveCursor(params.params[0] || 1, 0);\n return true;\n }\n\n /**\n * CSI Pm d Vertical Position Absolute (VPA)\n * [row] (default = [1,column])\n *\n * @vt: #Y CSI VPA \"Vertical Position Absolute\" \"CSI Ps d\" \"Move cursor to `Ps`-th row (default=1).\"\n */\n public linePosAbsolute(params: IParams): boolean {\n this._setCursor(this._activeBuffer.x, (params.params[0] || 1) - 1);\n return true;\n }\n\n /**\n * CSI Pm e Vertical Position Relative (VPR)\n * [rows] (default = [row+1,column])\n * reuse CSI Ps B ?\n *\n * @vt: #Y CSI VPR \"Vertical Position Relative\" \"CSI Ps e\" \"Move cursor `Ps` times down (default=1).\"\n */\n public vPositionRelative(params: IParams): boolean {\n this._moveCursor(0, params.params[0] || 1);\n return true;\n }\n\n /**\n * CSI Ps ; Ps f\n * Horizontal and Vertical Position [row;column] (default =\n * [1,1]) (HVP).\n * Same as CUP.\n *\n * @vt: #Y CSI HVP \"Horizontal and Vertical Position\" \"CSI Ps ; Ps f\" \"Same as CUP.\"\n */\n public hVPosition(params: IParams): boolean {\n this.cursorPosition(params);\n return true;\n }\n\n /**\n * CSI Ps g Tab Clear (TBC).\n * Ps = 0 -> Clear Current Column (default).\n * Ps = 3 -> Clear All.\n * Potentially:\n * Ps = 2 -> Clear Stops on Line.\n * http://vt100.net/annarbor/aaa-ug/section6.html\n *\n * @vt: #Y CSI TBC \"Tab Clear\" \"CSI Ps g\" \"Clear tab stops at current position (0) or all (3) (default=0).\"\n * Clearing tabstops off the active row (Ps = 2, VT100) is currently not supported.\n */\n public tabClear(params: IParams): boolean {\n const param = params.params[0];\n if (param === 0) {\n delete this._activeBuffer.tabs[this._activeBuffer.x];\n } else if (param === 3) {\n this._activeBuffer.tabs = {};\n }\n return true;\n }\n\n /**\n * CSI Ps I\n * Cursor Forward Tabulation Ps tab stops (default = 1) (CHT).\n *\n * @vt: #Y CSI CHT \"Cursor Horizontal Tabulation\" \"CSI Ps I\" \"Move cursor `Ps` times tabs forward (default=1).\"\n */\n public cursorForwardTab(params: IParams): boolean {\n if (this._activeBuffer.x >= this._bufferService.cols) {\n return true;\n }\n let param = params.params[0] || 1;\n while (param--) {\n this._activeBuffer.x = this._activeBuffer.nextStop();\n }\n return true;\n }\n\n /**\n * CSI Ps Z Cursor Backward Tabulation Ps tab stops (default = 1) (CBT).\n *\n * @vt: #Y CSI CBT \"Cursor Backward Tabulation\" \"CSI Ps Z\" \"Move cursor `Ps` tabs backward (default=1).\"\n */\n public cursorBackwardTab(params: IParams): boolean {\n if (this._activeBuffer.x >= this._bufferService.cols) {\n return true;\n }\n let param = params.params[0] || 1;\n\n while (param--) {\n this._activeBuffer.x = this._activeBuffer.prevStop();\n }\n return true;\n }\n\n /**\n * CSI Ps \" q Select Character Protection Attribute (DECSCA).\n *\n * @vt: #Y CSI DECSCA \"Select Character Protection Attribute\" \"CSI Ps \" q\" \"Whether DECSED and DECSEL can erase (0=default, 2) or not (1).\"\n */\n public selectProtected(params: IParams): boolean {\n const p = params.params[0];\n if (p === 1) this._curAttrData.bg |= BgFlags.PROTECTED;\n if (p === 2 || p === 0) this._curAttrData.bg &= ~BgFlags.PROTECTED;\n return true;\n }\n\n\n /**\n * Helper method to erase cells in a terminal row.\n * The cell gets replaced with the eraseChar of the terminal.\n * @param y The row index relative to the viewport.\n * @param start The start x index of the range to be erased.\n * @param end The end x index of the range to be erased (exclusive).\n * @param clearWrap clear the isWrapped flag\n * @param respectProtect Whether to respect the protection attribute (DECSCA).\n */\n private _eraseInBufferLine(y: number, start: number, end: number, clearWrap: boolean = false, respectProtect: boolean = false): void {\n const line = this._activeBuffer.lines.get(this._activeBuffer.ybase + y)!;\n line.replaceCells(\n start,\n end,\n this._activeBuffer.getNullCell(this._eraseAttrData()),\n respectProtect\n );\n if (clearWrap) {\n line.isWrapped = false;\n }\n }\n\n /**\n * Helper method to reset cells in a terminal row. The cell gets replaced with the eraseChar of\n * the terminal and the isWrapped property is set to false.\n * @param y row index\n */\n private _resetBufferLine(y: number, respectProtect: boolean = false): void {\n const line = this._activeBuffer.lines.get(this._activeBuffer.ybase + y);\n if (line) {\n line.fill(this._activeBuffer.getNullCell(this._eraseAttrData()), respectProtect);\n this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase + y);\n line.isWrapped = false;\n }\n }\n\n /**\n * CSI Ps J Erase in Display (ED).\n * Ps = 0 -> Erase Below (default).\n * Ps = 1 -> Erase Above.\n * Ps = 2 -> Erase All.\n * Ps = 3 -> Erase Saved Lines (xterm).\n * CSI ? Ps J\n * Erase in Display (DECSED).\n * Ps = 0 -> Selective Erase Below (default).\n * Ps = 1 -> Selective Erase Above.\n * Ps = 2 -> Selective Erase All.\n *\n * @vt: #Y CSI ED \"Erase In Display\" \"CSI Ps J\" \"Erase various parts of the viewport.\"\n * Supported param values:\n *\n * | Ps | Effect |\n * | -- | ------------------------------------------------------------ |\n * | 0 | Erase from the cursor through the end of the viewport. |\n * | 1 | Erase from the beginning of the viewport through the cursor. |\n * | 2 | Erase complete viewport. |\n * | 3 | Erase scrollback. |\n *\n * @vt: #Y CSI DECSED \"Selective Erase In Display\" \"CSI ? Ps J\" \"Same as ED with respecting protection flag.\"\n */\n public eraseInDisplay(params: IParams, respectProtect: boolean = false): boolean {\n this._restrictCursor(this._bufferService.cols);\n let j;\n switch (params.params[0]) {\n case 0:\n j = this._activeBuffer.y;\n this._dirtyRowTracker.markDirty(j);\n this._eraseInBufferLine(j++, this._activeBuffer.x, this._bufferService.cols, this._activeBuffer.x === 0, respectProtect);\n for (; j < this._bufferService.rows; j++) {\n this._resetBufferLine(j, respectProtect);\n }\n this._dirtyRowTracker.markDirty(j);\n break;\n case 1:\n j = this._activeBuffer.y;\n this._dirtyRowTracker.markDirty(j);\n // Deleted front part of line and everything before. This line will no longer be wrapped.\n this._eraseInBufferLine(j, 0, this._activeBuffer.x + 1, true, respectProtect);\n if (this._activeBuffer.x + 1 >= this._bufferService.cols) {\n // Deleted entire previous line. This next line can no longer be wrapped.\n this._activeBuffer.lines.get(j + 1)!.isWrapped = false;\n }\n while (j--) {\n this._resetBufferLine(j, respectProtect);\n }\n this._dirtyRowTracker.markDirty(0);\n break;\n case 2:\n if (this._optionsService.rawOptions.scrollOnEraseInDisplay) {\n j = this._bufferService.rows;\n this._dirtyRowTracker.markRangeDirty(0, j - 1);\n while (j--) {\n const currentLine = this._activeBuffer.lines.get(this._activeBuffer.ybase + j);\n if (currentLine?.getTrimmedLength()) {\n break;\n }\n }\n for (; j >= 0; j--) {\n this._bufferService.scroll(this._eraseAttrData());\n }\n }\n else {\n j = this._bufferService.rows;\n this._dirtyRowTracker.markDirty(j - 1);\n while (j--) {\n this._resetBufferLine(j, respectProtect);\n }\n this._dirtyRowTracker.markDirty(0);\n }\n break;\n case 3:\n // Clear scrollback (everything not in viewport)\n const scrollBackSize = this._activeBuffer.lines.length - this._bufferService.rows;\n if (scrollBackSize > 0) {\n this._activeBuffer.lines.trimStart(scrollBackSize);\n this._activeBuffer.ybase = Math.max(this._activeBuffer.ybase - scrollBackSize, 0);\n this._activeBuffer.ydisp = Math.max(this._activeBuffer.ydisp - scrollBackSize, 0);\n // Force a scroll event to refresh viewport\n this._onScroll.fire(0);\n }\n break;\n }\n return true;\n }\n\n /**\n * CSI Ps K Erase in Line (EL).\n * Ps = 0 -> Erase to Right (default).\n * Ps = 1 -> Erase to Left.\n * Ps = 2 -> Erase All.\n * CSI ? Ps K\n * Erase in Line (DECSEL).\n * Ps = 0 -> Selective Erase to Right (default).\n * Ps = 1 -> Selective Erase to Left.\n * Ps = 2 -> Selective Erase All.\n *\n * @vt: #Y CSI EL \"Erase In Line\" \"CSI Ps K\" \"Erase various parts of the active row.\"\n * Supported param values:\n *\n * | Ps | Effect |\n * | -- | -------------------------------------------------------- |\n * | 0 | Erase from the cursor through the end of the row. |\n * | 1 | Erase from the beginning of the line through the cursor. |\n * | 2 | Erase complete line. |\n *\n * @vt: #Y CSI DECSEL \"Selective Erase In Line\" \"CSI ? Ps K\" \"Same as EL with respecting protecting flag.\"\n */\n public eraseInLine(params: IParams, respectProtect: boolean = false): boolean {\n this._restrictCursor(this._bufferService.cols);\n switch (params.params[0]) {\n case 0:\n this._eraseInBufferLine(this._activeBuffer.y, this._activeBuffer.x, this._bufferService.cols, this._activeBuffer.x === 0, respectProtect);\n break;\n case 1:\n this._eraseInBufferLine(this._activeBuffer.y, 0, this._activeBuffer.x + 1, false, respectProtect);\n break;\n case 2:\n this._eraseInBufferLine(this._activeBuffer.y, 0, this._bufferService.cols, true, respectProtect);\n break;\n }\n this._dirtyRowTracker.markDirty(this._activeBuffer.y);\n return true;\n }\n\n /**\n * CSI Ps L\n * Insert Ps Line(s) (default = 1) (IL).\n *\n * @vt: #Y CSI IL \"Insert Line\" \"CSI Ps L\" \"Insert `Ps` blank lines at active row (default=1).\"\n * For every inserted line at the scroll top one line at the scroll bottom gets removed.\n * The cursor is set to the first column.\n * IL has no effect if the cursor is outside the scroll margins.\n */\n public insertLines(params: IParams): boolean {\n this._restrictCursor();\n let param = params.params[0] || 1;\n\n if (this._activeBuffer.y > this._activeBuffer.scrollBottom || this._activeBuffer.y < this._activeBuffer.scrollTop) {\n return true;\n }\n\n const row: number = this._activeBuffer.ybase + this._activeBuffer.y;\n\n const scrollBottomRowsOffset = this._bufferService.rows - 1 - this._activeBuffer.scrollBottom;\n const scrollBottomAbsolute = this._bufferService.rows - 1 + this._activeBuffer.ybase - scrollBottomRowsOffset + 1;\n while (param--) {\n // test: echo -e '\\e[44m\\e[1L\\e[0m'\n // blankLine(true) - xterm/linux behavior\n this._activeBuffer.lines.splice(scrollBottomAbsolute - 1, 1);\n this._activeBuffer.lines.splice(row, 0, this._activeBuffer.getBlankLine(this._eraseAttrData()));\n }\n\n this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y, this._activeBuffer.scrollBottom);\n this._activeBuffer.x = 0; // see https://vt100.net/docs/vt220-rm/chapter4.html - vt220 only?\n return true;\n }\n\n /**\n * CSI Ps M\n * Delete Ps Line(s) (default = 1) (DL).\n *\n * @vt: #Y CSI DL \"Delete Line\" \"CSI Ps M\" \"Delete `Ps` lines at active row (default=1).\"\n * For every deleted line at the scroll top one blank line at the scroll bottom gets appended.\n * The cursor is set to the first column.\n * DL has no effect if the cursor is outside the scroll margins.\n */\n public deleteLines(params: IParams): boolean {\n this._restrictCursor();\n let param = params.params[0] || 1;\n\n if (this._activeBuffer.y > this._activeBuffer.scrollBottom || this._activeBuffer.y < this._activeBuffer.scrollTop) {\n return true;\n }\n\n const row: number = this._activeBuffer.ybase + this._activeBuffer.y;\n\n let j: number;\n j = this._bufferService.rows - 1 - this._activeBuffer.scrollBottom;\n j = this._bufferService.rows - 1 + this._activeBuffer.ybase - j;\n while (param--) {\n // test: echo -e '\\e[44m\\e[1M\\e[0m'\n // blankLine(true) - xterm/linux behavior\n this._activeBuffer.lines.splice(row, 1);\n this._activeBuffer.lines.splice(j, 0, this._activeBuffer.getBlankLine(this._eraseAttrData()));\n }\n\n this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y, this._activeBuffer.scrollBottom);\n this._activeBuffer.x = 0; // see https://vt100.net/docs/vt220-rm/chapter4.html - vt220 only?\n return true;\n }\n\n /**\n * CSI Ps @\n * Insert Ps (Blank) Character(s) (default = 1) (ICH).\n *\n * @vt: #Y CSI ICH \"Insert Characters\" \"CSI Ps @\" \"Insert `Ps` (blank) characters (default = 1).\"\n * The ICH sequence inserts `Ps` blank characters. The cursor remains at the beginning of the\n * blank characters. Text between the cursor and right margin moves to the right. Characters moved\n * past the right margin are lost.\n *\n *\n * FIXME: check against xterm - should not work outside of scroll margins (see VT520 manual)\n */\n public insertChars(params: IParams): boolean {\n this._restrictCursor();\n const line = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y);\n if (line) {\n line.insertCells(\n this._activeBuffer.x,\n params.params[0] || 1,\n this._activeBuffer.getNullCell(this._eraseAttrData())\n );\n this._dirtyRowTracker.markDirty(this._activeBuffer.y);\n }\n return true;\n }\n\n /**\n * CSI Ps P\n * Delete Ps Character(s) (default = 1) (DCH).\n *\n * @vt: #Y CSI DCH \"Delete Character\" \"CSI Ps P\" \"Delete `Ps` characters (default=1).\"\n * As characters are deleted, the remaining characters between the cursor and right margin move to\n * the left. Character attributes move with the characters. The terminal adds blank characters at\n * the right margin.\n *\n *\n * FIXME: check against xterm - should not work outside of scroll margins (see VT520 manual)\n */\n public deleteChars(params: IParams): boolean {\n this._restrictCursor();\n const line = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y);\n if (line) {\n line.deleteCells(\n this._activeBuffer.x,\n params.params[0] || 1,\n this._activeBuffer.getNullCell(this._eraseAttrData())\n );\n this._dirtyRowTracker.markDirty(this._activeBuffer.y);\n }\n return true;\n }\n\n /**\n * CSI Ps S Scroll up Ps lines (default = 1) (SU).\n *\n * @vt: #Y CSI SU \"Scroll Up\" \"CSI Ps S\" \"Scroll `Ps` lines up (default=1).\"\n *\n *\n * FIXME: scrolled out lines at top = 1 should add to scrollback (xterm)\n */\n public scrollUp(params: IParams): boolean {\n let param = params.params[0] || 1;\n\n while (param--) {\n this._activeBuffer.lines.splice(this._activeBuffer.ybase + this._activeBuffer.scrollTop, 1);\n this._activeBuffer.lines.splice(this._activeBuffer.ybase + this._activeBuffer.scrollBottom, 0, this._activeBuffer.getBlankLine(this._eraseAttrData()));\n }\n this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom);\n return true;\n }\n\n /**\n * CSI Ps T Scroll down Ps lines (default = 1) (SD).\n *\n * @vt: #Y CSI SD \"Scroll Down\" \"CSI Ps T\" \"Scroll `Ps` lines down (default=1).\"\n */\n public scrollDown(params: IParams): boolean {\n let param = params.params[0] || 1;\n\n while (param--) {\n this._activeBuffer.lines.splice(this._activeBuffer.ybase + this._activeBuffer.scrollBottom, 1);\n this._activeBuffer.lines.splice(this._activeBuffer.ybase + this._activeBuffer.scrollTop, 0, this._activeBuffer.getBlankLine(DEFAULT_ATTR_DATA));\n }\n this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom);\n return true;\n }\n\n /**\n * CSI Ps SP @ Scroll left Ps columns (default = 1) (SL) ECMA-48\n *\n * Notation: (Pn)\n * Representation: CSI Pn 02/00 04/00\n * Parameter default value: Pn = 1\n * SL causes the data in the presentation component to be moved by n character positions\n * if the line orientation is horizontal, or by n line positions if the line orientation\n * is vertical, such that the data appear to move to the left; where n equals the value of Pn.\n * The active presentation position is not affected by this control function.\n *\n * Supported:\n * - always left shift (no line orientation setting respected)\n *\n * @vt: #Y CSI SL \"Scroll Left\" \"CSI Ps SP @\" \"Scroll viewport `Ps` times to the left.\"\n * SL moves the content of all lines within the scroll margins `Ps` times to the left.\n * SL has no effect outside of the scroll margins.\n */\n public scrollLeft(params: IParams): boolean {\n if (this._activeBuffer.y > this._activeBuffer.scrollBottom || this._activeBuffer.y < this._activeBuffer.scrollTop) {\n return true;\n }\n const param = params.params[0] || 1;\n for (let y = this._activeBuffer.scrollTop; y <= this._activeBuffer.scrollBottom; ++y) {\n const line = this._activeBuffer.lines.get(this._activeBuffer.ybase + y)!;\n line.deleteCells(0, param, this._activeBuffer.getNullCell(this._eraseAttrData()));\n line.isWrapped = false;\n }\n this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom);\n return true;\n }\n\n /**\n * CSI Ps SP A Scroll right Ps columns (default = 1) (SR) ECMA-48\n *\n * Notation: (Pn)\n * Representation: CSI Pn 02/00 04/01\n * Parameter default value: Pn = 1\n * SR causes the data in the presentation component to be moved by n character positions\n * if the line orientation is horizontal, or by n line positions if the line orientation\n * is vertical, such that the data appear to move to the right; where n equals the value of Pn.\n * The active presentation position is not affected by this control function.\n *\n * Supported:\n * - always right shift (no line orientation setting respected)\n *\n * @vt: #Y CSI SR \"Scroll Right\" \"CSI Ps SP A\" \"Scroll viewport `Ps` times to the right.\"\n * SL moves the content of all lines within the scroll margins `Ps` times to the right.\n * Content at the right margin is lost.\n * SL has no effect outside of the scroll margins.\n */\n public scrollRight(params: IParams): boolean {\n if (this._activeBuffer.y > this._activeBuffer.scrollBottom || this._activeBuffer.y < this._activeBuffer.scrollTop) {\n return true;\n }\n const param = params.params[0] || 1;\n for (let y = this._activeBuffer.scrollTop; y <= this._activeBuffer.scrollBottom; ++y) {\n const line = this._activeBuffer.lines.get(this._activeBuffer.ybase + y)!;\n line.insertCells(0, param, this._activeBuffer.getNullCell(this._eraseAttrData()));\n line.isWrapped = false;\n }\n this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom);\n return true;\n }\n\n /**\n * CSI Pm ' }\n * Insert Ps Column(s) (default = 1) (DECIC), VT420 and up.\n *\n * @vt: #Y CSI DECIC \"Insert Columns\" \"CSI Ps ' }\" \"Insert `Ps` columns at cursor position.\"\n * DECIC inserts `Ps` times blank columns at the cursor position for all lines with the scroll\n * margins, moving content to the right. Content at the right margin is lost. DECIC has no effect\n * outside the scrolling margins.\n */\n public insertColumns(params: IParams): boolean {\n if (this._activeBuffer.y > this._activeBuffer.scrollBottom || this._activeBuffer.y < this._activeBuffer.scrollTop) {\n return true;\n }\n const param = params.params[0] || 1;\n for (let y = this._activeBuffer.scrollTop; y <= this._activeBuffer.scrollBottom; ++y) {\n const line = this._activeBuffer.lines.get(this._activeBuffer.ybase + y)!;\n line.insertCells(this._activeBuffer.x, param, this._activeBuffer.getNullCell(this._eraseAttrData()));\n line.isWrapped = false;\n }\n this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom);\n return true;\n }\n\n /**\n * CSI Pm ' ~\n * Delete Ps Column(s) (default = 1) (DECDC), VT420 and up.\n *\n * @vt: #Y CSI DECDC \"Delete Columns\" \"CSI Ps ' ~\" \"Delete `Ps` columns at cursor position.\"\n * DECDC deletes `Ps` times columns at the cursor position for all lines with the scroll margins,\n * moving content to the left. Blank columns are added at the right margin.\n * DECDC has no effect outside the scrolling margins.\n */\n public deleteColumns(params: IParams): boolean {\n if (this._activeBuffer.y > this._activeBuffer.scrollBottom || this._activeBuffer.y < this._activeBuffer.scrollTop) {\n return true;\n }\n const param = params.params[0] || 1;\n for (let y = this._activeBuffer.scrollTop; y <= this._activeBuffer.scrollBottom; ++y) {\n const line = this._activeBuffer.lines.get(this._activeBuffer.ybase + y)!;\n line.deleteCells(this._activeBuffer.x, param, this._activeBuffer.getNullCell(this._eraseAttrData()));\n line.isWrapped = false;\n }\n this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom);\n return true;\n }\n\n /**\n * CSI Ps X\n * Erase Ps Character(s) (default = 1) (ECH).\n *\n * @vt: #Y CSI ECH \"Erase Character\" \"CSI Ps X\" \"Erase `Ps` characters from current cursor position to the right (default=1).\"\n * ED erases `Ps` characters from current cursor position to the right.\n * ED works inside or outside the scrolling margins.\n */\n public eraseChars(params: IParams): boolean {\n this._restrictCursor();\n const line = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y);\n if (line) {\n line.replaceCells(\n this._activeBuffer.x,\n this._activeBuffer.x + (params.params[0] || 1),\n this._activeBuffer.getNullCell(this._eraseAttrData())\n );\n this._dirtyRowTracker.markDirty(this._activeBuffer.y);\n }\n return true;\n }\n\n /**\n * CSI Ps b Repeat the preceding graphic character Ps times (REP).\n * From ECMA 48 (@see http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-048.pdf)\n * Notation: (Pn)\n * Representation: CSI Pn 06/02\n * Parameter default value: Pn = 1\n * REP is used to indicate that the preceding character in the data stream,\n * if it is a graphic character (represented by one or more bit combinations) including SPACE,\n * is to be repeated n times, where n equals the value of Pn.\n * If the character preceding REP is a control function or part of a control function,\n * the effect of REP is not defined by this Standard.\n *\n * We extend xterm's behavior to allow repeating entire grapheme clusters.\n * This isn't 100% xterm-compatible, but it seems saner and more useful.\n * - text attrs are applied normally\n * - wrap around is respected\n * - any valid sequence resets the carried forward char\n *\n * Note: To get reset on a valid sequence working correctly without much runtime penalty, the\n * preceding codepoint is stored on the parser in `this.print` and reset during `parser.parse`.\n *\n * @vt: #Y CSI REP \"Repeat Preceding Character\" \"CSI Ps b\" \"Repeat preceding character `Ps` times (default=1).\"\n * REP repeats the previous character `Ps` times advancing the cursor, also wrapping if DECAWM is\n * set. REP has no effect if the sequence does not follow a printable ASCII character\n * (NOOP for any other sequence in between or NON ASCII characters).\n */\n public repeatPrecedingCharacter(params: IParams): boolean {\n const joinState = this._parser.precedingJoinState;\n if (!joinState) {\n return true;\n }\n // call print to insert the chars and handle correct wrapping\n const length = params.params[0] || 1;\n const chWidth = UnicodeService.extractWidth(joinState);\n const x = this._activeBuffer.x - chWidth;\n const bufferRow = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y)!;\n const text = bufferRow.getString(x);\n const data = new Uint32Array(text.length * length);\n let idata = 0;\n for (let itext = 0; itext < text.length;) {\n const ch = text.codePointAt(itext) || 0;\n data[idata++] = ch;\n itext += ch > 0xffff ? 2 : 1;\n }\n let tlength = idata;\n for (let i = 1; i < length; ++i) {\n data.copyWithin(tlength, 0, idata);\n tlength += idata;\n }\n this.print(data, 0, tlength);\n return true;\n }\n\n /**\n * CSI Ps c Send Device Attributes (Primary DA).\n * Ps = 0 or omitted -> request attributes from terminal. The\n * response depends on the decTerminalID resource setting.\n * -> CSI ? 1 ; 2 c (``VT100 with Advanced Video Option'')\n * -> CSI ? 1 ; 0 c (``VT101 with No Options'')\n * -> CSI ? 6 c (``VT102'')\n * -> CSI ? 6 0 ; 1 ; 2 ; 6 ; 8 ; 9 ; 1 5 ; c (``VT220'')\n * The VT100-style response parameters do not mean anything by\n * themselves. VT220 parameters do, telling the host what fea-\n * tures the terminal supports:\n * Ps = 1 -> 132-columns.\n * Ps = 2 -> Printer.\n * Ps = 6 -> Selective erase.\n * Ps = 8 -> User-defined keys.\n * Ps = 9 -> National replacement character sets.\n * Ps = 1 5 -> Technical characters.\n * Ps = 2 2 -> ANSI color, e.g., VT525.\n * Ps = 2 9 -> ANSI text locator (i.e., DEC Locator mode).\n *\n * @vt: #Y CSI DA1 \"Primary Device Attributes\" \"CSI c\" \"Send primary device attributes.\"\n *\n *\n * TODO: fix and cleanup response\n */\n public sendDeviceAttributesPrimary(params: IParams): boolean {\n if (params.params[0] > 0) {\n return true;\n }\n if (this._is('xterm') || this._is('rxvt-unicode') || this._is('screen')) {\n this._coreService.triggerDataEvent(C0.ESC + '[?1;2c');\n } else if (this._is('linux')) {\n this._coreService.triggerDataEvent(C0.ESC + '[?6c');\n }\n return true;\n }\n\n /**\n * CSI > Ps c\n * Send Device Attributes (Secondary DA).\n * Ps = 0 or omitted -> request the terminal's identification\n * code. The response depends on the decTerminalID resource set-\n * ting. It should apply only to VT220 and up, but xterm extends\n * this to VT100.\n * -> CSI > Pp ; Pv ; Pc c\n * where Pp denotes the terminal type\n * Pp = 0 -> ``VT100''.\n * Pp = 1 -> ``VT220''.\n * and Pv is the firmware version (for xterm, this was originally\n * the XFree86 patch number, starting with 95). In a DEC termi-\n * nal, Pc indicates the ROM cartridge registration number and is\n * always zero.\n * More information:\n * xterm/charproc.c - line 2012, for more information.\n * vim responds with ^[[?0c or ^[[?1c after the terminal's response (?)\n *\n * @vt: #Y CSI DA2 \"Secondary Device Attributes\" \"CSI > c\" \"Send primary device attributes.\"\n *\n *\n * TODO: fix and cleanup response\n */\n public sendDeviceAttributesSecondary(params: IParams): boolean {\n if (params.params[0] > 0) {\n return true;\n }\n // xterm and urxvt\n // seem to spit this\n // out around ~370 times (?).\n if (this._is('xterm')) {\n this._coreService.triggerDataEvent(C0.ESC + '[>0;276;0c');\n } else if (this._is('rxvt-unicode')) {\n this._coreService.triggerDataEvent(C0.ESC + '[>85;95;0c');\n } else if (this._is('linux')) {\n // not supported by linux console.\n // linux console echoes parameters.\n this._coreService.triggerDataEvent(params.params[0] + 'c');\n } else if (this._is('screen')) {\n this._coreService.triggerDataEvent(C0.ESC + '[>83;40003;0c');\n }\n return true;\n }\n\n /**\n * Evaluate if the current terminal is the given argument.\n * @param term The terminal name to evaluate\n */\n private _is(term: string): boolean {\n return (this._optionsService.rawOptions.termName + '').indexOf(term) === 0;\n }\n\n /**\n * CSI Pm h Set Mode (SM).\n * Ps = 2 -> Keyboard Action Mode (AM).\n * Ps = 4 -> Insert Mode (IRM).\n * Ps = 1 2 -> Send/receive (SRM).\n * Ps = 2 0 -> Automatic Newline (LNM).\n *\n * @vt: #P[Only IRM is supported.] CSI SM \"Set Mode\" \"CSI Pm h\" \"Set various terminal modes.\"\n * Supported param values by SM:\n *\n * | Param | Action | Support |\n * | ----- | -------------------------------------- | ------- |\n * | 2 | Keyboard Action Mode (KAM). Always on. | #N |\n * | 4 | Insert Mode (IRM). | #Y |\n * | 12 | Send/receive (SRM). Always off. | #N |\n * | 20 | Automatic Newline (LNM). | #Y |\n */\n public setMode(params: IParams): boolean {\n for (let i = 0; i < params.length; i++) {\n switch (params.params[i]) {\n case 4:\n this._coreService.modes.insertMode = true;\n break;\n case 20:\n this._optionsService.options.convertEol = true;\n break;\n }\n }\n return true;\n }\n\n /**\n * CSI ? Pm h\n * DEC Private Mode Set (DECSET).\n * Ps = 1 -> Application Cursor Keys (DECCKM).\n * Ps = 2 -> Designate USASCII for character sets G0-G3\n * (DECANM), and set VT100 mode.\n * Ps = 3 -> 132 Column Mode (DECCOLM).\n * Ps = 4 -> Smooth (Slow) Scroll (DECSCLM).\n * Ps = 5 -> Reverse Video (DECSCNM).\n * Ps = 6 -> Origin Mode (DECOM).\n * Ps = 7 -> Wraparound Mode (DECAWM).\n * Ps = 8 -> Auto-repeat Keys (DECARM).\n * Ps = 9 -> Send Mouse X & Y on button press. See the sec-\n * tion Mouse Tracking.\n * Ps = 1 0 -> Show toolbar (rxvt).\n * Ps = 1 2 -> Start Blinking Cursor (att610).\n * Ps = 1 8 -> Print form feed (DECPFF).\n * Ps = 1 9 -> Set print extent to full screen (DECPEX).\n * Ps = 2 5 -> Show Cursor (DECTCEM).\n * Ps = 3 0 -> Show scrollbar (rxvt).\n * Ps = 3 5 -> Enable font-shifting functions (rxvt).\n * Ps = 3 8 -> Enter Tektronix Mode (DECTEK).\n * Ps = 4 0 -> Allow 80 -> 132 Mode.\n * Ps = 4 1 -> more(1) fix (see curses resource).\n * Ps = 4 2 -> Enable Nation Replacement Character sets (DECN-\n * RCM).\n * Ps = 4 4 -> Turn On Margin Bell.\n * Ps = 4 5 -> Reverse-wraparound Mode.\n * Ps = 4 6 -> Start Logging. This is normally disabled by a\n * compile-time option.\n * Ps = 4 7 -> Use Alternate Screen Buffer. (This may be dis-\n * abled by the titeInhibit resource).\n * Ps = 6 6 -> Application keypad (DECNKM).\n * Ps = 6 7 -> Backarrow key sends backspace (DECBKM).\n * Ps = 1 0 0 0 -> Send Mouse X & Y on button press and\n * release. See the section Mouse Tracking.\n * Ps = 1 0 0 1 -> Use Hilite Mouse Tracking.\n * Ps = 1 0 0 2 -> Use Cell Motion Mouse Tracking.\n * Ps = 1 0 0 3 -> Use All Motion Mouse Tracking.\n * Ps = 1 0 0 4 -> Send FocusIn/FocusOut events.\n * Ps = 1 0 0 5 -> Enable Extended Mouse Mode.\n * Ps = 1 0 1 0 -> Scroll to bottom on tty output (rxvt).\n * Ps = 1 0 1 1 -> Scroll to bottom on key press (rxvt).\n * Ps = 1 0 3 4 -> Interpret \"meta\" key, sets eighth bit.\n * (enables the eightBitInput resource).\n * Ps = 1 0 3 5 -> Enable special modifiers for Alt and Num-\n * Lock keys. (This enables the numLock resource).\n * Ps = 1 0 3 6 -> Send ESC when Meta modifies a key. (This\n * enables the metaSendsEscape resource).\n * Ps = 1 0 3 7 -> Send DEL from the editing-keypad Delete\n * key.\n * Ps = 1 0 3 9 -> Send ESC when Alt modifies a key. (This\n * enables the altSendsEscape resource).\n * Ps = 1 0 4 0 -> Keep selection even if not highlighted.\n * (This enables the keepSelection resource).\n * Ps = 1 0 4 1 -> Use the CLIPBOARD selection. (This enables\n * the selectToClipboard resource).\n * Ps = 1 0 4 2 -> Enable Urgency window manager hint when\n * Control-G is received. (This enables the bellIsUrgent\n * resource).\n * Ps = 1 0 4 3 -> Enable raising of the window when Control-G\n * is received. (enables the popOnBell resource).\n * Ps = 1 0 4 7 -> Use Alternate Screen Buffer. (This may be\n * disabled by the titeInhibit resource).\n * Ps = 1 0 4 8 -> Save cursor as in DECSC. (This may be dis-\n * abled by the titeInhibit resource).\n * Ps = 1 0 4 9 -> Save cursor as in DECSC and use Alternate\n * Screen Buffer, clearing it first. (This may be disabled by\n * the titeInhibit resource). This combines the effects of the 1\n * 0 4 7 and 1 0 4 8 modes. Use this with terminfo-based\n * applications rather than the 4 7 mode.\n * Ps = 1 0 5 0 -> Set terminfo/termcap function-key mode.\n * Ps = 1 0 5 1 -> Set Sun function-key mode.\n * Ps = 1 0 5 2 -> Set HP function-key mode.\n * Ps = 1 0 5 3 -> Set SCO function-key mode.\n * Ps = 1 0 6 0 -> Set legacy keyboard emulation (X11R6).\n * Ps = 1 0 6 1 -> Set VT220 keyboard emulation.\n * Ps = 2 0 0 4 -> Set bracketed paste mode.\n * Modes:\n * http: *vt100.net/docs/vt220-rm/chapter4.html\n *\n * @vt: #P[See below for supported modes.] CSI DECSET \"DEC Private Set Mode\" \"CSI ? Pm h\" \"Set various terminal attributes.\"\n * Supported param values by DECSET:\n *\n * | param | Action | Support |\n * | ----- | ------------------------------------------------------- | --------|\n * | 1 | Application Cursor Keys (DECCKM). | #Y |\n * | 2 | Designate US-ASCII for character sets G0-G3 (DECANM). | #Y |\n * | 3 | 132 Column Mode (DECCOLM). | #Y |\n * | 6 | Origin Mode (DECOM). | #Y |\n * | 7 | Auto-wrap Mode (DECAWM). | #Y |\n * | 8 | Auto-repeat Keys (DECARM). Always on. | #N |\n * | 9 | X10 xterm mouse protocol. | #Y |\n * | 12 | Start Blinking Cursor. | #Y |\n * | 25 | Show Cursor (DECTCEM). | #Y |\n * | 45 | Reverse wrap-around. | #Y |\n * | 47 | Use Alternate Screen Buffer. | #Y |\n * | 66 | Application keypad (DECNKM). | #Y |\n * | 1000 | X11 xterm mouse protocol. | #Y |\n * | 1002 | Use Cell Motion Mouse Tracking. | #Y |\n * | 1003 | Use All Motion Mouse Tracking. | #Y |\n * | 1004 | Send FocusIn/FocusOut events | #Y |\n * | 1005 | Enable UTF-8 Mouse Mode. | #N |\n * | 1006 | Enable SGR Mouse Mode. | #Y |\n * | 1015 | Enable urxvt Mouse Mode. | #N |\n * | 1016 | Enable SGR-Pixels Mouse Mode. | #Y |\n * | 1047 | Use Alternate Screen Buffer. | #Y |\n * | 1048 | Save cursor as in DECSC. | #Y |\n * | 1049 | Save cursor and switch to alternate buffer clearing it. | #P[Does not clear the alternate buffer.] |\n * | 2004 | Set bracketed paste mode. | #Y |\n *\n *\n * FIXME: implement DECSCNM, 1049 should clear altbuffer\n */\n public setModePrivate(params: IParams): boolean {\n for (let i = 0; i < params.length; i++) {\n switch (params.params[i]) {\n case 1:\n this._coreService.decPrivateModes.applicationCursorKeys = true;\n break;\n case 2:\n this._charsetService.setgCharset(0, DEFAULT_CHARSET);\n this._charsetService.setgCharset(1, DEFAULT_CHARSET);\n this._charsetService.setgCharset(2, DEFAULT_CHARSET);\n this._charsetService.setgCharset(3, DEFAULT_CHARSET);\n // set VT100 mode here\n break;\n case 3:\n /**\n * DECCOLM - 132 column mode.\n * This is only active if 'SetWinLines' (24) is enabled\n * through `options.windowsOptions`.\n */\n if (this._optionsService.rawOptions.windowOptions.setWinLines) {\n this._bufferService.resize(132, this._bufferService.rows);\n this._onRequestReset.fire();\n }\n break;\n case 6:\n this._coreService.decPrivateModes.origin = true;\n this._setCursor(0, 0);\n break;\n case 7:\n this._coreService.decPrivateModes.wraparound = true;\n break;\n case 12:\n this._optionsService.options.cursorBlink = true;\n break;\n case 45:\n this._coreService.decPrivateModes.reverseWraparound = true;\n break;\n case 66:\n this._logService.debug('Serial port requested application keypad.');\n this._coreService.decPrivateModes.applicationKeypad = true;\n this._onRequestSyncScrollBar.fire();\n break;\n case 9: // X10 Mouse\n // no release, no motion, no wheel, no modifiers.\n this._coreMouseService.activeProtocol = 'X10';\n break;\n case 1000: // vt200 mouse\n // no motion.\n this._coreMouseService.activeProtocol = 'VT200';\n break;\n case 1002: // button event mouse\n this._coreMouseService.activeProtocol = 'DRAG';\n break;\n case 1003: // any event mouse\n // any event - sends motion events,\n // even if there is no button held down.\n this._coreMouseService.activeProtocol = 'ANY';\n break;\n case 1004: // send focusin/focusout events\n // focusin: ^[[I\n // focusout: ^[[O\n this._coreService.decPrivateModes.sendFocus = true;\n this._onRequestSendFocus.fire();\n break;\n case 1005: // utf8 ext mode mouse - removed in #2507\n this._logService.debug('DECSET 1005 not supported (see #2507)');\n break;\n case 1006: // sgr ext mode mouse\n this._coreMouseService.activeEncoding = 'SGR';\n break;\n case 1015: // urxvt ext mode mouse - removed in #2507\n this._logService.debug('DECSET 1015 not supported (see #2507)');\n break;\n case 1016: // sgr pixels mode mouse\n this._coreMouseService.activeEncoding = 'SGR_PIXELS';\n break;\n case 25: // show cursor\n this._coreService.isCursorHidden = false;\n break;\n case 1048: // alt screen cursor\n this.saveCursor();\n break;\n case 1049: // alt screen buffer cursor\n this.saveCursor();\n // FALL-THROUGH\n case 47: // alt screen buffer\n case 1047: // alt screen buffer\n this._bufferService.buffers.activateAltBuffer(this._eraseAttrData());\n this._coreService.isCursorInitialized = true;\n this._onRequestRefreshRows.fire(undefined);\n this._onRequestSyncScrollBar.fire();\n break;\n case 2004: // bracketed paste mode (https://cirw.in/blog/bracketed-paste)\n this._coreService.decPrivateModes.bracketedPasteMode = true;\n break;\n case 2026: // synchronized output (https://github.com/contour-terminal/vt-extensions/blob/master/synchronized-output.md)\n this._coreService.decPrivateModes.synchronizedOutput = true;\n break;\n }\n }\n return true;\n }\n\n\n /**\n * CSI Pm l Reset Mode (RM).\n * Ps = 2 -> Keyboard Action Mode (AM).\n * Ps = 4 -> Replace Mode (IRM).\n * Ps = 1 2 -> Send/receive (SRM).\n * Ps = 2 0 -> Normal Linefeed (LNM).\n *\n * @vt: #P[Only IRM is supported.] CSI RM \"Reset Mode\" \"CSI Pm l\" \"Set various terminal attributes.\"\n * Supported param values by RM:\n *\n * | Param | Action | Support |\n * | ----- | -------------------------------------- | ------- |\n * | 2 | Keyboard Action Mode (KAM). Always on. | #N |\n * | 4 | Replace Mode (IRM). (default) | #Y |\n * | 12 | Send/receive (SRM). Always off. | #N |\n * | 20 | Normal Linefeed (LNM). | #Y |\n *\n *\n * FIXME: why is LNM commented out?\n */\n public resetMode(params: IParams): boolean {\n for (let i = 0; i < params.length; i++) {\n switch (params.params[i]) {\n case 4:\n this._coreService.modes.insertMode = false;\n break;\n case 20:\n this._optionsService.options.convertEol = false;\n break;\n }\n }\n return true;\n }\n\n /**\n * CSI ? Pm l\n * DEC Private Mode Reset (DECRST).\n * Ps = 1 -> Normal Cursor Keys (DECCKM).\n * Ps = 2 -> Designate VT52 mode (DECANM).\n * Ps = 3 -> 80 Column Mode (DECCOLM).\n * Ps = 4 -> Jump (Fast) Scroll (DECSCLM).\n * Ps = 5 -> Normal Video (DECSCNM).\n * Ps = 6 -> Normal Cursor Mode (DECOM).\n * Ps = 7 -> No Wraparound Mode (DECAWM).\n * Ps = 8 -> No Auto-repeat Keys (DECARM).\n * Ps = 9 -> Don't send Mouse X & Y on button press.\n * Ps = 1 0 -> Hide toolbar (rxvt).\n * Ps = 1 2 -> Stop Blinking Cursor (att610).\n * Ps = 1 8 -> Don't print form feed (DECPFF).\n * Ps = 1 9 -> Limit print to scrolling region (DECPEX).\n * Ps = 2 5 -> Hide Cursor (DECTCEM).\n * Ps = 3 0 -> Don't show scrollbar (rxvt).\n * Ps = 3 5 -> Disable font-shifting functions (rxvt).\n * Ps = 4 0 -> Disallow 80 -> 132 Mode.\n * Ps = 4 1 -> No more(1) fix (see curses resource).\n * Ps = 4 2 -> Disable Nation Replacement Character sets (DEC-\n * NRCM).\n * Ps = 4 4 -> Turn Off Margin Bell.\n * Ps = 4 5 -> No Reverse-wraparound Mode.\n * Ps = 4 6 -> Stop Logging. (This is normally disabled by a\n * compile-time option).\n * Ps = 4 7 -> Use Normal Screen Buffer.\n * Ps = 6 6 -> Numeric keypad (DECNKM).\n * Ps = 6 7 -> Backarrow key sends delete (DECBKM).\n * Ps = 1 0 0 0 -> Don't send Mouse X & Y on button press and\n * release. See the section Mouse Tracking.\n * Ps = 1 0 0 1 -> Don't use Hilite Mouse Tracking.\n * Ps = 1 0 0 2 -> Don't use Cell Motion Mouse Tracking.\n * Ps = 1 0 0 3 -> Don't use All Motion Mouse Tracking.\n * Ps = 1 0 0 4 -> Don't send FocusIn/FocusOut events.\n * Ps = 1 0 0 5 -> Disable Extended Mouse Mode.\n * Ps = 1 0 1 0 -> Don't scroll to bottom on tty output\n * (rxvt).\n * Ps = 1 0 1 1 -> Don't scroll to bottom on key press (rxvt).\n * Ps = 1 0 3 4 -> Don't interpret \"meta\" key. (This disables\n * the eightBitInput resource).\n * Ps = 1 0 3 5 -> Disable special modifiers for Alt and Num-\n * Lock keys. (This disables the numLock resource).\n * Ps = 1 0 3 6 -> Don't send ESC when Meta modifies a key.\n * (This disables the metaSendsEscape resource).\n * Ps = 1 0 3 7 -> Send VT220 Remove from the editing-keypad\n * Delete key.\n * Ps = 1 0 3 9 -> Don't send ESC when Alt modifies a key.\n * (This disables the altSendsEscape resource).\n * Ps = 1 0 4 0 -> Do not keep selection when not highlighted.\n * (This disables the keepSelection resource).\n * Ps = 1 0 4 1 -> Use the PRIMARY selection. (This disables\n * the selectToClipboard resource).\n * Ps = 1 0 4 2 -> Disable Urgency window manager hint when\n * Control-G is received. (This disables the bellIsUrgent\n * resource).\n * Ps = 1 0 4 3 -> Disable raising of the window when Control-\n * G is received. (This disables the popOnBell resource).\n * Ps = 1 0 4 7 -> Use Normal Screen Buffer, clearing screen\n * first if in the Alternate Screen. (This may be disabled by\n * the titeInhibit resource).\n * Ps = 1 0 4 8 -> Restore cursor as in DECRC. (This may be\n * disabled by the titeInhibit resource).\n * Ps = 1 0 4 9 -> Use Normal Screen Buffer and restore cursor\n * as in DECRC. (This may be disabled by the titeInhibit\n * resource). This combines the effects of the 1 0 4 7 and 1 0\n * 4 8 modes. Use this with terminfo-based applications rather\n * than the 4 7 mode.\n * Ps = 1 0 5 0 -> Reset terminfo/termcap function-key mode.\n * Ps = 1 0 5 1 -> Reset Sun function-key mode.\n * Ps = 1 0 5 2 -> Reset HP function-key mode.\n * Ps = 1 0 5 3 -> Reset SCO function-key mode.\n * Ps = 1 0 6 0 -> Reset legacy keyboard emulation (X11R6).\n * Ps = 1 0 6 1 -> Reset keyboard emulation to Sun/PC style.\n * Ps = 2 0 0 4 -> Reset bracketed paste mode.\n *\n * @vt: #P[See below for supported modes.] CSI DECRST \"DEC Private Reset Mode\" \"CSI ? Pm l\" \"Reset various terminal attributes.\"\n * Supported param values by DECRST:\n *\n * | param | Action | Support |\n * | ----- | ------------------------------------------------------- | ------- |\n * | 1 | Normal Cursor Keys (DECCKM). | #Y |\n * | 2 | Designate VT52 mode (DECANM). | #N |\n * | 3 | 80 Column Mode (DECCOLM). | #B[Switches to old column width instead of 80.] |\n * | 6 | Normal Cursor Mode (DECOM). | #Y |\n * | 7 | No Wraparound Mode (DECAWM). | #Y |\n * | 8 | No Auto-repeat Keys (DECARM). | #N |\n * | 9 | Don't send Mouse X & Y on button press. | #Y |\n * | 12 | Stop Blinking Cursor. | #Y |\n * | 25 | Hide Cursor (DECTCEM). | #Y |\n * | 45 | No reverse wrap-around. | #Y |\n * | 47 | Use Normal Screen Buffer. | #Y |\n * | 66 | Numeric keypad (DECNKM). | #Y |\n * | 1000 | Don't send Mouse reports. | #Y |\n * | 1002 | Don't use Cell Motion Mouse Tracking. | #Y |\n * | 1003 | Don't use All Motion Mouse Tracking. | #Y |\n * | 1004 | Don't send FocusIn/FocusOut events. | #Y |\n * | 1005 | Disable UTF-8 Mouse Mode. | #N |\n * | 1006 | Disable SGR Mouse Mode. | #Y |\n * | 1015 | Disable urxvt Mouse Mode. | #N |\n * | 1016 | Disable SGR-Pixels Mouse Mode. | #Y |\n * | 1047 | Use Normal Screen Buffer (clearing screen if in alt). | #Y |\n * | 1048 | Restore cursor as in DECRC. | #Y |\n * | 1049 | Use Normal Screen Buffer and restore cursor. | #Y |\n * | 2004 | Reset bracketed paste mode. | #Y |\n *\n *\n * FIXME: DECCOLM is currently broken (already fixed in window options PR)\n */\n public resetModePrivate(params: IParams): boolean {\n for (let i = 0; i < params.length; i++) {\n switch (params.params[i]) {\n case 1:\n this._coreService.decPrivateModes.applicationCursorKeys = false;\n break;\n case 3:\n /**\n * DECCOLM - 80 column mode.\n * This is only active if 'SetWinLines' (24) is enabled\n * through `options.windowsOptions`.\n */\n if (this._optionsService.rawOptions.windowOptions.setWinLines) {\n this._bufferService.resize(80, this._bufferService.rows);\n this._onRequestReset.fire();\n }\n break;\n case 6:\n this._coreService.decPrivateModes.origin = false;\n this._setCursor(0, 0);\n break;\n case 7:\n this._coreService.decPrivateModes.wraparound = false;\n break;\n case 12:\n this._optionsService.options.cursorBlink = false;\n break;\n case 45:\n this._coreService.decPrivateModes.reverseWraparound = false;\n break;\n case 66:\n this._logService.debug('Switching back to normal keypad.');\n this._coreService.decPrivateModes.applicationKeypad = false;\n this._onRequestSyncScrollBar.fire();\n break;\n case 9: // X10 Mouse\n case 1000: // vt200 mouse\n case 1002: // button event mouse\n case 1003: // any event mouse\n this._coreMouseService.activeProtocol = 'NONE';\n break;\n case 1004: // send focusin/focusout events\n this._coreService.decPrivateModes.sendFocus = false;\n break;\n case 1005: // utf8 ext mode mouse - removed in #2507\n this._logService.debug('DECRST 1005 not supported (see #2507)');\n break;\n case 1006: // sgr ext mode mouse\n this._coreMouseService.activeEncoding = 'DEFAULT';\n break;\n case 1015: // urxvt ext mode mouse - removed in #2507\n this._logService.debug('DECRST 1015 not supported (see #2507)');\n break;\n case 1016: // sgr pixels mode mouse\n this._coreMouseService.activeEncoding = 'DEFAULT';\n break;\n case 25: // hide cursor\n this._coreService.isCursorHidden = true;\n break;\n case 1048: // alt screen cursor\n this.restoreCursor();\n break;\n case 1049: // alt screen buffer cursor\n // FALL-THROUGH\n case 47: // normal screen buffer\n case 1047: // normal screen buffer - clearing it first\n // Ensure the selection manager has the correct buffer\n this._bufferService.buffers.activateNormalBuffer();\n if (params.params[i] === 1049) {\n this.restoreCursor();\n }\n this._coreService.isCursorInitialized = true;\n this._onRequestRefreshRows.fire(undefined);\n this._onRequestSyncScrollBar.fire();\n break;\n case 2004: // bracketed paste mode (https://cirw.in/blog/bracketed-paste)\n this._coreService.decPrivateModes.bracketedPasteMode = false;\n break;\n case 2026: // synchronized output (https://github.com/contour-terminal/vt-extensions/blob/master/synchronized-output.md)\n this._coreService.decPrivateModes.synchronizedOutput = false;\n this._onRequestRefreshRows.fire(undefined);\n break;\n }\n }\n return true;\n }\n\n /**\n * CSI Ps $ p Request ANSI Mode (DECRQM).\n *\n * Reports CSI Ps; Pm $ y (DECRPM), where Ps is the mode number as in SM/RM,\n * and Pm is the mode value:\n * 0 - not recognized\n * 1 - set\n * 2 - reset\n * 3 - permanently set\n * 4 - permanently reset\n *\n * @vt: #Y CSI DECRQM \"Request Mode\" \"CSI Ps $p\" \"Request mode state.\"\n * Returns a report as `CSI Ps; Pm $ y` (DECRPM), where `Ps` is the mode number as in SM/RM\n * or DECSET/DECRST, and `Pm` is the mode value:\n * - 0: not recognized\n * - 1: set\n * - 2: reset\n * - 3: permanently set\n * - 4: permanently reset\n *\n * For modes not understood xterm.js always returns `notRecognized`. In general this means,\n * that a certain operation mode is not implemented and cannot be used.\n *\n * Modes changing the active terminal buffer (47, 1047, 1049) are not subqueried\n * and only report, whether the alternate buffer is set.\n *\n * Mouse encodings and mouse protocols are handled mutual exclusive,\n * thus only one of each of those can be set at a given time.\n *\n * There is a chance, that some mode reports are not fully in line with xterm.js' behavior,\n * e.g. if the default implementation already exposes a certain behavior. If you find\n * discrepancies in the mode reports, please file a bug.\n */\n public requestMode(params: IParams, ansi: boolean): boolean {\n // return value as in DECRPM\n const enum V {\n NOT_RECOGNIZED = 0,\n SET = 1,\n RESET = 2,\n PERMANENTLY_SET = 3,\n PERMANENTLY_RESET = 4\n }\n\n // access helpers\n const dm = this._coreService.decPrivateModes;\n const { activeProtocol: mouseProtocol, activeEncoding: mouseEncoding } = this._coreMouseService;\n const cs = this._coreService;\n const { buffers, cols } = this._bufferService;\n const { active, alt } = buffers;\n const opts = this._optionsService.rawOptions;\n\n const f = (m: number, v: V): boolean => {\n cs.triggerDataEvent(`${C0.ESC}[${ansi ? '' : '?'}${m};${v}$y`);\n return true;\n };\n const b2v = (value: boolean): V => value ? V.SET : V.RESET;\n\n const p = params.params[0];\n\n if (ansi) {\n if (p === 2) return f(p, V.PERMANENTLY_RESET);\n if (p === 4) return f(p, b2v(cs.modes.insertMode));\n if (p === 12) return f(p, V.PERMANENTLY_SET);\n if (p === 20) return f(p, b2v(opts.convertEol));\n return f(p, V.NOT_RECOGNIZED);\n }\n\n if (p === 1) return f(p, b2v(dm.applicationCursorKeys));\n if (p === 3) return f(p, opts.windowOptions.setWinLines ? (cols === 80 ? V.RESET : cols === 132 ? V.SET : V.NOT_RECOGNIZED) : V.NOT_RECOGNIZED);\n if (p === 6) return f(p, b2v(dm.origin));\n if (p === 7) return f(p, b2v(dm.wraparound));\n if (p === 8) return f(p, V.PERMANENTLY_SET);\n if (p === 9) return f(p, b2v(mouseProtocol === 'X10'));\n if (p === 12) return f(p, b2v(opts.cursorBlink));\n if (p === 25) return f(p, b2v(!cs.isCursorHidden));\n if (p === 45) return f(p, b2v(dm.reverseWraparound));\n if (p === 66) return f(p, b2v(dm.applicationKeypad));\n if (p === 67) return f(p, V.PERMANENTLY_RESET);\n if (p === 1000) return f(p, b2v(mouseProtocol === 'VT200'));\n if (p === 1002) return f(p, b2v(mouseProtocol === 'DRAG'));\n if (p === 1003) return f(p, b2v(mouseProtocol === 'ANY'));\n if (p === 1004) return f(p, b2v(dm.sendFocus));\n if (p === 1005) return f(p, V.PERMANENTLY_RESET);\n if (p === 1006) return f(p, b2v(mouseEncoding === 'SGR'));\n if (p === 1015) return f(p, V.PERMANENTLY_RESET);\n if (p === 1016) return f(p, b2v(mouseEncoding === 'SGR_PIXELS'));\n if (p === 1048) return f(p, V.SET); // xterm always returns SET here\n if (p === 47 || p === 1047 || p === 1049) return f(p, b2v(active === alt));\n if (p === 2004) return f(p, b2v(dm.bracketedPasteMode));\n if (p === 2026) return f(p, b2v(dm.synchronizedOutput));\n return f(p, V.NOT_RECOGNIZED);\n }\n\n /**\n * Helper to write color information packed with color mode.\n */\n private _updateAttrColor(color: number, mode: number, c1: number, c2: number, c3: number): number {\n if (mode === 2) {\n color |= Attributes.CM_RGB;\n color &= ~Attributes.RGB_MASK;\n color |= AttributeData.fromColorRGB([c1, c2, c3]);\n } else if (mode === 5) {\n color &= ~(Attributes.CM_MASK | Attributes.PCOLOR_MASK);\n color |= Attributes.CM_P256 | (c1 & 0xff);\n }\n return color;\n }\n\n /**\n * Helper to extract and apply color params/subparams.\n * Returns advance for params index.\n */\n private _extractColor(params: IParams, pos: number, attr: IAttributeData): number {\n // normalize params\n // meaning: [target, CM, ign, val, val, val]\n // RGB : [ 38/48, 2, ign, r, g, b]\n // P256 : [ 38/48, 5, ign, v, ign, ign]\n const accu = [0, 0, -1, 0, 0, 0];\n\n // alignment placeholder for non color space sequences\n let cSpace = 0;\n\n // return advance we took in params\n let advance = 0;\n\n do {\n accu[advance + cSpace] = params.params[pos + advance];\n if (params.hasSubParams(pos + advance)) {\n const subparams = params.getSubParams(pos + advance)!;\n let i = 0;\n do {\n if (accu[1] === 5) {\n cSpace = 1;\n }\n accu[advance + i + 1 + cSpace] = subparams[i];\n } while (++i < subparams.length && i + advance + 1 + cSpace < accu.length);\n break;\n }\n // exit early if can decide color mode with semicolons\n if ((accu[1] === 5 && advance + cSpace >= 2)\n || (accu[1] === 2 && advance + cSpace >= 5)) {\n break;\n }\n // offset colorSpace slot for semicolon mode\n if (accu[1]) {\n cSpace = 1;\n }\n } while (++advance + pos < params.length && advance + cSpace < accu.length);\n\n // set default values to 0\n for (let i = 2; i < accu.length; ++i) {\n if (accu[i] === -1) {\n accu[i] = 0;\n }\n }\n\n // apply colors\n switch (accu[0]) {\n case 38:\n attr.fg = this._updateAttrColor(attr.fg, accu[1], accu[3], accu[4], accu[5]);\n break;\n case 48:\n attr.bg = this._updateAttrColor(attr.bg, accu[1], accu[3], accu[4], accu[5]);\n break;\n case 58:\n attr.extended = attr.extended.clone();\n attr.extended.underlineColor = this._updateAttrColor(attr.extended.underlineColor, accu[1], accu[3], accu[4], accu[5]);\n }\n\n return advance;\n }\n\n /**\n * SGR 4 subparams:\n * 4:0 - equal to SGR 24 (turn off all underline)\n * 4:1 - equal to SGR 4 (single underline)\n * 4:2 - equal to SGR 21 (double underline)\n * 4:3 - curly underline\n * 4:4 - dotted underline\n * 4:5 - dashed underline\n */\n private _processUnderline(style: number, attr: IAttributeData): void {\n // treat extended attrs as immutable, thus always clone from old one\n // this is needed since the buffer only holds references to it\n attr.extended = attr.extended.clone();\n\n // default to 1 == single underline\n if (!~style || style > 5) {\n style = 1;\n }\n attr.extended.underlineStyle = style;\n attr.fg |= FgFlags.UNDERLINE;\n\n // 0 deactivates underline\n if (style === 0) {\n attr.fg &= ~FgFlags.UNDERLINE;\n }\n\n // update HAS_EXTENDED in BG\n attr.updateExtended();\n }\n\n private _processSGR0(attr: IAttributeData): void {\n attr.fg = DEFAULT_ATTR_DATA.fg;\n attr.bg = DEFAULT_ATTR_DATA.bg;\n attr.extended = attr.extended.clone();\n // Reset underline style and color. Note that we don't want to reset other\n // fields such as the url id.\n attr.extended.underlineStyle = UnderlineStyle.NONE;\n attr.extended.underlineColor &= ~(Attributes.CM_MASK | Attributes.RGB_MASK);\n attr.updateExtended();\n }\n\n /**\n * CSI Pm m Character Attributes (SGR).\n *\n * @vt: #P[See below for supported attributes.] CSI SGR \"Select Graphic Rendition\" \"CSI Pm m\" \"Set/Reset various text attributes.\"\n * SGR selects one or more character attributes at the same time. Multiple params (up to 32)\n * are applied in order from left to right. The changed attributes are applied to all new\n * characters received. If you move characters in the viewport by scrolling or any other means,\n * then the attributes move with the characters.\n *\n * Supported param values by SGR:\n *\n * | Param | Meaning | Support |\n * | --------- | -------------------------------------------------------- | ------- |\n * | 0 | Normal (default). Resets any other preceding SGR. | #Y |\n * | 1 | Bold. (also see `options.drawBoldTextInBrightColors`) | #Y |\n * | 2 | Faint, decreased intensity. | #Y |\n * | 3 | Italic. | #Y |\n * | 4 | Underlined (see below for style support). | #Y |\n * | 5 | Slowly blinking. | #N |\n * | 6 | Rapidly blinking. | #N |\n * | 7 | Inverse. Flips foreground and background color. | #Y |\n * | 8 | Invisible (hidden). | #Y |\n * | 9 | Crossed-out characters (strikethrough). | #Y |\n * | 21 | Doubly underlined. | #Y |\n * | 22 | Normal (neither bold nor faint). | #Y |\n * | 23 | No italic. | #Y |\n * | 24 | Not underlined. | #Y |\n * | 25 | Steady (not blinking). | #Y |\n * | 27 | Positive (not inverse). | #Y |\n * | 28 | Visible (not hidden). | #Y |\n * | 29 | Not Crossed-out (strikethrough). | #Y |\n * | 30 | Foreground color: Black. | #Y |\n * | 31 | Foreground color: Red. | #Y |\n * | 32 | Foreground color: Green. | #Y |\n * | 33 | Foreground color: Yellow. | #Y |\n * | 34 | Foreground color: Blue. | #Y |\n * | 35 | Foreground color: Magenta. | #Y |\n * | 36 | Foreground color: Cyan. | #Y |\n * | 37 | Foreground color: White. | #Y |\n * | 38 | Foreground color: Extended color. | #P[Support for RGB and indexed colors, see below.] |\n * | 39 | Foreground color: Default (original). | #Y |\n * | 40 | Background color: Black. | #Y |\n * | 41 | Background color: Red. | #Y |\n * | 42 | Background color: Green. | #Y |\n * | 43 | Background color: Yellow. | #Y |\n * | 44 | Background color: Blue. | #Y |\n * | 45 | Background color: Magenta. | #Y |\n * | 46 | Background color: Cyan. | #Y |\n * | 47 | Background color: White. | #Y |\n * | 48 | Background color: Extended color. | #P[Support for RGB and indexed colors, see below.] |\n * | 49 | Background color: Default (original). | #Y |\n * | 53 | Overlined. | #Y |\n * | 55 | Not Overlined. | #Y |\n * | 58 | Underline color: Extended color. | #P[Support for RGB and indexed colors, see below.] |\n * | 90 - 97 | Bright foreground color (analogous to 30 - 37). | #Y |\n * | 100 - 107 | Bright background color (analogous to 40 - 47). | #Y |\n *\n * Underline supports subparams to denote the style in the form `4 : x`:\n *\n * | x | Meaning | Support |\n * | ------ | ------------------------------------------------------------- | ------- |\n * | 0 | No underline. Same as `SGR 24 m`. | #Y |\n * | 1 | Single underline. Same as `SGR 4 m`. | #Y |\n * | 2 | Double underline. | #Y |\n * | 3 | Curly underline. | #Y |\n * | 4 | Dotted underline. | #Y |\n * | 5 | Dashed underline. | #Y |\n * | other | Single underline. Same as `SGR 4 m`. | #Y |\n *\n * Extended colors are supported for foreground (Ps=38), background (Ps=48) and underline (Ps=58)\n * as follows:\n *\n * | Ps + 1 | Meaning | Support |\n * | ------ | ------------------------------------------------------------- | ------- |\n * | 0 | Implementation defined. | #N |\n * | 1 | Transparent. | #N |\n * | 2 | RGB color as `Ps ; 2 ; R ; G ; B` or `Ps : 2 : : R : G : B`. | #Y |\n * | 3 | CMY color. | #N |\n * | 4 | CMYK color. | #N |\n * | 5 | Indexed (256 colors) as `Ps ; 5 ; INDEX` or `Ps : 5 : INDEX`. | #Y |\n *\n *\n * FIXME: blinking is implemented in attrs, but not working in renderers?\n * FIXME: remove dead branch for p=100\n */\n public charAttributes(params: IParams): boolean {\n // Optimize a single SGR0.\n if (params.length === 1 && params.params[0] === 0) {\n this._processSGR0(this._curAttrData);\n return true;\n }\n\n const l = params.length;\n let p;\n const attr = this._curAttrData;\n\n for (let i = 0; i < l; i++) {\n p = params.params[i];\n if (p >= 30 && p <= 37) {\n // fg color 8\n attr.fg &= ~(Attributes.CM_MASK | Attributes.PCOLOR_MASK);\n attr.fg |= Attributes.CM_P16 | (p - 30);\n } else if (p >= 40 && p <= 47) {\n // bg color 8\n attr.bg &= ~(Attributes.CM_MASK | Attributes.PCOLOR_MASK);\n attr.bg |= Attributes.CM_P16 | (p - 40);\n } else if (p >= 90 && p <= 97) {\n // fg color 16\n attr.fg &= ~(Attributes.CM_MASK | Attributes.PCOLOR_MASK);\n attr.fg |= Attributes.CM_P16 | (p - 90) | 8;\n } else if (p >= 100 && p <= 107) {\n // bg color 16\n attr.bg &= ~(Attributes.CM_MASK | Attributes.PCOLOR_MASK);\n attr.bg |= Attributes.CM_P16 | (p - 100) | 8;\n } else if (p === 0) {\n // default\n this._processSGR0(attr);\n } else if (p === 1) {\n // bold text\n attr.fg |= FgFlags.BOLD;\n } else if (p === 3) {\n // italic text\n attr.bg |= BgFlags.ITALIC;\n } else if (p === 4) {\n // underlined text\n attr.fg |= FgFlags.UNDERLINE;\n this._processUnderline(params.hasSubParams(i) ? params.getSubParams(i)![0] : UnderlineStyle.SINGLE, attr);\n } else if (p === 5) {\n // blink\n attr.fg |= FgFlags.BLINK;\n } else if (p === 7) {\n // inverse and positive\n // test with: echo -e '\\e[31m\\e[42mhello\\e[7mworld\\e[27mhi\\e[m'\n attr.fg |= FgFlags.INVERSE;\n } else if (p === 8) {\n // invisible\n attr.fg |= FgFlags.INVISIBLE;\n } else if (p === 9) {\n // strikethrough\n attr.fg |= FgFlags.STRIKETHROUGH;\n } else if (p === 2) {\n // dimmed text\n attr.bg |= BgFlags.DIM;\n } else if (p === 21) {\n // double underline\n this._processUnderline(UnderlineStyle.DOUBLE, attr);\n } else if (p === 22) {\n // not bold nor faint\n attr.fg &= ~FgFlags.BOLD;\n attr.bg &= ~BgFlags.DIM;\n } else if (p === 23) {\n // not italic\n attr.bg &= ~BgFlags.ITALIC;\n } else if (p === 24) {\n // not underlined\n attr.fg &= ~FgFlags.UNDERLINE;\n this._processUnderline(UnderlineStyle.NONE, attr);\n } else if (p === 25) {\n // not blink\n attr.fg &= ~FgFlags.BLINK;\n } else if (p === 27) {\n // not inverse\n attr.fg &= ~FgFlags.INVERSE;\n } else if (p === 28) {\n // not invisible\n attr.fg &= ~FgFlags.INVISIBLE;\n } else if (p === 29) {\n // not strikethrough\n attr.fg &= ~FgFlags.STRIKETHROUGH;\n } else if (p === 39) {\n // reset fg\n attr.fg &= ~(Attributes.CM_MASK | Attributes.RGB_MASK);\n attr.fg |= DEFAULT_ATTR_DATA.fg & (Attributes.PCOLOR_MASK | Attributes.RGB_MASK);\n } else if (p === 49) {\n // reset bg\n attr.bg &= ~(Attributes.CM_MASK | Attributes.RGB_MASK);\n attr.bg |= DEFAULT_ATTR_DATA.bg & (Attributes.PCOLOR_MASK | Attributes.RGB_MASK);\n } else if (p === 38 || p === 48 || p === 58) {\n // fg color 256 and RGB\n i += this._extractColor(params, i, attr);\n } else if (p === 53) {\n // overline\n attr.bg |= BgFlags.OVERLINE;\n } else if (p === 55) {\n // not overline\n attr.bg &= ~BgFlags.OVERLINE;\n } else if (p === 59) {\n attr.extended = attr.extended.clone();\n attr.extended.underlineColor = -1;\n attr.updateExtended();\n } else if (p === 100) { // FIXME: dead branch, p=100 already handled above!\n // reset fg/bg\n attr.fg &= ~(Attributes.CM_MASK | Attributes.RGB_MASK);\n attr.fg |= DEFAULT_ATTR_DATA.fg & (Attributes.PCOLOR_MASK | Attributes.RGB_MASK);\n attr.bg &= ~(Attributes.CM_MASK | Attributes.RGB_MASK);\n attr.bg |= DEFAULT_ATTR_DATA.bg & (Attributes.PCOLOR_MASK | Attributes.RGB_MASK);\n } else {\n this._logService.debug('Unknown SGR attribute: %d.', p);\n }\n }\n return true;\n }\n\n /**\n * CSI Ps n Device Status Report (DSR).\n * Ps = 5 -> Status Report. Result (``OK'') is\n * CSI 0 n\n * Ps = 6 -> Report Cursor Position (CPR) [row;column].\n * Result is\n * CSI r ; c R\n * CSI ? Ps n\n * Device Status Report (DSR, DEC-specific).\n * Ps = 6 -> Report Cursor Position (CPR) [row;column] as CSI\n * ? r ; c R (assumes page is zero).\n * Ps = 1 5 -> Report Printer status as CSI ? 1 0 n (ready).\n * or CSI ? 1 1 n (not ready).\n * Ps = 2 5 -> Report UDK status as CSI ? 2 0 n (unlocked)\n * or CSI ? 2 1 n (locked).\n * Ps = 2 6 -> Report Keyboard status as\n * CSI ? 2 7 ; 1 ; 0 ; 0 n (North American).\n * The last two parameters apply to VT400 & up, and denote key-\n * board ready and LK01 respectively.\n * Ps = 5 3 -> Report Locator status as\n * CSI ? 5 3 n Locator available, if compiled-in, or\n * CSI ? 5 0 n No Locator, if not.\n *\n * @vt: #Y CSI DSR \"Device Status Report\" \"CSI Ps n\" \"Request cursor position (CPR) with `Ps` = 6.\"\n */\n public deviceStatus(params: IParams): boolean {\n switch (params.params[0]) {\n case 5:\n // status report\n this._coreService.triggerDataEvent(`${C0.ESC}[0n`);\n break;\n case 6:\n // cursor position\n const y = this._activeBuffer.y + 1;\n const x = this._activeBuffer.x + 1;\n this._coreService.triggerDataEvent(`${C0.ESC}[${y};${x}R`);\n break;\n }\n return true;\n }\n\n // @vt: #P[Only CPR is supported.] CSI DECDSR \"DEC Device Status Report\" \"CSI ? Ps n\" \"Only CPR is supported (same as DSR).\"\n public deviceStatusPrivate(params: IParams): boolean {\n // modern xterm doesnt seem to\n // respond to any of these except ?6, 6, and 5\n switch (params.params[0]) {\n case 6:\n // cursor position\n const y = this._activeBuffer.y + 1;\n const x = this._activeBuffer.x + 1;\n this._coreService.triggerDataEvent(`${C0.ESC}[?${y};${x}R`);\n break;\n case 15:\n // no printer\n // this.handler(C0.ESC + '[?11n');\n break;\n case 25:\n // dont support user defined keys\n // this.handler(C0.ESC + '[?21n');\n break;\n case 26:\n // north american keyboard\n // this.handler(C0.ESC + '[?27;1;0;0n');\n break;\n case 53:\n // no dec locator/mouse\n // this.handler(C0.ESC + '[?50n');\n break;\n }\n return true;\n }\n\n /**\n * CSI ! p Soft terminal reset (DECSTR).\n * http://vt100.net/docs/vt220-rm/table4-10.html\n *\n * @vt: #Y CSI DECSTR \"Soft Terminal Reset\" \"CSI ! p\" \"Reset several terminal attributes to initial state.\"\n * There are two terminal reset sequences - RIS and DECSTR. While RIS performs almost a full\n * terminal bootstrap, DECSTR only resets certain attributes. For most needs DECSTR should be\n * sufficient.\n *\n * The following terminal attributes are reset to default values:\n * - IRM is reset (dafault = false)\n * - scroll margins are reset (default = viewport size)\n * - erase attributes are reset to default\n * - charsets are reset\n * - DECSC data is reset to initial values\n * - DECOM is reset to absolute mode\n *\n *\n * FIXME: there are several more attributes missing (see VT520 manual)\n */\n public softReset(params: IParams): boolean {\n this._coreService.isCursorHidden = false;\n this._onRequestSyncScrollBar.fire();\n this._activeBuffer.scrollTop = 0;\n this._activeBuffer.scrollBottom = this._bufferService.rows - 1;\n this._curAttrData = DEFAULT_ATTR_DATA.clone();\n this._coreService.reset();\n this._charsetService.reset();\n\n // reset DECSC data\n this._activeBuffer.savedX = 0;\n this._activeBuffer.savedY = this._activeBuffer.ybase;\n this._activeBuffer.savedCurAttrData.fg = this._curAttrData.fg;\n this._activeBuffer.savedCurAttrData.bg = this._curAttrData.bg;\n this._activeBuffer.savedCharset = this._charsetService.charset;\n\n // reset DECOM\n this._coreService.decPrivateModes.origin = false;\n return true;\n }\n\n /**\n * CSI Ps SP q Set cursor style (DECSCUSR, VT520).\n * Ps = 0 -> reset to option.\n * Ps = 1 -> blinking block (default).\n * Ps = 2 -> steady block.\n * Ps = 3 -> blinking underline.\n * Ps = 4 -> steady underline.\n * Ps = 5 -> blinking bar (xterm).\n * Ps = 6 -> steady bar (xterm).\n *\n * @vt: #Y CSI DECSCUSR \"Set Cursor Style\" \"CSI Ps SP q\" \"Set cursor style.\"\n * Supported cursor styles:\n * - 0: reset to option\n * - empty, 1: blinking block\n * - 2: steady block\n * - 3: blinking underline\n * - 4: steady underline\n * - 5: blinking bar\n * - 6: steady bar\n */\n public setCursorStyle(params: IParams): boolean {\n const param = params.length === 0 ? 1 : params.params[0];\n if (param === 0) {\n this._coreService.decPrivateModes.cursorStyle = undefined;\n this._coreService.decPrivateModes.cursorBlink = undefined;\n } else {\n switch (param) {\n case 1:\n case 2:\n this._coreService.decPrivateModes.cursorStyle = 'block';\n break;\n case 3:\n case 4:\n this._coreService.decPrivateModes.cursorStyle = 'underline';\n break;\n case 5:\n case 6:\n this._coreService.decPrivateModes.cursorStyle = 'bar';\n break;\n }\n const isBlinking = param % 2 === 1;\n this._coreService.decPrivateModes.cursorBlink = isBlinking;\n }\n return true;\n }\n\n /**\n * CSI Ps ; Ps r\n * Set Scrolling Region [top;bottom] (default = full size of win-\n * dow) (DECSTBM).\n *\n * @vt: #Y CSI DECSTBM \"Set Top and Bottom Margin\" \"CSI Ps ; Ps r\" \"Set top and bottom margins of the viewport [top;bottom] (default = viewport size).\"\n */\n public setScrollRegion(params: IParams): boolean {\n const top = params.params[0] || 1;\n let bottom: number;\n\n if (params.length < 2 || (bottom = params.params[1]) > this._bufferService.rows || bottom === 0) {\n bottom = this._bufferService.rows;\n }\n\n if (bottom > top) {\n this._activeBuffer.scrollTop = top - 1;\n this._activeBuffer.scrollBottom = bottom - 1;\n this._setCursor(0, 0);\n }\n return true;\n }\n\n /**\n * CSI Ps ; Ps ; Ps t - Various window manipulations and reports (xterm)\n *\n * Note: Only those listed below are supported. All others are left to integrators and\n * need special treatment based on the embedding environment.\n *\n * Ps = 1 4 supported\n * Report xterm text area size in pixels.\n * Result is CSI 4 ; height ; width t\n * Ps = 14 ; 2 not implemented\n * Ps = 16 supported\n * Report xterm character cell size in pixels.\n * Result is CSI 6 ; height ; width t\n * Ps = 18 supported\n * Report the size of the text area in characters.\n * Result is CSI 8 ; height ; width t\n * Ps = 20 supported\n * Report xterm window's icon label.\n * Result is OSC L label ST\n * Ps = 21 supported\n * Report xterm window's title.\n * Result is OSC l label ST\n * Ps = 22 ; 0 -> Save xterm icon and window title on stack. supported\n * Ps = 22 ; 1 -> Save xterm icon title on stack. supported\n * Ps = 22 ; 2 -> Save xterm window title on stack. supported\n * Ps = 23 ; 0 -> Restore xterm icon and window title from stack. supported\n * Ps = 23 ; 1 -> Restore xterm icon title from stack. supported\n * Ps = 23 ; 2 -> Restore xterm window title from stack. supported\n * Ps >= 24 not implemented\n */\n public windowOptions(params: IParams): boolean {\n if (!paramToWindowOption(params.params[0], this._optionsService.rawOptions.windowOptions)) {\n return true;\n }\n const second = (params.length > 1) ? params.params[1] : 0;\n switch (params.params[0]) {\n case 14: // GetWinSizePixels, returns CSI 4 ; height ; width t\n if (second !== 2) {\n this._onRequestWindowsOptionsReport.fire(WindowsOptionsReportType.GET_WIN_SIZE_PIXELS);\n }\n break;\n case 16: // GetCellSizePixels, returns CSI 6 ; height ; width t\n this._onRequestWindowsOptionsReport.fire(WindowsOptionsReportType.GET_CELL_SIZE_PIXELS);\n break;\n case 18: // GetWinSizeChars, returns CSI 8 ; height ; width t\n if (this._bufferService) {\n this._coreService.triggerDataEvent(`${C0.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);\n }\n break;\n case 22: // PushTitle\n if (second === 0 || second === 2) {\n this._windowTitleStack.push(this._windowTitle);\n if (this._windowTitleStack.length > STACK_LIMIT) {\n this._windowTitleStack.shift();\n }\n }\n if (second === 0 || second === 1) {\n this._iconNameStack.push(this._iconName);\n if (this._iconNameStack.length > STACK_LIMIT) {\n this._iconNameStack.shift();\n }\n }\n break;\n case 23: // PopTitle\n if (second === 0 || second === 2) {\n if (this._windowTitleStack.length) {\n this.setTitle(this._windowTitleStack.pop()!);\n }\n }\n if (second === 0 || second === 1) {\n if (this._iconNameStack.length) {\n this.setIconName(this._iconNameStack.pop()!);\n }\n }\n break;\n }\n return true;\n }\n\n\n /**\n * CSI s\n * ESC 7\n * Save cursor (ANSI.SYS).\n *\n * @vt: #P[TODO...] CSI SCOSC \"Save Cursor\" \"CSI s\" \"Save cursor position, charmap and text attributes.\"\n * @vt: #Y ESC SC \"Save Cursor\" \"ESC 7\" \"Save cursor position, charmap and text attributes.\"\n */\n public saveCursor(params?: IParams): boolean {\n this._activeBuffer.savedX = this._activeBuffer.x;\n this._activeBuffer.savedY = this._activeBuffer.ybase + this._activeBuffer.y;\n this._activeBuffer.savedCurAttrData.fg = this._curAttrData.fg;\n this._activeBuffer.savedCurAttrData.bg = this._curAttrData.bg;\n this._activeBuffer.savedCharset = this._charsetService.charset;\n return true;\n }\n\n\n /**\n * CSI u\n * ESC 8\n * Restore cursor (ANSI.SYS).\n *\n * @vt: #P[TODO...] CSI SCORC \"Restore Cursor\" \"CSI u\" \"Restore cursor position, charmap and text attributes.\"\n * @vt: #Y ESC RC \"Restore Cursor\" \"ESC 8\" \"Restore cursor position, charmap and text attributes.\"\n */\n public restoreCursor(params?: IParams): boolean {\n this._activeBuffer.x = this._activeBuffer.savedX || 0;\n this._activeBuffer.y = Math.max(this._activeBuffer.savedY - this._activeBuffer.ybase, 0);\n this._curAttrData.fg = this._activeBuffer.savedCurAttrData.fg;\n this._curAttrData.bg = this._activeBuffer.savedCurAttrData.bg;\n this._charsetService.charset = (this as any)._savedCharset;\n if (this._activeBuffer.savedCharset) {\n this._charsetService.charset = this._activeBuffer.savedCharset;\n }\n this._restrictCursor();\n return true;\n }\n\n\n /**\n * OSC 2; ST (set window title)\n * Proxy to set window title.\n *\n * @vt: #P[Icon name is not exposed.] OSC 0 \"Set Windows Title and Icon Name\" \"OSC 0 ; Pt BEL\" \"Set window title and icon name.\"\n * Icon name is not supported. For Window Title see below.\n *\n * @vt: #Y OSC 2 \"Set Windows Title\" \"OSC 2 ; Pt BEL\" \"Set window title.\"\n * xterm.js does not manipulate the title directly, instead exposes changes via the event\n * `Terminal.onTitleChange`.\n */\n public setTitle(data: string): boolean {\n this._windowTitle = data;\n this._onTitleChange.fire(data);\n return true;\n }\n\n /**\n * OSC 1; ST\n * Note: Icon name is not exposed.\n */\n public setIconName(data: string): boolean {\n this._iconName = data;\n return true;\n }\n\n /**\n * OSC 4; ; ST (set ANSI color to )\n *\n * @vt: #Y OSC 4 \"Set ANSI color\" \"OSC 4 ; c ; spec BEL\" \"Change color number `c` to the color specified by `spec`.\"\n * `c` is the color index between 0 and 255. The color format of `spec` is derived from\n * `XParseColor` (see OSC 10 for supported formats). There may be multipe `c ; spec` pairs present\n * in the same instruction. If `spec` contains `?` the terminal returns a sequence with the\n * currently set color.\n */\n public setOrReportIndexedColor(data: string): boolean {\n const event: IColorEvent = [];\n const slots = data.split(';');\n while (slots.length > 1) {\n const idx = slots.shift() as string;\n const spec = slots.shift() as string;\n if (/^\\d+$/.exec(idx)) {\n const index = parseInt(idx);\n if (isValidColorIndex(index)) {\n if (spec === '?') {\n event.push({ type: ColorRequestType.REPORT, index });\n } else {\n const color = parseColor(spec);\n if (color) {\n event.push({ type: ColorRequestType.SET, index, color });\n }\n }\n }\n }\n }\n if (event.length) {\n this._onColor.fire(event);\n }\n return true;\n }\n\n /**\n * OSC 8 ; ; ST - create hyperlink\n * OSC 8 ; ; ST - finish hyperlink\n *\n * Test case:\n *\n * ```sh\n * printf '\\e]8;;http://example.com\\e\\\\This is a link\\e]8;;\\e\\\\\\n'\n * ```\n *\n * @vt: #Y OSC 8 \"Create hyperlink\" \"OSC 8 ; params ; uri BEL\" \"Create a hyperlink to `uri` using `params`.\"\n * `uri` is a hyperlink starting with `http://`, `https://`, `ftp://`, `file://` or `mailto://`. `params` is an\n * optional list of key=value assignments, separated by the : character.\n * Example: `id=xyz123:foo=bar:baz=quux`.\n * Currently only the id key is defined. Cells that share the same ID and URI share hover\n * feedback. Use `OSC 8 ; ; BEL` to finish the current hyperlink.\n */\n public setHyperlink(data: string): boolean {\n // Arg parsing is special cases to support unencoded semi-colons in the URIs (#4944)\n const idx = data.indexOf(';');\n if (idx === -1) {\n // malformed sequence, just return as handled\n return true;\n }\n const id = data.slice(0, idx).trim();\n const uri = data.slice(idx + 1);\n if (uri) {\n return this._createHyperlink(id, uri);\n }\n if (id.trim()) {\n return false;\n }\n return this._finishHyperlink();\n }\n\n private _createHyperlink(params: string, uri: string): boolean {\n // It's legal to open a new hyperlink without explicitly finishing the previous one\n if (this._getCurrentLinkId()) {\n this._finishHyperlink();\n }\n const parsedParams = params.split(':');\n let id: string | undefined;\n const idParamIndex = parsedParams.findIndex(e => e.startsWith('id='));\n if (idParamIndex !== -1) {\n id = parsedParams[idParamIndex].slice(3) || undefined;\n }\n this._curAttrData.extended = this._curAttrData.extended.clone();\n this._curAttrData.extended.urlId = this._oscLinkService.registerLink({ id, uri });\n this._curAttrData.updateExtended();\n return true;\n }\n\n private _finishHyperlink(): boolean {\n this._curAttrData.extended = this._curAttrData.extended.clone();\n this._curAttrData.extended.urlId = 0;\n this._curAttrData.updateExtended();\n return true;\n }\n\n // special colors - OSC 10 | 11 | 12\n private _specialColors = [SpecialColorIndex.FOREGROUND, SpecialColorIndex.BACKGROUND, SpecialColorIndex.CURSOR];\n\n /**\n * Apply colors requests for special colors in OSC 10 | 11 | 12.\n * Since these commands are stacking from multiple parameters,\n * we handle them in a loop with an entry offset to `_specialColors`.\n */\n private _setOrReportSpecialColor(data: string, offset: number): boolean {\n const slots = data.split(';');\n for (let i = 0; i < slots.length; ++i, ++offset) {\n if (offset >= this._specialColors.length) break;\n if (slots[i] === '?') {\n this._onColor.fire([{ type: ColorRequestType.REPORT, index: this._specialColors[offset] }]);\n } else {\n const color = parseColor(slots[i]);\n if (color) {\n this._onColor.fire([{ type: ColorRequestType.SET, index: this._specialColors[offset], color }]);\n }\n }\n }\n return true;\n }\n\n /**\n * OSC 10 ; | ST - set or query default foreground color\n *\n * @vt: #Y OSC 10 \"Set or query default foreground color\" \"OSC 10 ; Pt BEL\" \"Set or query default foreground color.\"\n * To set the color, the following color specification formats are supported:\n * - `rgb://` for `, , ` in `h | hh | hhh | hhhh`, where\n * `h` is a single hexadecimal digit (case insignificant). The different widths scale\n * from 4 bit (`h`) to 16 bit (`hhhh`) and get converted to 8 bit (`hh`).\n * - `#RGB` - 4 bits per channel, expanded to `#R0G0B0`\n * - `#RRGGBB` - 8 bits per channel\n * - `#RRRGGGBBB` - 12 bits per channel, truncated to `#RRGGBB`\n * - `#RRRRGGGGBBBB` - 16 bits per channel, truncated to `#RRGGBB`\n *\n * **Note:** X11 named colors are currently unsupported.\n *\n * If `Pt` contains `?` instead of a color specification, the terminal\n * returns a sequence with the current default foreground color\n * (use that sequence to restore the color after changes).\n *\n * **Note:** Other than xterm, xterm.js does not support OSC 12 - 19.\n * Therefore stacking multiple `Pt` separated by `;` only works for the first two entries.\n */\n public setOrReportFgColor(data: string): boolean {\n return this._setOrReportSpecialColor(data, 0);\n }\n\n /**\n * OSC 11 ; | ST - set or query default background color\n *\n * @vt: #Y OSC 11 \"Set or query default background color\" \"OSC 11 ; Pt BEL\" \"Same as OSC 10, but for default background.\"\n */\n public setOrReportBgColor(data: string): boolean {\n return this._setOrReportSpecialColor(data, 1);\n }\n\n /**\n * OSC 12 ; | ST - set or query default cursor color\n *\n * @vt: #Y OSC 12 \"Set or query default cursor color\" \"OSC 12 ; Pt BEL\" \"Same as OSC 10, but for default cursor color.\"\n */\n public setOrReportCursorColor(data: string): boolean {\n return this._setOrReportSpecialColor(data, 2);\n }\n\n /**\n * OSC 104 ; ST - restore ANSI color \n *\n * @vt: #Y OSC 104 \"Reset ANSI color\" \"OSC 104 ; c BEL\" \"Reset color number `c` to themed color.\"\n * `c` is the color index between 0 and 255. This function restores the default color for `c` as\n * specified by the loaded theme. Any number of `c` parameters may be given.\n * If no parameters are given, the entire indexed color table will be reset.\n */\n public restoreIndexedColor(data: string): boolean {\n if (!data) {\n this._onColor.fire([{ type: ColorRequestType.RESTORE }]);\n return true;\n }\n const event: IColorEvent = [];\n const slots = data.split(';');\n for (let i = 0; i < slots.length; ++i) {\n if (/^\\d+$/.exec(slots[i])) {\n const index = parseInt(slots[i]);\n if (isValidColorIndex(index)) {\n event.push({ type: ColorRequestType.RESTORE, index });\n }\n }\n }\n if (event.length) {\n this._onColor.fire(event);\n }\n return true;\n }\n\n /**\n * OSC 110 ST - restore default foreground color\n *\n * @vt: #Y OSC 110 \"Restore default foreground color\" \"OSC 110 BEL\" \"Restore default foreground to themed color.\"\n */\n public restoreFgColor(data: string): boolean {\n this._onColor.fire([{ type: ColorRequestType.RESTORE, index: SpecialColorIndex.FOREGROUND }]);\n return true;\n }\n\n /**\n * OSC 111 ST - restore default background color\n *\n * @vt: #Y OSC 111 \"Restore default background color\" \"OSC 111 BEL\" \"Restore default background to themed color.\"\n */\n public restoreBgColor(data: string): boolean {\n this._onColor.fire([{ type: ColorRequestType.RESTORE, index: SpecialColorIndex.BACKGROUND }]);\n return true;\n }\n\n /**\n * OSC 112 ST - restore default cursor color\n *\n * @vt: #Y OSC 112 \"Restore default cursor color\" \"OSC 112 BEL\" \"Restore default cursor to themed color.\"\n */\n public restoreCursorColor(data: string): boolean {\n this._onColor.fire([{ type: ColorRequestType.RESTORE, index: SpecialColorIndex.CURSOR }]);\n return true;\n }\n\n /**\n * ESC E\n * C1.NEL\n * DEC mnemonic: NEL (https://vt100.net/docs/vt510-rm/NEL)\n * Moves cursor to first position on next line.\n *\n * @vt: #Y C1 NEL \"Next Line\" \"\\x85\" \"Move the cursor to the beginning of the next row.\"\n * @vt: #Y ESC NEL \"Next Line\" \"ESC E\" \"Move the cursor to the beginning of the next row.\"\n */\n public nextLine(): boolean {\n this._activeBuffer.x = 0;\n this.index();\n return true;\n }\n\n /**\n * ESC =\n * DEC mnemonic: DECKPAM (https://vt100.net/docs/vt510-rm/DECKPAM.html)\n * Enables the numeric keypad to send application sequences to the host.\n */\n public keypadApplicationMode(): boolean {\n this._logService.debug('Serial port requested application keypad.');\n this._coreService.decPrivateModes.applicationKeypad = true;\n this._onRequestSyncScrollBar.fire();\n return true;\n }\n\n /**\n * ESC >\n * DEC mnemonic: DECKPNM (https://vt100.net/docs/vt510-rm/DECKPNM.html)\n * Enables the keypad to send numeric characters to the host.\n */\n public keypadNumericMode(): boolean {\n this._logService.debug('Switching back to normal keypad.');\n this._coreService.decPrivateModes.applicationKeypad = false;\n this._onRequestSyncScrollBar.fire();\n return true;\n }\n\n /**\n * ESC % @\n * ESC % G\n * Select default character set. UTF-8 is not supported (string are unicode anyways)\n * therefore ESC % G does the same.\n */\n public selectDefaultCharset(): boolean {\n this._charsetService.setgLevel(0);\n this._charsetService.setgCharset(0, DEFAULT_CHARSET); // US (default)\n return true;\n }\n\n /**\n * ESC ( C\n * Designate G0 Character Set, VT100, ISO 2022.\n * ESC ) C\n * Designate G1 Character Set (ISO 2022, VT100).\n * ESC * C\n * Designate G2 Character Set (ISO 2022, VT220).\n * ESC + C\n * Designate G3 Character Set (ISO 2022, VT220).\n * ESC - C\n * Designate G1 Character Set (VT300).\n * ESC . C\n * Designate G2 Character Set (VT300).\n * ESC / C\n * Designate G3 Character Set (VT300). C = A -> ISO Latin-1 Supplemental. - Supported?\n */\n public selectCharset(collectAndFlag: string): boolean {\n if (collectAndFlag.length !== 2) {\n this.selectDefaultCharset();\n return true;\n }\n if (collectAndFlag[0] === '/') {\n return true; // TODO: Is this supported?\n }\n this._charsetService.setgCharset(GLEVEL[collectAndFlag[0]], CHARSETS[collectAndFlag[1]] || DEFAULT_CHARSET);\n return true;\n }\n\n /**\n * ESC D\n * C1.IND\n * DEC mnemonic: IND (https://vt100.net/docs/vt510-rm/IND.html)\n * Moves the cursor down one line in the same column.\n *\n * @vt: #Y C1 IND \"Index\" \"\\x84\" \"Move the cursor one line down scrolling if needed.\"\n * @vt: #Y ESC IND \"Index\" \"ESC D\" \"Move the cursor one line down scrolling if needed.\"\n */\n public index(): boolean {\n this._restrictCursor();\n this._activeBuffer.y++;\n if (this._activeBuffer.y === this._activeBuffer.scrollBottom + 1) {\n this._activeBuffer.y--;\n this._bufferService.scroll(this._eraseAttrData());\n } else if (this._activeBuffer.y >= this._bufferService.rows) {\n this._activeBuffer.y = this._bufferService.rows - 1;\n }\n this._restrictCursor();\n return true;\n }\n\n /**\n * ESC H\n * C1.HTS\n * DEC mnemonic: HTS (https://vt100.net/docs/vt510-rm/HTS.html)\n * Sets a horizontal tab stop at the column position indicated by\n * the value of the active column when the terminal receives an HTS.\n *\n * @vt: #Y C1 HTS \"Horizontal Tabulation Set\" \"\\x88\" \"Places a tab stop at the current cursor position.\"\n * @vt: #Y ESC HTS \"Horizontal Tabulation Set\" \"ESC H\" \"Places a tab stop at the current cursor position.\"\n */\n public tabSet(): boolean {\n this._activeBuffer.tabs[this._activeBuffer.x] = true;\n return true;\n }\n\n /**\n * ESC M\n * C1.RI\n * DEC mnemonic: HTS\n * Moves the cursor up one line in the same column. If the cursor is at the top margin,\n * the page scrolls down.\n *\n * @vt: #Y ESC IR \"Reverse Index\" \"ESC M\" \"Move the cursor one line up scrolling if needed.\"\n */\n public reverseIndex(): boolean {\n this._restrictCursor();\n if (this._activeBuffer.y === this._activeBuffer.scrollTop) {\n // possibly move the code below to term.reverseScroll();\n // test: echo -ne '\\e[1;1H\\e[44m\\eM\\e[0m'\n // blankLine(true) is xterm/linux behavior\n const scrollRegionHeight = this._activeBuffer.scrollBottom - this._activeBuffer.scrollTop;\n this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase + this._activeBuffer.y, scrollRegionHeight, 1);\n this._activeBuffer.lines.set(this._activeBuffer.ybase + this._activeBuffer.y, this._activeBuffer.getBlankLine(this._eraseAttrData()));\n this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom);\n } else {\n this._activeBuffer.y--;\n this._restrictCursor(); // quickfix to not run out of bounds\n }\n return true;\n }\n\n /**\n * ESC c\n * DEC mnemonic: RIS (https://vt100.net/docs/vt510-rm/RIS.html)\n * Reset to initial state.\n */\n public fullReset(): boolean {\n this._parser.reset();\n this._onRequestReset.fire();\n return true;\n }\n\n public reset(): void {\n this._curAttrData = DEFAULT_ATTR_DATA.clone();\n this._eraseAttrDataInternal = DEFAULT_ATTR_DATA.clone();\n }\n\n /**\n * back_color_erase feature for xterm.\n */\n private _eraseAttrData(): IAttributeData {\n this._eraseAttrDataInternal.bg &= ~(Attributes.CM_MASK | 0xFFFFFF);\n this._eraseAttrDataInternal.bg |= this._curAttrData.bg & ~0xFC000000;\n return this._eraseAttrDataInternal;\n }\n\n /**\n * ESC n\n * ESC o\n * ESC |\n * ESC }\n * ESC ~\n * DEC mnemonic: LS (https://vt100.net/docs/vt510-rm/LS.html)\n * When you use a locking shift, the character set remains in GL or GR until\n * you use another locking shift. (partly supported)\n */\n public setgLevel(level: number): boolean {\n this._charsetService.setgLevel(level);\n return true;\n }\n\n /**\n * ESC # 8\n * DEC mnemonic: DECALN (https://vt100.net/docs/vt510-rm/DECALN.html)\n * This control function fills the complete screen area with\n * a test pattern (E) used for adjusting screen alignment.\n *\n * @vt: #Y ESC DECALN \"Screen Alignment Pattern\" \"ESC # 8\" \"Fill viewport with a test pattern (E).\"\n */\n public screenAlignmentPattern(): boolean {\n // prepare cell data\n const cell = new CellData();\n cell.content = 1 << Content.WIDTH_SHIFT | 'E'.charCodeAt(0);\n cell.fg = this._curAttrData.fg;\n cell.bg = this._curAttrData.bg;\n\n\n this._setCursor(0, 0);\n for (let yOffset = 0; yOffset < this._bufferService.rows; ++yOffset) {\n const row = this._activeBuffer.ybase + this._activeBuffer.y + yOffset;\n const line = this._activeBuffer.lines.get(row);\n if (line) {\n line.fill(cell);\n line.isWrapped = false;\n }\n }\n this._dirtyRowTracker.markAllDirty();\n this._setCursor(0, 0);\n return true;\n }\n\n\n /**\n * DCS $ q Pt ST\n * DECRQSS (https://vt100.net/docs/vt510-rm/DECRQSS.html)\n * Request Status String (DECRQSS), VT420 and up.\n * Response: DECRPSS (https://vt100.net/docs/vt510-rm/DECRPSS.html)\n *\n * @vt: #P[Limited support, see below.] DCS DECRQSS \"Request Selection or Setting\" \"DCS $ q Pt ST\" \"Request several terminal settings.\"\n * Response is in the form `ESC P 1 $ r Pt ST` for valid requests, where `Pt` contains the\n * corresponding CSI string, `ESC P 0 ST` for invalid requests.\n *\n * Supported requests and responses:\n *\n * | Type | Request | Response (`Pt`) |\n * | -------------------------------- | ----------------- | ----------------------------------------------------- |\n * | Graphic Rendition (SGR) | `DCS $ q m ST` | always reporting `0m` (currently broken) |\n * | Top and Bottom Margins (DECSTBM) | `DCS $ q r ST` | `Ps ; Ps r` |\n * | Cursor Style (DECSCUSR) | `DCS $ q SP q ST` | `Ps SP q` |\n * | Protection Attribute (DECSCA) | `DCS $ q \" q ST` | `Ps \" q` (DECSCA 2 is reported as Ps = 0) |\n * | Conformance Level (DECSCL) | `DCS $ q \" p ST` | always reporting `61 ; 1 \" p` (DECSCL is unsupported) |\n *\n *\n * TODO:\n * - fix SGR report\n * - either check which conformance is better suited or remove the report completely\n * --> we are currently a mixture of all up to VT400 but dont follow anyone strictly\n */\n public requestStatusString(data: string, params: IParams): boolean {\n const f = (s: string): boolean => {\n this._coreService.triggerDataEvent(`${C0.ESC}${s}${C0.ESC}\\\\`);\n return true;\n };\n\n // access helpers\n const b = this._bufferService.buffer;\n const opts = this._optionsService.rawOptions;\n const STYLES: { [key: string]: number } = { 'block': 2, 'underline': 4, 'bar': 6 };\n\n if (data === '\"q') return f(`P1$r${this._curAttrData.isProtected() ? 1 : 0}\"q`);\n if (data === '\"p') return f(`P1$r61;1\"p`);\n if (data === 'r') return f(`P1$r${b.scrollTop + 1};${b.scrollBottom + 1}r`);\n // FIXME: report real SGR settings instead of 0m\n if (data === 'm') return f(`P1$r0m`);\n if (data === ' q') return f(`P1$r${STYLES[opts.cursorStyle] - (opts.cursorBlink ? 1 : 0)} q`);\n return f(`P0$r`);\n }\n\n public markRangeDirty(y1: number, y2: number): void {\n this._dirtyRowTracker.markRangeDirty(y1, y2);\n }\n}\n\nexport interface IDirtyRowTracker {\n readonly start: number;\n readonly end: number;\n\n clearRange(): void;\n markDirty(y: number): void;\n markRangeDirty(y1: number, y2: number): void;\n markAllDirty(): void;\n}\n\nclass DirtyRowTracker implements IDirtyRowTracker {\n public start!: number;\n public end!: number;\n\n constructor(\n @IBufferService private readonly _bufferService: IBufferService\n ) {\n this.clearRange();\n }\n\n public clearRange(): void {\n this.start = this._bufferService.buffer.y;\n this.end = this._bufferService.buffer.y;\n }\n\n public markDirty(y: number): void {\n if (y < this.start) {\n this.start = y;\n } else if (y > this.end) {\n this.end = y;\n }\n }\n\n public markRangeDirty(y1: number, y2: number): void {\n if (y1 > y2) {\n $temp = y1;\n y1 = y2;\n y2 = $temp;\n }\n if (y1 < this.start) {\n this.start = y1;\n }\n if (y2 > this.end) {\n this.end = y2;\n }\n }\n\n public markAllDirty(): void {\n this.markRangeDirty(0, this._bufferService.rows - 1);\n }\n}\n\nexport function isValidColorIndex(value: number): value is ColorIndex {\n return 0 <= value && value < 256;\n}\n","/**\n * Copyright (c) 2022 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nexport class TwoKeyMap {\n private _data: { [bg: string | number]: { [fg: string | number]: TValue | undefined } | undefined } = {};\n\n public set(first: TFirst, second: TSecond, value: TValue): void {\n if (!this._data[first]) {\n this._data[first] = {};\n }\n this._data[first as string | number]![second] = value;\n }\n\n public get(first: TFirst, second: TSecond): TValue | undefined {\n return this._data[first as string | number] ? this._data[first as string | number]![second] : undefined;\n }\n\n public clear(): void {\n this._data = {};\n }\n}\n\nexport class FourKeyMap {\n private _data: TwoKeyMap> = new TwoKeyMap();\n\n public set(first: TFirst, second: TSecond, third: TThird, fourth: TFourth, value: TValue): void {\n if (!this._data.get(first, second)) {\n this._data.set(first, second, new TwoKeyMap());\n }\n this._data.get(first, second)!.set(third, fourth, value);\n }\n\n public get(first: TFirst, second: TSecond, third: TThird, fourth: TFourth): TValue | undefined {\n return this._data.get(first, second)?.get(third, fourth);\n }\n\n public clear(): void {\n this._data.clear();\n }\n}\n","/**\n * Copyright (c) 2016 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\ninterface INavigator {\n userAgent: string;\n language: string;\n platform: string;\n}\n\n// We're declaring a navigator global here as we expect it in all runtimes (node and browser), but\n// we want this module to live in common.\ndeclare const navigator: INavigator;\ndeclare const process: unknown;\n\nexport const isNode = (typeof process !== 'undefined' && 'title' in (process as any)) ? true : false;\nconst userAgent = (isNode) ? 'node' : navigator.userAgent;\nconst platform = (isNode) ? 'node' : navigator.platform;\n\nexport const isFirefox = userAgent.includes('Firefox');\nexport const isLegacyEdge = userAgent.includes('Edge');\nexport const isSafari = /^((?!chrome|android).)*safari/i.test(userAgent);\nexport function getSafariVersion(): number {\n if (!isSafari) {\n return 0;\n }\n const majorVersion = userAgent.match(/Version\\/(\\d+)/);\n if (majorVersion === null || majorVersion.length < 2) {\n return 0;\n }\n return parseInt(majorVersion[1]);\n}\n\n// Find the users platform. We use this to interpret the meta key\n// and ISO third level shifts.\n// http://stackoverflow.com/q/19877924/577598\nexport const isMac = ['Macintosh', 'MacIntel', 'MacPPC', 'Mac68K'].includes(platform);\nexport const isIpad = platform === 'iPad';\nexport const isIphone = platform === 'iPhone';\nexport const isWindows = ['Windows', 'Win16', 'Win32', 'WinCE'].includes(platform);\nexport const isLinux = platform.indexOf('Linux') >= 0;\n// Note that when this is true, isLinux will also be true.\nexport const isChromeOS = /\\bCrOS\\b/.test(userAgent);\n","/**\n * Copyright (c) 2022 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IdleTaskQueue } from 'common/TaskQueue';\n\n// Work variables to avoid garbage collection.\nlet i = 0;\n\n/**\n * A generic list that is maintained in sorted order and allows values with duplicate keys. Deferred\n * batch insertion and deletion is used to significantly reduce the time it takes to insert and\n * delete a large amount of items in succession. This list is based on binary search and as such\n * locating a key will take O(log n) amortized, this includes the by key iterator.\n */\nexport class SortedList {\n private _array: T[] = [];\n\n private readonly _insertedValues: T[] = [];\n private readonly _flushInsertedTask = new IdleTaskQueue();\n private _isFlushingInserted = false;\n\n private readonly _deletedIndices: number[] = [];\n private readonly _flushDeletedTask = new IdleTaskQueue();\n private _isFlushingDeleted = false;\n\n constructor(\n private readonly _getKey: (value: T) => number\n ) {\n }\n\n public clear(): void {\n this._array.length = 0;\n this._insertedValues.length = 0;\n this._flushInsertedTask.clear();\n this._isFlushingInserted = false;\n this._deletedIndices.length = 0;\n this._flushDeletedTask.clear();\n this._isFlushingDeleted = false;\n }\n\n public insert(value: T): void {\n this._flushCleanupDeleted();\n if (this._insertedValues.length === 0) {\n this._flushInsertedTask.enqueue(() => this._flushInserted());\n }\n this._insertedValues.push(value);\n }\n\n private _flushInserted(): void {\n const sortedAddedValues = this._insertedValues.sort((a, b) => this._getKey(a) - this._getKey(b));\n let sortedAddedValuesIndex = 0;\n let arrayIndex = 0;\n\n const newArray = new Array(this._array.length + this._insertedValues.length);\n\n for (let newArrayIndex = 0; newArrayIndex < newArray.length; newArrayIndex++) {\n if (arrayIndex >= this._array.length || this._getKey(sortedAddedValues[sortedAddedValuesIndex]) <= this._getKey(this._array[arrayIndex])) {\n newArray[newArrayIndex] = sortedAddedValues[sortedAddedValuesIndex];\n sortedAddedValuesIndex++;\n } else {\n newArray[newArrayIndex] = this._array[arrayIndex++];\n }\n }\n\n this._array = newArray;\n this._insertedValues.length = 0;\n }\n\n private _flushCleanupInserted(): void {\n if (!this._isFlushingInserted && this._insertedValues.length > 0) {\n this._flushInsertedTask.flush();\n }\n }\n\n public delete(value: T): boolean {\n this._flushCleanupInserted();\n if (this._array.length === 0) {\n return false;\n }\n const key = this._getKey(value);\n if (key === undefined) {\n return false;\n }\n i = this._search(key);\n if (i === -1) {\n return false;\n }\n if (this._getKey(this._array[i]) !== key) {\n return false;\n }\n do {\n if (this._array[i] === value) {\n if (this._deletedIndices.length === 0) {\n this._flushDeletedTask.enqueue(() => this._flushDeleted());\n }\n this._deletedIndices.push(i);\n return true;\n }\n } while (++i < this._array.length && this._getKey(this._array[i]) === key);\n return false;\n }\n\n private _flushDeleted(): void {\n this._isFlushingDeleted = true;\n const sortedDeletedIndices = this._deletedIndices.sort((a, b) => a - b);\n let sortedDeletedIndicesIndex = 0;\n const newArray = new Array(this._array.length - sortedDeletedIndices.length);\n let newArrayIndex = 0;\n for (let i = 0; i < this._array.length; i++) {\n if (sortedDeletedIndices[sortedDeletedIndicesIndex] === i) {\n sortedDeletedIndicesIndex++;\n } else {\n newArray[newArrayIndex++] = this._array[i];\n }\n }\n this._array = newArray;\n this._deletedIndices.length = 0;\n this._isFlushingDeleted = false;\n }\n\n private _flushCleanupDeleted(): void {\n if (!this._isFlushingDeleted && this._deletedIndices.length > 0) {\n this._flushDeletedTask.flush();\n }\n }\n\n public *getKeyIterator(key: number): IterableIterator {\n this._flushCleanupInserted();\n this._flushCleanupDeleted();\n if (this._array.length === 0) {\n return;\n }\n i = this._search(key);\n if (i < 0 || i >= this._array.length) {\n return;\n }\n if (this._getKey(this._array[i]) !== key) {\n return;\n }\n do {\n yield this._array[i];\n } while (++i < this._array.length && this._getKey(this._array[i]) === key);\n }\n\n public forEachByKey(key: number, callback: (value: T) => void): void {\n this._flushCleanupInserted();\n this._flushCleanupDeleted();\n if (this._array.length === 0) {\n return;\n }\n i = this._search(key);\n if (i < 0 || i >= this._array.length) {\n return;\n }\n if (this._getKey(this._array[i]) !== key) {\n return;\n }\n do {\n callback(this._array[i]);\n } while (++i < this._array.length && this._getKey(this._array[i]) === key);\n }\n\n public values(): IterableIterator {\n this._flushCleanupInserted();\n this._flushCleanupDeleted();\n // Duplicate the array to avoid issues when _array changes while iterating\n return [...this._array].values();\n }\n\n private _search(key: number): number {\n let min = 0;\n let max = this._array.length - 1;\n while (max >= min) {\n let mid = (min + max) >> 1;\n const midKey = this._getKey(this._array[mid]);\n if (midKey > key) {\n max = mid - 1;\n } else if (midKey < key) {\n min = mid + 1;\n } else {\n // key in list, walk to lowest duplicate\n while (mid > 0 && this._getKey(this._array[mid - 1]) === key) {\n mid--;\n }\n return mid;\n }\n }\n // key not in list\n // still return closest min (also used as insert position)\n return min;\n }\n}\n","/**\n * Copyright (c) 2022 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { isNode } from 'common/Platform';\n\ninterface ITaskQueue {\n /**\n * Adds a task to the queue which will run in a future idle callback.\n * To avoid perceivable stalls on the mainthread, tasks with heavy workload\n * should split their work into smaller pieces and return `true` to get\n * called again until the work is done (on falsy return value).\n */\n enqueue(task: () => boolean | void): void;\n\n /**\n * Flushes the queue, running all remaining tasks synchronously.\n */\n flush(): void;\n\n /**\n * Clears any remaining tasks from the queue, these will not be run.\n */\n clear(): void;\n}\n\ninterface ITaskDeadline {\n timeRemaining(): number;\n}\ntype CallbackWithDeadline = (deadline: ITaskDeadline) => void;\n\nabstract class TaskQueue implements ITaskQueue {\n private _tasks: (() => boolean | void)[] = [];\n private _idleCallback?: number;\n private _i = 0;\n\n protected abstract _requestCallback(callback: CallbackWithDeadline): number;\n protected abstract _cancelCallback(identifier: number): void;\n\n public enqueue(task: () => boolean | void): void {\n this._tasks.push(task);\n this._start();\n }\n\n public flush(): void {\n while (this._i < this._tasks.length) {\n if (!this._tasks[this._i]()) {\n this._i++;\n }\n }\n this.clear();\n }\n\n public clear(): void {\n if (this._idleCallback) {\n this._cancelCallback(this._idleCallback);\n this._idleCallback = undefined;\n }\n this._i = 0;\n this._tasks.length = 0;\n }\n\n private _start(): void {\n if (!this._idleCallback) {\n this._idleCallback = this._requestCallback(this._process.bind(this));\n }\n }\n\n private _process(deadline: ITaskDeadline): void {\n this._idleCallback = undefined;\n let taskDuration = 0;\n let longestTask = 0;\n let lastDeadlineRemaining = deadline.timeRemaining();\n let deadlineRemaining = 0;\n while (this._i < this._tasks.length) {\n taskDuration = performance.now();\n if (!this._tasks[this._i]()) {\n this._i++;\n }\n // other than performance.now, performance.now might not be stable (changes on wall clock\n // changes), this is not an issue here as a clock change during a short running task is very\n // unlikely in case it still happened and leads to negative duration, simply assume 1 msec\n taskDuration = Math.max(1, performance.now() - taskDuration);\n longestTask = Math.max(taskDuration, longestTask);\n // Guess the following task will take a similar time to the longest task in this batch, allow\n // additional room to try avoid exceeding the deadline\n deadlineRemaining = deadline.timeRemaining();\n if (longestTask * 1.5 > deadlineRemaining) {\n // Warn when the time exceeding the deadline is over 20ms, if this happens in practice the\n // task should be split into sub-tasks to ensure the UI remains responsive.\n if (lastDeadlineRemaining - taskDuration < -20) {\n console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(lastDeadlineRemaining - taskDuration))}ms`);\n }\n this._start();\n return;\n }\n lastDeadlineRemaining = deadlineRemaining;\n }\n this.clear();\n }\n}\n\n/**\n * A queue of that runs tasks over several tasks via setTimeout, trying to maintain above 60 frames\n * per second. The tasks will run in the order they are enqueued, but they will run some time later,\n * and care should be taken to ensure they're non-urgent and will not introduce race conditions.\n */\nexport class PriorityTaskQueue extends TaskQueue {\n protected _requestCallback(callback: CallbackWithDeadline): number {\n return setTimeout(() => callback(this._createDeadline(16)));\n }\n\n protected _cancelCallback(identifier: number): void {\n clearTimeout(identifier);\n }\n\n private _createDeadline(duration: number): ITaskDeadline {\n const end = performance.now() + duration;\n return {\n timeRemaining: () => Math.max(0, end - performance.now())\n };\n }\n}\n\nclass IdleTaskQueueInternal extends TaskQueue {\n protected _requestCallback(callback: IdleRequestCallback): number {\n return requestIdleCallback(callback);\n }\n\n protected _cancelCallback(identifier: number): void {\n cancelIdleCallback(identifier);\n }\n}\n\n/**\n * A queue of that runs tasks over several idle callbacks, trying to respect the idle callback's\n * deadline given by the environment. The tasks will run in the order they are enqueued, but they\n * will run some time later, and care should be taken to ensure they're non-urgent and will not\n * introduce race conditions.\n *\n * This reverts to a {@link PriorityTaskQueue} if the environment does not support idle callbacks.\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport const IdleTaskQueue = (!isNode && 'requestIdleCallback' in window) ? IdleTaskQueueInternal : PriorityTaskQueue;\n\n/**\n * An object that tracks a single debounced task that will run on the next idle frame. When called\n * multiple times, only the last set task will run.\n */\nexport class DebouncedIdleTask {\n private _queue: ITaskQueue;\n\n constructor() {\n this._queue = new IdleTaskQueue();\n }\n\n public set(task: () => boolean | void): void {\n this._queue.clear();\n this._queue.enqueue(task);\n }\n\n public flush(): void {\n this._queue.flush();\n }\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { CHAR_DATA_CODE_INDEX, NULL_CELL_CODE, WHITESPACE_CELL_CODE } from 'common/buffer/Constants';\nimport { IBufferService } from 'common/services/Services';\n\nexport function updateWindowsModeWrappedState(bufferService: IBufferService): void {\n // Winpty does not support wraparound mode which means that lines will never\n // be marked as wrapped. This causes issues for things like copying a line\n // retaining the wrapped new line characters or if consumers are listening\n // in on the data stream.\n //\n // The workaround for this is to listen to every incoming line feed and mark\n // the line as wrapped if the last character in the previous line is not a\n // space. This is certainly not without its problems, but generally on\n // Windows when text reaches the end of the terminal it's likely going to be\n // wrapped.\n const line = bufferService.buffer.lines.get(bufferService.buffer.ybase + bufferService.buffer.y - 1);\n const lastChar = line?.get(bufferService.cols - 1);\n\n const nextLine = bufferService.buffer.lines.get(bufferService.buffer.ybase + bufferService.buffer.y);\n if (nextLine && lastChar) {\n nextLine.isWrapped = (lastChar[CHAR_DATA_CODE_INDEX] !== NULL_CELL_CODE && lastChar[CHAR_DATA_CODE_INDEX] !== WHITESPACE_CELL_CODE);\n }\n}\n","/**\n * Copyright (c) 2018 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IAttributeData, IColorRGB, IExtendedAttrs } from 'common/Types';\nimport { Attributes, FgFlags, BgFlags, UnderlineStyle, ExtFlags } from 'common/buffer/Constants';\n\nexport class AttributeData implements IAttributeData {\n public static toColorRGB(value: number): IColorRGB {\n return [\n value >>> Attributes.RED_SHIFT & 255,\n value >>> Attributes.GREEN_SHIFT & 255,\n value & 255\n ];\n }\n\n public static fromColorRGB(value: IColorRGB): number {\n return (value[0] & 255) << Attributes.RED_SHIFT | (value[1] & 255) << Attributes.GREEN_SHIFT | value[2] & 255;\n }\n\n public clone(): IAttributeData {\n const newObj = new AttributeData();\n newObj.fg = this.fg;\n newObj.bg = this.bg;\n newObj.extended = this.extended.clone();\n return newObj;\n }\n\n // data\n public fg = 0;\n public bg = 0;\n public extended: IExtendedAttrs = new ExtendedAttrs();\n\n // flags\n public isInverse(): number { return this.fg & FgFlags.INVERSE; }\n public isBold(): number { return this.fg & FgFlags.BOLD; }\n public isUnderline(): number {\n if (this.hasExtendedAttrs() && this.extended.underlineStyle !== UnderlineStyle.NONE) {\n return 1;\n }\n return this.fg & FgFlags.UNDERLINE;\n }\n public isBlink(): number { return this.fg & FgFlags.BLINK; }\n public isInvisible(): number { return this.fg & FgFlags.INVISIBLE; }\n public isItalic(): number { return this.bg & BgFlags.ITALIC; }\n public isDim(): number { return this.bg & BgFlags.DIM; }\n public isStrikethrough(): number { return this.fg & FgFlags.STRIKETHROUGH; }\n public isProtected(): number { return this.bg & BgFlags.PROTECTED; }\n public isOverline(): number { return this.bg & BgFlags.OVERLINE; }\n\n // color modes\n public getFgColorMode(): number { return this.fg & Attributes.CM_MASK; }\n public getBgColorMode(): number { return this.bg & Attributes.CM_MASK; }\n public isFgRGB(): boolean { return (this.fg & Attributes.CM_MASK) === Attributes.CM_RGB; }\n public isBgRGB(): boolean { return (this.bg & Attributes.CM_MASK) === Attributes.CM_RGB; }\n public isFgPalette(): boolean { return (this.fg & Attributes.CM_MASK) === Attributes.CM_P16 || (this.fg & Attributes.CM_MASK) === Attributes.CM_P256; }\n public isBgPalette(): boolean { return (this.bg & Attributes.CM_MASK) === Attributes.CM_P16 || (this.bg & Attributes.CM_MASK) === Attributes.CM_P256; }\n public isFgDefault(): boolean { return (this.fg & Attributes.CM_MASK) === 0; }\n public isBgDefault(): boolean { return (this.bg & Attributes.CM_MASK) === 0; }\n public isAttributeDefault(): boolean { return this.fg === 0 && this.bg === 0; }\n\n // colors\n public getFgColor(): number {\n switch (this.fg & Attributes.CM_MASK) {\n case Attributes.CM_P16:\n case Attributes.CM_P256: return this.fg & Attributes.PCOLOR_MASK;\n case Attributes.CM_RGB: return this.fg & Attributes.RGB_MASK;\n default: return -1; // CM_DEFAULT defaults to -1\n }\n }\n public getBgColor(): number {\n switch (this.bg & Attributes.CM_MASK) {\n case Attributes.CM_P16:\n case Attributes.CM_P256: return this.bg & Attributes.PCOLOR_MASK;\n case Attributes.CM_RGB: return this.bg & Attributes.RGB_MASK;\n default: return -1; // CM_DEFAULT defaults to -1\n }\n }\n\n // extended attrs\n public hasExtendedAttrs(): number {\n return this.bg & BgFlags.HAS_EXTENDED;\n }\n public updateExtended(): void {\n if (this.extended.isEmpty()) {\n this.bg &= ~BgFlags.HAS_EXTENDED;\n } else {\n this.bg |= BgFlags.HAS_EXTENDED;\n }\n }\n public getUnderlineColor(): number {\n if ((this.bg & BgFlags.HAS_EXTENDED) && ~this.extended.underlineColor) {\n switch (this.extended.underlineColor & Attributes.CM_MASK) {\n case Attributes.CM_P16:\n case Attributes.CM_P256: return this.extended.underlineColor & Attributes.PCOLOR_MASK;\n case Attributes.CM_RGB: return this.extended.underlineColor & Attributes.RGB_MASK;\n default: return this.getFgColor();\n }\n }\n return this.getFgColor();\n }\n public getUnderlineColorMode(): number {\n return (this.bg & BgFlags.HAS_EXTENDED) && ~this.extended.underlineColor\n ? this.extended.underlineColor & Attributes.CM_MASK\n : this.getFgColorMode();\n }\n public isUnderlineColorRGB(): boolean {\n return (this.bg & BgFlags.HAS_EXTENDED) && ~this.extended.underlineColor\n ? (this.extended.underlineColor & Attributes.CM_MASK) === Attributes.CM_RGB\n : this.isFgRGB();\n }\n public isUnderlineColorPalette(): boolean {\n return (this.bg & BgFlags.HAS_EXTENDED) && ~this.extended.underlineColor\n ? (this.extended.underlineColor & Attributes.CM_MASK) === Attributes.CM_P16\n || (this.extended.underlineColor & Attributes.CM_MASK) === Attributes.CM_P256\n : this.isFgPalette();\n }\n public isUnderlineColorDefault(): boolean {\n return (this.bg & BgFlags.HAS_EXTENDED) && ~this.extended.underlineColor\n ? (this.extended.underlineColor & Attributes.CM_MASK) === 0\n : this.isFgDefault();\n }\n public getUnderlineStyle(): UnderlineStyle {\n return this.fg & FgFlags.UNDERLINE\n ? (this.bg & BgFlags.HAS_EXTENDED ? this.extended.underlineStyle : UnderlineStyle.SINGLE)\n : UnderlineStyle.NONE;\n }\n public getUnderlineVariantOffset(): number {\n return this.extended.underlineVariantOffset;\n }\n}\n\n\n/**\n * Extended attributes for a cell.\n * Holds information about different underline styles and color.\n */\nexport class ExtendedAttrs implements IExtendedAttrs {\n private _ext: number = 0;\n public get ext(): number {\n if (this._urlId) {\n return (\n (this._ext & ~ExtFlags.UNDERLINE_STYLE) |\n (this.underlineStyle << 26)\n );\n }\n return this._ext;\n }\n public set ext(value: number) { this._ext = value; }\n\n public get underlineStyle(): UnderlineStyle {\n // Always return the URL style if it has one\n if (this._urlId) {\n return UnderlineStyle.DASHED;\n }\n return (this._ext & ExtFlags.UNDERLINE_STYLE) >> 26;\n }\n public set underlineStyle(value: UnderlineStyle) {\n this._ext &= ~ExtFlags.UNDERLINE_STYLE;\n this._ext |= (value << 26) & ExtFlags.UNDERLINE_STYLE;\n }\n\n public get underlineColor(): number {\n return this._ext & (Attributes.CM_MASK | Attributes.RGB_MASK);\n }\n public set underlineColor(value: number) {\n this._ext &= ~(Attributes.CM_MASK | Attributes.RGB_MASK);\n this._ext |= value & (Attributes.CM_MASK | Attributes.RGB_MASK);\n }\n\n private _urlId: number = 0;\n public get urlId(): number {\n return this._urlId;\n }\n public set urlId(value: number) {\n this._urlId = value;\n }\n\n public get underlineVariantOffset(): number {\n const val = (this._ext & ExtFlags.VARIANT_OFFSET) >> 29;\n if (val < 0) {\n return val ^ 0xFFFFFFF8;\n }\n return val;\n }\n public set underlineVariantOffset(value: number) {\n this._ext &= ~ExtFlags.VARIANT_OFFSET;\n this._ext |= (value << 29) & ExtFlags.VARIANT_OFFSET;\n }\n\n constructor(\n ext: number = 0,\n urlId: number = 0\n ) {\n this._ext = ext;\n this._urlId = urlId;\n }\n\n public clone(): IExtendedAttrs {\n return new ExtendedAttrs(this._ext, this._urlId);\n }\n\n /**\n * Convenient method to indicate whether the object holds no additional information,\n * that needs to be persistant in the buffer.\n */\n public isEmpty(): boolean {\n return this.underlineStyle === UnderlineStyle.NONE && this._urlId === 0;\n }\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { CircularList, IInsertEvent } from 'common/CircularList';\nimport { IdleTaskQueue } from 'common/TaskQueue';\nimport { IAttributeData, IBufferLine, ICellData, ICharset } from 'common/Types';\nimport { ExtendedAttrs } from 'common/buffer/AttributeData';\nimport { BufferLine, DEFAULT_ATTR_DATA } from 'common/buffer/BufferLine';\nimport { getWrappedLineTrimmedLength, reflowLargerApplyNewLayout, reflowLargerCreateNewLayout, reflowLargerGetLinesToRemove, reflowSmallerGetNewLineLengths } from 'common/buffer/BufferReflow';\nimport { CellData } from 'common/buffer/CellData';\nimport { NULL_CELL_CHAR, NULL_CELL_CODE, NULL_CELL_WIDTH, WHITESPACE_CELL_CHAR, WHITESPACE_CELL_CODE, WHITESPACE_CELL_WIDTH } from 'common/buffer/Constants';\nimport { Marker } from 'common/buffer/Marker';\nimport { IBuffer } from 'common/buffer/Types';\nimport { DEFAULT_CHARSET } from 'common/data/Charsets';\nimport { IBufferService, IOptionsService } from 'common/services/Services';\n\nexport const MAX_BUFFER_SIZE = 4294967295; // 2^32 - 1\n\n/**\n * This class represents a terminal buffer (an internal state of the terminal), where the\n * following information is stored (in high-level):\n * - text content of this particular buffer\n * - cursor position\n * - scroll position\n */\nexport class Buffer implements IBuffer {\n public lines: CircularList;\n public ydisp: number = 0;\n public ybase: number = 0;\n public y: number = 0;\n public x: number = 0;\n public scrollBottom: number;\n public scrollTop: number;\n public tabs: { [column: number]: boolean | undefined } = {};\n public savedY: number = 0;\n public savedX: number = 0;\n public savedCurAttrData = DEFAULT_ATTR_DATA.clone();\n public savedCharset: ICharset | undefined = DEFAULT_CHARSET;\n public markers: Marker[] = [];\n private _nullCell: ICellData = CellData.fromCharData([0, NULL_CELL_CHAR, NULL_CELL_WIDTH, NULL_CELL_CODE]);\n private _whitespaceCell: ICellData = CellData.fromCharData([0, WHITESPACE_CELL_CHAR, WHITESPACE_CELL_WIDTH, WHITESPACE_CELL_CODE]);\n private _cols: number;\n private _rows: number;\n private _isClearing: boolean = false;\n\n constructor(\n private _hasScrollback: boolean,\n private _optionsService: IOptionsService,\n private _bufferService: IBufferService\n ) {\n this._cols = this._bufferService.cols;\n this._rows = this._bufferService.rows;\n this.lines = new CircularList(this._getCorrectBufferLength(this._rows));\n this.scrollTop = 0;\n this.scrollBottom = this._rows - 1;\n this.setupTabStops();\n }\n\n public getNullCell(attr?: IAttributeData): ICellData {\n if (attr) {\n this._nullCell.fg = attr.fg;\n this._nullCell.bg = attr.bg;\n this._nullCell.extended = attr.extended;\n } else {\n this._nullCell.fg = 0;\n this._nullCell.bg = 0;\n this._nullCell.extended = new ExtendedAttrs();\n }\n return this._nullCell;\n }\n\n public getWhitespaceCell(attr?: IAttributeData): ICellData {\n if (attr) {\n this._whitespaceCell.fg = attr.fg;\n this._whitespaceCell.bg = attr.bg;\n this._whitespaceCell.extended = attr.extended;\n } else {\n this._whitespaceCell.fg = 0;\n this._whitespaceCell.bg = 0;\n this._whitespaceCell.extended = new ExtendedAttrs();\n }\n return this._whitespaceCell;\n }\n\n public getBlankLine(attr: IAttributeData, isWrapped?: boolean): IBufferLine {\n return new BufferLine(this._bufferService.cols, this.getNullCell(attr), isWrapped);\n }\n\n public get hasScrollback(): boolean {\n return this._hasScrollback && this.lines.maxLength > this._rows;\n }\n\n public get isCursorInViewport(): boolean {\n const absoluteY = this.ybase + this.y;\n const relativeY = absoluteY - this.ydisp;\n return (relativeY >= 0 && relativeY < this._rows);\n }\n\n /**\n * Gets the correct buffer length based on the rows provided, the terminal's\n * scrollback and whether this buffer is flagged to have scrollback or not.\n * @param rows The terminal rows to use in the calculation.\n */\n private _getCorrectBufferLength(rows: number): number {\n if (!this._hasScrollback) {\n return rows;\n }\n\n const correctBufferLength = rows + this._optionsService.rawOptions.scrollback;\n\n return correctBufferLength > MAX_BUFFER_SIZE ? MAX_BUFFER_SIZE : correctBufferLength;\n }\n\n /**\n * Fills the buffer's viewport with blank lines.\n */\n public fillViewportRows(fillAttr?: IAttributeData): void {\n if (this.lines.length === 0) {\n if (fillAttr === undefined) {\n fillAttr = DEFAULT_ATTR_DATA;\n }\n let i = this._rows;\n while (i--) {\n this.lines.push(this.getBlankLine(fillAttr));\n }\n }\n }\n\n /**\n * Clears the buffer to it's initial state, discarding all previous data.\n */\n public clear(): void {\n this.ydisp = 0;\n this.ybase = 0;\n this.y = 0;\n this.x = 0;\n this.lines = new CircularList(this._getCorrectBufferLength(this._rows));\n this.scrollTop = 0;\n this.scrollBottom = this._rows - 1;\n this.setupTabStops();\n }\n\n /**\n * Resizes the buffer, adjusting its data accordingly.\n * @param newCols The new number of columns.\n * @param newRows The new number of rows.\n */\n public resize(newCols: number, newRows: number): void {\n // store reference to null cell with default attrs\n const nullCell = this.getNullCell(DEFAULT_ATTR_DATA);\n\n // count bufferlines with overly big memory to be cleaned afterwards\n let dirtyMemoryLines = 0;\n\n // Increase max length if needed before adjustments to allow space to fill\n // as required.\n const newMaxLength = this._getCorrectBufferLength(newRows);\n if (newMaxLength > this.lines.maxLength) {\n this.lines.maxLength = newMaxLength;\n }\n\n // if (this._cols > newCols) {\n // console.log('increase!');\n // }\n\n // The following adjustments should only happen if the buffer has been\n // initialized/filled.\n if (this.lines.length > 0) {\n // Deal with columns increasing (reducing needs to happen after reflow)\n if (this._cols < newCols) {\n for (let i = 0; i < this.lines.length; i++) {\n // +boolean for fast 0 or 1 conversion\n dirtyMemoryLines += +this.lines.get(i)!.resize(newCols, nullCell);\n }\n }\n\n // Resize rows in both directions as needed\n let addToY = 0;\n if (this._rows < newRows) {\n for (let y = this._rows; y < newRows; y++) {\n if (this.lines.length < newRows + this.ybase) {\n if (this._optionsService.rawOptions.windowsMode || this._optionsService.rawOptions.windowsPty.backend !== undefined || this._optionsService.rawOptions.windowsPty.buildNumber !== undefined) {\n // Just add the new missing rows on Windows as conpty reprints the screen with it's\n // view of the world. Once a line enters scrollback for conpty it remains there\n this.lines.push(new BufferLine(newCols, nullCell));\n } else {\n if (this.ybase > 0 && this.lines.length <= this.ybase + this.y + addToY + 1) {\n // There is room above the buffer and there are no empty elements below the line,\n // scroll up\n this.ybase--;\n addToY++;\n if (this.ydisp > 0) {\n // Viewport is at the top of the buffer, must increase downwards\n this.ydisp--;\n }\n } else {\n // Add a blank line if there is no buffer left at the top to scroll to, or if there\n // are blank lines after the cursor\n this.lines.push(new BufferLine(newCols, nullCell));\n }\n }\n }\n }\n } else { // (this._rows >= newRows)\n for (let y = this._rows; y > newRows; y--) {\n if (this.lines.length > newRows + this.ybase) {\n if (this.lines.length > this.ybase + this.y + 1) {\n // The line is a blank line below the cursor, remove it\n this.lines.pop();\n } else {\n // The line is the cursor, scroll down\n this.ybase++;\n this.ydisp++;\n }\n }\n }\n }\n\n // Reduce max length if needed after adjustments, this is done after as it\n // would otherwise cut data from the bottom of the buffer.\n if (newMaxLength < this.lines.maxLength) {\n // Trim from the top of the buffer and adjust ybase and ydisp.\n const amountToTrim = this.lines.length - newMaxLength;\n if (amountToTrim > 0) {\n this.lines.trimStart(amountToTrim);\n this.ybase = Math.max(this.ybase - amountToTrim, 0);\n this.ydisp = Math.max(this.ydisp - amountToTrim, 0);\n this.savedY = Math.max(this.savedY - amountToTrim, 0);\n }\n this.lines.maxLength = newMaxLength;\n }\n\n // Make sure that the cursor stays on screen\n this.x = Math.min(this.x, newCols - 1);\n this.y = Math.min(this.y, newRows - 1);\n if (addToY) {\n this.y += addToY;\n }\n this.savedX = Math.min(this.savedX, newCols - 1);\n\n this.scrollTop = 0;\n }\n\n this.scrollBottom = newRows - 1;\n\n if (this._isReflowEnabled) {\n this._reflow(newCols, newRows);\n\n // Trim the end of the line off if cols shrunk\n if (this._cols > newCols) {\n for (let i = 0; i < this.lines.length; i++) {\n // +boolean for fast 0 or 1 conversion\n dirtyMemoryLines += +this.lines.get(i)!.resize(newCols, nullCell);\n }\n }\n }\n\n this._cols = newCols;\n this._rows = newRows;\n\n this._memoryCleanupQueue.clear();\n // schedule memory cleanup only, if more than 10% of the lines are affected\n if (dirtyMemoryLines > 0.1 * this.lines.length) {\n this._memoryCleanupPosition = 0;\n this._memoryCleanupQueue.enqueue(() => this._batchedMemoryCleanup());\n }\n }\n\n private _memoryCleanupQueue = new IdleTaskQueue();\n private _memoryCleanupPosition = 0;\n\n private _batchedMemoryCleanup(): boolean {\n let normalRun = true;\n if (this._memoryCleanupPosition >= this.lines.length) {\n // cleanup made it once through all lines, thus rescan in loop below to also catch shifted\n // lines, which should finish rather quick if there are no more cleanups pending\n this._memoryCleanupPosition = 0;\n normalRun = false;\n }\n let counted = 0;\n while (this._memoryCleanupPosition < this.lines.length) {\n counted += this.lines.get(this._memoryCleanupPosition++)!.cleanupMemory();\n // cleanup max 100 lines per batch\n if (counted > 100) {\n return true;\n }\n }\n // normal runs always need another rescan afterwards\n // if we made it here with normalRun=false, we are in a final run\n // and can end the cleanup task for sure\n return normalRun;\n }\n\n private get _isReflowEnabled(): boolean {\n const windowsPty = this._optionsService.rawOptions.windowsPty;\n if (windowsPty && windowsPty.buildNumber) {\n return this._hasScrollback && windowsPty.backend === 'conpty' && windowsPty.buildNumber >= 21376;\n }\n return this._hasScrollback && !this._optionsService.rawOptions.windowsMode;\n }\n\n private _reflow(newCols: number, newRows: number): void {\n if (this._cols === newCols) {\n return;\n }\n\n // Iterate through rows, ignore the last one as it cannot be wrapped\n if (newCols > this._cols) {\n this._reflowLarger(newCols, newRows);\n } else {\n this._reflowSmaller(newCols, newRows);\n }\n }\n\n private _reflowLarger(newCols: number, newRows: number): void {\n const reflowCursorLine = this._optionsService.rawOptions.reflowCursorLine;\n const toRemove: number[] = reflowLargerGetLinesToRemove(this.lines, this._cols, newCols, this.ybase + this.y, this.getNullCell(DEFAULT_ATTR_DATA), reflowCursorLine);\n if (toRemove.length > 0) {\n const newLayoutResult = reflowLargerCreateNewLayout(this.lines, toRemove);\n reflowLargerApplyNewLayout(this.lines, newLayoutResult.layout);\n this._reflowLargerAdjustViewport(newCols, newRows, newLayoutResult.countRemoved);\n }\n }\n\n private _reflowLargerAdjustViewport(newCols: number, newRows: number, countRemoved: number): void {\n const nullCell = this.getNullCell(DEFAULT_ATTR_DATA);\n // Adjust viewport based on number of items removed\n let viewportAdjustments = countRemoved;\n while (viewportAdjustments-- > 0) {\n if (this.ybase === 0) {\n if (this.y > 0) {\n this.y--;\n }\n if (this.lines.length < newRows) {\n // Add an extra row at the bottom of the viewport\n this.lines.push(new BufferLine(newCols, nullCell));\n }\n } else {\n if (this.ydisp === this.ybase) {\n this.ydisp--;\n }\n this.ybase--;\n }\n }\n this.savedY = Math.max(this.savedY - countRemoved, 0);\n }\n\n private _reflowSmaller(newCols: number, newRows: number): void {\n const reflowCursorLine = this._optionsService.rawOptions.reflowCursorLine;\n const nullCell = this.getNullCell(DEFAULT_ATTR_DATA);\n // Gather all BufferLines that need to be inserted into the Buffer here so that they can be\n // batched up and only committed once\n const toInsert = [];\n let countToInsert = 0;\n // Go backwards as many lines may be trimmed and this will avoid considering them\n for (let y = this.lines.length - 1; y >= 0; y--) {\n // Check whether this line is a problem\n let nextLine = this.lines.get(y) as BufferLine;\n if (!nextLine || !nextLine.isWrapped && nextLine.getTrimmedLength() <= newCols) {\n continue;\n }\n\n // Gather wrapped lines and adjust y to be the starting line\n const wrappedLines: BufferLine[] = [nextLine];\n while (nextLine.isWrapped && y > 0) {\n nextLine = this.lines.get(--y) as BufferLine;\n wrappedLines.unshift(nextLine);\n }\n\n if (!reflowCursorLine) {\n // If these lines contain the cursor don't touch them, the program will handle fixing up\n // wrapped lines with the cursor\n const absoluteY = this.ybase + this.y;\n if (absoluteY >= y && absoluteY < y + wrappedLines.length) {\n continue;\n }\n }\n\n const lastLineLength = wrappedLines[wrappedLines.length - 1].getTrimmedLength();\n const destLineLengths = reflowSmallerGetNewLineLengths(wrappedLines, this._cols, newCols);\n const linesToAdd = destLineLengths.length - wrappedLines.length;\n let trimmedLines: number;\n if (this.ybase === 0 && this.y !== this.lines.length - 1) {\n // If the top section of the buffer is not yet filled\n trimmedLines = Math.max(0, this.y - this.lines.maxLength + linesToAdd);\n } else {\n trimmedLines = Math.max(0, this.lines.length - this.lines.maxLength + linesToAdd);\n }\n\n // Add the new lines\n const newLines: BufferLine[] = [];\n for (let i = 0; i < linesToAdd; i++) {\n const newLine = this.getBlankLine(DEFAULT_ATTR_DATA, true) as BufferLine;\n newLines.push(newLine);\n }\n if (newLines.length > 0) {\n toInsert.push({\n // countToInsert here gets the actual index, taking into account other inserted items.\n // using this we can iterate through the list forwards\n start: y + wrappedLines.length + countToInsert,\n newLines\n });\n countToInsert += newLines.length;\n }\n wrappedLines.push(...newLines);\n\n // Copy buffer data to new locations, this needs to happen backwards to do in-place\n let destLineIndex = destLineLengths.length - 1; // Math.floor(cellsNeeded / newCols);\n let destCol = destLineLengths[destLineIndex]; // cellsNeeded % newCols;\n if (destCol === 0) {\n destLineIndex--;\n destCol = destLineLengths[destLineIndex];\n }\n let srcLineIndex = wrappedLines.length - linesToAdd - 1;\n let srcCol = lastLineLength;\n while (srcLineIndex >= 0) {\n const cellsToCopy = Math.min(srcCol, destCol);\n if (wrappedLines[destLineIndex] === undefined) {\n // Sanity check that the line exists, this has been known to fail for an unknown reason\n // which would stop the reflow from happening if an exception would throw.\n break;\n }\n wrappedLines[destLineIndex].copyCellsFrom(wrappedLines[srcLineIndex], srcCol - cellsToCopy, destCol - cellsToCopy, cellsToCopy, true);\n destCol -= cellsToCopy;\n if (destCol === 0) {\n destLineIndex--;\n destCol = destLineLengths[destLineIndex];\n }\n srcCol -= cellsToCopy;\n if (srcCol === 0) {\n srcLineIndex--;\n const wrappedLinesIndex = Math.max(srcLineIndex, 0);\n srcCol = getWrappedLineTrimmedLength(wrappedLines, wrappedLinesIndex, this._cols);\n }\n }\n\n // Null out the end of the line ends if a wide character wrapped to the following line\n for (let i = 0; i < wrappedLines.length; i++) {\n if (destLineLengths[i] < newCols) {\n wrappedLines[i].setCell(destLineLengths[i], nullCell);\n }\n }\n\n // Adjust viewport as needed\n let viewportAdjustments = linesToAdd - trimmedLines;\n while (viewportAdjustments-- > 0) {\n if (this.ybase === 0) {\n if (this.y < newRows - 1) {\n this.y++;\n this.lines.pop();\n } else {\n this.ybase++;\n this.ydisp++;\n }\n } else {\n // Ensure ybase does not exceed its maximum value\n if (this.ybase < Math.min(this.lines.maxLength, this.lines.length + countToInsert) - newRows) {\n if (this.ybase === this.ydisp) {\n this.ydisp++;\n }\n this.ybase++;\n }\n }\n }\n this.savedY = Math.min(this.savedY + linesToAdd, this.ybase + newRows - 1);\n }\n\n // Rearrange lines in the buffer if there are any insertions, this is done at the end rather\n // than earlier so that it's a single O(n) pass through the buffer, instead of O(n^2) from many\n // costly calls to CircularList.splice.\n if (toInsert.length > 0) {\n // Record buffer insert events and then play them back backwards so that the indexes are\n // correct\n const insertEvents: IInsertEvent[] = [];\n\n // Record original lines so they don't get overridden when we rearrange the list\n const originalLines: BufferLine[] = [];\n for (let i = 0; i < this.lines.length; i++) {\n originalLines.push(this.lines.get(i) as BufferLine);\n }\n const originalLinesLength = this.lines.length;\n\n let originalLineIndex = originalLinesLength - 1;\n let nextToInsertIndex = 0;\n let nextToInsert = toInsert[nextToInsertIndex];\n this.lines.length = Math.min(this.lines.maxLength, this.lines.length + countToInsert);\n let countInsertedSoFar = 0;\n for (let i = Math.min(this.lines.maxLength - 1, originalLinesLength + countToInsert - 1); i >= 0; i--) {\n if (nextToInsert && nextToInsert.start > originalLineIndex + countInsertedSoFar) {\n // Insert extra lines here, adjusting i as needed\n for (let nextI = nextToInsert.newLines.length - 1; nextI >= 0; nextI--) {\n this.lines.set(i--, nextToInsert.newLines[nextI]);\n }\n i++;\n\n // Create insert events for later\n insertEvents.push({\n index: originalLineIndex + 1,\n amount: nextToInsert.newLines.length\n });\n\n countInsertedSoFar += nextToInsert.newLines.length;\n nextToInsert = toInsert[++nextToInsertIndex];\n } else {\n this.lines.set(i, originalLines[originalLineIndex--]);\n }\n }\n\n // Update markers\n let insertCountEmitted = 0;\n for (let i = insertEvents.length - 1; i >= 0; i--) {\n insertEvents[i].index += insertCountEmitted;\n this.lines.onInsertEmitter.fire(insertEvents[i]);\n insertCountEmitted += insertEvents[i].amount;\n }\n const amountToTrim = Math.max(0, originalLinesLength + countToInsert - this.lines.maxLength);\n if (amountToTrim > 0) {\n this.lines.onTrimEmitter.fire(amountToTrim);\n }\n }\n }\n\n /**\n * Translates a buffer line to a string, with optional start and end columns.\n * Wide characters will count as two columns in the resulting string. This\n * function is useful for getting the actual text underneath the raw selection\n * position.\n * @param lineIndex The absolute index of the line being translated.\n * @param trimRight Whether to trim whitespace to the right.\n * @param startCol The column to start at.\n * @param endCol The column to end at.\n */\n public translateBufferLineToString(lineIndex: number, trimRight: boolean, startCol: number = 0, endCol?: number): string {\n const line = this.lines.get(lineIndex);\n if (!line) {\n return '';\n }\n return line.translateToString(trimRight, startCol, endCol);\n }\n\n public getWrappedRangeForLine(y: number): { first: number, last: number } {\n let first = y;\n let last = y;\n // Scan upwards for wrapped lines\n while (first > 0 && this.lines.get(first)!.isWrapped) {\n first--;\n }\n // Scan downwards for wrapped lines\n while (last + 1 < this.lines.length && this.lines.get(last + 1)!.isWrapped) {\n last++;\n }\n return { first, last };\n }\n\n /**\n * Setup the tab stops.\n * @param i The index to start setting up tab stops from.\n */\n public setupTabStops(i?: number): void {\n if (i !== null && i !== undefined) {\n if (!this.tabs[i]) {\n i = this.prevStop(i);\n }\n } else {\n this.tabs = {};\n i = 0;\n }\n\n for (; i < this._cols; i += this._optionsService.rawOptions.tabStopWidth) {\n this.tabs[i] = true;\n }\n }\n\n /**\n * Move the cursor to the previous tab stop from the given position (default is current).\n * @param x The position to move the cursor to the previous tab stop.\n */\n public prevStop(x?: number): number {\n if (x === null || x === undefined) {\n x = this.x;\n }\n while (!this.tabs[--x] && x > 0);\n return x >= this._cols ? this._cols - 1 : x < 0 ? 0 : x;\n }\n\n /**\n * Move the cursor one tab stop forward from the given position (default is current).\n * @param x The position to move the cursor one tab stop forward.\n */\n public nextStop(x?: number): number {\n if (x === null || x === undefined) {\n x = this.x;\n }\n while (!this.tabs[++x] && x < this._cols);\n return x >= this._cols ? this._cols - 1 : x < 0 ? 0 : x;\n }\n\n /**\n * Clears markers on single line.\n * @param y The line to clear.\n */\n public clearMarkers(y: number): void {\n this._isClearing = true;\n for (let i = 0; i < this.markers.length; i++) {\n if (this.markers[i].line === y) {\n this.markers[i].dispose();\n this.markers.splice(i--, 1);\n }\n }\n this._isClearing = false;\n }\n\n /**\n * Clears markers on all lines\n */\n public clearAllMarkers(): void {\n this._isClearing = true;\n for (let i = 0; i < this.markers.length; i++) {\n this.markers[i].dispose();\n }\n this.markers.length = 0;\n this._isClearing = false;\n }\n\n public addMarker(y: number): Marker {\n const marker = new Marker(y);\n this.markers.push(marker);\n marker.register(this.lines.onTrim(amount => {\n marker.line -= amount;\n // The marker should be disposed when the line is trimmed from the buffer\n if (marker.line < 0) {\n marker.dispose();\n }\n }));\n marker.register(this.lines.onInsert(event => {\n if (marker.line >= event.index) {\n marker.line += event.amount;\n }\n }));\n marker.register(this.lines.onDelete(event => {\n // Delete the marker if it's within the range\n if (marker.line >= event.index && marker.line < event.index + event.amount) {\n marker.dispose();\n }\n\n // Shift the marker if it's after the deleted range\n if (marker.line > event.index) {\n marker.line -= event.amount;\n }\n }));\n marker.register(marker.onDispose(() => this._removeMarker(marker)));\n return marker;\n }\n\n private _removeMarker(marker: Marker): void {\n if (!this._isClearing) {\n this.markers.splice(this.markers.indexOf(marker), 1);\n }\n }\n}\n","/**\n * Copyright (c) 2018 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { CharData, IAttributeData, IBufferLine, ICellData, IExtendedAttrs } from 'common/Types';\nimport { AttributeData } from 'common/buffer/AttributeData';\nimport { CellData } from 'common/buffer/CellData';\nimport { Attributes, BgFlags, CHAR_DATA_ATTR_INDEX, CHAR_DATA_CHAR_INDEX, CHAR_DATA_WIDTH_INDEX, Content, NULL_CELL_CHAR, NULL_CELL_CODE, NULL_CELL_WIDTH, WHITESPACE_CELL_CHAR } from 'common/buffer/Constants';\nimport { stringFromCodePoint } from 'common/input/TextDecoder';\n\n/**\n * buffer memory layout:\n *\n * | uint32_t | uint32_t | uint32_t |\n * | `content` | `FG` | `BG` |\n * | wcwidth(2) comb(1) codepoint(21) | flags(8) R(8) G(8) B(8) | flags(8) R(8) G(8) B(8) |\n */\n\n\n/** typed array slots taken by one cell */\nconst CELL_SIZE = 3;\n\n/**\n * Cell member indices.\n *\n * Direct access:\n * `content = data[column * CELL_SIZE + Cell.CONTENT];`\n * `fg = data[column * CELL_SIZE + Cell.FG];`\n * `bg = data[column * CELL_SIZE + Cell.BG];`\n */\nconst enum Cell {\n CONTENT = 0,\n FG = 1, // currently simply holds all known attrs\n BG = 2 // currently unused\n}\n\nexport const DEFAULT_ATTR_DATA = Object.freeze(new AttributeData());\n\n// Work variables to avoid garbage collection\nlet $startIndex = 0;\n\n/** Factor when to cleanup underlying array buffer after shrinking. */\nconst CLEANUP_THRESHOLD = 2;\n\n/**\n * Typed array based bufferline implementation.\n *\n * There are 2 ways to insert data into the cell buffer:\n * - `setCellFromCodepoint` + `addCodepointToCell`\n * Use these for data that is already UTF32.\n * Used during normal input in `InputHandler` for faster buffer access.\n * - `setCell`\n * This method takes a CellData object and stores the data in the buffer.\n * Use `CellData.fromCharData` to create the CellData object (e.g. from JS string).\n *\n * To retrieve data from the buffer use either one of the primitive methods\n * (if only one particular value is needed) or `loadCell`. For `loadCell` in a loop\n * memory allocs / GC pressure can be greatly reduced by reusing the CellData object.\n */\nexport class BufferLine implements IBufferLine {\n protected _data: Uint32Array;\n protected _combined: {[index: number]: string} = {};\n protected _extendedAttrs: {[index: number]: IExtendedAttrs | undefined} = {};\n public length: number;\n\n constructor(cols: number, fillCellData?: ICellData, public isWrapped: boolean = false) {\n this._data = new Uint32Array(cols * CELL_SIZE);\n const cell = fillCellData || CellData.fromCharData([0, NULL_CELL_CHAR, NULL_CELL_WIDTH, NULL_CELL_CODE]);\n for (let i = 0; i < cols; ++i) {\n this.setCell(i, cell);\n }\n this.length = cols;\n }\n\n /**\n * Get cell data CharData.\n * @deprecated\n */\n public get(index: number): CharData {\n const content = this._data[index * CELL_SIZE + Cell.CONTENT];\n const cp = content & Content.CODEPOINT_MASK;\n return [\n this._data[index * CELL_SIZE + Cell.FG],\n (content & Content.IS_COMBINED_MASK)\n ? this._combined[index]\n : (cp) ? stringFromCodePoint(cp) : '',\n content >> Content.WIDTH_SHIFT,\n (content & Content.IS_COMBINED_MASK)\n ? this._combined[index].charCodeAt(this._combined[index].length - 1)\n : cp\n ];\n }\n\n /**\n * Set cell data from CharData.\n * @deprecated\n */\n public set(index: number, value: CharData): void {\n this._data[index * CELL_SIZE + Cell.FG] = value[CHAR_DATA_ATTR_INDEX];\n if (value[CHAR_DATA_CHAR_INDEX].length > 1) {\n this._combined[index] = value[1];\n this._data[index * CELL_SIZE + Cell.CONTENT] = index | Content.IS_COMBINED_MASK | (value[CHAR_DATA_WIDTH_INDEX] << Content.WIDTH_SHIFT);\n } else {\n this._data[index * CELL_SIZE + Cell.CONTENT] = value[CHAR_DATA_CHAR_INDEX].charCodeAt(0) | (value[CHAR_DATA_WIDTH_INDEX] << Content.WIDTH_SHIFT);\n }\n }\n\n /**\n * primitive getters\n * use these when only one value is needed, otherwise use `loadCell`\n */\n public getWidth(index: number): number {\n return this._data[index * CELL_SIZE + Cell.CONTENT] >> Content.WIDTH_SHIFT;\n }\n\n /** Test whether content has width. */\n public hasWidth(index: number): number {\n return this._data[index * CELL_SIZE + Cell.CONTENT] & Content.WIDTH_MASK;\n }\n\n /** Get FG cell component. */\n public getFg(index: number): number {\n return this._data[index * CELL_SIZE + Cell.FG];\n }\n\n /** Get BG cell component. */\n public getBg(index: number): number {\n return this._data[index * CELL_SIZE + Cell.BG];\n }\n\n /**\n * Test whether contains any chars.\n * Basically an empty has no content, but other cells might differ in FG/BG\n * from real empty cells.\n */\n public hasContent(index: number): number {\n return this._data[index * CELL_SIZE + Cell.CONTENT] & Content.HAS_CONTENT_MASK;\n }\n\n /**\n * Get codepoint of the cell.\n * To be in line with `code` in CharData this either returns\n * a single UTF32 codepoint or the last codepoint of a combined string.\n */\n public getCodePoint(index: number): number {\n const content = this._data[index * CELL_SIZE + Cell.CONTENT];\n if (content & Content.IS_COMBINED_MASK) {\n return this._combined[index].charCodeAt(this._combined[index].length - 1);\n }\n return content & Content.CODEPOINT_MASK;\n }\n\n /** Test whether the cell contains a combined string. */\n public isCombined(index: number): number {\n return this._data[index * CELL_SIZE + Cell.CONTENT] & Content.IS_COMBINED_MASK;\n }\n\n /** Returns the string content of the cell. */\n public getString(index: number): string {\n const content = this._data[index * CELL_SIZE + Cell.CONTENT];\n if (content & Content.IS_COMBINED_MASK) {\n return this._combined[index];\n }\n if (content & Content.CODEPOINT_MASK) {\n return stringFromCodePoint(content & Content.CODEPOINT_MASK);\n }\n // return empty string for empty cells\n return '';\n }\n\n /** Get state of protected flag. */\n public isProtected(index: number): number {\n return this._data[index * CELL_SIZE + Cell.BG] & BgFlags.PROTECTED;\n }\n\n /**\n * Load data at `index` into `cell`. This is used to access cells in a way that's more friendly\n * to GC as it significantly reduced the amount of new objects/references needed.\n */\n public loadCell(index: number, cell: ICellData): ICellData {\n $startIndex = index * CELL_SIZE;\n cell.content = this._data[$startIndex + Cell.CONTENT];\n cell.fg = this._data[$startIndex + Cell.FG];\n cell.bg = this._data[$startIndex + Cell.BG];\n if (cell.content & Content.IS_COMBINED_MASK) {\n cell.combinedData = this._combined[index];\n }\n if (cell.bg & BgFlags.HAS_EXTENDED) {\n cell.extended = this._extendedAttrs[index]!;\n }\n return cell;\n }\n\n /**\n * Set data at `index` to `cell`.\n */\n public setCell(index: number, cell: ICellData): void {\n if (cell.content & Content.IS_COMBINED_MASK) {\n this._combined[index] = cell.combinedData;\n }\n if (cell.bg & BgFlags.HAS_EXTENDED) {\n this._extendedAttrs[index] = cell.extended;\n }\n this._data[index * CELL_SIZE + Cell.CONTENT] = cell.content;\n this._data[index * CELL_SIZE + Cell.FG] = cell.fg;\n this._data[index * CELL_SIZE + Cell.BG] = cell.bg;\n }\n\n /**\n * Set cell data from input handler.\n * Since the input handler see the incoming chars as UTF32 codepoints,\n * it gets an optimized access method.\n */\n public setCellFromCodepoint(index: number, codePoint: number, width: number, attrs: IAttributeData): void {\n if (attrs.bg & BgFlags.HAS_EXTENDED) {\n this._extendedAttrs[index] = attrs.extended;\n }\n this._data[index * CELL_SIZE + Cell.CONTENT] = codePoint | (width << Content.WIDTH_SHIFT);\n this._data[index * CELL_SIZE + Cell.FG] = attrs.fg;\n this._data[index * CELL_SIZE + Cell.BG] = attrs.bg;\n }\n\n /**\n * Add a codepoint to a cell from input handler.\n * During input stage combining chars with a width of 0 follow and stack\n * onto a leading char. Since we already set the attrs\n * by the previous `setDataFromCodePoint` call, we can omit it here.\n */\n public addCodepointToCell(index: number, codePoint: number, width: number): void {\n let content = this._data[index * CELL_SIZE + Cell.CONTENT];\n if (content & Content.IS_COMBINED_MASK) {\n // we already have a combined string, simply add\n this._combined[index] += stringFromCodePoint(codePoint);\n } else {\n if (content & Content.CODEPOINT_MASK) {\n // normal case for combining chars:\n // - move current leading char + new one into combined string\n // - set combined flag\n this._combined[index] = stringFromCodePoint(content & Content.CODEPOINT_MASK) + stringFromCodePoint(codePoint);\n content &= ~Content.CODEPOINT_MASK; // set codepoint in buffer to 0\n content |= Content.IS_COMBINED_MASK;\n } else {\n // should not happen - we actually have no data in the cell yet\n // simply set the data in the cell buffer with a width of 1\n content = codePoint | (1 << Content.WIDTH_SHIFT);\n }\n }\n if (width) {\n content &= ~Content.WIDTH_MASK;\n content |= width << Content.WIDTH_SHIFT;\n }\n this._data[index * CELL_SIZE + Cell.CONTENT] = content;\n }\n\n public insertCells(pos: number, n: number, fillCellData: ICellData): void {\n pos %= this.length;\n\n // handle fullwidth at pos: reset cell one to the left if pos is second cell of a wide char\n if (pos && this.getWidth(pos - 1) === 2) {\n this.setCellFromCodepoint(pos - 1, 0, 1, fillCellData);\n }\n\n if (n < this.length - pos) {\n const cell = new CellData();\n for (let i = this.length - pos - n - 1; i >= 0; --i) {\n this.setCell(pos + n + i, this.loadCell(pos + i, cell));\n }\n for (let i = 0; i < n; ++i) {\n this.setCell(pos + i, fillCellData);\n }\n } else {\n for (let i = pos; i < this.length; ++i) {\n this.setCell(i, fillCellData);\n }\n }\n\n // handle fullwidth at line end: reset last cell if it is first cell of a wide char\n if (this.getWidth(this.length - 1) === 2) {\n this.setCellFromCodepoint(this.length - 1, 0, 1, fillCellData);\n }\n }\n\n public deleteCells(pos: number, n: number, fillCellData: ICellData): void {\n pos %= this.length;\n if (n < this.length - pos) {\n const cell = new CellData();\n for (let i = 0; i < this.length - pos - n; ++i) {\n this.setCell(pos + i, this.loadCell(pos + n + i, cell));\n }\n for (let i = this.length - n; i < this.length; ++i) {\n this.setCell(i, fillCellData);\n }\n } else {\n for (let i = pos; i < this.length; ++i) {\n this.setCell(i, fillCellData);\n }\n }\n\n // handle fullwidth at pos:\n // - reset pos-1 if wide char\n // - reset pos if width==0 (previous second cell of a wide char)\n if (pos && this.getWidth(pos - 1) === 2) {\n this.setCellFromCodepoint(pos - 1, 0, 1, fillCellData);\n }\n if (this.getWidth(pos) === 0 && !this.hasContent(pos)) {\n this.setCellFromCodepoint(pos, 0, 1, fillCellData);\n }\n }\n\n public replaceCells(start: number, end: number, fillCellData: ICellData, respectProtect: boolean = false): void {\n // full branching on respectProtect==true, hopefully getting fast JIT for standard case\n if (respectProtect) {\n if (start && this.getWidth(start - 1) === 2 && !this.isProtected(start - 1)) {\n this.setCellFromCodepoint(start - 1, 0, 1, fillCellData);\n }\n if (end < this.length && this.getWidth(end - 1) === 2 && !this.isProtected(end)) {\n this.setCellFromCodepoint(end, 0, 1, fillCellData);\n }\n while (start < end && start < this.length) {\n if (!this.isProtected(start)) {\n this.setCell(start, fillCellData);\n }\n start++;\n }\n return;\n }\n\n // handle fullwidth at start: reset cell one to the left if start is second cell of a wide char\n if (start && this.getWidth(start - 1) === 2) {\n this.setCellFromCodepoint(start - 1, 0, 1, fillCellData);\n }\n // handle fullwidth at last cell + 1: reset to empty cell if it is second part of a wide char\n if (end < this.length && this.getWidth(end - 1) === 2) {\n this.setCellFromCodepoint(end, 0, 1, fillCellData);\n }\n\n while (start < end && start < this.length) {\n this.setCell(start++, fillCellData);\n }\n }\n\n /**\n * Resize BufferLine to `cols` filling excess cells with `fillCellData`.\n * The underlying array buffer will not change if there is still enough space\n * to hold the new buffer line data.\n * Returns a boolean indicating, whether a `cleanupMemory` call would free\n * excess memory (true after shrinking > CLEANUP_THRESHOLD).\n */\n public resize(cols: number, fillCellData: ICellData): boolean {\n if (cols === this.length) {\n return this._data.length * 4 * CLEANUP_THRESHOLD < this._data.buffer.byteLength;\n }\n const uint32Cells = cols * CELL_SIZE;\n if (cols > this.length) {\n if (this._data.buffer.byteLength >= uint32Cells * 4) {\n // optimization: avoid alloc and data copy if buffer has enough room\n this._data = new Uint32Array(this._data.buffer, 0, uint32Cells);\n } else {\n // slow path: new alloc and full data copy\n const data = new Uint32Array(uint32Cells);\n data.set(this._data);\n this._data = data;\n }\n for (let i = this.length; i < cols; ++i) {\n this.setCell(i, fillCellData);\n }\n } else {\n // optimization: just shrink the view on existing buffer\n this._data = this._data.subarray(0, uint32Cells);\n // Remove any cut off combined data\n const keys = Object.keys(this._combined);\n for (let i = 0; i < keys.length; i++) {\n const key = parseInt(keys[i], 10);\n if (key >= cols) {\n delete this._combined[key];\n }\n }\n // remove any cut off extended attributes\n const extKeys = Object.keys(this._extendedAttrs);\n for (let i = 0; i < extKeys.length; i++) {\n const key = parseInt(extKeys[i], 10);\n if (key >= cols) {\n delete this._extendedAttrs[key];\n }\n }\n }\n this.length = cols;\n return uint32Cells * 4 * CLEANUP_THRESHOLD < this._data.buffer.byteLength;\n }\n\n /**\n * Cleanup underlying array buffer.\n * A cleanup will be triggered if the array buffer exceeds the actual used\n * memory by a factor of CLEANUP_THRESHOLD.\n * Returns 0 or 1 indicating whether a cleanup happened.\n */\n public cleanupMemory(): number {\n if (this._data.length * 4 * CLEANUP_THRESHOLD < this._data.buffer.byteLength) {\n const data = new Uint32Array(this._data.length);\n data.set(this._data);\n this._data = data;\n return 1;\n }\n return 0;\n }\n\n /** fill a line with fillCharData */\n public fill(fillCellData: ICellData, respectProtect: boolean = false): void {\n // full branching on respectProtect==true, hopefully getting fast JIT for standard case\n if (respectProtect) {\n for (let i = 0; i < this.length; ++i) {\n if (!this.isProtected(i)) {\n this.setCell(i, fillCellData);\n }\n }\n return;\n }\n this._combined = {};\n this._extendedAttrs = {};\n for (let i = 0; i < this.length; ++i) {\n this.setCell(i, fillCellData);\n }\n }\n\n /** alter to a full copy of line */\n public copyFrom(line: BufferLine): void {\n if (this.length !== line.length) {\n this._data = new Uint32Array(line._data);\n } else {\n // use high speed copy if lengths are equal\n this._data.set(line._data);\n }\n this.length = line.length;\n this._combined = {};\n for (const el in line._combined) {\n this._combined[el] = line._combined[el];\n }\n this._extendedAttrs = {};\n for (const el in line._extendedAttrs) {\n this._extendedAttrs[el] = line._extendedAttrs[el];\n }\n this.isWrapped = line.isWrapped;\n }\n\n /** create a new clone */\n public clone(): IBufferLine {\n const newLine = new BufferLine(0);\n newLine._data = new Uint32Array(this._data);\n newLine.length = this.length;\n for (const el in this._combined) {\n newLine._combined[el] = this._combined[el];\n }\n for (const el in this._extendedAttrs) {\n newLine._extendedAttrs[el] = this._extendedAttrs[el];\n }\n newLine.isWrapped = this.isWrapped;\n return newLine;\n }\n\n public getTrimmedLength(): number {\n for (let i = this.length - 1; i >= 0; --i) {\n if ((this._data[i * CELL_SIZE + Cell.CONTENT] & Content.HAS_CONTENT_MASK)) {\n return i + (this._data[i * CELL_SIZE + Cell.CONTENT] >> Content.WIDTH_SHIFT);\n }\n }\n return 0;\n }\n\n public getNoBgTrimmedLength(): number {\n for (let i = this.length - 1; i >= 0; --i) {\n if ((this._data[i * CELL_SIZE + Cell.CONTENT] & Content.HAS_CONTENT_MASK) || (this._data[i * CELL_SIZE + Cell.BG] & Attributes.CM_MASK)) {\n return i + (this._data[i * CELL_SIZE + Cell.CONTENT] >> Content.WIDTH_SHIFT);\n }\n }\n return 0;\n }\n\n public copyCellsFrom(src: BufferLine, srcCol: number, destCol: number, length: number, applyInReverse: boolean): void {\n const srcData = src._data;\n if (applyInReverse) {\n for (let cell = length - 1; cell >= 0; cell--) {\n for (let i = 0; i < CELL_SIZE; i++) {\n this._data[(destCol + cell) * CELL_SIZE + i] = srcData[(srcCol + cell) * CELL_SIZE + i];\n }\n if (srcData[(srcCol + cell) * CELL_SIZE + Cell.BG] & BgFlags.HAS_EXTENDED) {\n this._extendedAttrs[destCol + cell] = src._extendedAttrs[srcCol + cell];\n }\n }\n } else {\n for (let cell = 0; cell < length; cell++) {\n for (let i = 0; i < CELL_SIZE; i++) {\n this._data[(destCol + cell) * CELL_SIZE + i] = srcData[(srcCol + cell) * CELL_SIZE + i];\n }\n if (srcData[(srcCol + cell) * CELL_SIZE + Cell.BG] & BgFlags.HAS_EXTENDED) {\n this._extendedAttrs[destCol + cell] = src._extendedAttrs[srcCol + cell];\n }\n }\n }\n\n // Move any combined data over as needed, FIXME: repeat for extended attrs\n const srcCombinedKeys = Object.keys(src._combined);\n for (let i = 0; i < srcCombinedKeys.length; i++) {\n const key = parseInt(srcCombinedKeys[i], 10);\n if (key >= srcCol) {\n this._combined[key - srcCol + destCol] = src._combined[key];\n }\n }\n }\n\n /**\n * Translates the buffer line to a string.\n *\n * @param trimRight Whether to trim any empty cells on the right.\n * @param startCol The column to start the string (0-based inclusive).\n * @param endCol The column to end the string (0-based exclusive).\n * @param outColumns if specified, this array will be filled with column numbers such that\n * `returnedString[i]` is displayed at `outColumns[i]` column. `outColumns[returnedString.length]`\n * is where the character following `returnedString` will be displayed.\n *\n * When a single cell is translated to multiple UTF-16 code units (e.g. surrogate pair) in the\n * returned string, the corresponding entries in `outColumns` will have the same column number.\n */\n public translateToString(trimRight?: boolean, startCol?: number, endCol?: number, outColumns?: number[]): string {\n startCol = startCol ?? 0;\n endCol = endCol ?? this.length;\n if (trimRight) {\n endCol = Math.min(endCol, this.getTrimmedLength());\n }\n if (outColumns) {\n outColumns.length = 0;\n }\n let result = '';\n while (startCol < endCol) {\n const content = this._data[startCol * CELL_SIZE + Cell.CONTENT];\n const cp = content & Content.CODEPOINT_MASK;\n const chars = (content & Content.IS_COMBINED_MASK) ? this._combined[startCol] : (cp) ? stringFromCodePoint(cp) : WHITESPACE_CELL_CHAR;\n result += chars;\n if (outColumns) {\n for (let i = 0; i < chars.length; ++i) {\n outColumns.push(startCol);\n }\n }\n startCol += (content >> Content.WIDTH_SHIFT) || 1; // always advance by at least 1\n }\n if (outColumns) {\n outColumns.push(startCol);\n }\n return result;\n }\n}\n","/**\n * Copyright (c) 2021 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IBufferRange } from '@xterm/xterm';\n\nexport function getRangeLength(range: IBufferRange, bufferCols: number): number {\n if (range.start.y > range.end.y) {\n throw new Error(`Buffer range end (${range.end.x}, ${range.end.y}) cannot be before start (${range.start.x}, ${range.start.y})`);\n }\n return bufferCols * (range.end.y - range.start.y) + (range.end.x - range.start.x + 1);\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { BufferLine } from 'common/buffer/BufferLine';\nimport { CircularList } from 'common/CircularList';\nimport { IBufferLine, ICellData } from 'common/Types';\n\nexport interface INewLayoutResult {\n layout: number[];\n countRemoved: number;\n}\n\n/**\n * Evaluates and returns indexes to be removed after a reflow larger occurs. Lines will be removed\n * when a wrapped line unwraps.\n * @param lines The buffer lines.\n * @param oldCols The columns before resize\n * @param newCols The columns after resize.\n * @param bufferAbsoluteY The absolute y position of the cursor (baseY + cursorY).\n * @param nullCell The cell data to use when filling in empty cells.\n * @param reflowCursorLine Whether to reflow the line containing the cursor.\n */\nexport function reflowLargerGetLinesToRemove(lines: CircularList, oldCols: number, newCols: number, bufferAbsoluteY: number, nullCell: ICellData, reflowCursorLine: boolean): number[] {\n // Gather all BufferLines that need to be removed from the Buffer here so that they can be\n // batched up and only committed once\n const toRemove: number[] = [];\n\n for (let y = 0; y < lines.length - 1; y++) {\n // Check if this row is wrapped\n let i = y;\n let nextLine = lines.get(++i) as BufferLine;\n if (!nextLine.isWrapped) {\n continue;\n }\n\n // Check how many lines it's wrapped for\n const wrappedLines: BufferLine[] = [lines.get(y) as BufferLine];\n while (i < lines.length && nextLine.isWrapped) {\n wrappedLines.push(nextLine);\n nextLine = lines.get(++i) as BufferLine;\n }\n\n if (!reflowCursorLine) {\n // If these lines contain the cursor don't touch them, the program will handle fixing up\n // wrapped lines with the cursor\n if (bufferAbsoluteY >= y && bufferAbsoluteY < i) {\n y += wrappedLines.length - 1;\n continue;\n }\n }\n\n // Copy buffer data to new locations\n let destLineIndex = 0;\n let destCol = getWrappedLineTrimmedLength(wrappedLines, destLineIndex, oldCols);\n let srcLineIndex = 1;\n let srcCol = 0;\n while (srcLineIndex < wrappedLines.length) {\n const srcTrimmedTineLength = getWrappedLineTrimmedLength(wrappedLines, srcLineIndex, oldCols);\n const srcRemainingCells = srcTrimmedTineLength - srcCol;\n const destRemainingCells = newCols - destCol;\n const cellsToCopy = Math.min(srcRemainingCells, destRemainingCells);\n\n wrappedLines[destLineIndex].copyCellsFrom(wrappedLines[srcLineIndex], srcCol, destCol, cellsToCopy, false);\n\n destCol += cellsToCopy;\n if (destCol === newCols) {\n destLineIndex++;\n destCol = 0;\n }\n srcCol += cellsToCopy;\n if (srcCol === srcTrimmedTineLength) {\n srcLineIndex++;\n srcCol = 0;\n }\n\n // Make sure the last cell isn't wide, if it is copy it to the current dest\n if (destCol === 0 && destLineIndex !== 0) {\n if (wrappedLines[destLineIndex - 1].getWidth(newCols - 1) === 2) {\n wrappedLines[destLineIndex].copyCellsFrom(wrappedLines[destLineIndex - 1], newCols - 1, destCol++, 1, false);\n // Null out the end of the last row\n wrappedLines[destLineIndex - 1].setCell(newCols - 1, nullCell);\n }\n }\n }\n\n // Clear out remaining cells or fragments could remain;\n wrappedLines[destLineIndex].replaceCells(destCol, newCols, nullCell);\n\n // Work backwards and remove any rows at the end that only contain null cells\n let countToRemove = 0;\n for (let i = wrappedLines.length - 1; i > 0; i--) {\n if (i > destLineIndex || wrappedLines[i].getTrimmedLength() === 0) {\n countToRemove++;\n } else {\n break;\n }\n }\n\n if (countToRemove > 0) {\n toRemove.push(y + wrappedLines.length - countToRemove); // index\n toRemove.push(countToRemove);\n }\n\n y += wrappedLines.length - 1;\n }\n return toRemove;\n}\n\n/**\n * Creates and return the new layout for lines given an array of indexes to be removed.\n * @param lines The buffer lines.\n * @param toRemove The indexes to remove.\n */\nexport function reflowLargerCreateNewLayout(lines: CircularList, toRemove: number[]): INewLayoutResult {\n const layout: number[] = [];\n // First iterate through the list and get the actual indexes to use for rows\n let nextToRemoveIndex = 0;\n let nextToRemoveStart = toRemove[nextToRemoveIndex];\n let countRemovedSoFar = 0;\n for (let i = 0; i < lines.length; i++) {\n if (nextToRemoveStart === i) {\n const countToRemove = toRemove[++nextToRemoveIndex];\n\n // Tell markers that there was a deletion\n lines.onDeleteEmitter.fire({\n index: i - countRemovedSoFar,\n amount: countToRemove\n });\n\n i += countToRemove - 1;\n countRemovedSoFar += countToRemove;\n nextToRemoveStart = toRemove[++nextToRemoveIndex];\n } else {\n layout.push(i);\n }\n }\n return {\n layout,\n countRemoved: countRemovedSoFar\n };\n}\n\n/**\n * Applies a new layout to the buffer. This essentially does the same as many splice calls but it's\n * done all at once in a single iteration through the list since splice is very expensive.\n * @param lines The buffer lines.\n * @param newLayout The new layout to apply.\n */\nexport function reflowLargerApplyNewLayout(lines: CircularList, newLayout: number[]): void {\n // Record original lines so they don't get overridden when we rearrange the list\n const newLayoutLines: BufferLine[] = [];\n for (let i = 0; i < newLayout.length; i++) {\n newLayoutLines.push(lines.get(newLayout[i]) as BufferLine);\n }\n\n // Rearrange the list\n for (let i = 0; i < newLayoutLines.length; i++) {\n lines.set(i, newLayoutLines[i]);\n }\n lines.length = newLayout.length;\n}\n\n/**\n * Gets the new line lengths for a given wrapped line. The purpose of this function it to pre-\n * compute the wrapping points since wide characters may need to be wrapped onto the following line.\n * This function will return an array of numbers of where each line wraps to, the resulting array\n * will only contain the values `newCols` (when the line does not end with a wide character) and\n * `newCols - 1` (when the line does end with a wide character), except for the last value which\n * will contain the remaining items to fill the line.\n *\n * Calling this with a `newCols` value of `1` will lock up.\n *\n * @param wrappedLines The wrapped lines to evaluate.\n * @param oldCols The columns before resize.\n * @param newCols The columns after resize.\n */\nexport function reflowSmallerGetNewLineLengths(wrappedLines: BufferLine[], oldCols: number, newCols: number): number[] {\n const newLineLengths: number[] = [];\n const cellsNeeded = wrappedLines.map((l, i) => getWrappedLineTrimmedLength(wrappedLines, i, oldCols)).reduce((p, c) => p + c);\n\n // Use srcCol and srcLine to find the new wrapping point, use that to get the cellsAvailable and\n // linesNeeded\n let srcCol = 0;\n let srcLine = 0;\n let cellsAvailable = 0;\n while (cellsAvailable < cellsNeeded) {\n if (cellsNeeded - cellsAvailable < newCols) {\n // Add the final line and exit the loop\n newLineLengths.push(cellsNeeded - cellsAvailable);\n break;\n }\n srcCol += newCols;\n const oldTrimmedLength = getWrappedLineTrimmedLength(wrappedLines, srcLine, oldCols);\n if (srcCol > oldTrimmedLength) {\n srcCol -= oldTrimmedLength;\n srcLine++;\n }\n const endsWithWide = wrappedLines[srcLine].getWidth(srcCol - 1) === 2;\n if (endsWithWide) {\n srcCol--;\n }\n const lineLength = endsWithWide ? newCols - 1 : newCols;\n newLineLengths.push(lineLength);\n cellsAvailable += lineLength;\n }\n\n return newLineLengths;\n}\n\nexport function getWrappedLineTrimmedLength(lines: BufferLine[], i: number, cols: number): number {\n // If this is the last row in the wrapped line, get the actual trimmed length\n if (i === lines.length - 1) {\n return lines[i].getTrimmedLength();\n }\n // Detect whether the following line starts with a wide character and the end of the current line\n // is null, if so then we can be pretty sure the null character should be excluded from the line\n // length]\n const endsInNull = !(lines[i].hasContent(cols - 1)) && lines[i].getWidth(cols - 1) === 1;\n const followingLineStartsWithWide = lines[i + 1].getWidth(0) === 2;\n if (endsInNull && followingLineStartsWithWide) {\n return cols - 1;\n }\n return cols;\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { Disposable } from 'vs/base/common/lifecycle';\nimport { IAttributeData } from 'common/Types';\nimport { Buffer } from 'common/buffer/Buffer';\nimport { IBuffer, IBufferSet } from 'common/buffer/Types';\nimport { IBufferService, IOptionsService } from 'common/services/Services';\nimport { Emitter } from 'vs/base/common/event';\n\n/**\n * The BufferSet represents the set of two buffers used by xterm terminals (normal and alt) and\n * provides also utilities for working with them.\n */\nexport class BufferSet extends Disposable implements IBufferSet {\n private _normal!: Buffer;\n private _alt!: Buffer;\n private _activeBuffer!: Buffer;\n\n private readonly _onBufferActivate = this._register(new Emitter<{ activeBuffer: IBuffer, inactiveBuffer: IBuffer }>());\n public readonly onBufferActivate = this._onBufferActivate.event;\n\n /**\n * Create a new BufferSet for the given terminal.\n */\n constructor(\n private readonly _optionsService: IOptionsService,\n private readonly _bufferService: IBufferService\n ) {\n super();\n this.reset();\n this._register(this._optionsService.onSpecificOptionChange('scrollback', () => this.resize(this._bufferService.cols, this._bufferService.rows)));\n this._register(this._optionsService.onSpecificOptionChange('tabStopWidth', () => this.setupTabStops()));\n }\n\n public reset(): void {\n this._normal = new Buffer(true, this._optionsService, this._bufferService);\n this._normal.fillViewportRows();\n\n // The alt buffer should never have scrollback.\n // See http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h2-The-Alternate-Screen-Buffer\n this._alt = new Buffer(false, this._optionsService, this._bufferService);\n this._activeBuffer = this._normal;\n this._onBufferActivate.fire({\n activeBuffer: this._normal,\n inactiveBuffer: this._alt\n });\n\n this.setupTabStops();\n }\n\n /**\n * Returns the alt Buffer of the BufferSet\n */\n public get alt(): Buffer {\n return this._alt;\n }\n\n /**\n * Returns the currently active Buffer of the BufferSet\n */\n public get active(): Buffer {\n return this._activeBuffer;\n }\n\n /**\n * Returns the normal Buffer of the BufferSet\n */\n public get normal(): Buffer {\n return this._normal;\n }\n\n /**\n * Sets the normal Buffer of the BufferSet as its currently active Buffer\n */\n public activateNormalBuffer(): void {\n if (this._activeBuffer === this._normal) {\n return;\n }\n this._normal.x = this._alt.x;\n this._normal.y = this._alt.y;\n // The alt buffer should always be cleared when we switch to the normal\n // buffer. This frees up memory since the alt buffer should always be new\n // when activated.\n this._alt.clearAllMarkers();\n this._alt.clear();\n this._activeBuffer = this._normal;\n this._onBufferActivate.fire({\n activeBuffer: this._normal,\n inactiveBuffer: this._alt\n });\n }\n\n /**\n * Sets the alt Buffer of the BufferSet as its currently active Buffer\n */\n public activateAltBuffer(fillAttr?: IAttributeData): void {\n if (this._activeBuffer === this._alt) {\n return;\n }\n // Since the alt buffer is always cleared when the normal buffer is\n // activated, we want to fill it when switching to it.\n this._alt.fillViewportRows(fillAttr);\n this._alt.x = this._normal.x;\n this._alt.y = this._normal.y;\n this._activeBuffer = this._alt;\n this._onBufferActivate.fire({\n activeBuffer: this._alt,\n inactiveBuffer: this._normal\n });\n }\n\n /**\n * Resizes both normal and alt buffers, adjusting their data accordingly.\n * @param newCols The new number of columns.\n * @param newRows The new number of rows.\n */\n public resize(newCols: number, newRows: number): void {\n this._normal.resize(newCols, newRows);\n this._alt.resize(newCols, newRows);\n this.setupTabStops(newCols);\n }\n\n /**\n * Setup the tab stops.\n * @param i The index to start setting up tab stops from.\n */\n public setupTabStops(i?: number): void {\n this._normal.setupTabStops(i);\n this._alt.setupTabStops(i);\n }\n}\n","/**\n * Copyright (c) 2018 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { CharData, ICellData, IExtendedAttrs } from 'common/Types';\nimport { stringFromCodePoint } from 'common/input/TextDecoder';\nimport { CHAR_DATA_CHAR_INDEX, CHAR_DATA_WIDTH_INDEX, CHAR_DATA_ATTR_INDEX, Content } from 'common/buffer/Constants';\nimport { AttributeData, ExtendedAttrs } from 'common/buffer/AttributeData';\n\n/**\n * CellData - represents a single Cell in the terminal buffer.\n */\nexport class CellData extends AttributeData implements ICellData {\n /** Helper to create CellData from CharData. */\n public static fromCharData(value: CharData): CellData {\n const obj = new CellData();\n obj.setFromCharData(value);\n return obj;\n }\n /** Primitives from terminal buffer. */\n public content = 0;\n public fg = 0;\n public bg = 0;\n public extended: IExtendedAttrs = new ExtendedAttrs();\n public combinedData = '';\n /** Whether cell contains a combined string. */\n public isCombined(): number {\n return this.content & Content.IS_COMBINED_MASK;\n }\n /** Width of the cell. */\n public getWidth(): number {\n return this.content >> Content.WIDTH_SHIFT;\n }\n /** JS string of the content. */\n public getChars(): string {\n if (this.content & Content.IS_COMBINED_MASK) {\n return this.combinedData;\n }\n if (this.content & Content.CODEPOINT_MASK) {\n return stringFromCodePoint(this.content & Content.CODEPOINT_MASK);\n }\n return '';\n }\n /**\n * Codepoint of cell\n * Note this returns the UTF32 codepoint of single chars,\n * if content is a combined string it returns the codepoint\n * of the last char in string to be in line with code in CharData.\n */\n public getCode(): number {\n return (this.isCombined())\n ? this.combinedData.charCodeAt(this.combinedData.length - 1)\n : this.content & Content.CODEPOINT_MASK;\n }\n /** Set data from CharData */\n public setFromCharData(value: CharData): void {\n this.fg = value[CHAR_DATA_ATTR_INDEX];\n this.bg = 0;\n let combined = false;\n // surrogates and combined strings need special treatment\n if (value[CHAR_DATA_CHAR_INDEX].length > 2) {\n combined = true;\n }\n else if (value[CHAR_DATA_CHAR_INDEX].length === 2) {\n const code = value[CHAR_DATA_CHAR_INDEX].charCodeAt(0);\n // if the 2-char string is a surrogate create single codepoint\n // everything else is combined\n if (0xD800 <= code && code <= 0xDBFF) {\n const second = value[CHAR_DATA_CHAR_INDEX].charCodeAt(1);\n if (0xDC00 <= second && second <= 0xDFFF) {\n this.content = ((code - 0xD800) * 0x400 + second - 0xDC00 + 0x10000) | (value[CHAR_DATA_WIDTH_INDEX] << Content.WIDTH_SHIFT);\n }\n else {\n combined = true;\n }\n }\n else {\n combined = true;\n }\n }\n else {\n this.content = value[CHAR_DATA_CHAR_INDEX].charCodeAt(0) | (value[CHAR_DATA_WIDTH_INDEX] << Content.WIDTH_SHIFT);\n }\n if (combined) {\n this.combinedData = value[CHAR_DATA_CHAR_INDEX];\n this.content = Content.IS_COMBINED_MASK | (value[CHAR_DATA_WIDTH_INDEX] << Content.WIDTH_SHIFT);\n }\n }\n /** Get data as CharData. */\n public getAsCharData(): CharData {\n return [this.fg, this.getChars(), this.getWidth(), this.getCode()];\n }\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nexport const DEFAULT_COLOR = 0;\nexport const DEFAULT_ATTR = (0 << 18) | (DEFAULT_COLOR << 9) | (256 << 0);\nexport const DEFAULT_EXT = 0;\n\nexport const CHAR_DATA_ATTR_INDEX = 0;\nexport const CHAR_DATA_CHAR_INDEX = 1;\nexport const CHAR_DATA_WIDTH_INDEX = 2;\nexport const CHAR_DATA_CODE_INDEX = 3;\n\n/**\n * Null cell - a real empty cell (containing nothing).\n * Note that code should always be 0 for a null cell as\n * several test condition of the buffer line rely on this.\n */\nexport const NULL_CELL_CHAR = '';\nexport const NULL_CELL_WIDTH = 1;\nexport const NULL_CELL_CODE = 0;\n\n/**\n * Whitespace cell.\n * This is meant as a replacement for empty cells when needed\n * during rendering lines to preserve correct aligment.\n */\nexport const WHITESPACE_CELL_CHAR = ' ';\nexport const WHITESPACE_CELL_WIDTH = 1;\nexport const WHITESPACE_CELL_CODE = 32;\n\n/**\n * Bitmasks for accessing data in `content`.\n */\nexport const enum Content {\n /**\n * bit 1..21 codepoint, max allowed in UTF32 is 0x10FFFF (21 bits taken)\n * read: `codepoint = content & Content.codepointMask;`\n * write: `content |= codepoint & Content.codepointMask;`\n * shortcut if precondition `codepoint <= 0x10FFFF` is met:\n * `content |= codepoint;`\n */\n CODEPOINT_MASK = 0x1FFFFF,\n\n /**\n * bit 22 flag indication whether a cell contains combined content\n * read: `isCombined = content & Content.isCombined;`\n * set: `content |= Content.isCombined;`\n * clear: `content &= ~Content.isCombined;`\n */\n IS_COMBINED_MASK = 0x200000, // 1 << 21\n\n /**\n * bit 1..22 mask to check whether a cell contains any string data\n * we need to check for codepoint and isCombined bits to see\n * whether a cell contains anything\n * read: `isEmpty = !(content & Content.hasContent)`\n */\n HAS_CONTENT_MASK = 0x3FFFFF,\n\n /**\n * bit 23..24 wcwidth value of cell, takes 2 bits (ranges from 0..2)\n * read: `width = (content & Content.widthMask) >> Content.widthShift;`\n * `hasWidth = content & Content.widthMask;`\n * as long as wcwidth is highest value in `content`:\n * `width = content >> Content.widthShift;`\n * write: `content |= (width << Content.widthShift) & Content.widthMask;`\n * shortcut if precondition `0 <= width <= 3` is met:\n * `content |= width << Content.widthShift;`\n */\n WIDTH_MASK = 0xC00000, // 3 << 22\n WIDTH_SHIFT = 22\n}\n\nexport const enum Attributes {\n /**\n * bit 1..8 blue in RGB, color in P256 and P16\n */\n BLUE_MASK = 0xFF,\n BLUE_SHIFT = 0,\n PCOLOR_MASK = 0xFF,\n PCOLOR_SHIFT = 0,\n\n /**\n * bit 9..16 green in RGB\n */\n GREEN_MASK = 0xFF00,\n GREEN_SHIFT = 8,\n\n /**\n * bit 17..24 red in RGB\n */\n RED_MASK = 0xFF0000,\n RED_SHIFT = 16,\n\n /**\n * bit 25..26 color mode: DEFAULT (0) | P16 (1) | P256 (2) | RGB (3)\n */\n CM_MASK = 0x3000000,\n CM_DEFAULT = 0,\n CM_P16 = 0x1000000,\n CM_P256 = 0x2000000,\n CM_RGB = 0x3000000,\n\n /**\n * bit 1..24 RGB room\n */\n RGB_MASK = 0xFFFFFF\n}\n\nexport const enum FgFlags {\n /**\n * bit 27..32\n */\n INVERSE = 0x4000000,\n BOLD = 0x8000000,\n UNDERLINE = 0x10000000,\n BLINK = 0x20000000,\n INVISIBLE = 0x40000000,\n STRIKETHROUGH = 0x80000000,\n}\n\nexport const enum BgFlags {\n /**\n * bit 27..32 (upper 2 unused)\n */\n ITALIC = 0x4000000,\n DIM = 0x8000000,\n HAS_EXTENDED = 0x10000000,\n PROTECTED = 0x20000000,\n OVERLINE = 0x40000000\n}\n\nexport const enum ExtFlags {\n /**\n * bit 27..29\n */\n UNDERLINE_STYLE = 0x1C000000,\n\n /**\n * bit 30..32\n *\n * An optional variant for the glyph, this can be used for example to offset underlines by a\n * number of pixels to create a perfect pattern.\n */\n VARIANT_OFFSET = 0xE0000000\n}\n\nexport const enum UnderlineStyle {\n NONE = 0,\n SINGLE = 1,\n DOUBLE = 2,\n CURLY = 3,\n DOTTED = 4,\n DASHED = 5\n}\n","/**\n * Copyright (c) 2018 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IDisposable, IMarker } from 'common/Types';\nimport { Emitter } from 'vs/base/common/event';\nimport { dispose } from 'vs/base/common/lifecycle';\n\nexport class Marker implements IMarker {\n private static _nextId = 1;\n\n public isDisposed: boolean = false;\n private readonly _disposables: IDisposable[] = [];\n\n private readonly _id: number = Marker._nextId++;\n public get id(): number { return this._id; }\n\n private readonly _onDispose = this.register(new Emitter());\n public readonly onDispose = this._onDispose.event;\n\n constructor(\n public line: number\n ) {\n }\n\n public dispose(): void {\n if (this.isDisposed) {\n return;\n }\n this.isDisposed = true;\n this.line = -1;\n // Emit before super.dispose such that dispose listeners get a change to react\n this._onDispose.fire();\n dispose(this._disposables);\n this._disposables.length = 0;\n }\n\n public register(disposable: T): T {\n this._disposables.push(disposable);\n return disposable;\n }\n}\n","/**\n * Copyright (c) 2016 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { ICharset } from 'common/Types';\n\n/**\n * The character sets supported by the terminal. These enable several languages\n * to be represented within the terminal with only 8-bit encoding. See ISO 2022\n * for a discussion on character sets. Only VT100 character sets are supported.\n */\nexport const CHARSETS: { [key: string]: ICharset | undefined } = {};\n\n/**\n * The default character set, US.\n */\nexport const DEFAULT_CHARSET: ICharset | undefined = CHARSETS['B'];\n\n/**\n * DEC Special Character and Line Drawing Set.\n * Reference: http://vt100.net/docs/vt102-ug/table5-13.html\n * A lot of curses apps use this if they see TERM=xterm.\n * testing: echo -e '\\e(0a\\e(B'\n * The xterm output sometimes seems to conflict with the\n * reference above. xterm seems in line with the reference\n * when running vttest however.\n * The table below now uses xterm's output from vttest.\n */\nCHARSETS['0'] = {\n '`': '\\u25c6', // '◆'\n 'a': '\\u2592', // '▒'\n 'b': '\\u2409', // '␉' (HT)\n 'c': '\\u240c', // '␌' (FF)\n 'd': '\\u240d', // '␍' (CR)\n 'e': '\\u240a', // '␊' (LF)\n 'f': '\\u00b0', // '°'\n 'g': '\\u00b1', // '±'\n 'h': '\\u2424', // '␤' (NL)\n 'i': '\\u240b', // '␋' (VT)\n 'j': '\\u2518', // '┘'\n 'k': '\\u2510', // '┐'\n 'l': '\\u250c', // '┌'\n 'm': '\\u2514', // '└'\n 'n': '\\u253c', // '┼'\n 'o': '\\u23ba', // '⎺'\n 'p': '\\u23bb', // '⎻'\n 'q': '\\u2500', // '─'\n 'r': '\\u23bc', // '⎼'\n 's': '\\u23bd', // '⎽'\n 't': '\\u251c', // '├'\n 'u': '\\u2524', // '┤'\n 'v': '\\u2534', // '┴'\n 'w': '\\u252c', // '┬'\n 'x': '\\u2502', // '│'\n 'y': '\\u2264', // '≤'\n 'z': '\\u2265', // '≥'\n '{': '\\u03c0', // 'π'\n '|': '\\u2260', // '≠'\n '}': '\\u00a3', // '£'\n '~': '\\u00b7' // '·'\n};\n\n/**\n * British character set\n * ESC (A\n * Reference: http://vt100.net/docs/vt220-rm/table2-5.html\n */\nCHARSETS['A'] = {\n '#': '£'\n};\n\n/**\n * United States character set\n * ESC (B\n */\nCHARSETS['B'] = undefined;\n\n/**\n * Dutch character set\n * ESC (4\n * Reference: http://vt100.net/docs/vt220-rm/table2-6.html\n */\nCHARSETS['4'] = {\n '#': '£',\n '@': '¾',\n '[': 'ij',\n '\\\\': '½',\n ']': '|',\n '{': '¨',\n '|': 'f',\n '}': '¼',\n '~': '´'\n};\n\n/**\n * Finnish character set\n * ESC (C or ESC (5\n * Reference: http://vt100.net/docs/vt220-rm/table2-7.html\n */\nCHARSETS['C'] =\nCHARSETS['5'] = {\n '[': 'Ä',\n '\\\\': 'Ö',\n ']': 'Å',\n '^': 'Ü',\n '`': 'é',\n '{': 'ä',\n '|': 'ö',\n '}': 'å',\n '~': 'ü'\n};\n\n/**\n * French character set\n * ESC (R\n * Reference: http://vt100.net/docs/vt220-rm/table2-8.html\n */\nCHARSETS['R'] = {\n '#': '£',\n '@': 'à',\n '[': '°',\n '\\\\': 'ç',\n ']': '§',\n '{': 'é',\n '|': 'ù',\n '}': 'è',\n '~': '¨'\n};\n\n/**\n * French Canadian character set\n * ESC (Q\n * Reference: http://vt100.net/docs/vt220-rm/table2-9.html\n */\nCHARSETS['Q'] = {\n '@': 'à',\n '[': 'â',\n '\\\\': 'ç',\n ']': 'ê',\n '^': 'î',\n '`': 'ô',\n '{': 'é',\n '|': 'ù',\n '}': 'è',\n '~': 'û'\n};\n\n/**\n * German character set\n * ESC (K\n * Reference: http://vt100.net/docs/vt220-rm/table2-10.html\n */\nCHARSETS['K'] = {\n '@': '§',\n '[': 'Ä',\n '\\\\': 'Ö',\n ']': 'Ü',\n '{': 'ä',\n '|': 'ö',\n '}': 'ü',\n '~': 'ß'\n};\n\n/**\n * Italian character set\n * ESC (Y\n * Reference: http://vt100.net/docs/vt220-rm/table2-11.html\n */\nCHARSETS['Y'] = {\n '#': '£',\n '@': '§',\n '[': '°',\n '\\\\': 'ç',\n ']': 'é',\n '`': 'ù',\n '{': 'à',\n '|': 'ò',\n '}': 'è',\n '~': 'ì'\n};\n\n/**\n * Norwegian/Danish character set\n * ESC (E or ESC (6\n * Reference: http://vt100.net/docs/vt220-rm/table2-12.html\n */\nCHARSETS['E'] =\nCHARSETS['6'] = {\n '@': 'Ä',\n '[': 'Æ',\n '\\\\': 'Ø',\n ']': 'Å',\n '^': 'Ü',\n '`': 'ä',\n '{': 'æ',\n '|': 'ø',\n '}': 'å',\n '~': 'ü'\n};\n\n/**\n * Spanish character set\n * ESC (Z\n * Reference: http://vt100.net/docs/vt220-rm/table2-13.html\n */\nCHARSETS['Z'] = {\n '#': '£',\n '@': '§',\n '[': '¡',\n '\\\\': 'Ñ',\n ']': '¿',\n '{': '°',\n '|': 'ñ',\n '}': 'ç'\n};\n\n/**\n * Swedish character set\n * ESC (H or ESC (7\n * Reference: http://vt100.net/docs/vt220-rm/table2-14.html\n */\nCHARSETS['H'] =\nCHARSETS['7'] = {\n '@': 'É',\n '[': 'Ä',\n '\\\\': 'Ö',\n ']': 'Å',\n '^': 'Ü',\n '`': 'é',\n '{': 'ä',\n '|': 'ö',\n '}': 'å',\n '~': 'ü'\n};\n\n/**\n * Swiss character set\n * ESC (=\n * Reference: http://vt100.net/docs/vt220-rm/table2-15.html\n */\nCHARSETS['='] = {\n '#': 'ù',\n '@': 'à',\n '[': 'é',\n '\\\\': 'ç',\n ']': 'ê',\n '^': 'î',\n // eslint-disable-next-line @typescript-eslint/naming-convention\n '_': 'è',\n '`': 'ô',\n '{': 'ä',\n '|': 'ö',\n '}': 'ü',\n '~': 'û'\n};\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\n/**\n * C0 control codes\n * See = https://en.wikipedia.org/wiki/C0_and_C1_control_codes\n */\nexport namespace C0 {\n /** Null (Caret = ^@, C = \\0) */\n export const NUL = '\\x00';\n /** Start of Heading (Caret = ^A) */\n export const SOH = '\\x01';\n /** Start of Text (Caret = ^B) */\n export const STX = '\\x02';\n /** End of Text (Caret = ^C) */\n export const ETX = '\\x03';\n /** End of Transmission (Caret = ^D) */\n export const EOT = '\\x04';\n /** Enquiry (Caret = ^E) */\n export const ENQ = '\\x05';\n /** Acknowledge (Caret = ^F) */\n export const ACK = '\\x06';\n /** Bell (Caret = ^G, C = \\a) */\n export const BEL = '\\x07';\n /** Backspace (Caret = ^H, C = \\b) */\n export const BS = '\\x08';\n /** Character Tabulation, Horizontal Tabulation (Caret = ^I, C = \\t) */\n export const HT = '\\x09';\n /** Line Feed (Caret = ^J, C = \\n) */\n export const LF = '\\x0a';\n /** Line Tabulation, Vertical Tabulation (Caret = ^K, C = \\v) */\n export const VT = '\\x0b';\n /** Form Feed (Caret = ^L, C = \\f) */\n export const FF = '\\x0c';\n /** Carriage Return (Caret = ^M, C = \\r) */\n export const CR = '\\x0d';\n /** Shift Out (Caret = ^N) */\n export const SO = '\\x0e';\n /** Shift In (Caret = ^O) */\n export const SI = '\\x0f';\n /** Data Link Escape (Caret = ^P) */\n export const DLE = '\\x10';\n /** Device Control One (XON) (Caret = ^Q) */\n export const DC1 = '\\x11';\n /** Device Control Two (Caret = ^R) */\n export const DC2 = '\\x12';\n /** Device Control Three (XOFF) (Caret = ^S) */\n export const DC3 = '\\x13';\n /** Device Control Four (Caret = ^T) */\n export const DC4 = '\\x14';\n /** Negative Acknowledge (Caret = ^U) */\n export const NAK = '\\x15';\n /** Synchronous Idle (Caret = ^V) */\n export const SYN = '\\x16';\n /** End of Transmission Block (Caret = ^W) */\n export const ETB = '\\x17';\n /** Cancel (Caret = ^X) */\n export const CAN = '\\x18';\n /** End of Medium (Caret = ^Y) */\n export const EM = '\\x19';\n /** Substitute (Caret = ^Z) */\n export const SUB = '\\x1a';\n /** Escape (Caret = ^[, C = \\e) */\n export const ESC = '\\x1b';\n /** File Separator (Caret = ^\\) */\n export const FS = '\\x1c';\n /** Group Separator (Caret = ^]) */\n export const GS = '\\x1d';\n /** Record Separator (Caret = ^^) */\n export const RS = '\\x1e';\n /** Unit Separator (Caret = ^_) */\n export const US = '\\x1f';\n /** Space */\n export const SP = '\\x20';\n /** Delete (Caret = ^?) */\n export const DEL = '\\x7f';\n}\n\n/**\n * C1 control codes\n * See = https://en.wikipedia.org/wiki/C0_and_C1_control_codes\n */\nexport namespace C1 {\n /** padding character */\n export const PAD = '\\x80';\n /** High Octet Preset */\n export const HOP = '\\x81';\n /** Break Permitted Here */\n export const BPH = '\\x82';\n /** No Break Here */\n export const NBH = '\\x83';\n /** Index */\n export const IND = '\\x84';\n /** Next Line */\n export const NEL = '\\x85';\n /** Start of Selected Area */\n export const SSA = '\\x86';\n /** End of Selected Area */\n export const ESA = '\\x87';\n /** Horizontal Tabulation Set */\n export const HTS = '\\x88';\n /** Horizontal Tabulation With Justification */\n export const HTJ = '\\x89';\n /** Vertical Tabulation Set */\n export const VTS = '\\x8a';\n /** Partial Line Down */\n export const PLD = '\\x8b';\n /** Partial Line Up */\n export const PLU = '\\x8c';\n /** Reverse Index */\n export const RI = '\\x8d';\n /** Single-Shift 2 */\n export const SS2 = '\\x8e';\n /** Single-Shift 3 */\n export const SS3 = '\\x8f';\n /** Device Control String */\n export const DCS = '\\x90';\n /** Private Use 1 */\n export const PU1 = '\\x91';\n /** Private Use 2 */\n export const PU2 = '\\x92';\n /** Set Transmit State */\n export const STS = '\\x93';\n /** Destructive backspace, intended to eliminate ambiguity about meaning of BS. */\n export const CCH = '\\x94';\n /** Message Waiting */\n export const MW = '\\x95';\n /** Start of Protected Area */\n export const SPA = '\\x96';\n /** End of Protected Area */\n export const EPA = '\\x97';\n /** Start of String */\n export const SOS = '\\x98';\n /** Single Graphic Character Introducer */\n export const SGCI = '\\x99';\n /** Single Character Introducer */\n export const SCI = '\\x9a';\n /** Control Sequence Introducer */\n export const CSI = '\\x9b';\n /** String Terminator */\n export const ST = '\\x9c';\n /** Operating System Command */\n export const OSC = '\\x9d';\n /** Privacy Message */\n export const PM = '\\x9e';\n /** Application Program Command */\n export const APC = '\\x9f';\n}\nexport namespace C1_ESCAPED {\n export const ST = `${C0.ESC}\\\\`;\n}\n","/**\n * Copyright (c) 2014 The xterm.js authors. All rights reserved.\n * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)\n * @license MIT\n */\n\nimport { IKeyboardEvent, IKeyboardResult, KeyboardResultType } from 'common/Types';\nimport { C0 } from 'common/data/EscapeSequences';\n\n// reg + shift key mappings for digits and special chars\nconst KEYCODE_KEY_MAPPINGS: { [key: number]: [string, string]} = {\n // digits 0-9\n 48: ['0', ')'],\n 49: ['1', '!'],\n 50: ['2', '@'],\n 51: ['3', '#'],\n 52: ['4', '$'],\n 53: ['5', '%'],\n 54: ['6', '^'],\n 55: ['7', '&'],\n 56: ['8', '*'],\n 57: ['9', '('],\n\n // special chars\n 186: [';', ':'],\n 187: ['=', '+'],\n 188: [',', '<'],\n 189: ['-', '_'],\n 190: ['.', '>'],\n 191: ['/', '?'],\n 192: ['`', '~'],\n 219: ['[', '{'],\n 220: ['\\\\', '|'],\n 221: [']', '}'],\n 222: ['\\'', '\"']\n};\n\nexport function evaluateKeyboardEvent(\n ev: IKeyboardEvent,\n applicationCursorMode: boolean,\n isMac: boolean,\n macOptionIsMeta: boolean\n): IKeyboardResult {\n const result: IKeyboardResult = {\n type: KeyboardResultType.SEND_KEY,\n // Whether to cancel event propagation (NOTE: this may not be needed since the event is\n // canceled at the end of keyDown\n cancel: false,\n // The new key even to emit\n key: undefined\n };\n const modifiers = (ev.shiftKey ? 1 : 0) | (ev.altKey ? 2 : 0) | (ev.ctrlKey ? 4 : 0) | (ev.metaKey ? 8 : 0);\n switch (ev.keyCode) {\n case 0:\n if (ev.key === 'UIKeyInputUpArrow') {\n if (applicationCursorMode) {\n result.key = C0.ESC + 'OA';\n } else {\n result.key = C0.ESC + '[A';\n }\n }\n else if (ev.key === 'UIKeyInputLeftArrow') {\n if (applicationCursorMode) {\n result.key = C0.ESC + 'OD';\n } else {\n result.key = C0.ESC + '[D';\n }\n }\n else if (ev.key === 'UIKeyInputRightArrow') {\n if (applicationCursorMode) {\n result.key = C0.ESC + 'OC';\n } else {\n result.key = C0.ESC + '[C';\n }\n }\n else if (ev.key === 'UIKeyInputDownArrow') {\n if (applicationCursorMode) {\n result.key = C0.ESC + 'OB';\n } else {\n result.key = C0.ESC + '[B';\n }\n }\n break;\n case 8:\n // backspace\n result.key = ev.ctrlKey ? '\\b' : C0.DEL; // ^H or ^?\n if (ev.altKey) {\n result.key = C0.ESC + result.key;\n }\n break;\n case 9:\n // tab\n if (ev.shiftKey) {\n result.key = C0.ESC + '[Z';\n break;\n }\n result.key = C0.HT;\n result.cancel = true;\n break;\n case 13:\n // return/enter\n result.key = ev.altKey ? C0.ESC + C0.CR : C0.CR;\n result.cancel = true;\n break;\n case 27:\n // escape\n result.key = C0.ESC;\n if (ev.altKey) {\n result.key = C0.ESC + C0.ESC;\n }\n result.cancel = true;\n break;\n case 37:\n // left-arrow\n if (ev.metaKey) {\n break;\n }\n if (modifiers) {\n result.key = C0.ESC + '[1;' + (modifiers + 1) + 'D';\n } else if (applicationCursorMode) {\n result.key = C0.ESC + 'OD';\n } else {\n result.key = C0.ESC + '[D';\n }\n break;\n case 39:\n // right-arrow\n if (ev.metaKey) {\n break;\n }\n if (modifiers) {\n result.key = C0.ESC + '[1;' + (modifiers + 1) + 'C';\n } else if (applicationCursorMode) {\n result.key = C0.ESC + 'OC';\n } else {\n result.key = C0.ESC + '[C';\n }\n break;\n case 38:\n // up-arrow\n if (ev.metaKey) {\n break;\n }\n if (modifiers) {\n result.key = C0.ESC + '[1;' + (modifiers + 1) + 'A';\n } else if (applicationCursorMode) {\n result.key = C0.ESC + 'OA';\n } else {\n result.key = C0.ESC + '[A';\n }\n break;\n case 40:\n // down-arrow\n if (ev.metaKey) {\n break;\n }\n if (modifiers) {\n result.key = C0.ESC + '[1;' + (modifiers + 1) + 'B';\n } else if (applicationCursorMode) {\n result.key = C0.ESC + 'OB';\n } else {\n result.key = C0.ESC + '[B';\n }\n break;\n case 45:\n // insert\n if (!ev.shiftKey && !ev.ctrlKey) {\n // or + are used to\n // copy-paste on some systems.\n result.key = C0.ESC + '[2~';\n }\n break;\n case 46:\n // delete\n if (modifiers) {\n result.key = C0.ESC + '[3;' + (modifiers + 1) + '~';\n } else {\n result.key = C0.ESC + '[3~';\n }\n break;\n case 36:\n // home\n if (modifiers) {\n result.key = C0.ESC + '[1;' + (modifiers + 1) + 'H';\n } else if (applicationCursorMode) {\n result.key = C0.ESC + 'OH';\n } else {\n result.key = C0.ESC + '[H';\n }\n break;\n case 35:\n // end\n if (modifiers) {\n result.key = C0.ESC + '[1;' + (modifiers + 1) + 'F';\n } else if (applicationCursorMode) {\n result.key = C0.ESC + 'OF';\n } else {\n result.key = C0.ESC + '[F';\n }\n break;\n case 33:\n // page up\n if (ev.shiftKey) {\n result.type = KeyboardResultType.PAGE_UP;\n } else if (ev.ctrlKey) {\n result.key = C0.ESC + '[5;' + (modifiers + 1) + '~';\n } else {\n result.key = C0.ESC + '[5~';\n }\n break;\n case 34:\n // page down\n if (ev.shiftKey) {\n result.type = KeyboardResultType.PAGE_DOWN;\n } else if (ev.ctrlKey) {\n result.key = C0.ESC + '[6;' + (modifiers + 1) + '~';\n } else {\n result.key = C0.ESC + '[6~';\n }\n break;\n case 112:\n // F1-F12\n if (modifiers) {\n result.key = C0.ESC + '[1;' + (modifiers + 1) + 'P';\n } else {\n result.key = C0.ESC + 'OP';\n }\n break;\n case 113:\n if (modifiers) {\n result.key = C0.ESC + '[1;' + (modifiers + 1) + 'Q';\n } else {\n result.key = C0.ESC + 'OQ';\n }\n break;\n case 114:\n if (modifiers) {\n result.key = C0.ESC + '[1;' + (modifiers + 1) + 'R';\n } else {\n result.key = C0.ESC + 'OR';\n }\n break;\n case 115:\n if (modifiers) {\n result.key = C0.ESC + '[1;' + (modifiers + 1) + 'S';\n } else {\n result.key = C0.ESC + 'OS';\n }\n break;\n case 116:\n if (modifiers) {\n result.key = C0.ESC + '[15;' + (modifiers + 1) + '~';\n } else {\n result.key = C0.ESC + '[15~';\n }\n break;\n case 117:\n if (modifiers) {\n result.key = C0.ESC + '[17;' + (modifiers + 1) + '~';\n } else {\n result.key = C0.ESC + '[17~';\n }\n break;\n case 118:\n if (modifiers) {\n result.key = C0.ESC + '[18;' + (modifiers + 1) + '~';\n } else {\n result.key = C0.ESC + '[18~';\n }\n break;\n case 119:\n if (modifiers) {\n result.key = C0.ESC + '[19;' + (modifiers + 1) + '~';\n } else {\n result.key = C0.ESC + '[19~';\n }\n break;\n case 120:\n if (modifiers) {\n result.key = C0.ESC + '[20;' + (modifiers + 1) + '~';\n } else {\n result.key = C0.ESC + '[20~';\n }\n break;\n case 121:\n if (modifiers) {\n result.key = C0.ESC + '[21;' + (modifiers + 1) + '~';\n } else {\n result.key = C0.ESC + '[21~';\n }\n break;\n case 122:\n if (modifiers) {\n result.key = C0.ESC + '[23;' + (modifiers + 1) + '~';\n } else {\n result.key = C0.ESC + '[23~';\n }\n break;\n case 123:\n if (modifiers) {\n result.key = C0.ESC + '[24;' + (modifiers + 1) + '~';\n } else {\n result.key = C0.ESC + '[24~';\n }\n break;\n default:\n // a-z and space\n if (ev.ctrlKey && !ev.shiftKey && !ev.altKey && !ev.metaKey) {\n if (ev.keyCode >= 65 && ev.keyCode <= 90) {\n result.key = String.fromCharCode(ev.keyCode - 64);\n } else if (ev.keyCode === 32) {\n result.key = C0.NUL;\n } else if (ev.keyCode >= 51 && ev.keyCode <= 55) {\n // escape, file sep, group sep, record sep, unit sep\n result.key = String.fromCharCode(ev.keyCode - 51 + 27);\n } else if (ev.keyCode === 56) {\n result.key = C0.DEL;\n } else if (ev.keyCode === 219) {\n result.key = C0.ESC;\n } else if (ev.keyCode === 220) {\n result.key = C0.FS;\n } else if (ev.keyCode === 221) {\n result.key = C0.GS;\n }\n } else if ((!isMac || macOptionIsMeta) && ev.altKey && !ev.metaKey) {\n // On macOS this is a third level shift when !macOptionIsMeta. Use instead.\n const keyMapping = KEYCODE_KEY_MAPPINGS[ev.keyCode];\n const key = keyMapping?.[!ev.shiftKey ? 0 : 1];\n if (key) {\n result.key = C0.ESC + key;\n } else if (ev.keyCode >= 65 && ev.keyCode <= 90) {\n const keyCode = ev.ctrlKey ? ev.keyCode - 64 : ev.keyCode + 32;\n let keyString = String.fromCharCode(keyCode);\n if (ev.shiftKey) {\n keyString = keyString.toUpperCase();\n }\n result.key = C0.ESC + keyString;\n } else if (ev.keyCode === 32) {\n result.key = C0.ESC + (ev.ctrlKey ? C0.NUL : ' ');\n } else if (ev.key === 'Dead' && ev.code.startsWith('Key')) {\n // Reference: https://github.com/xtermjs/xterm.js/issues/3725\n // Alt will produce a \"dead key\" (initate composition) with some\n // of the letters in US layout (e.g. N/E/U).\n // It's safe to match against Key* since no other `code` values begin with \"Key\".\n // https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code/code_values#code_values_on_mac\n let keyString = ev.code.slice(3, 4);\n if (!ev.shiftKey) {\n keyString = keyString.toLowerCase();\n }\n result.key = C0.ESC + keyString;\n result.cancel = true;\n }\n } else if (isMac && !ev.altKey && !ev.ctrlKey && !ev.shiftKey && ev.metaKey) {\n if (ev.keyCode === 65) { // cmd + a\n result.type = KeyboardResultType.SELECT_ALL;\n }\n } else if (ev.key && !ev.ctrlKey && !ev.altKey && !ev.metaKey && ev.keyCode >= 48 && ev.key.length === 1) {\n // Include only keys that that result in a _single_ character; don't include num lock,\n // volume up, etc.\n result.key = ev.key;\n } else if (ev.key && ev.ctrlKey) {\n if (ev.key === '_') { // ^_\n result.key = C0.US;\n }\n if (ev.key === '@') { // ^ + shift + 2 = ^ + @\n result.key = C0.NUL;\n }\n }\n break;\n }\n\n return result;\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\n/**\n * Polyfill - Convert UTF32 codepoint into JS string.\n * Note: The built-in String.fromCodePoint happens to be much slower\n * due to additional sanity checks. We can avoid them since\n * we always operate on legal UTF32 (granted by the input decoders)\n * and use this faster version instead.\n */\nexport function stringFromCodePoint(codePoint: number): string {\n if (codePoint > 0xFFFF) {\n codePoint -= 0x10000;\n return String.fromCharCode((codePoint >> 10) + 0xD800) + String.fromCharCode((codePoint % 0x400) + 0xDC00);\n }\n return String.fromCharCode(codePoint);\n}\n\n/**\n * Convert UTF32 char codes into JS string.\n * Basically the same as `stringFromCodePoint` but for multiple codepoints\n * in a loop (which is a lot faster).\n */\nexport function utf32ToString(data: Uint32Array, start: number = 0, end: number = data.length): string {\n let result = '';\n for (let i = start; i < end; ++i) {\n let codepoint = data[i];\n if (codepoint > 0xFFFF) {\n // JS strings are encoded as UTF16, thus a non BMP codepoint gets converted into a surrogate\n // pair conversion rules:\n // - subtract 0x10000 from code point, leaving a 20 bit number\n // - add high 10 bits to 0xD800 --> first surrogate\n // - add low 10 bits to 0xDC00 --> second surrogate\n codepoint -= 0x10000;\n result += String.fromCharCode((codepoint >> 10) + 0xD800) + String.fromCharCode((codepoint % 0x400) + 0xDC00);\n } else {\n result += String.fromCharCode(codepoint);\n }\n }\n return result;\n}\n\n/**\n * StringToUtf32 - decodes UTF16 sequences into UTF32 codepoints.\n * To keep the decoder in line with JS strings it handles single surrogates as UCS2.\n */\nexport class StringToUtf32 {\n private _interim: number = 0;\n\n /**\n * Clears interim and resets decoder to clean state.\n */\n public clear(): void {\n this._interim = 0;\n }\n\n /**\n * Decode JS string to UTF32 codepoints.\n * The methods assumes stream input and will store partly transmitted\n * surrogate pairs and decode them with the next data chunk.\n * Note: The method does no bound checks for target, therefore make sure\n * the provided input data does not exceed the size of `target`.\n * Returns the number of written codepoints in `target`.\n */\n public decode(input: string, target: Uint32Array): number {\n const length = input.length;\n\n if (!length) {\n return 0;\n }\n\n let size = 0;\n let startPos = 0;\n\n // handle leftover surrogate high\n if (this._interim) {\n const second = input.charCodeAt(startPos++);\n if (0xDC00 <= second && second <= 0xDFFF) {\n target[size++] = (this._interim - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;\n } else {\n // illegal codepoint (USC2 handling)\n target[size++] = this._interim;\n target[size++] = second;\n }\n this._interim = 0;\n }\n\n for (let i = startPos; i < length; ++i) {\n const code = input.charCodeAt(i);\n // surrogate pair first\n if (0xD800 <= code && code <= 0xDBFF) {\n if (++i >= length) {\n this._interim = code;\n return size;\n }\n const second = input.charCodeAt(i);\n if (0xDC00 <= second && second <= 0xDFFF) {\n target[size++] = (code - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;\n } else {\n // illegal codepoint (USC2 handling)\n target[size++] = code;\n target[size++] = second;\n }\n continue;\n }\n if (code === 0xFEFF) {\n // BOM\n continue;\n }\n target[size++] = code;\n }\n return size;\n }\n}\n\n/**\n * Utf8Decoder - decodes UTF8 byte sequences into UTF32 codepoints.\n */\nexport class Utf8ToUtf32 {\n public interim: Uint8Array = new Uint8Array(3);\n\n /**\n * Clears interim bytes and resets decoder to clean state.\n */\n public clear(): void {\n this.interim.fill(0);\n }\n\n /**\n * Decodes UTF8 byte sequences in `input` to UTF32 codepoints in `target`.\n * The methods assumes stream input and will store partly transmitted bytes\n * and decode them with the next data chunk.\n * Note: The method does no bound checks for target, therefore make sure\n * the provided data chunk does not exceed the size of `target`.\n * Returns the number of written codepoints in `target`.\n */\n public decode(input: Uint8Array, target: Uint32Array): number {\n const length = input.length;\n\n if (!length) {\n return 0;\n }\n\n let size = 0;\n let byte1: number;\n let byte2: number;\n let byte3: number;\n let byte4: number;\n let codepoint = 0;\n let startPos = 0;\n\n // handle leftover bytes\n if (this.interim[0]) {\n let discardInterim = false;\n let cp = this.interim[0];\n cp &= ((((cp & 0xE0) === 0xC0)) ? 0x1F : (((cp & 0xF0) === 0xE0)) ? 0x0F : 0x07);\n let pos = 0;\n let tmp: number;\n while ((tmp = this.interim[++pos] & 0x3F) && pos < 4) {\n cp <<= 6;\n cp |= tmp;\n }\n // missing bytes - read ahead from input\n const type = (((this.interim[0] & 0xE0) === 0xC0)) ? 2 : (((this.interim[0] & 0xF0) === 0xE0)) ? 3 : 4;\n const missing = type - pos;\n while (startPos < missing) {\n if (startPos >= length) {\n return 0;\n }\n tmp = input[startPos++];\n if ((tmp & 0xC0) !== 0x80) {\n // wrong continuation, discard interim bytes completely\n startPos--;\n discardInterim = true;\n break;\n } else {\n // need to save so we can continue short inputs in next call\n this.interim[pos++] = tmp;\n cp <<= 6;\n cp |= tmp & 0x3F;\n }\n }\n if (!discardInterim) {\n // final test is type dependent\n if (type === 2) {\n if (cp < 0x80) {\n // wrong starter byte\n startPos--;\n } else {\n target[size++] = cp;\n }\n } else if (type === 3) {\n if (cp < 0x0800 || (cp >= 0xD800 && cp <= 0xDFFF) || cp === 0xFEFF) {\n // illegal codepoint or BOM\n } else {\n target[size++] = cp;\n }\n } else {\n if (cp < 0x010000 || cp > 0x10FFFF) {\n // illegal codepoint\n } else {\n target[size++] = cp;\n }\n }\n }\n this.interim.fill(0);\n }\n\n // loop through input\n const fourStop = length - 4;\n let i = startPos;\n while (i < length) {\n /**\n * ASCII shortcut with loop unrolled to 4 consecutive ASCII chars.\n * This is a compromise between speed gain for ASCII\n * and penalty for non ASCII:\n * For best ASCII performance the char should be stored directly into target,\n * but even a single attempt to write to target and compare afterwards\n * penalizes non ASCII really bad (-50%), thus we load the char into byteX first,\n * which reduces ASCII performance by ~15%.\n * This trial for ASCII reduces non ASCII performance by ~10% which seems acceptible\n * compared to the gains.\n * Note that this optimization only takes place for 4 consecutive ASCII chars,\n * for any shorter it bails out. Worst case - all 4 bytes being read but\n * thrown away due to the last being a non ASCII char (-10% performance).\n */\n while (i < fourStop\n && !((byte1 = input[i]) & 0x80)\n && !((byte2 = input[i + 1]) & 0x80)\n && !((byte3 = input[i + 2]) & 0x80)\n && !((byte4 = input[i + 3]) & 0x80))\n {\n target[size++] = byte1;\n target[size++] = byte2;\n target[size++] = byte3;\n target[size++] = byte4;\n i += 4;\n }\n\n // reread byte1\n byte1 = input[i++];\n\n // 1 byte\n if (byte1 < 0x80) {\n target[size++] = byte1;\n\n // 2 bytes\n } else if ((byte1 & 0xE0) === 0xC0) {\n if (i >= length) {\n this.interim[0] = byte1;\n return size;\n }\n byte2 = input[i++];\n if ((byte2 & 0xC0) !== 0x80) {\n // wrong continuation\n i--;\n continue;\n }\n codepoint = (byte1 & 0x1F) << 6 | (byte2 & 0x3F);\n if (codepoint < 0x80) {\n // wrong starter byte\n i--;\n continue;\n }\n target[size++] = codepoint;\n\n // 3 bytes\n } else if ((byte1 & 0xF0) === 0xE0) {\n if (i >= length) {\n this.interim[0] = byte1;\n return size;\n }\n byte2 = input[i++];\n if ((byte2 & 0xC0) !== 0x80) {\n // wrong continuation\n i--;\n continue;\n }\n if (i >= length) {\n this.interim[0] = byte1;\n this.interim[1] = byte2;\n return size;\n }\n byte3 = input[i++];\n if ((byte3 & 0xC0) !== 0x80) {\n // wrong continuation\n i--;\n continue;\n }\n codepoint = (byte1 & 0x0F) << 12 | (byte2 & 0x3F) << 6 | (byte3 & 0x3F);\n if (codepoint < 0x0800 || (codepoint >= 0xD800 && codepoint <= 0xDFFF) || codepoint === 0xFEFF) {\n // illegal codepoint or BOM, no i-- here\n continue;\n }\n target[size++] = codepoint;\n\n // 4 bytes\n } else if ((byte1 & 0xF8) === 0xF0) {\n if (i >= length) {\n this.interim[0] = byte1;\n return size;\n }\n byte2 = input[i++];\n if ((byte2 & 0xC0) !== 0x80) {\n // wrong continuation\n i--;\n continue;\n }\n if (i >= length) {\n this.interim[0] = byte1;\n this.interim[1] = byte2;\n return size;\n }\n byte3 = input[i++];\n if ((byte3 & 0xC0) !== 0x80) {\n // wrong continuation\n i--;\n continue;\n }\n if (i >= length) {\n this.interim[0] = byte1;\n this.interim[1] = byte2;\n this.interim[2] = byte3;\n return size;\n }\n byte4 = input[i++];\n if ((byte4 & 0xC0) !== 0x80) {\n // wrong continuation\n i--;\n continue;\n }\n codepoint = (byte1 & 0x07) << 18 | (byte2 & 0x3F) << 12 | (byte3 & 0x3F) << 6 | (byte4 & 0x3F);\n if (codepoint < 0x010000 || codepoint > 0x10FFFF) {\n // illegal codepoint, no i-- here\n continue;\n }\n target[size++] = codepoint;\n } else {\n // illegal byte, just skip\n }\n }\n return size;\n }\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\nimport { IUnicodeVersionProvider, UnicodeCharProperties, UnicodeCharWidth } from 'common/services/Services';\nimport { UnicodeService } from 'common/services/UnicodeService';\n\nconst BMP_COMBINING = [\n [0x0300, 0x036F], [0x0483, 0x0486], [0x0488, 0x0489],\n [0x0591, 0x05BD], [0x05BF, 0x05BF], [0x05C1, 0x05C2],\n [0x05C4, 0x05C5], [0x05C7, 0x05C7], [0x0600, 0x0603],\n [0x0610, 0x0615], [0x064B, 0x065E], [0x0670, 0x0670],\n [0x06D6, 0x06E4], [0x06E7, 0x06E8], [0x06EA, 0x06ED],\n [0x070F, 0x070F], [0x0711, 0x0711], [0x0730, 0x074A],\n [0x07A6, 0x07B0], [0x07EB, 0x07F3], [0x0901, 0x0902],\n [0x093C, 0x093C], [0x0941, 0x0948], [0x094D, 0x094D],\n [0x0951, 0x0954], [0x0962, 0x0963], [0x0981, 0x0981],\n [0x09BC, 0x09BC], [0x09C1, 0x09C4], [0x09CD, 0x09CD],\n [0x09E2, 0x09E3], [0x0A01, 0x0A02], [0x0A3C, 0x0A3C],\n [0x0A41, 0x0A42], [0x0A47, 0x0A48], [0x0A4B, 0x0A4D],\n [0x0A70, 0x0A71], [0x0A81, 0x0A82], [0x0ABC, 0x0ABC],\n [0x0AC1, 0x0AC5], [0x0AC7, 0x0AC8], [0x0ACD, 0x0ACD],\n [0x0AE2, 0x0AE3], [0x0B01, 0x0B01], [0x0B3C, 0x0B3C],\n [0x0B3F, 0x0B3F], [0x0B41, 0x0B43], [0x0B4D, 0x0B4D],\n [0x0B56, 0x0B56], [0x0B82, 0x0B82], [0x0BC0, 0x0BC0],\n [0x0BCD, 0x0BCD], [0x0C3E, 0x0C40], [0x0C46, 0x0C48],\n [0x0C4A, 0x0C4D], [0x0C55, 0x0C56], [0x0CBC, 0x0CBC],\n [0x0CBF, 0x0CBF], [0x0CC6, 0x0CC6], [0x0CCC, 0x0CCD],\n [0x0CE2, 0x0CE3], [0x0D41, 0x0D43], [0x0D4D, 0x0D4D],\n [0x0DCA, 0x0DCA], [0x0DD2, 0x0DD4], [0x0DD6, 0x0DD6],\n [0x0E31, 0x0E31], [0x0E34, 0x0E3A], [0x0E47, 0x0E4E],\n [0x0EB1, 0x0EB1], [0x0EB4, 0x0EB9], [0x0EBB, 0x0EBC],\n [0x0EC8, 0x0ECD], [0x0F18, 0x0F19], [0x0F35, 0x0F35],\n [0x0F37, 0x0F37], [0x0F39, 0x0F39], [0x0F71, 0x0F7E],\n [0x0F80, 0x0F84], [0x0F86, 0x0F87], [0x0F90, 0x0F97],\n [0x0F99, 0x0FBC], [0x0FC6, 0x0FC6], [0x102D, 0x1030],\n [0x1032, 0x1032], [0x1036, 0x1037], [0x1039, 0x1039],\n [0x1058, 0x1059], [0x1160, 0x11FF], [0x135F, 0x135F],\n [0x1712, 0x1714], [0x1732, 0x1734], [0x1752, 0x1753],\n [0x1772, 0x1773], [0x17B4, 0x17B5], [0x17B7, 0x17BD],\n [0x17C6, 0x17C6], [0x17C9, 0x17D3], [0x17DD, 0x17DD],\n [0x180B, 0x180D], [0x18A9, 0x18A9], [0x1920, 0x1922],\n [0x1927, 0x1928], [0x1932, 0x1932], [0x1939, 0x193B],\n [0x1A17, 0x1A18], [0x1B00, 0x1B03], [0x1B34, 0x1B34],\n [0x1B36, 0x1B3A], [0x1B3C, 0x1B3C], [0x1B42, 0x1B42],\n [0x1B6B, 0x1B73], [0x1DC0, 0x1DCA], [0x1DFE, 0x1DFF],\n [0x200B, 0x200F], [0x202A, 0x202E], [0x2060, 0x2063],\n [0x206A, 0x206F], [0x20D0, 0x20EF], [0x302A, 0x302F],\n [0x3099, 0x309A], [0xA806, 0xA806], [0xA80B, 0xA80B],\n [0xA825, 0xA826], [0xFB1E, 0xFB1E], [0xFE00, 0xFE0F],\n [0xFE20, 0xFE23], [0xFEFF, 0xFEFF], [0xFFF9, 0xFFFB]\n];\nconst HIGH_COMBINING = [\n [0x10A01, 0x10A03], [0x10A05, 0x10A06], [0x10A0C, 0x10A0F],\n [0x10A38, 0x10A3A], [0x10A3F, 0x10A3F], [0x1D167, 0x1D169],\n [0x1D173, 0x1D182], [0x1D185, 0x1D18B], [0x1D1AA, 0x1D1AD],\n [0x1D242, 0x1D244], [0xE0001, 0xE0001], [0xE0020, 0xE007F],\n [0xE0100, 0xE01EF]\n];\n\n// BMP lookup table, lazy initialized during first addon loading\nlet table: Uint8Array;\n\nfunction bisearch(ucs: number, data: number[][]): boolean {\n let min = 0;\n let max = data.length - 1;\n let mid;\n if (ucs < data[0][0] || ucs > data[max][1]) {\n return false;\n }\n while (max >= min) {\n mid = (min + max) >> 1;\n if (ucs > data[mid][1]) {\n min = mid + 1;\n } else if (ucs < data[mid][0]) {\n max = mid - 1;\n } else {\n return true;\n }\n }\n return false;\n}\n\nexport class UnicodeV6 implements IUnicodeVersionProvider {\n public readonly version = '6';\n\n constructor() {\n // init lookup table once\n if (!table) {\n table = new Uint8Array(65536);\n table.fill(1);\n table[0] = 0;\n // control chars\n table.fill(0, 1, 32);\n table.fill(0, 0x7f, 0xa0);\n\n // apply wide char rules first\n // wide chars\n table.fill(2, 0x1100, 0x1160);\n table[0x2329] = 2;\n table[0x232a] = 2;\n table.fill(2, 0x2e80, 0xa4d0);\n table[0x303f] = 1; // wrongly in last line\n\n table.fill(2, 0xac00, 0xd7a4);\n table.fill(2, 0xf900, 0xfb00);\n table.fill(2, 0xfe10, 0xfe1a);\n table.fill(2, 0xfe30, 0xfe70);\n table.fill(2, 0xff00, 0xff61);\n table.fill(2, 0xffe0, 0xffe7);\n\n // apply combining last to ensure we overwrite\n // wrongly wide set chars:\n // the original algo evals combining first and falls\n // through to wide check so we simply do here the opposite\n // combining 0\n for (let r = 0; r < BMP_COMBINING.length; ++r) {\n table.fill(0, BMP_COMBINING[r][0], BMP_COMBINING[r][1] + 1);\n }\n }\n }\n\n public wcwidth(num: number): UnicodeCharWidth {\n if (num < 32) return 0;\n if (num < 127) return 1;\n if (num < 65536) return table[num] as UnicodeCharWidth;\n if (bisearch(num, HIGH_COMBINING)) return 0;\n if ((num >= 0x20000 && num <= 0x2fffd) || (num >= 0x30000 && num <= 0x3fffd)) return 2;\n return 1;\n }\n\n public charProperties(codepoint: number, preceding: UnicodeCharProperties): UnicodeCharProperties {\n let width = this.wcwidth(codepoint);\n let shouldJoin = width === 0 && preceding !== 0;\n if (shouldJoin) {\n const oldWidth = UnicodeService.extractWidth(preceding);\n if (oldWidth === 0) {\n shouldJoin = false;\n } else if (oldWidth > width) {\n width = oldWidth;\n }\n }\n return UnicodeService.createPropertyValue(0, width, shouldJoin);\n }\n}\n","\n/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { Disposable } from 'vs/base/common/lifecycle';\nimport { Emitter } from 'vs/base/common/event';\n\ndeclare const setTimeout: (handler: () => void, timeout?: number) => void;\n\n/**\n * Safety watermark to avoid memory exhaustion and browser engine crash on fast data input.\n * Enable flow control to avoid this limit and make sure that your backend correctly\n * propagates this to the underlying pty. (see docs for further instructions)\n * Since this limit is meant as a safety parachute to prevent browser crashs,\n * it is set to a very high number. Typically xterm.js gets unresponsive with\n * a 100 times lower number (>500 kB).\n */\nconst DISCARD_WATERMARK = 50000000; // ~50 MB\n\n/**\n * The max number of ms to spend on writes before allowing the renderer to\n * catch up with a 0ms setTimeout. A value of < 33 to keep us close to\n * 30fps, and a value of < 16 to try to run at 60fps. Of course, the real FPS\n * depends on the time it takes for the renderer to draw the frame.\n */\nconst WRITE_TIMEOUT_MS = 12;\n\n/**\n * Threshold of max held chunks in the write buffer, that were already processed.\n * This is a tradeoff between extensive write buffer shifts (bad runtime) and high\n * memory consumption by data thats not used anymore.\n */\nconst WRITE_BUFFER_LENGTH_THRESHOLD = 50;\n\nexport class WriteBuffer extends Disposable {\n private _writeBuffer: (string | Uint8Array)[] = [];\n private _callbacks: ((() => void) | undefined)[] = [];\n private _pendingData = 0;\n private _bufferOffset = 0;\n private _isSyncWriting = false;\n private _syncCalls = 0;\n private _didUserInput = false;\n\n private readonly _onWriteParsed = this._register(new Emitter());\n public readonly onWriteParsed = this._onWriteParsed.event;\n\n constructor(private _action: (data: string | Uint8Array, promiseResult?: boolean) => void | Promise) {\n super();\n }\n\n public handleUserInput(): void {\n this._didUserInput = true;\n }\n\n /**\n * @deprecated Unreliable, to be removed soon.\n */\n public writeSync(data: string | Uint8Array, maxSubsequentCalls?: number): void {\n // stop writeSync recursions with maxSubsequentCalls argument\n // This is dangerous to use as it will lose the current data chunk\n // and return immediately.\n if (maxSubsequentCalls !== undefined && this._syncCalls > maxSubsequentCalls) {\n // comment next line if a whole loop block should only contain x `writeSync` calls\n // (total flat vs. deep nested limit)\n this._syncCalls = 0;\n return;\n }\n // append chunk to buffer\n this._pendingData += data.length;\n this._writeBuffer.push(data);\n this._callbacks.push(undefined);\n\n // increase recursion counter\n this._syncCalls++;\n // exit early if another writeSync loop is active\n if (this._isSyncWriting) {\n return;\n }\n this._isSyncWriting = true;\n\n // force sync processing on pending data chunks to avoid in-band data scrambling\n // does the same as innerWrite but without event loop\n // we have to do it here as single loop steps to not corrupt loop subject\n // by another writeSync call triggered from _action\n let chunk: string | Uint8Array | undefined;\n while (chunk = this._writeBuffer.shift()) {\n this._action(chunk);\n const cb = this._callbacks.shift();\n if (cb) cb();\n }\n // reset to avoid reprocessing of chunks with scheduled innerWrite call\n // stopping scheduled innerWrite by offset > length condition\n this._pendingData = 0;\n this._bufferOffset = 0x7FFFFFFF;\n\n // allow another writeSync to loop\n this._isSyncWriting = false;\n this._syncCalls = 0;\n }\n\n public write(data: string | Uint8Array, callback?: () => void): void {\n if (this._pendingData > DISCARD_WATERMARK) {\n throw new Error('write data discarded, use flow control to avoid losing data');\n }\n\n // schedule chunk processing for next event loop run\n if (!this._writeBuffer.length) {\n this._bufferOffset = 0;\n\n // If this is the first write call after the user has done some input,\n // parse it immediately to minimize input latency,\n // otherwise schedule for the next event\n if (this._didUserInput) {\n this._didUserInput = false;\n this._pendingData += data.length;\n this._writeBuffer.push(data);\n this._callbacks.push(callback);\n this._innerWrite();\n return;\n }\n\n setTimeout(() => this._innerWrite());\n }\n\n this._pendingData += data.length;\n this._writeBuffer.push(data);\n this._callbacks.push(callback);\n }\n\n /**\n * Inner write call, that enters the sliced chunk processing by timing.\n *\n * `lastTime` indicates, when the last _innerWrite call had started.\n * It is used to aggregate async handler execution under a timeout constraint\n * effectively lowering the redrawing needs, schematically:\n *\n * macroTask _innerWrite:\n * if (performance.now() - (lastTime | 0) < WRITE_TIMEOUT_MS):\n * schedule microTask _innerWrite(lastTime)\n * else:\n * schedule macroTask _innerWrite(0)\n *\n * overall execution order on task queues:\n *\n * macrotasks: [...] --> _innerWrite(0) --> [...] --> screenUpdate --> [...]\n * m t: |\n * i a: [...]\n * c s: |\n * r k: while < timeout:\n * o s: _innerWrite(timeout)\n *\n * `promiseResult` depicts the promise resolve value of an async handler.\n * This value gets carried forward through all saved stack states of the\n * paused parser for proper continuation.\n *\n * Note, for pure sync code `lastTime` and `promiseResult` have no meaning.\n */\n protected _innerWrite(lastTime: number = 0, promiseResult: boolean = true): void {\n const startTime = lastTime || performance.now();\n while (this._writeBuffer.length > this._bufferOffset) {\n const data = this._writeBuffer[this._bufferOffset];\n const result = this._action(data, promiseResult);\n if (result) {\n /**\n * If we get a promise as return value, we re-schedule the continuation\n * as thenable on the promise and exit right away.\n *\n * The exit here means, that we block input processing at the current active chunk,\n * the exact execution position within the chunk is preserved by the saved\n * stack content in InputHandler and EscapeSequenceParser.\n *\n * Resuming happens automatically from that saved stack state.\n * Also the resolved promise value is passed along the callstack to\n * `EscapeSequenceParser.parse` to correctly resume the stopped handler loop.\n *\n * Exceptions on async handlers will be logged to console async, but do not interrupt\n * the input processing (continues with next handler at the current input position).\n */\n\n /**\n * If a promise takes long to resolve, we should schedule continuation behind setTimeout.\n * This might already be too late, if our .then enters really late (executor + prev thens\n * took very long). This cannot be solved here for the handler itself (it is the handlers\n * responsibility to slice hard work), but we can at least schedule a screen update as we\n * gain control.\n */\n const continuation: (r: boolean) => void = (r: boolean) => performance.now() - startTime >= WRITE_TIMEOUT_MS\n ? setTimeout(() => this._innerWrite(0, r))\n : this._innerWrite(startTime, r);\n\n /**\n * Optimization considerations:\n * The continuation above favors FPS over throughput by eval'ing `startTime` on resolve.\n * This might schedule too many screen updates with bad throughput drops (in case a slow\n * resolving handler sliced its work properly behind setTimeout calls). We cannot spot\n * this condition here, also the renderer has no way to spot nonsense updates either.\n * FIXME: A proper fix for this would track the FPS at the renderer entry level separately.\n *\n * If favoring of FPS shows bad throughtput impact, use the following instead. It favors\n * throughput by eval'ing `startTime` upfront pulling at least one more chunk into the\n * current microtask queue (executed before setTimeout).\n */\n // const continuation: (r: boolean) => void = performance.now() - startTime >=\n // WRITE_TIMEOUT_MS\n // ? r => setTimeout(() => this._innerWrite(0, r))\n // : r => this._innerWrite(startTime, r);\n\n // Handle exceptions synchronously to current band position, idea:\n // 1. spawn a single microtask which we allow to throw hard\n // 2. spawn a promise immediately resolving to `true`\n // (executed on the same queue, thus properly aligned before continuation happens)\n result.catch(err => {\n queueMicrotask(() => {throw err;});\n return Promise.resolve(false);\n }).then(continuation);\n return;\n }\n\n const cb = this._callbacks[this._bufferOffset];\n if (cb) cb();\n this._bufferOffset++;\n this._pendingData -= data.length;\n\n if (performance.now() - startTime >= WRITE_TIMEOUT_MS) {\n break;\n }\n }\n if (this._writeBuffer.length > this._bufferOffset) {\n // Allow renderer to catch up before processing the next batch\n // trim already processed chunks if we are above threshold\n if (this._bufferOffset > WRITE_BUFFER_LENGTH_THRESHOLD) {\n this._writeBuffer = this._writeBuffer.slice(this._bufferOffset);\n this._callbacks = this._callbacks.slice(this._bufferOffset);\n this._bufferOffset = 0;\n }\n setTimeout(() => this._innerWrite());\n } else {\n this._writeBuffer.length = 0;\n this._callbacks.length = 0;\n this._pendingData = 0;\n this._bufferOffset = 0;\n }\n this._onWriteParsed.fire();\n }\n}\n","/**\n * Copyright (c) 2021 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\n\n// 'rgb:' rule - matching: r/g/b | rr/gg/bb | rrr/ggg/bbb | rrrr/gggg/bbbb (hex digits)\nconst RGB_REX = /^([\\da-f])\\/([\\da-f])\\/([\\da-f])$|^([\\da-f]{2})\\/([\\da-f]{2})\\/([\\da-f]{2})$|^([\\da-f]{3})\\/([\\da-f]{3})\\/([\\da-f]{3})$|^([\\da-f]{4})\\/([\\da-f]{4})\\/([\\da-f]{4})$/;\n// '#...' rule - matching any hex digits\nconst HASH_REX = /^[\\da-f]+$/;\n\n/**\n * Parse color spec to RGB values (8 bit per channel).\n * See `man xparsecolor` for details about certain format specifications.\n *\n * Supported formats:\n * - rgb:// with , , in h | hh | hhh | hhhh\n * - #RGB, #RRGGBB, #RRRGGGBBB, #RRRRGGGGBBBB\n *\n * All other formats like rgbi: or device-independent string specifications\n * with float numbering are not supported.\n */\nexport function parseColor(data: string): [number, number, number] | undefined {\n if (!data) return;\n // also handle uppercases\n let low = data.toLowerCase();\n if (low.indexOf('rgb:') === 0) {\n // 'rgb:' specifier\n low = low.slice(4);\n const m = RGB_REX.exec(low);\n if (m) {\n const base = m[1] ? 15 : m[4] ? 255 : m[7] ? 4095 : 65535;\n return [\n Math.round(parseInt(m[1] || m[4] || m[7] || m[10], 16) / base * 255),\n Math.round(parseInt(m[2] || m[5] || m[8] || m[11], 16) / base * 255),\n Math.round(parseInt(m[3] || m[6] || m[9] || m[12], 16) / base * 255)\n ];\n }\n } else if (low.indexOf('#') === 0) {\n // '#' specifier\n low = low.slice(1);\n if (HASH_REX.exec(low) && [3, 6, 9, 12].includes(low.length)) {\n const adv = low.length / 3;\n const result: [number, number, number] = [0, 0, 0];\n for (let i = 0; i < 3; ++i) {\n const c = parseInt(low.slice(adv * i, adv * i + adv), 16);\n result[i] = adv === 1 ? c << 4 : adv === 2 ? c : adv === 3 ? c >> 4 : c >> 8;\n }\n return result;\n }\n }\n\n // Named colors are currently not supported due to the large addition to the xterm.js bundle size\n // they would add. In order to support named colors, we would need some way of optionally loading\n // additional payloads so startup/download time is not bloated (see #3530).\n}\n\n// pad hex output to requested bit width\nfunction pad(n: number, bits: number): string {\n const s = n.toString(16);\n const s2 = s.length < 2 ? '0' + s : s;\n switch (bits) {\n case 4:\n return s[0];\n case 8:\n return s2;\n case 12:\n return (s2 + s2).slice(0, 3);\n default:\n return s2 + s2;\n }\n}\n\n/**\n * Convert a given color to rgb:../../.. string of `bits` depth.\n */\nexport function toRgbString(color: [number, number, number], bits: number = 16): string {\n const [r, g, b] = color;\n return `rgb:${pad(r, bits)}/${pad(g, bits)}/${pad(b, bits)}`;\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\n/**\n * Internal states of EscapeSequenceParser.\n */\nexport const enum ParserState {\n GROUND = 0,\n ESCAPE = 1,\n ESCAPE_INTERMEDIATE = 2,\n CSI_ENTRY = 3,\n CSI_PARAM = 4,\n CSI_INTERMEDIATE = 5,\n CSI_IGNORE = 6,\n SOS_PM_APC_STRING = 7,\n OSC_STRING = 8,\n DCS_ENTRY = 9,\n DCS_PARAM = 10,\n DCS_IGNORE = 11,\n DCS_INTERMEDIATE = 12,\n DCS_PASSTHROUGH = 13\n}\n\n/**\n * Internal actions of EscapeSequenceParser.\n */\nexport const enum ParserAction {\n IGNORE = 0,\n ERROR = 1,\n PRINT = 2,\n EXECUTE = 3,\n OSC_START = 4,\n OSC_PUT = 5,\n OSC_END = 6,\n CSI_DISPATCH = 7,\n PARAM = 8,\n COLLECT = 9,\n ESC_DISPATCH = 10,\n CLEAR = 11,\n DCS_HOOK = 12,\n DCS_PUT = 13,\n DCS_UNHOOK = 14\n}\n\n/**\n * Internal states of OscParser.\n */\nexport const enum OscState {\n START = 0,\n ID = 1,\n PAYLOAD = 2,\n ABORT = 3\n}\n\n// payload limit for OSC and DCS\nexport const PAYLOAD_LIMIT = 10000000;\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IDisposable } from 'common/Types';\nimport { IDcsHandler, IParams, IHandlerCollection, IDcsParser, DcsFallbackHandlerType, ISubParserStackState } from 'common/parser/Types';\nimport { utf32ToString } from 'common/input/TextDecoder';\nimport { Params } from 'common/parser/Params';\nimport { PAYLOAD_LIMIT } from 'common/parser/Constants';\n\nconst EMPTY_HANDLERS: IDcsHandler[] = [];\n\nexport class DcsParser implements IDcsParser {\n private _handlers: IHandlerCollection = Object.create(null);\n private _active: IDcsHandler[] = EMPTY_HANDLERS;\n private _ident: number = 0;\n private _handlerFb: DcsFallbackHandlerType = () => { };\n private _stack: ISubParserStackState = {\n paused: false,\n loopPosition: 0,\n fallThrough: false\n };\n\n public dispose(): void {\n this._handlers = Object.create(null);\n this._handlerFb = () => { };\n this._active = EMPTY_HANDLERS;\n }\n\n public registerHandler(ident: number, handler: IDcsHandler): IDisposable {\n if (this._handlers[ident] === undefined) {\n this._handlers[ident] = [];\n }\n const handlerList = this._handlers[ident];\n handlerList.push(handler);\n return {\n dispose: () => {\n const handlerIndex = handlerList.indexOf(handler);\n if (handlerIndex !== -1) {\n handlerList.splice(handlerIndex, 1);\n }\n }\n };\n }\n\n public clearHandler(ident: number): void {\n if (this._handlers[ident]) delete this._handlers[ident];\n }\n\n public setHandlerFallback(handler: DcsFallbackHandlerType): void {\n this._handlerFb = handler;\n }\n\n public reset(): void {\n // force cleanup leftover handlers\n if (this._active.length) {\n for (let j = this._stack.paused ? this._stack.loopPosition - 1 : this._active.length - 1; j >= 0; --j) {\n this._active[j].unhook(false);\n }\n }\n this._stack.paused = false;\n this._active = EMPTY_HANDLERS;\n this._ident = 0;\n }\n\n public hook(ident: number, params: IParams): void {\n // always reset leftover handlers\n this.reset();\n this._ident = ident;\n this._active = this._handlers[ident] || EMPTY_HANDLERS;\n if (!this._active.length) {\n this._handlerFb(this._ident, 'HOOK', params);\n } else {\n for (let j = this._active.length - 1; j >= 0; j--) {\n this._active[j].hook(params);\n }\n }\n }\n\n public put(data: Uint32Array, start: number, end: number): void {\n if (!this._active.length) {\n this._handlerFb(this._ident, 'PUT', utf32ToString(data, start, end));\n } else {\n for (let j = this._active.length - 1; j >= 0; j--) {\n this._active[j].put(data, start, end);\n }\n }\n }\n\n public unhook(success: boolean, promiseResult: boolean = true): void | Promise {\n if (!this._active.length) {\n this._handlerFb(this._ident, 'UNHOOK', success);\n } else {\n let handlerResult: boolean | Promise = false;\n let j = this._active.length - 1;\n let fallThrough = false;\n if (this._stack.paused) {\n j = this._stack.loopPosition - 1;\n handlerResult = promiseResult;\n fallThrough = this._stack.fallThrough;\n this._stack.paused = false;\n }\n if (!fallThrough && handlerResult === false) {\n for (; j >= 0; j--) {\n handlerResult = this._active[j].unhook(success);\n if (handlerResult === true) {\n break;\n } else if (handlerResult instanceof Promise) {\n this._stack.paused = true;\n this._stack.loopPosition = j;\n this._stack.fallThrough = false;\n return handlerResult;\n }\n }\n j--;\n }\n // cleanup left over handlers (fallThrough for async)\n for (; j >= 0; j--) {\n handlerResult = this._active[j].unhook(false);\n if (handlerResult instanceof Promise) {\n this._stack.paused = true;\n this._stack.loopPosition = j;\n this._stack.fallThrough = true;\n return handlerResult;\n }\n }\n }\n this._active = EMPTY_HANDLERS;\n this._ident = 0;\n }\n}\n\n// predefine empty params as [0] (ZDM)\nconst EMPTY_PARAMS = new Params();\nEMPTY_PARAMS.addParam(0);\n\n/**\n * Convenient class to create a DCS handler from a single callback function.\n * Note: The payload is currently limited to 50 MB (hardcoded).\n */\nexport class DcsHandler implements IDcsHandler {\n private _data = '';\n private _params: IParams = EMPTY_PARAMS;\n private _hitLimit: boolean = false;\n\n constructor(private _handler: (data: string, params: IParams) => boolean | Promise) { }\n\n public hook(params: IParams): void {\n // since we need to preserve params until `unhook`, we have to clone it\n // (only borrowed from parser and spans multiple parser states)\n // perf optimization:\n // clone only, if we have non empty params, otherwise stick with default\n this._params = (params.length > 1 || params.params[0]) ? params.clone() : EMPTY_PARAMS;\n this._data = '';\n this._hitLimit = false;\n }\n\n public put(data: Uint32Array, start: number, end: number): void {\n if (this._hitLimit) {\n return;\n }\n this._data += utf32ToString(data, start, end);\n if (this._data.length > PAYLOAD_LIMIT) {\n this._data = '';\n this._hitLimit = true;\n }\n }\n\n public unhook(success: boolean): boolean | Promise {\n let ret: boolean | Promise = false;\n if (this._hitLimit) {\n ret = false;\n } else if (success) {\n ret = this._handler(this._data, this._params);\n if (ret instanceof Promise) {\n // need to hold data and params until `ret` got resolved\n // dont care for errors, data will be freed anyway on next start\n return ret.then(res => {\n this._params = EMPTY_PARAMS;\n this._data = '';\n this._hitLimit = false;\n return res;\n });\n }\n }\n this._params = EMPTY_PARAMS;\n this._data = '';\n this._hitLimit = false;\n return ret;\n }\n}\n","/**\n * Copyright (c) 2018 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IParsingState, IDcsHandler, IEscapeSequenceParser, IParams, IOscHandler, IHandlerCollection, CsiHandlerType, OscFallbackHandlerType, IOscParser, EscHandlerType, IDcsParser, DcsFallbackHandlerType, IFunctionIdentifier, ExecuteFallbackHandlerType, CsiFallbackHandlerType, EscFallbackHandlerType, PrintHandlerType, PrintFallbackHandlerType, ExecuteHandlerType, IParserStackState, ParserStackType, ResumableHandlersType } from 'common/parser/Types';\nimport { ParserState, ParserAction } from 'common/parser/Constants';\nimport { Disposable, toDisposable } from 'vs/base/common/lifecycle';\nimport { IDisposable } from 'common/Types';\nimport { Params } from 'common/parser/Params';\nimport { OscParser } from 'common/parser/OscParser';\nimport { DcsParser } from 'common/parser/DcsParser';\n\n/**\n * Table values are generated like this:\n * index: currentState << TableValue.INDEX_STATE_SHIFT | charCode\n * value: action << TableValue.TRANSITION_ACTION_SHIFT | nextState\n */\nconst enum TableAccess {\n TRANSITION_ACTION_SHIFT = 4,\n TRANSITION_STATE_MASK = 15,\n INDEX_STATE_SHIFT = 8\n}\n\n/**\n * Transition table for EscapeSequenceParser.\n */\nexport class TransitionTable {\n public table: Uint8Array;\n\n constructor(length: number) {\n this.table = new Uint8Array(length);\n }\n\n /**\n * Set default transition.\n * @param action default action\n * @param next default next state\n */\n public setDefault(action: ParserAction, next: ParserState): void {\n this.table.fill(action << TableAccess.TRANSITION_ACTION_SHIFT | next);\n }\n\n /**\n * Add a transition to the transition table.\n * @param code input character code\n * @param state current parser state\n * @param action parser action to be done\n * @param next next parser state\n */\n public add(code: number, state: ParserState, action: ParserAction, next: ParserState): void {\n this.table[state << TableAccess.INDEX_STATE_SHIFT | code] = action << TableAccess.TRANSITION_ACTION_SHIFT | next;\n }\n\n /**\n * Add transitions for multiple input character codes.\n * @param codes input character code array\n * @param state current parser state\n * @param action parser action to be done\n * @param next next parser state\n */\n public addMany(codes: number[], state: ParserState, action: ParserAction, next: ParserState): void {\n for (let i = 0; i < codes.length; i++) {\n this.table[state << TableAccess.INDEX_STATE_SHIFT | codes[i]] = action << TableAccess.TRANSITION_ACTION_SHIFT | next;\n }\n }\n}\n\n\n// Pseudo-character placeholder for printable non-ascii characters (unicode).\nconst NON_ASCII_PRINTABLE = 0xA0;\n\n\n/**\n * VT500 compatible transition table.\n * Taken from https://vt100.net/emu/dec_ansi_parser.\n */\nexport const VT500_TRANSITION_TABLE = (function (): TransitionTable {\n const table: TransitionTable = new TransitionTable(4095);\n\n // range macro for byte\n const BYTE_VALUES = 256;\n const blueprint = Array.apply(null, Array(BYTE_VALUES)).map((unused: any, i: number) => i);\n const r = (start: number, end: number): number[] => blueprint.slice(start, end);\n\n // Default definitions.\n const PRINTABLES = r(0x20, 0x7f); // 0x20 (SP) included, 0x7F (DEL) excluded\n const EXECUTABLES = r(0x00, 0x18);\n EXECUTABLES.push(0x19);\n EXECUTABLES.push.apply(EXECUTABLES, r(0x1c, 0x20));\n\n const states: number[] = r(ParserState.GROUND, ParserState.DCS_PASSTHROUGH + 1);\n let state: any;\n\n // set default transition\n table.setDefault(ParserAction.ERROR, ParserState.GROUND);\n // printables\n table.addMany(PRINTABLES, ParserState.GROUND, ParserAction.PRINT, ParserState.GROUND);\n // global anywhere rules\n for (state in states) {\n table.addMany([0x18, 0x1a, 0x99, 0x9a], state, ParserAction.EXECUTE, ParserState.GROUND);\n table.addMany(r(0x80, 0x90), state, ParserAction.EXECUTE, ParserState.GROUND);\n table.addMany(r(0x90, 0x98), state, ParserAction.EXECUTE, ParserState.GROUND);\n table.add(0x9c, state, ParserAction.IGNORE, ParserState.GROUND); // ST as terminator\n table.add(0x1b, state, ParserAction.CLEAR, ParserState.ESCAPE); // ESC\n table.add(0x9d, state, ParserAction.OSC_START, ParserState.OSC_STRING); // OSC\n table.addMany([0x98, 0x9e, 0x9f], state, ParserAction.IGNORE, ParserState.SOS_PM_APC_STRING);\n table.add(0x9b, state, ParserAction.CLEAR, ParserState.CSI_ENTRY); // CSI\n table.add(0x90, state, ParserAction.CLEAR, ParserState.DCS_ENTRY); // DCS\n }\n // rules for executables and 7f\n table.addMany(EXECUTABLES, ParserState.GROUND, ParserAction.EXECUTE, ParserState.GROUND);\n table.addMany(EXECUTABLES, ParserState.ESCAPE, ParserAction.EXECUTE, ParserState.ESCAPE);\n table.add(0x7f, ParserState.ESCAPE, ParserAction.IGNORE, ParserState.ESCAPE);\n table.addMany(EXECUTABLES, ParserState.OSC_STRING, ParserAction.IGNORE, ParserState.OSC_STRING);\n table.addMany(EXECUTABLES, ParserState.CSI_ENTRY, ParserAction.EXECUTE, ParserState.CSI_ENTRY);\n table.add(0x7f, ParserState.CSI_ENTRY, ParserAction.IGNORE, ParserState.CSI_ENTRY);\n table.addMany(EXECUTABLES, ParserState.CSI_PARAM, ParserAction.EXECUTE, ParserState.CSI_PARAM);\n table.add(0x7f, ParserState.CSI_PARAM, ParserAction.IGNORE, ParserState.CSI_PARAM);\n table.addMany(EXECUTABLES, ParserState.CSI_IGNORE, ParserAction.EXECUTE, ParserState.CSI_IGNORE);\n table.addMany(EXECUTABLES, ParserState.CSI_INTERMEDIATE, ParserAction.EXECUTE, ParserState.CSI_INTERMEDIATE);\n table.add(0x7f, ParserState.CSI_INTERMEDIATE, ParserAction.IGNORE, ParserState.CSI_INTERMEDIATE);\n table.addMany(EXECUTABLES, ParserState.ESCAPE_INTERMEDIATE, ParserAction.EXECUTE, ParserState.ESCAPE_INTERMEDIATE);\n table.add(0x7f, ParserState.ESCAPE_INTERMEDIATE, ParserAction.IGNORE, ParserState.ESCAPE_INTERMEDIATE);\n // osc\n table.add(0x5d, ParserState.ESCAPE, ParserAction.OSC_START, ParserState.OSC_STRING);\n table.addMany(PRINTABLES, ParserState.OSC_STRING, ParserAction.OSC_PUT, ParserState.OSC_STRING);\n table.add(0x7f, ParserState.OSC_STRING, ParserAction.OSC_PUT, ParserState.OSC_STRING);\n table.addMany([0x9c, 0x1b, 0x18, 0x1a, 0x07], ParserState.OSC_STRING, ParserAction.OSC_END, ParserState.GROUND);\n table.addMany(r(0x1c, 0x20), ParserState.OSC_STRING, ParserAction.IGNORE, ParserState.OSC_STRING);\n // sos/pm/apc does nothing\n table.addMany([0x58, 0x5e, 0x5f], ParserState.ESCAPE, ParserAction.IGNORE, ParserState.SOS_PM_APC_STRING);\n table.addMany(PRINTABLES, ParserState.SOS_PM_APC_STRING, ParserAction.IGNORE, ParserState.SOS_PM_APC_STRING);\n table.addMany(EXECUTABLES, ParserState.SOS_PM_APC_STRING, ParserAction.IGNORE, ParserState.SOS_PM_APC_STRING);\n table.add(0x9c, ParserState.SOS_PM_APC_STRING, ParserAction.IGNORE, ParserState.GROUND);\n table.add(0x7f, ParserState.SOS_PM_APC_STRING, ParserAction.IGNORE, ParserState.SOS_PM_APC_STRING);\n // csi entries\n table.add(0x5b, ParserState.ESCAPE, ParserAction.CLEAR, ParserState.CSI_ENTRY);\n table.addMany(r(0x40, 0x7f), ParserState.CSI_ENTRY, ParserAction.CSI_DISPATCH, ParserState.GROUND);\n table.addMany(r(0x30, 0x3c), ParserState.CSI_ENTRY, ParserAction.PARAM, ParserState.CSI_PARAM);\n table.addMany([0x3c, 0x3d, 0x3e, 0x3f], ParserState.CSI_ENTRY, ParserAction.COLLECT, ParserState.CSI_PARAM);\n table.addMany(r(0x30, 0x3c), ParserState.CSI_PARAM, ParserAction.PARAM, ParserState.CSI_PARAM);\n table.addMany(r(0x40, 0x7f), ParserState.CSI_PARAM, ParserAction.CSI_DISPATCH, ParserState.GROUND);\n table.addMany([0x3c, 0x3d, 0x3e, 0x3f], ParserState.CSI_PARAM, ParserAction.IGNORE, ParserState.CSI_IGNORE);\n table.addMany(r(0x20, 0x40), ParserState.CSI_IGNORE, ParserAction.IGNORE, ParserState.CSI_IGNORE);\n table.add(0x7f, ParserState.CSI_IGNORE, ParserAction.IGNORE, ParserState.CSI_IGNORE);\n table.addMany(r(0x40, 0x7f), ParserState.CSI_IGNORE, ParserAction.IGNORE, ParserState.GROUND);\n table.addMany(r(0x20, 0x30), ParserState.CSI_ENTRY, ParserAction.COLLECT, ParserState.CSI_INTERMEDIATE);\n table.addMany(r(0x20, 0x30), ParserState.CSI_INTERMEDIATE, ParserAction.COLLECT, ParserState.CSI_INTERMEDIATE);\n table.addMany(r(0x30, 0x40), ParserState.CSI_INTERMEDIATE, ParserAction.IGNORE, ParserState.CSI_IGNORE);\n table.addMany(r(0x40, 0x7f), ParserState.CSI_INTERMEDIATE, ParserAction.CSI_DISPATCH, ParserState.GROUND);\n table.addMany(r(0x20, 0x30), ParserState.CSI_PARAM, ParserAction.COLLECT, ParserState.CSI_INTERMEDIATE);\n // esc_intermediate\n table.addMany(r(0x20, 0x30), ParserState.ESCAPE, ParserAction.COLLECT, ParserState.ESCAPE_INTERMEDIATE);\n table.addMany(r(0x20, 0x30), ParserState.ESCAPE_INTERMEDIATE, ParserAction.COLLECT, ParserState.ESCAPE_INTERMEDIATE);\n table.addMany(r(0x30, 0x7f), ParserState.ESCAPE_INTERMEDIATE, ParserAction.ESC_DISPATCH, ParserState.GROUND);\n table.addMany(r(0x30, 0x50), ParserState.ESCAPE, ParserAction.ESC_DISPATCH, ParserState.GROUND);\n table.addMany(r(0x51, 0x58), ParserState.ESCAPE, ParserAction.ESC_DISPATCH, ParserState.GROUND);\n table.addMany([0x59, 0x5a, 0x5c], ParserState.ESCAPE, ParserAction.ESC_DISPATCH, ParserState.GROUND);\n table.addMany(r(0x60, 0x7f), ParserState.ESCAPE, ParserAction.ESC_DISPATCH, ParserState.GROUND);\n // dcs entry\n table.add(0x50, ParserState.ESCAPE, ParserAction.CLEAR, ParserState.DCS_ENTRY);\n table.addMany(EXECUTABLES, ParserState.DCS_ENTRY, ParserAction.IGNORE, ParserState.DCS_ENTRY);\n table.add(0x7f, ParserState.DCS_ENTRY, ParserAction.IGNORE, ParserState.DCS_ENTRY);\n table.addMany(r(0x1c, 0x20), ParserState.DCS_ENTRY, ParserAction.IGNORE, ParserState.DCS_ENTRY);\n table.addMany(r(0x20, 0x30), ParserState.DCS_ENTRY, ParserAction.COLLECT, ParserState.DCS_INTERMEDIATE);\n table.addMany(r(0x30, 0x3c), ParserState.DCS_ENTRY, ParserAction.PARAM, ParserState.DCS_PARAM);\n table.addMany([0x3c, 0x3d, 0x3e, 0x3f], ParserState.DCS_ENTRY, ParserAction.COLLECT, ParserState.DCS_PARAM);\n table.addMany(EXECUTABLES, ParserState.DCS_IGNORE, ParserAction.IGNORE, ParserState.DCS_IGNORE);\n table.addMany(r(0x20, 0x80), ParserState.DCS_IGNORE, ParserAction.IGNORE, ParserState.DCS_IGNORE);\n table.addMany(r(0x1c, 0x20), ParserState.DCS_IGNORE, ParserAction.IGNORE, ParserState.DCS_IGNORE);\n table.addMany(EXECUTABLES, ParserState.DCS_PARAM, ParserAction.IGNORE, ParserState.DCS_PARAM);\n table.add(0x7f, ParserState.DCS_PARAM, ParserAction.IGNORE, ParserState.DCS_PARAM);\n table.addMany(r(0x1c, 0x20), ParserState.DCS_PARAM, ParserAction.IGNORE, ParserState.DCS_PARAM);\n table.addMany(r(0x30, 0x3c), ParserState.DCS_PARAM, ParserAction.PARAM, ParserState.DCS_PARAM);\n table.addMany([0x3c, 0x3d, 0x3e, 0x3f], ParserState.DCS_PARAM, ParserAction.IGNORE, ParserState.DCS_IGNORE);\n table.addMany(r(0x20, 0x30), ParserState.DCS_PARAM, ParserAction.COLLECT, ParserState.DCS_INTERMEDIATE);\n table.addMany(EXECUTABLES, ParserState.DCS_INTERMEDIATE, ParserAction.IGNORE, ParserState.DCS_INTERMEDIATE);\n table.add(0x7f, ParserState.DCS_INTERMEDIATE, ParserAction.IGNORE, ParserState.DCS_INTERMEDIATE);\n table.addMany(r(0x1c, 0x20), ParserState.DCS_INTERMEDIATE, ParserAction.IGNORE, ParserState.DCS_INTERMEDIATE);\n table.addMany(r(0x20, 0x30), ParserState.DCS_INTERMEDIATE, ParserAction.COLLECT, ParserState.DCS_INTERMEDIATE);\n table.addMany(r(0x30, 0x40), ParserState.DCS_INTERMEDIATE, ParserAction.IGNORE, ParserState.DCS_IGNORE);\n table.addMany(r(0x40, 0x7f), ParserState.DCS_INTERMEDIATE, ParserAction.DCS_HOOK, ParserState.DCS_PASSTHROUGH);\n table.addMany(r(0x40, 0x7f), ParserState.DCS_PARAM, ParserAction.DCS_HOOK, ParserState.DCS_PASSTHROUGH);\n table.addMany(r(0x40, 0x7f), ParserState.DCS_ENTRY, ParserAction.DCS_HOOK, ParserState.DCS_PASSTHROUGH);\n table.addMany(EXECUTABLES, ParserState.DCS_PASSTHROUGH, ParserAction.DCS_PUT, ParserState.DCS_PASSTHROUGH);\n table.addMany(PRINTABLES, ParserState.DCS_PASSTHROUGH, ParserAction.DCS_PUT, ParserState.DCS_PASSTHROUGH);\n table.add(0x7f, ParserState.DCS_PASSTHROUGH, ParserAction.IGNORE, ParserState.DCS_PASSTHROUGH);\n table.addMany([0x1b, 0x9c, 0x18, 0x1a], ParserState.DCS_PASSTHROUGH, ParserAction.DCS_UNHOOK, ParserState.GROUND);\n // special handling of unicode chars\n table.add(NON_ASCII_PRINTABLE, ParserState.GROUND, ParserAction.PRINT, ParserState.GROUND);\n table.add(NON_ASCII_PRINTABLE, ParserState.OSC_STRING, ParserAction.OSC_PUT, ParserState.OSC_STRING);\n table.add(NON_ASCII_PRINTABLE, ParserState.CSI_IGNORE, ParserAction.IGNORE, ParserState.CSI_IGNORE);\n table.add(NON_ASCII_PRINTABLE, ParserState.DCS_IGNORE, ParserAction.IGNORE, ParserState.DCS_IGNORE);\n table.add(NON_ASCII_PRINTABLE, ParserState.DCS_PASSTHROUGH, ParserAction.DCS_PUT, ParserState.DCS_PASSTHROUGH);\n return table;\n})();\n\n\n/**\n * EscapeSequenceParser.\n * This class implements the ANSI/DEC compatible parser described by\n * Paul Williams (https://vt100.net/emu/dec_ansi_parser).\n *\n * To implement custom ANSI compliant escape sequences it is not needed to\n * alter this parser, instead consider registering a custom handler.\n * For non ANSI compliant sequences change the transition table with\n * the optional `transitions` constructor argument and\n * reimplement the `parse` method.\n *\n * This parser is currently hardcoded to operate in ZDM (Zero Default Mode)\n * as suggested by the original parser, thus empty parameters are set to 0.\n * This this is not in line with the latest ECMA-48 specification\n * (ZDM was part of the early specs and got completely removed later on).\n *\n * Other than the original parser from vt100.net this parser supports\n * sub parameters in digital parameters separated by colons. Empty sub parameters\n * are set to -1 (no ZDM for sub parameters).\n *\n * About prefix and intermediate bytes:\n * This parser follows the assumptions of the vt100.net parser with these restrictions:\n * - only one prefix byte is allowed as first parameter byte, byte range 0x3c .. 0x3f\n * - max. two intermediates are respected, byte range 0x20 .. 0x2f\n * Note that this is not in line with ECMA-48 which does not limit either of those.\n * Furthermore ECMA-48 allows the prefix byte range at any param byte position. Currently\n * there are no known sequences that follow the broader definition of the specification.\n *\n * TODO: implement error recovery hook via error handler return values\n */\nexport class EscapeSequenceParser extends Disposable implements IEscapeSequenceParser {\n public initialState: number;\n public currentState: number;\n public precedingJoinState: number; // UnicodeJoinProperties\n\n // buffers over several parse calls\n protected _params: Params;\n protected _collect: number;\n\n // handler lookup containers\n protected _printHandler: PrintHandlerType;\n protected _executeHandlers: { [flag: number]: ExecuteHandlerType };\n protected _csiHandlers: IHandlerCollection;\n protected _escHandlers: IHandlerCollection;\n protected readonly _oscParser: IOscParser;\n protected readonly _dcsParser: IDcsParser;\n protected _errorHandler: (state: IParsingState) => IParsingState;\n\n // fallback handlers\n protected _printHandlerFb: PrintFallbackHandlerType;\n protected _executeHandlerFb: ExecuteFallbackHandlerType;\n protected _csiHandlerFb: CsiFallbackHandlerType;\n protected _escHandlerFb: EscFallbackHandlerType;\n protected _errorHandlerFb: (state: IParsingState) => IParsingState;\n\n // parser stack save for async handler support\n protected _parseStack: IParserStackState = {\n state: ParserStackType.NONE,\n handlers: [],\n handlerPos: 0,\n transition: 0,\n chunkPos: 0\n };\n\n constructor(\n protected readonly _transitions: TransitionTable = VT500_TRANSITION_TABLE\n ) {\n super();\n\n this.initialState = ParserState.GROUND;\n this.currentState = this.initialState;\n this._params = new Params(); // defaults to 32 storable params/subparams\n this._params.addParam(0); // ZDM\n this._collect = 0;\n this.precedingJoinState = 0;\n\n // set default fallback handlers and handler lookup containers\n this._printHandlerFb = (data, start, end): void => { };\n this._executeHandlerFb = (code: number): void => { };\n this._csiHandlerFb = (ident: number, params: IParams): void => { };\n this._escHandlerFb = (ident: number): void => { };\n this._errorHandlerFb = (state: IParsingState): IParsingState => state;\n this._printHandler = this._printHandlerFb;\n this._executeHandlers = Object.create(null);\n this._csiHandlers = Object.create(null);\n this._escHandlers = Object.create(null);\n this._register(toDisposable(() => {\n this._csiHandlers = Object.create(null);\n this._executeHandlers = Object.create(null);\n this._escHandlers = Object.create(null);\n }));\n this._oscParser = this._register(new OscParser());\n this._dcsParser = this._register(new DcsParser());\n this._errorHandler = this._errorHandlerFb;\n\n // swallow 7bit ST (ESC+\\)\n this.registerEscHandler({ final: '\\\\' }, () => true);\n }\n\n protected _identifier(id: IFunctionIdentifier, finalRange: number[] = [0x40, 0x7e]): number {\n let res = 0;\n if (id.prefix) {\n if (id.prefix.length > 1) {\n throw new Error('only one byte as prefix supported');\n }\n res = id.prefix.charCodeAt(0);\n if (res && 0x3c > res || res > 0x3f) {\n throw new Error('prefix must be in range 0x3c .. 0x3f');\n }\n }\n if (id.intermediates) {\n if (id.intermediates.length > 2) {\n throw new Error('only two bytes as intermediates are supported');\n }\n for (let i = 0; i < id.intermediates.length; ++i) {\n const intermediate = id.intermediates.charCodeAt(i);\n if (0x20 > intermediate || intermediate > 0x2f) {\n throw new Error('intermediate must be in range 0x20 .. 0x2f');\n }\n res <<= 8;\n res |= intermediate;\n }\n }\n if (id.final.length !== 1) {\n throw new Error('final must be a single byte');\n }\n const finalCode = id.final.charCodeAt(0);\n if (finalRange[0] > finalCode || finalCode > finalRange[1]) {\n throw new Error(`final must be in range ${finalRange[0]} .. ${finalRange[1]}`);\n }\n res <<= 8;\n res |= finalCode;\n\n return res;\n }\n\n public identToString(ident: number): string {\n const res: string[] = [];\n while (ident) {\n res.push(String.fromCharCode(ident & 0xFF));\n ident >>= 8;\n }\n return res.reverse().join('');\n }\n\n public setPrintHandler(handler: PrintHandlerType): void {\n this._printHandler = handler;\n }\n public clearPrintHandler(): void {\n this._printHandler = this._printHandlerFb;\n }\n\n public registerEscHandler(id: IFunctionIdentifier, handler: EscHandlerType): IDisposable {\n const ident = this._identifier(id, [0x30, 0x7e]);\n if (this._escHandlers[ident] === undefined) {\n this._escHandlers[ident] = [];\n }\n const handlerList = this._escHandlers[ident];\n handlerList.push(handler);\n return {\n dispose: () => {\n const handlerIndex = handlerList.indexOf(handler);\n if (handlerIndex !== -1) {\n handlerList.splice(handlerIndex, 1);\n }\n }\n };\n }\n public clearEscHandler(id: IFunctionIdentifier): void {\n if (this._escHandlers[this._identifier(id, [0x30, 0x7e])]) delete this._escHandlers[this._identifier(id, [0x30, 0x7e])];\n }\n public setEscHandlerFallback(handler: EscFallbackHandlerType): void {\n this._escHandlerFb = handler;\n }\n\n public setExecuteHandler(flag: string, handler: ExecuteHandlerType): void {\n this._executeHandlers[flag.charCodeAt(0)] = handler;\n }\n public clearExecuteHandler(flag: string): void {\n if (this._executeHandlers[flag.charCodeAt(0)]) delete this._executeHandlers[flag.charCodeAt(0)];\n }\n public setExecuteHandlerFallback(handler: ExecuteFallbackHandlerType): void {\n this._executeHandlerFb = handler;\n }\n\n public registerCsiHandler(id: IFunctionIdentifier, handler: CsiHandlerType): IDisposable {\n const ident = this._identifier(id);\n if (this._csiHandlers[ident] === undefined) {\n this._csiHandlers[ident] = [];\n }\n const handlerList = this._csiHandlers[ident];\n handlerList.push(handler);\n return {\n dispose: () => {\n const handlerIndex = handlerList.indexOf(handler);\n if (handlerIndex !== -1) {\n handlerList.splice(handlerIndex, 1);\n }\n }\n };\n }\n public clearCsiHandler(id: IFunctionIdentifier): void {\n if (this._csiHandlers[this._identifier(id)]) delete this._csiHandlers[this._identifier(id)];\n }\n public setCsiHandlerFallback(callback: (ident: number, params: IParams) => void): void {\n this._csiHandlerFb = callback;\n }\n\n public registerDcsHandler(id: IFunctionIdentifier, handler: IDcsHandler): IDisposable {\n return this._dcsParser.registerHandler(this._identifier(id), handler);\n }\n public clearDcsHandler(id: IFunctionIdentifier): void {\n this._dcsParser.clearHandler(this._identifier(id));\n }\n public setDcsHandlerFallback(handler: DcsFallbackHandlerType): void {\n this._dcsParser.setHandlerFallback(handler);\n }\n\n public registerOscHandler(ident: number, handler: IOscHandler): IDisposable {\n return this._oscParser.registerHandler(ident, handler);\n }\n public clearOscHandler(ident: number): void {\n this._oscParser.clearHandler(ident);\n }\n public setOscHandlerFallback(handler: OscFallbackHandlerType): void {\n this._oscParser.setHandlerFallback(handler);\n }\n\n public setErrorHandler(callback: (state: IParsingState) => IParsingState): void {\n this._errorHandler = callback;\n }\n public clearErrorHandler(): void {\n this._errorHandler = this._errorHandlerFb;\n }\n\n /**\n * Reset parser to initial values.\n *\n * This can also be used to lift the improper continuation error condition\n * when dealing with async handlers. Use this only as a last resort to silence\n * that error when the terminal has no pending data to be processed. Note that\n * the interrupted async handler might continue its work in the future messing\n * up the terminal state even further.\n */\n public reset(): void {\n this.currentState = this.initialState;\n this._oscParser.reset();\n this._dcsParser.reset();\n this._params.reset();\n this._params.addParam(0); // ZDM\n this._collect = 0;\n this.precedingJoinState = 0;\n // abort pending continuation from async handler\n // Here the RESET type indicates, that the next parse call will\n // ignore any saved stack, instead continues sync with next codepoint from GROUND\n if (this._parseStack.state !== ParserStackType.NONE) {\n this._parseStack.state = ParserStackType.RESET;\n this._parseStack.handlers = []; // also release handlers ref\n }\n }\n\n /**\n * Async parse support.\n */\n protected _preserveStack(\n state: ParserStackType,\n handlers: ResumableHandlersType,\n handlerPos: number,\n transition: number,\n chunkPos: number\n ): void {\n this._parseStack.state = state;\n this._parseStack.handlers = handlers;\n this._parseStack.handlerPos = handlerPos;\n this._parseStack.transition = transition;\n this._parseStack.chunkPos = chunkPos;\n }\n\n /**\n * Parse UTF32 codepoints in `data` up to `length`.\n *\n * Note: For several actions with high data load the parsing is optimized\n * by using local read ahead loops with hardcoded conditions to\n * avoid costly table lookups. Make sure that any change of table values\n * will be reflected in the loop conditions as well and vice versa.\n * Affected states/actions:\n * - GROUND:PRINT\n * - CSI_PARAM:PARAM\n * - DCS_PARAM:PARAM\n * - OSC_STRING:OSC_PUT\n * - DCS_PASSTHROUGH:DCS_PUT\n *\n * Note on asynchronous handler support:\n * Any handler returning a promise will be treated as asynchronous.\n * To keep the in-band blocking working for async handlers, `parse` pauses execution,\n * creates a stack save and returns the promise to the caller.\n * For proper continuation of the paused state it is important\n * to await the promise resolving. On resolve the parse must be repeated\n * with the same chunk of data and the resolved value in `promiseResult`\n * until no promise is returned.\n *\n * Important: With only sync handlers defined, parsing is completely synchronous as well.\n * As soon as an async handler is involved, synchronous parsing is not possible anymore.\n *\n * Boilerplate for proper parsing of multiple chunks with async handlers:\n *\n * ```typescript\n * async function parseMultipleChunks(chunks: Uint32Array[]): Promise {\n * for (const chunk of chunks) {\n * let result: void | Promise;\n * let prev: boolean | undefined;\n * while (result = parser.parse(chunk, chunk.length, prev)) {\n * prev = await result;\n * }\n * }\n * // finished parsing all chunks...\n * }\n * ```\n */\n public parse(data: Uint32Array, length: number, promiseResult?: boolean): void | Promise {\n let code = 0;\n let transition = 0;\n let start = 0;\n let handlerResult: void | boolean | Promise;\n\n // resume from async handler\n if (this._parseStack.state) {\n // allow sync parser reset even in continuation mode\n // Note: can be used to recover parser from improper continuation error below\n if (this._parseStack.state === ParserStackType.RESET) {\n this._parseStack.state = ParserStackType.NONE;\n start = this._parseStack.chunkPos + 1; // continue with next codepoint in GROUND\n } else {\n if (promiseResult === undefined || this._parseStack.state === ParserStackType.FAIL) {\n /**\n * Reject further parsing on improper continuation after pausing. This is a really bad\n * condition with screwed up execution order and prolly messed up terminal state,\n * therefore we exit hard with an exception and reject any further parsing.\n *\n * Note: With `Terminal.write` usage this exception should never occur, as the top level\n * calls are guaranteed to handle async conditions properly. If you ever encounter this\n * exception in your terminal integration it indicates, that you injected data chunks to\n * `InputHandler.parse` or `EscapeSequenceParser.parse` synchronously without waiting for\n * continuation of a running async handler.\n *\n * It is possible to get rid of this error by calling `reset`. But dont rely on that, as\n * the pending async handler still might mess up the terminal later. Instead fix the\n * faulty async handling, so this error will not be thrown anymore.\n */\n this._parseStack.state = ParserStackType.FAIL;\n throw new Error('improper continuation due to previous async handler, giving up parsing');\n }\n\n // we have to resume the old handler loop if:\n // - return value of the promise was `false`\n // - handlers are not exhausted yet\n const handlers = this._parseStack.handlers;\n let handlerPos = this._parseStack.handlerPos - 1;\n switch (this._parseStack.state) {\n case ParserStackType.CSI:\n if (promiseResult === false && handlerPos > -1) {\n for (; handlerPos >= 0; handlerPos--) {\n handlerResult = (handlers as CsiHandlerType[])[handlerPos](this._params);\n if (handlerResult === true) {\n break;\n } else if (handlerResult instanceof Promise) {\n this._parseStack.handlerPos = handlerPos;\n return handlerResult;\n }\n }\n }\n this._parseStack.handlers = [];\n break;\n case ParserStackType.ESC:\n if (promiseResult === false && handlerPos > -1) {\n for (; handlerPos >= 0; handlerPos--) {\n handlerResult = (handlers as EscHandlerType[])[handlerPos]();\n if (handlerResult === true) {\n break;\n } else if (handlerResult instanceof Promise) {\n this._parseStack.handlerPos = handlerPos;\n return handlerResult;\n }\n }\n }\n this._parseStack.handlers = [];\n break;\n case ParserStackType.DCS:\n code = data[this._parseStack.chunkPos];\n handlerResult = this._dcsParser.unhook(code !== 0x18 && code !== 0x1a, promiseResult);\n if (handlerResult) {\n return handlerResult;\n }\n if (code === 0x1b) this._parseStack.transition |= ParserState.ESCAPE;\n this._params.reset();\n this._params.addParam(0); // ZDM\n this._collect = 0;\n break;\n case ParserStackType.OSC:\n code = data[this._parseStack.chunkPos];\n handlerResult = this._oscParser.end(code !== 0x18 && code !== 0x1a, promiseResult);\n if (handlerResult) {\n return handlerResult;\n }\n if (code === 0x1b) this._parseStack.transition |= ParserState.ESCAPE;\n this._params.reset();\n this._params.addParam(0); // ZDM\n this._collect = 0;\n break;\n }\n // cleanup before continuing with the main sync loop\n this._parseStack.state = ParserStackType.NONE;\n start = this._parseStack.chunkPos + 1;\n this.precedingJoinState = 0;\n this.currentState = this._parseStack.transition & TableAccess.TRANSITION_STATE_MASK;\n }\n }\n\n // continue with main sync loop\n\n // process input string\n for (let i = start; i < length; ++i) {\n code = data[i];\n\n // normal transition & action lookup\n transition = this._transitions.table[this.currentState << TableAccess.INDEX_STATE_SHIFT | (code < 0xa0 ? code : NON_ASCII_PRINTABLE)];\n switch (transition >> TableAccess.TRANSITION_ACTION_SHIFT) {\n case ParserAction.PRINT:\n // read ahead with loop unrolling\n // Note: 0x20 (SP) is included, 0x7F (DEL) is excluded\n for (let j = i + 1; ; ++j) {\n if (j >= length || (code = data[j]) < 0x20 || (code > 0x7e && code < NON_ASCII_PRINTABLE)) {\n this._printHandler(data, i, j);\n i = j - 1;\n break;\n }\n if (++j >= length || (code = data[j]) < 0x20 || (code > 0x7e && code < NON_ASCII_PRINTABLE)) {\n this._printHandler(data, i, j);\n i = j - 1;\n break;\n }\n if (++j >= length || (code = data[j]) < 0x20 || (code > 0x7e && code < NON_ASCII_PRINTABLE)) {\n this._printHandler(data, i, j);\n i = j - 1;\n break;\n }\n if (++j >= length || (code = data[j]) < 0x20 || (code > 0x7e && code < NON_ASCII_PRINTABLE)) {\n this._printHandler(data, i, j);\n i = j - 1;\n break;\n }\n }\n break;\n case ParserAction.EXECUTE:\n if (this._executeHandlers[code]) this._executeHandlers[code]();\n else this._executeHandlerFb(code);\n this.precedingJoinState = 0;\n break;\n case ParserAction.IGNORE:\n break;\n case ParserAction.ERROR:\n const inject: IParsingState = this._errorHandler(\n {\n position: i,\n code,\n currentState: this.currentState,\n collect: this._collect,\n params: this._params,\n abort: false\n });\n if (inject.abort) return;\n // inject values: currently not implemented\n break;\n case ParserAction.CSI_DISPATCH:\n // Trigger CSI Handler\n const handlers = this._csiHandlers[this._collect << 8 | code];\n let j = handlers ? handlers.length - 1 : -1;\n for (; j >= 0; j--) {\n // true means success and to stop bubbling\n // a promise indicates an async handler that needs to finish before progressing\n handlerResult = handlers[j](this._params);\n if (handlerResult === true) {\n break;\n } else if (handlerResult instanceof Promise) {\n this._preserveStack(ParserStackType.CSI, handlers, j, transition, i);\n return handlerResult;\n }\n }\n if (j < 0) {\n this._csiHandlerFb(this._collect << 8 | code, this._params);\n }\n this.precedingJoinState = 0;\n break;\n case ParserAction.PARAM:\n // inner loop: digits (0x30 - 0x39) and ; (0x3b) and : (0x3a)\n do {\n switch (code) {\n case 0x3b:\n this._params.addParam(0); // ZDM\n break;\n case 0x3a:\n this._params.addSubParam(-1);\n break;\n default: // 0x30 - 0x39\n this._params.addDigit(code - 48);\n }\n } while (++i < length && (code = data[i]) > 0x2f && code < 0x3c);\n i--;\n break;\n case ParserAction.COLLECT:\n this._collect <<= 8;\n this._collect |= code;\n break;\n case ParserAction.ESC_DISPATCH:\n const handlersEsc = this._escHandlers[this._collect << 8 | code];\n let jj = handlersEsc ? handlersEsc.length - 1 : -1;\n for (; jj >= 0; jj--) {\n // true means success and to stop bubbling\n // a promise indicates an async handler that needs to finish before progressing\n handlerResult = handlersEsc[jj]();\n if (handlerResult === true) {\n break;\n } else if (handlerResult instanceof Promise) {\n this._preserveStack(ParserStackType.ESC, handlersEsc, jj, transition, i);\n return handlerResult;\n }\n }\n if (jj < 0) {\n this._escHandlerFb(this._collect << 8 | code);\n }\n this.precedingJoinState = 0;\n break;\n case ParserAction.CLEAR:\n this._params.reset();\n this._params.addParam(0); // ZDM\n this._collect = 0;\n break;\n case ParserAction.DCS_HOOK:\n this._dcsParser.hook(this._collect << 8 | code, this._params);\n break;\n case ParserAction.DCS_PUT:\n // inner loop - exit DCS_PUT: 0x18, 0x1a, 0x1b, 0x7f, 0x80 - 0x9f\n // unhook triggered by: 0x1b, 0x9c (success) and 0x18, 0x1a (abort)\n for (let j = i + 1; ; ++j) {\n if (j >= length || (code = data[j]) === 0x18 || code === 0x1a || code === 0x1b || (code > 0x7f && code < NON_ASCII_PRINTABLE)) {\n this._dcsParser.put(data, i, j);\n i = j - 1;\n break;\n }\n }\n break;\n case ParserAction.DCS_UNHOOK:\n handlerResult = this._dcsParser.unhook(code !== 0x18 && code !== 0x1a);\n if (handlerResult) {\n this._preserveStack(ParserStackType.DCS, [], 0, transition, i);\n return handlerResult;\n }\n if (code === 0x1b) transition |= ParserState.ESCAPE;\n this._params.reset();\n this._params.addParam(0); // ZDM\n this._collect = 0;\n this.precedingJoinState = 0;\n break;\n case ParserAction.OSC_START:\n this._oscParser.start();\n break;\n case ParserAction.OSC_PUT:\n // inner loop: 0x20 (SP) included, 0x7F (DEL) included\n for (let j = i + 1; ; j++) {\n if (j >= length || (code = data[j]) < 0x20 || (code > 0x7f && code < NON_ASCII_PRINTABLE)) {\n this._oscParser.put(data, i, j);\n i = j - 1;\n break;\n }\n }\n break;\n case ParserAction.OSC_END:\n handlerResult = this._oscParser.end(code !== 0x18 && code !== 0x1a);\n if (handlerResult) {\n this._preserveStack(ParserStackType.OSC, [], 0, transition, i);\n return handlerResult;\n }\n if (code === 0x1b) transition |= ParserState.ESCAPE;\n this._params.reset();\n this._params.addParam(0); // ZDM\n this._collect = 0;\n this.precedingJoinState = 0;\n break;\n }\n this.currentState = transition & TableAccess.TRANSITION_STATE_MASK;\n }\n }\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IOscHandler, IHandlerCollection, OscFallbackHandlerType, IOscParser, ISubParserStackState } from 'common/parser/Types';\nimport { OscState, PAYLOAD_LIMIT } from 'common/parser/Constants';\nimport { utf32ToString } from 'common/input/TextDecoder';\nimport { IDisposable } from 'common/Types';\n\nconst EMPTY_HANDLERS: IOscHandler[] = [];\n\nexport class OscParser implements IOscParser {\n private _state = OscState.START;\n private _active = EMPTY_HANDLERS;\n private _id = -1;\n private _handlers: IHandlerCollection = Object.create(null);\n private _handlerFb: OscFallbackHandlerType = () => { };\n private _stack: ISubParserStackState = {\n paused: false,\n loopPosition: 0,\n fallThrough: false\n };\n\n public registerHandler(ident: number, handler: IOscHandler): IDisposable {\n if (this._handlers[ident] === undefined) {\n this._handlers[ident] = [];\n }\n const handlerList = this._handlers[ident];\n handlerList.push(handler);\n return {\n dispose: () => {\n const handlerIndex = handlerList.indexOf(handler);\n if (handlerIndex !== -1) {\n handlerList.splice(handlerIndex, 1);\n }\n }\n };\n }\n public clearHandler(ident: number): void {\n if (this._handlers[ident]) delete this._handlers[ident];\n }\n public setHandlerFallback(handler: OscFallbackHandlerType): void {\n this._handlerFb = handler;\n }\n\n public dispose(): void {\n this._handlers = Object.create(null);\n this._handlerFb = () => { };\n this._active = EMPTY_HANDLERS;\n }\n\n public reset(): void {\n // force cleanup handlers if payload was already sent\n if (this._state === OscState.PAYLOAD) {\n for (let j = this._stack.paused ? this._stack.loopPosition - 1 : this._active.length - 1; j >= 0; --j) {\n this._active[j].end(false);\n }\n }\n this._stack.paused = false;\n this._active = EMPTY_HANDLERS;\n this._id = -1;\n this._state = OscState.START;\n }\n\n private _start(): void {\n this._active = this._handlers[this._id] || EMPTY_HANDLERS;\n if (!this._active.length) {\n this._handlerFb(this._id, 'START');\n } else {\n for (let j = this._active.length - 1; j >= 0; j--) {\n this._active[j].start();\n }\n }\n }\n\n private _put(data: Uint32Array, start: number, end: number): void {\n if (!this._active.length) {\n this._handlerFb(this._id, 'PUT', utf32ToString(data, start, end));\n } else {\n for (let j = this._active.length - 1; j >= 0; j--) {\n this._active[j].put(data, start, end);\n }\n }\n }\n\n public start(): void {\n // always reset leftover handlers\n this.reset();\n this._state = OscState.ID;\n }\n\n /**\n * Put data to current OSC command.\n * Expects the identifier of the OSC command in the form\n * OSC id ; payload ST/BEL\n * Payload chunks are not further processed and get\n * directly passed to the handlers.\n */\n public put(data: Uint32Array, start: number, end: number): void {\n if (this._state === OscState.ABORT) {\n return;\n }\n if (this._state === OscState.ID) {\n while (start < end) {\n const code = data[start++];\n if (code === 0x3b) {\n this._state = OscState.PAYLOAD;\n this._start();\n break;\n }\n if (code < 0x30 || 0x39 < code) {\n this._state = OscState.ABORT;\n return;\n }\n if (this._id === -1) {\n this._id = 0;\n }\n this._id = this._id * 10 + code - 48;\n }\n }\n if (this._state === OscState.PAYLOAD && end - start > 0) {\n this._put(data, start, end);\n }\n }\n\n /**\n * Indicates end of an OSC command.\n * Whether the OSC got aborted or finished normally\n * is indicated by `success`.\n */\n public end(success: boolean, promiseResult: boolean = true): void | Promise {\n if (this._state === OscState.START) {\n return;\n }\n // do nothing if command was faulty\n if (this._state !== OscState.ABORT) {\n // if we are still in ID state and get an early end\n // means that the command has no payload thus we still have\n // to announce START and send END right after\n if (this._state === OscState.ID) {\n this._start();\n }\n\n if (!this._active.length) {\n this._handlerFb(this._id, 'END', success);\n } else {\n let handlerResult: boolean | Promise = false;\n let j = this._active.length - 1;\n let fallThrough = false;\n if (this._stack.paused) {\n j = this._stack.loopPosition - 1;\n handlerResult = promiseResult;\n fallThrough = this._stack.fallThrough;\n this._stack.paused = false;\n }\n if (!fallThrough && handlerResult === false) {\n for (; j >= 0; j--) {\n handlerResult = this._active[j].end(success);\n if (handlerResult === true) {\n break;\n } else if (handlerResult instanceof Promise) {\n this._stack.paused = true;\n this._stack.loopPosition = j;\n this._stack.fallThrough = false;\n return handlerResult;\n }\n }\n j--;\n }\n // cleanup left over handlers\n // we always have to call .end for proper cleanup,\n // here we use `success` to indicate whether a handler should execute\n for (; j >= 0; j--) {\n handlerResult = this._active[j].end(false);\n if (handlerResult instanceof Promise) {\n this._stack.paused = true;\n this._stack.loopPosition = j;\n this._stack.fallThrough = true;\n return handlerResult;\n }\n }\n }\n\n }\n this._active = EMPTY_HANDLERS;\n this._id = -1;\n this._state = OscState.START;\n }\n}\n\n/**\n * Convenient class to allow attaching string based handler functions\n * as OSC handlers.\n */\nexport class OscHandler implements IOscHandler {\n private _data = '';\n private _hitLimit: boolean = false;\n\n constructor(private _handler: (data: string) => boolean | Promise) { }\n\n public start(): void {\n this._data = '';\n this._hitLimit = false;\n }\n\n public put(data: Uint32Array, start: number, end: number): void {\n if (this._hitLimit) {\n return;\n }\n this._data += utf32ToString(data, start, end);\n if (this._data.length > PAYLOAD_LIMIT) {\n this._data = '';\n this._hitLimit = true;\n }\n }\n\n public end(success: boolean): boolean | Promise {\n let ret: boolean | Promise = false;\n if (this._hitLimit) {\n ret = false;\n } else if (success) {\n ret = this._handler(this._data);\n if (ret instanceof Promise) {\n // need to hold data until `ret` got resolved\n // dont care for errors, data will be freed anyway on next start\n return ret.then(res => {\n this._data = '';\n this._hitLimit = false;\n return res;\n });\n }\n }\n this._data = '';\n this._hitLimit = false;\n return ret;\n }\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\nimport { IParams, ParamsArray } from 'common/parser/Types';\n\n// max value supported for a single param/subparam (clamped to positive int32 range)\nconst MAX_VALUE = 0x7FFFFFFF;\n// max allowed subparams for a single sequence (hardcoded limitation)\nconst MAX_SUBPARAMS = 256;\n\n/**\n * Params storage class.\n * This type is used by the parser to accumulate sequence parameters and sub parameters\n * and transmit them to the input handler actions.\n *\n * NOTES:\n * - params object for action handlers is borrowed, use `.toArray` or `.clone` to get a copy\n * - never read beyond `params.length - 1` (likely to contain arbitrary data)\n * - `.getSubParams` returns a borrowed typed array, use `.getSubParamsAll` for cloned sub params\n * - hardcoded limitations:\n * - max. value for a single (sub) param is 2^31 - 1 (greater values are clamped to that)\n * - max. 256 sub params possible\n * - negative values are not allowed beside -1 (placeholder for default value)\n *\n * About ZDM (Zero Default Mode):\n * ZDM is not orchestrated by this class. If the parser is in ZDM,\n * it should add 0 for empty params, otherwise -1. This does not apply\n * to subparams, empty subparams should always be added with -1.\n */\nexport class Params implements IParams {\n // params store and length\n public params: Int32Array;\n public length: number;\n\n // sub params store and length\n protected _subParams: Int32Array;\n protected _subParamsLength: number;\n\n // sub params offsets from param: param idx --> [start, end] offset\n private _subParamsIdx: Uint16Array;\n private _rejectDigits: boolean;\n private _rejectSubDigits: boolean;\n private _digitIsSub: boolean;\n\n /**\n * Create a `Params` type from JS array representation.\n */\n public static fromArray(values: ParamsArray): Params {\n const params = new Params();\n if (!values.length) {\n return params;\n }\n // skip leading sub params\n for (let i = (Array.isArray(values[0])) ? 1 : 0; i < values.length; ++i) {\n const value = values[i];\n if (Array.isArray(value)) {\n for (let k = 0; k < value.length; ++k) {\n params.addSubParam(value[k]);\n }\n } else {\n params.addParam(value);\n }\n }\n return params;\n }\n\n /**\n * @param maxLength max length of storable parameters\n * @param maxSubParamsLength max length of storable sub parameters\n */\n constructor(public maxLength: number = 32, public maxSubParamsLength: number = 32) {\n if (maxSubParamsLength > MAX_SUBPARAMS) {\n throw new Error('maxSubParamsLength must not be greater than 256');\n }\n this.params = new Int32Array(maxLength);\n this.length = 0;\n this._subParams = new Int32Array(maxSubParamsLength);\n this._subParamsLength = 0;\n this._subParamsIdx = new Uint16Array(maxLength);\n this._rejectDigits = false;\n this._rejectSubDigits = false;\n this._digitIsSub = false;\n }\n\n /**\n * Clone object.\n */\n public clone(): Params {\n const newParams = new Params(this.maxLength, this.maxSubParamsLength);\n newParams.params.set(this.params);\n newParams.length = this.length;\n newParams._subParams.set(this._subParams);\n newParams._subParamsLength = this._subParamsLength;\n newParams._subParamsIdx.set(this._subParamsIdx);\n newParams._rejectDigits = this._rejectDigits;\n newParams._rejectSubDigits = this._rejectSubDigits;\n newParams._digitIsSub = this._digitIsSub;\n return newParams;\n }\n\n /**\n * Get a JS array representation of the current parameters and sub parameters.\n * The array is structured as follows:\n * sequence: \"1;2:3:4;5::6\"\n * array : [1, 2, [3, 4], 5, [-1, 6]]\n */\n public toArray(): ParamsArray {\n const res: ParamsArray = [];\n for (let i = 0; i < this.length; ++i) {\n res.push(this.params[i]);\n const start = this._subParamsIdx[i] >> 8;\n const end = this._subParamsIdx[i] & 0xFF;\n if (end - start > 0) {\n res.push(Array.prototype.slice.call(this._subParams, start, end));\n }\n }\n return res;\n }\n\n /**\n * Reset to initial empty state.\n */\n public reset(): void {\n this.length = 0;\n this._subParamsLength = 0;\n this._rejectDigits = false;\n this._rejectSubDigits = false;\n this._digitIsSub = false;\n }\n\n /**\n * Add a parameter value.\n * `Params` only stores up to `maxLength` parameters, any later\n * parameter will be ignored.\n * Note: VT devices only stored up to 16 values, xterm seems to\n * store up to 30.\n */\n public addParam(value: number): void {\n this._digitIsSub = false;\n if (this.length >= this.maxLength) {\n this._rejectDigits = true;\n return;\n }\n if (value < -1) {\n throw new Error('values lesser than -1 are not allowed');\n }\n this._subParamsIdx[this.length] = this._subParamsLength << 8 | this._subParamsLength;\n this.params[this.length++] = value > MAX_VALUE ? MAX_VALUE : value;\n }\n\n /**\n * Add a sub parameter value.\n * The sub parameter is automatically associated with the last parameter value.\n * Thus it is not possible to add a subparameter without any parameter added yet.\n * `Params` only stores up to `subParamsLength` sub parameters, any later\n * sub parameter will be ignored.\n */\n public addSubParam(value: number): void {\n this._digitIsSub = true;\n if (!this.length) {\n return;\n }\n if (this._rejectDigits || this._subParamsLength >= this.maxSubParamsLength) {\n this._rejectSubDigits = true;\n return;\n }\n if (value < -1) {\n throw new Error('values lesser than -1 are not allowed');\n }\n this._subParams[this._subParamsLength++] = value > MAX_VALUE ? MAX_VALUE : value;\n this._subParamsIdx[this.length - 1]++;\n }\n\n /**\n * Whether parameter at index `idx` has sub parameters.\n */\n public hasSubParams(idx: number): boolean {\n return ((this._subParamsIdx[idx] & 0xFF) - (this._subParamsIdx[idx] >> 8) > 0);\n }\n\n /**\n * Return sub parameters for parameter at index `idx`.\n * Note: The values are borrowed, thus you need to copy\n * the values if you need to hold them in nonlocal scope.\n */\n public getSubParams(idx: number): Int32Array | null {\n const start = this._subParamsIdx[idx] >> 8;\n const end = this._subParamsIdx[idx] & 0xFF;\n if (end - start > 0) {\n return this._subParams.subarray(start, end);\n }\n return null;\n }\n\n /**\n * Return all sub parameters as {idx: subparams} mapping.\n * Note: The values are not borrowed.\n */\n public getSubParamsAll(): {[idx: number]: Int32Array} {\n const result: {[idx: number]: Int32Array} = {};\n for (let i = 0; i < this.length; ++i) {\n const start = this._subParamsIdx[i] >> 8;\n const end = this._subParamsIdx[i] & 0xFF;\n if (end - start > 0) {\n result[i] = this._subParams.slice(start, end);\n }\n }\n return result;\n }\n\n /**\n * Add a single digit value to current parameter.\n * This is used by the parser to account digits on a char by char basis.\n */\n public addDigit(value: number): void {\n let length;\n if (this._rejectDigits\n || !(length = this._digitIsSub ? this._subParamsLength : this.length)\n || (this._digitIsSub && this._rejectSubDigits)\n ) {\n return;\n }\n\n const store = this._digitIsSub ? this._subParams : this.params;\n const cur = store[length - 1];\n store[length - 1] = ~cur ? Math.min(cur * 10 + value, MAX_VALUE) : value;\n }\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { ITerminalAddon, IDisposable, Terminal } from '@xterm/xterm';\n\nexport interface ILoadedAddon {\n instance: ITerminalAddon;\n dispose: () => void;\n isDisposed: boolean;\n}\n\nexport class AddonManager implements IDisposable {\n protected _addons: ILoadedAddon[] = [];\n\n public dispose(): void {\n for (let i = this._addons.length - 1; i >= 0; i--) {\n this._addons[i].instance.dispose();\n }\n }\n\n public loadAddon(terminal: Terminal, instance: ITerminalAddon): void {\n const loadedAddon: ILoadedAddon = {\n instance,\n dispose: instance.dispose,\n isDisposed: false\n };\n this._addons.push(loadedAddon);\n instance.dispose = () => this._wrappedAddonDispose(loadedAddon);\n instance.activate(terminal as any);\n }\n\n private _wrappedAddonDispose(loadedAddon: ILoadedAddon): void {\n if (loadedAddon.isDisposed) {\n // Do nothing if already disposed\n return;\n }\n let index = -1;\n for (let i = 0; i < this._addons.length; i++) {\n if (this._addons[i] === loadedAddon) {\n index = i;\n break;\n }\n }\n if (index === -1) {\n throw new Error('Could not dispose an addon that has not been loaded');\n }\n loadedAddon.isDisposed = true;\n loadedAddon.dispose.apply(loadedAddon.instance);\n this._addons.splice(index, 1);\n }\n}\n","/**\n * Copyright (c) 2021 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IBuffer as IBufferApi, IBufferLine as IBufferLineApi, IBufferCell as IBufferCellApi } from '@xterm/xterm';\nimport { IBuffer } from 'common/buffer/Types';\nimport { BufferLineApiView } from 'common/public/BufferLineApiView';\nimport { CellData } from 'common/buffer/CellData';\n\nexport class BufferApiView implements IBufferApi {\n constructor(\n private _buffer: IBuffer,\n public readonly type: 'normal' | 'alternate'\n ) { }\n\n public init(buffer: IBuffer): BufferApiView {\n this._buffer = buffer;\n return this;\n }\n\n public get cursorY(): number { return this._buffer.y; }\n public get cursorX(): number { return this._buffer.x; }\n public get viewportY(): number { return this._buffer.ydisp; }\n public get baseY(): number { return this._buffer.ybase; }\n public get length(): number { return this._buffer.lines.length; }\n public getLine(y: number): IBufferLineApi | undefined {\n const line = this._buffer.lines.get(y);\n if (!line) {\n return undefined;\n }\n return new BufferLineApiView(line);\n }\n public getNullCell(): IBufferCellApi { return new CellData(); }\n}\n","/**\n * Copyright (c) 2021 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { CellData } from 'common/buffer/CellData';\nimport { IBufferLine, ICellData } from 'common/Types';\nimport { IBufferCell as IBufferCellApi, IBufferLine as IBufferLineApi } from '@xterm/xterm';\n\nexport class BufferLineApiView implements IBufferLineApi {\n constructor(private _line: IBufferLine) { }\n\n public get isWrapped(): boolean { return this._line.isWrapped; }\n public get length(): number { return this._line.length; }\n public getCell(x: number, cell?: IBufferCellApi): IBufferCellApi | undefined {\n if (x < 0 || x >= this._line.length) {\n return undefined;\n }\n\n if (cell) {\n this._line.loadCell(x, cell as ICellData);\n return cell;\n }\n return this._line.loadCell(x, new CellData());\n }\n public translateToString(trimRight?: boolean, startColumn?: number, endColumn?: number): string {\n return this._line.translateToString(trimRight, startColumn, endColumn);\n }\n}\n","/**\n * Copyright (c) 2021 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IBuffer as IBufferApi, IBufferNamespace as IBufferNamespaceApi } from '@xterm/xterm';\nimport { BufferApiView } from 'common/public/BufferApiView';\nimport { ICoreTerminal } from 'common/Types';\nimport { Disposable } from 'vs/base/common/lifecycle';\nimport { Emitter } from 'vs/base/common/event';\n\nexport class BufferNamespaceApi extends Disposable implements IBufferNamespaceApi {\n private _normal: BufferApiView;\n private _alternate: BufferApiView;\n\n private readonly _onBufferChange = this._register(new Emitter());\n public readonly onBufferChange = this._onBufferChange.event;\n\n constructor(private _core: ICoreTerminal) {\n super();\n this._normal = new BufferApiView(this._core.buffers.normal, 'normal');\n this._alternate = new BufferApiView(this._core.buffers.alt, 'alternate');\n this._core.buffers.onBufferActivate(() => this._onBufferChange.fire(this.active));\n }\n public get active(): IBufferApi {\n if (this._core.buffers.active === this._core.buffers.normal) { return this.normal; }\n if (this._core.buffers.active === this._core.buffers.alt) { return this.alternate; }\n throw new Error('Active buffer is neither normal nor alternate');\n }\n public get normal(): IBufferApi {\n return this._normal.init(this._core.buffers.normal);\n }\n public get alternate(): IBufferApi {\n return this._alternate.init(this._core.buffers.alt);\n }\n}\n","/**\n * Copyright (c) 2021 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IParams } from 'common/parser/Types';\nimport { IDisposable, IFunctionIdentifier, IParser } from '@xterm/xterm';\nimport { ICoreTerminal } from 'common/Types';\n\nexport class ParserApi implements IParser {\n constructor(private _core: ICoreTerminal) { }\n\n public registerCsiHandler(id: IFunctionIdentifier, callback: (params: (number | number[])[]) => boolean | Promise): IDisposable {\n return this._core.registerCsiHandler(id, (params: IParams) => callback(params.toArray()));\n }\n public addCsiHandler(id: IFunctionIdentifier, callback: (params: (number | number[])[]) => boolean | Promise): IDisposable {\n return this.registerCsiHandler(id, callback);\n }\n public registerDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: (number | number[])[]) => boolean | Promise): IDisposable {\n return this._core.registerDcsHandler(id, (data: string, params: IParams) => callback(data, params.toArray()));\n }\n public addDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: (number | number[])[]) => boolean | Promise): IDisposable {\n return this.registerDcsHandler(id, callback);\n }\n public registerEscHandler(id: IFunctionIdentifier, handler: () => boolean | Promise): IDisposable {\n return this._core.registerEscHandler(id, handler);\n }\n public addEscHandler(id: IFunctionIdentifier, handler: () => boolean | Promise): IDisposable {\n return this.registerEscHandler(id, handler);\n }\n public registerOscHandler(ident: number, callback: (data: string) => boolean | Promise): IDisposable {\n return this._core.registerOscHandler(ident, callback);\n }\n public addOscHandler(ident: number, callback: (data: string) => boolean | Promise): IDisposable {\n return this.registerOscHandler(ident, callback);\n }\n}\n","/**\n * Copyright (c) 2021 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { ICoreTerminal } from 'common/Types';\nimport { IUnicodeHandling, IUnicodeVersionProvider } from '@xterm/xterm';\n\nexport class UnicodeApi implements IUnicodeHandling {\n constructor(private _core: ICoreTerminal) { }\n\n public register(provider: IUnicodeVersionProvider): void {\n this._core.unicodeService.register(provider);\n }\n\n public get versions(): string[] {\n return this._core.unicodeService.versions;\n }\n\n public get activeVersion(): string {\n return this._core.unicodeService.activeVersion;\n }\n\n public set activeVersion(version: string) {\n this._core.unicodeService.activeVersion = version;\n }\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { Disposable } from 'vs/base/common/lifecycle';\nimport { IAttributeData, IBufferLine } from 'common/Types';\nimport { BufferSet } from 'common/buffer/BufferSet';\nimport { IBuffer, IBufferSet } from 'common/buffer/Types';\nimport { IBufferService, IOptionsService, type IBufferResizeEvent } from 'common/services/Services';\nimport { Emitter } from 'vs/base/common/event';\n\nexport const MINIMUM_COLS = 2; // Less than 2 can mess with wide chars\nexport const MINIMUM_ROWS = 1;\n\nexport class BufferService extends Disposable implements IBufferService {\n public serviceBrand: any;\n\n public cols: number;\n public rows: number;\n public buffers: IBufferSet;\n /** Whether the user is scrolling (locks the scroll position) */\n public isUserScrolling: boolean = false;\n\n private readonly _onResize = this._register(new Emitter());\n public readonly onResize = this._onResize.event;\n private readonly _onScroll = this._register(new Emitter());\n public readonly onScroll = this._onScroll.event;\n\n public get buffer(): IBuffer { return this.buffers.active; }\n\n /** An IBufferline to clone/copy from for new blank lines */\n private _cachedBlankLine: IBufferLine | undefined;\n\n constructor(@IOptionsService optionsService: IOptionsService) {\n super();\n this.cols = Math.max(optionsService.rawOptions.cols || 0, MINIMUM_COLS);\n this.rows = Math.max(optionsService.rawOptions.rows || 0, MINIMUM_ROWS);\n this.buffers = this._register(new BufferSet(optionsService, this));\n this._register(this.buffers.onBufferActivate(e => {\n this._onScroll.fire(e.activeBuffer.ydisp);\n }));\n }\n\n public resize(cols: number, rows: number): void {\n const colsChanged = this.cols !== cols;\n const rowsChanged = this.rows !== rows;\n this.cols = cols;\n this.rows = rows;\n this.buffers.resize(cols, rows);\n this._onResize.fire({ cols, rows, colsChanged, rowsChanged });\n }\n\n public reset(): void {\n this.buffers.reset();\n this.isUserScrolling = false;\n }\n\n /**\n * Scroll the terminal down 1 row, creating a blank line.\n * @param eraseAttr The attribute data to use the for blank line.\n * @param isWrapped Whether the new line is wrapped from the previous line.\n */\n public scroll(eraseAttr: IAttributeData, isWrapped: boolean = false): void {\n const buffer = this.buffer;\n\n let newLine: IBufferLine | undefined;\n newLine = this._cachedBlankLine;\n if (!newLine || newLine.length !== this.cols || newLine.getFg(0) !== eraseAttr.fg || newLine.getBg(0) !== eraseAttr.bg) {\n newLine = buffer.getBlankLine(eraseAttr, isWrapped);\n this._cachedBlankLine = newLine;\n }\n newLine.isWrapped = isWrapped;\n\n const topRow = buffer.ybase + buffer.scrollTop;\n const bottomRow = buffer.ybase + buffer.scrollBottom;\n\n if (buffer.scrollTop === 0) {\n // Determine whether the buffer is going to be trimmed after insertion.\n const willBufferBeTrimmed = buffer.lines.isFull;\n\n // Insert the line using the fastest method\n if (bottomRow === buffer.lines.length - 1) {\n if (willBufferBeTrimmed) {\n buffer.lines.recycle().copyFrom(newLine);\n } else {\n buffer.lines.push(newLine.clone());\n }\n } else {\n buffer.lines.splice(bottomRow + 1, 0, newLine.clone());\n }\n\n // Only adjust ybase and ydisp when the buffer is not trimmed\n if (!willBufferBeTrimmed) {\n buffer.ybase++;\n // Only scroll the ydisp with ybase if the user has not scrolled up\n if (!this.isUserScrolling) {\n buffer.ydisp++;\n }\n } else {\n // When the buffer is full and the user has scrolled up, keep the text\n // stable unless ydisp is right at the top\n if (this.isUserScrolling) {\n buffer.ydisp = Math.max(buffer.ydisp - 1, 0);\n }\n }\n } else {\n // scrollTop is non-zero which means no line will be going to the\n // scrollback, instead we can just shift them in-place.\n const scrollRegionHeight = bottomRow - topRow + 1 /* as it's zero-based */;\n buffer.lines.shiftElements(topRow + 1, scrollRegionHeight - 1, -1);\n buffer.lines.set(bottomRow, newLine.clone());\n }\n\n // Move the viewport to the bottom of the buffer unless the user is\n // scrolling.\n if (!this.isUserScrolling) {\n buffer.ydisp = buffer.ybase;\n }\n\n this._onScroll.fire(buffer.ydisp);\n }\n\n /**\n * Scroll the display of the terminal\n * @param disp The number of lines to scroll down (negative scroll up).\n * @param suppressScrollEvent Don't emit the scroll event as scrollLines. This is used\n * to avoid unwanted events being handled by the viewport when the event was triggered from the\n * viewport originally.\n */\n public scrollLines(disp: number, suppressScrollEvent?: boolean): void {\n const buffer = this.buffer;\n if (disp < 0) {\n if (buffer.ydisp === 0) {\n return;\n }\n this.isUserScrolling = true;\n } else if (disp + buffer.ydisp >= buffer.ybase) {\n this.isUserScrolling = false;\n }\n\n const oldYdisp = buffer.ydisp;\n buffer.ydisp = Math.max(Math.min(buffer.ydisp + disp, buffer.ybase), 0);\n\n // No change occurred, don't trigger scroll/refresh\n if (oldYdisp === buffer.ydisp) {\n return;\n }\n\n if (!suppressScrollEvent) {\n this._onScroll.fire(buffer.ydisp);\n }\n }\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { ICharsetService } from 'common/services/Services';\nimport { ICharset } from 'common/Types';\n\nexport class CharsetService implements ICharsetService {\n public serviceBrand: any;\n\n public charset: ICharset | undefined;\n public glevel: number = 0;\n\n private _charsets: (ICharset | undefined)[] = [];\n\n public reset(): void {\n this.charset = undefined;\n this._charsets = [];\n this.glevel = 0;\n }\n\n public setgLevel(g: number): void {\n this.glevel = g;\n this.charset = this._charsets[g];\n }\n\n public setgCharset(g: number, charset: ICharset | undefined): void {\n this._charsets[g] = charset;\n if (this.glevel === g) {\n this.charset = charset;\n }\n }\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\nimport { IBufferService, ICoreService, ICoreMouseService, IOptionsService } from 'common/services/Services';\nimport { ICoreMouseProtocol, ICoreMouseEvent, CoreMouseEncoding, CoreMouseEventType, CoreMouseButton, CoreMouseAction } from 'common/Types';\nimport { Disposable } from 'vs/base/common/lifecycle';\nimport { Emitter } from 'vs/base/common/event';\n\n/**\n * Supported default protocols.\n */\nconst DEFAULT_PROTOCOLS: { [key: string]: ICoreMouseProtocol } = {\n /**\n * NONE\n * Events: none\n * Modifiers: none\n */\n NONE: {\n events: CoreMouseEventType.NONE,\n restrict: () => false\n },\n /**\n * X10\n * Events: mousedown\n * Modifiers: none\n */\n X10: {\n events: CoreMouseEventType.DOWN,\n restrict: (e: ICoreMouseEvent) => {\n // no wheel, no move, no up\n if (e.button === CoreMouseButton.WHEEL || e.action !== CoreMouseAction.DOWN) {\n return false;\n }\n // no modifiers\n e.ctrl = false;\n e.alt = false;\n e.shift = false;\n return true;\n }\n },\n /**\n * VT200\n * Events: mousedown / mouseup / wheel\n * Modifiers: all\n */\n VT200: {\n events: CoreMouseEventType.DOWN | CoreMouseEventType.UP | CoreMouseEventType.WHEEL,\n restrict: (e: ICoreMouseEvent) => {\n // no move\n if (e.action === CoreMouseAction.MOVE) {\n return false;\n }\n return true;\n }\n },\n /**\n * DRAG\n * Events: mousedown / mouseup / wheel / mousedrag\n * Modifiers: all\n */\n DRAG: {\n events: CoreMouseEventType.DOWN | CoreMouseEventType.UP | CoreMouseEventType.WHEEL | CoreMouseEventType.DRAG,\n restrict: (e: ICoreMouseEvent) => {\n // no move without button\n if (e.action === CoreMouseAction.MOVE && e.button === CoreMouseButton.NONE) {\n return false;\n }\n return true;\n }\n },\n /**\n * ANY\n * Events: all mouse related events\n * Modifiers: all\n */\n ANY: {\n events:\n CoreMouseEventType.DOWN | CoreMouseEventType.UP | CoreMouseEventType.WHEEL\n | CoreMouseEventType.DRAG | CoreMouseEventType.MOVE,\n restrict: (e: ICoreMouseEvent) => true\n }\n};\n\nconst enum Modifiers {\n SHIFT = 4,\n ALT = 8,\n CTRL = 16\n}\n\n// helper for default encoders to generate the event code.\nfunction eventCode(e: ICoreMouseEvent, isSGR: boolean): number {\n let code = (e.ctrl ? Modifiers.CTRL : 0) | (e.shift ? Modifiers.SHIFT : 0) | (e.alt ? Modifiers.ALT : 0);\n if (e.button === CoreMouseButton.WHEEL) {\n code |= 64;\n code |= e.action;\n } else {\n code |= e.button & 3;\n if (e.button & 4) {\n code |= 64;\n }\n if (e.button & 8) {\n code |= 128;\n }\n if (e.action === CoreMouseAction.MOVE) {\n code |= CoreMouseAction.MOVE;\n } else if (e.action === CoreMouseAction.UP && !isSGR) {\n // special case - only SGR can report button on release\n // all others have to go with NONE\n code |= CoreMouseButton.NONE;\n }\n }\n return code;\n}\n\nconst S = String.fromCharCode;\n\n/**\n * Supported default encodings.\n */\nconst DEFAULT_ENCODINGS: { [key: string]: CoreMouseEncoding } = {\n /**\n * DEFAULT - CSI M Pb Px Py\n * Single byte encoding for coords and event code.\n * Can encode values up to 223 (1-based).\n */\n DEFAULT: (e: ICoreMouseEvent) => {\n const params = [eventCode(e, false) + 32, e.col + 32, e.row + 32];\n // supress mouse report if we exceed addressible range\n // Note this is handled differently by emulators\n // - xterm: sends 0;0 coords instead\n // - vte, konsole: no report\n if (params[0] > 255 || params[1] > 255 || params[2] > 255) {\n return '';\n }\n return `\\x1b[M${S(params[0])}${S(params[1])}${S(params[2])}`;\n },\n /**\n * SGR - CSI < Pb ; Px ; Py M|m\n * No encoding limitation.\n * Can report button on release and works with a well formed sequence.\n */\n SGR: (e: ICoreMouseEvent) => {\n const final = (e.action === CoreMouseAction.UP && e.button !== CoreMouseButton.WHEEL) ? 'm' : 'M';\n return `\\x1b[<${eventCode(e, true)};${e.col};${e.row}${final}`;\n },\n SGR_PIXELS: (e: ICoreMouseEvent) => {\n const final = (e.action === CoreMouseAction.UP && e.button !== CoreMouseButton.WHEEL) ? 'm' : 'M';\n return `\\x1b[<${eventCode(e, true)};${e.x};${e.y}${final}`;\n }\n};\n\n/**\n * CoreMouseService\n *\n * Provides mouse tracking reports with different protocols and encodings.\n * - protocols: NONE (default), X10, VT200, DRAG, ANY\n * - encodings: DEFAULT, SGR (UTF8, URXVT removed in #2507)\n *\n * Custom protocols/encodings can be added by `addProtocol` / `addEncoding`.\n * To activate a protocol/encoding, set `activeProtocol` / `activeEncoding`.\n * Switching a protocol will send a notification event `onProtocolChange`\n * with a list of needed events to track.\n *\n * The service handles the mouse tracking state and decides whether to send\n * a tracking report to the backend based on protocol and encoding limitations.\n * To send a mouse event call `triggerMouseEvent`.\n */\nexport class CoreMouseService extends Disposable implements ICoreMouseService {\n public serviceBrand: any;\n\n private _protocols: { [name: string]: ICoreMouseProtocol } = {};\n private _encodings: { [name: string]: CoreMouseEncoding } = {};\n private _activeProtocol: string = '';\n private _activeEncoding: string = '';\n private _lastEvent: ICoreMouseEvent | null = null;\n private _wheelPartialScroll: number = 0;\n\n private readonly _onProtocolChange = this._register(new Emitter());\n public readonly onProtocolChange = this._onProtocolChange.event;\n\n constructor(\n @IBufferService private readonly _bufferService: IBufferService,\n @ICoreService private readonly _coreService: ICoreService,\n @IOptionsService private readonly _optionsService: IOptionsService\n ) {\n super();\n // register default protocols and encodings\n for (const name of Object.keys(DEFAULT_PROTOCOLS)) this.addProtocol(name, DEFAULT_PROTOCOLS[name]);\n for (const name of Object.keys(DEFAULT_ENCODINGS)) this.addEncoding(name, DEFAULT_ENCODINGS[name]);\n // call reset to set defaults\n this.reset();\n }\n\n public addProtocol(name: string, protocol: ICoreMouseProtocol): void {\n this._protocols[name] = protocol;\n }\n\n public addEncoding(name: string, encoding: CoreMouseEncoding): void {\n this._encodings[name] = encoding;\n }\n\n public get activeProtocol(): string {\n return this._activeProtocol;\n }\n\n public get areMouseEventsActive(): boolean {\n return this._protocols[this._activeProtocol].events !== 0;\n }\n\n public set activeProtocol(name: string) {\n if (!this._protocols[name]) {\n throw new Error(`unknown protocol \"${name}\"`);\n }\n this._activeProtocol = name;\n this._onProtocolChange.fire(this._protocols[name].events);\n }\n\n public get activeEncoding(): string {\n return this._activeEncoding;\n }\n\n public set activeEncoding(name: string) {\n if (!this._encodings[name]) {\n throw new Error(`unknown encoding \"${name}\"`);\n }\n this._activeEncoding = name;\n }\n\n public reset(): void {\n this.activeProtocol = 'NONE';\n this.activeEncoding = 'DEFAULT';\n this._lastEvent = null;\n this._wheelPartialScroll = 0;\n }\n\n /**\n * Processes a wheel event, accounting for partial scrolls for trackpad, mouse scrolls.\n * This prevents hyper-sensitive scrolling in alt buffer.\n */\n public consumeWheelEvent(ev: WheelEvent, cellHeight?: number, dpr?: number): number {\n // Do nothing if it's not a vertical scroll event\n if (ev.deltaY === 0 || ev.shiftKey) {\n return 0;\n }\n\n if (cellHeight === undefined || dpr === undefined) {\n return 0;\n }\n\n const targetWheelEventPixels = cellHeight / dpr;\n let amount = this._applyScrollModifier(ev.deltaY, ev);\n\n if (ev.deltaMode === WheelEvent.DOM_DELTA_PIXEL) {\n amount /= (targetWheelEventPixels + 0.0); // Prevent integer division\n\n const isLikelyTrackpad = Math.abs(ev.deltaY) < 50;\n if (isLikelyTrackpad) {\n amount *= 0.3;\n }\n\n this._wheelPartialScroll += amount;\n amount = Math.floor(Math.abs(this._wheelPartialScroll)) * (this._wheelPartialScroll > 0 ? 1 : -1);\n this._wheelPartialScroll %= 1;\n } else if (ev.deltaMode === WheelEvent.DOM_DELTA_PAGE) {\n amount *= this._bufferService.rows;\n }\n return amount;\n }\n\n private _applyScrollModifier(amount: number, ev: WheelEvent): number {\n // Multiply the scroll speed when the modifier key is pressed\n if (ev.altKey || ev.ctrlKey || ev.shiftKey) {\n return amount * this._optionsService.rawOptions.fastScrollSensitivity * this._optionsService.rawOptions.scrollSensitivity;\n }\n return amount * this._optionsService.rawOptions.scrollSensitivity;\n }\n\n /**\n * Triggers a mouse event to be sent.\n *\n * Returns true if the event passed all protocol restrictions and a report\n * was sent, otherwise false. The return value may be used to decide whether\n * the default event action in the bowser component should be omitted.\n *\n * Note: The method will change values of the given event object\n * to fullfill protocol and encoding restrictions.\n */\n public triggerMouseEvent(e: ICoreMouseEvent): boolean {\n // range check for col/row\n if (e.col < 0 || e.col >= this._bufferService.cols\n || e.row < 0 || e.row >= this._bufferService.rows) {\n return false;\n }\n\n // filter nonsense combinations of button + action\n if (e.button === CoreMouseButton.WHEEL && e.action === CoreMouseAction.MOVE) {\n return false;\n }\n if (e.button === CoreMouseButton.NONE && e.action !== CoreMouseAction.MOVE) {\n return false;\n }\n if (e.button !== CoreMouseButton.WHEEL && (e.action === CoreMouseAction.LEFT || e.action === CoreMouseAction.RIGHT)) {\n return false;\n }\n\n // report 1-based coords\n e.col++;\n e.row++;\n\n // debounce move events at grid or pixel level\n if (e.action === CoreMouseAction.MOVE\n && this._lastEvent\n && this._equalEvents(this._lastEvent, e, this._activeEncoding === 'SGR_PIXELS')\n ) {\n return false;\n }\n\n // apply protocol restrictions\n if (!this._protocols[this._activeProtocol].restrict(e)) {\n return false;\n }\n\n // encode report and send\n const report = this._encodings[this._activeEncoding](e);\n if (report) {\n // always send DEFAULT as binary data\n if (this._activeEncoding === 'DEFAULT') {\n this._coreService.triggerBinaryEvent(report);\n } else {\n this._coreService.triggerDataEvent(report, true);\n }\n }\n\n this._lastEvent = e;\n\n return true;\n }\n\n public explainEvents(events: CoreMouseEventType): { [event: string]: boolean } {\n return {\n down: !!(events & CoreMouseEventType.DOWN),\n up: !!(events & CoreMouseEventType.UP),\n drag: !!(events & CoreMouseEventType.DRAG),\n move: !!(events & CoreMouseEventType.MOVE),\n wheel: !!(events & CoreMouseEventType.WHEEL)\n };\n }\n\n private _equalEvents(e1: ICoreMouseEvent, e2: ICoreMouseEvent, pixels: boolean): boolean {\n if (pixels) {\n if (e1.x !== e2.x) return false;\n if (e1.y !== e2.y) return false;\n } else {\n if (e1.col !== e2.col) return false;\n if (e1.row !== e2.row) return false;\n }\n if (e1.button !== e2.button) return false;\n if (e1.action !== e2.action) return false;\n if (e1.ctrl !== e2.ctrl) return false;\n if (e1.alt !== e2.alt) return false;\n if (e1.shift !== e2.shift) return false;\n return true;\n }\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { clone } from 'common/Clone';\nimport { Disposable } from 'vs/base/common/lifecycle';\nimport { IDecPrivateModes, IModes } from 'common/Types';\nimport { IBufferService, ICoreService, ILogService, IOptionsService } from 'common/services/Services';\nimport { Emitter } from 'vs/base/common/event';\n\nconst DEFAULT_MODES: IModes = Object.freeze({\n insertMode: false\n});\n\nconst DEFAULT_DEC_PRIVATE_MODES: IDecPrivateModes = Object.freeze({\n applicationCursorKeys: false,\n applicationKeypad: false,\n bracketedPasteMode: false,\n cursorBlink: undefined,\n cursorStyle: undefined,\n origin: false,\n reverseWraparound: false,\n sendFocus: false,\n synchronizedOutput: false,\n wraparound: true // defaults: xterm - true, vt100 - false\n});\n\nexport class CoreService extends Disposable implements ICoreService {\n public serviceBrand: any;\n\n public isCursorInitialized: boolean = false;\n public isCursorHidden: boolean = false;\n public modes: IModes;\n public decPrivateModes: IDecPrivateModes;\n\n private readonly _onData = this._register(new Emitter());\n public readonly onData = this._onData.event;\n private readonly _onUserInput = this._register(new Emitter());\n public readonly onUserInput = this._onUserInput.event;\n private readonly _onBinary = this._register(new Emitter());\n public readonly onBinary = this._onBinary.event;\n private readonly _onRequestScrollToBottom = this._register(new Emitter());\n public readonly onRequestScrollToBottom = this._onRequestScrollToBottom.event;\n\n constructor(\n @IBufferService private readonly _bufferService: IBufferService,\n @ILogService private readonly _logService: ILogService,\n @IOptionsService private readonly _optionsService: IOptionsService\n ) {\n super();\n this.modes = clone(DEFAULT_MODES);\n this.decPrivateModes = clone(DEFAULT_DEC_PRIVATE_MODES);\n }\n\n public reset(): void {\n this.modes = clone(DEFAULT_MODES);\n this.decPrivateModes = clone(DEFAULT_DEC_PRIVATE_MODES);\n }\n\n public triggerDataEvent(data: string, wasUserInput: boolean = false): void {\n // Prevents all events to pty process if stdin is disabled\n if (this._optionsService.rawOptions.disableStdin) {\n return;\n }\n\n // Input is being sent to the terminal, the terminal should focus the prompt.\n const buffer = this._bufferService.buffer;\n if (wasUserInput && this._optionsService.rawOptions.scrollOnUserInput && buffer.ybase !== buffer.ydisp) {\n this._onRequestScrollToBottom.fire();\n }\n\n // Fire onUserInput so listeners can react as well (eg. clear selection)\n if (wasUserInput) {\n this._onUserInput.fire();\n }\n\n // Fire onData API\n this._logService.debug(`sending data \"${data}\"`);\n this._logService.trace(`sending data (codes)`, () => data.split('').map(e => e.charCodeAt(0)));\n this._onData.fire(data);\n }\n\n public triggerBinaryEvent(data: string): void {\n if (this._optionsService.rawOptions.disableStdin) {\n return;\n }\n this._logService.debug(`sending binary \"${data}\"`);\n this._logService.trace(`sending binary (codes)`, () => data.split('').map(e => e.charCodeAt(0)));\n this._onBinary.fire(data);\n }\n}\n","/**\n * Copyright (c) 2022 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { css } from 'common/Color';\nimport { Disposable, DisposableStore, toDisposable } from 'vs/base/common/lifecycle';\nimport { IDecorationService, IInternalDecoration } from 'common/services/Services';\nimport { SortedList } from 'common/SortedList';\nimport { IColor } from 'common/Types';\nimport { IDecoration, IDecorationOptions, IMarker } from '@xterm/xterm';\nimport { Emitter } from 'vs/base/common/event';\n\n// Work variables to avoid garbage collection\nlet $xmin = 0;\nlet $xmax = 0;\n\nexport class DecorationService extends Disposable implements IDecorationService {\n public serviceBrand: any;\n\n /**\n * A list of all decorations, sorted by the marker's line value. This relies on the fact that\n * while marker line values do change, they should all change by the same amount so this should\n * never become out of order.\n */\n private readonly _decorations: SortedList = new SortedList(e => e?.marker.line);\n\n private readonly _onDecorationRegistered = this._register(new Emitter());\n public readonly onDecorationRegistered = this._onDecorationRegistered.event;\n private readonly _onDecorationRemoved = this._register(new Emitter());\n public readonly onDecorationRemoved = this._onDecorationRemoved.event;\n\n public get decorations(): IterableIterator { return this._decorations.values(); }\n\n constructor() {\n super();\n\n this._register(toDisposable(() => this.reset()));\n }\n\n public registerDecoration(options: IDecorationOptions): IDecoration | undefined {\n if (options.marker.isDisposed) {\n return undefined;\n }\n const decoration = new Decoration(options);\n if (decoration) {\n const markerDispose = decoration.marker.onDispose(() => decoration.dispose());\n const listener = decoration.onDispose(() => {\n listener.dispose();\n if (decoration) {\n if (this._decorations.delete(decoration)) {\n this._onDecorationRemoved.fire(decoration);\n }\n markerDispose.dispose();\n }\n });\n this._decorations.insert(decoration);\n this._onDecorationRegistered.fire(decoration);\n }\n return decoration;\n }\n\n public reset(): void {\n for (const d of this._decorations.values()) {\n d.dispose();\n }\n this._decorations.clear();\n }\n\n public *getDecorationsAtCell(x: number, line: number, layer?: 'bottom' | 'top'): IterableIterator {\n let xmin = 0;\n let xmax = 0;\n for (const d of this._decorations.getKeyIterator(line)) {\n xmin = d.options.x ?? 0;\n xmax = xmin + (d.options.width ?? 1);\n if (x >= xmin && x < xmax && (!layer || (d.options.layer ?? 'bottom') === layer)) {\n yield d;\n }\n }\n }\n\n public forEachDecorationAtCell(x: number, line: number, layer: 'bottom' | 'top' | undefined, callback: (decoration: IInternalDecoration) => void): void {\n this._decorations.forEachByKey(line, d => {\n $xmin = d.options.x ?? 0;\n $xmax = $xmin + (d.options.width ?? 1);\n if (x >= $xmin && x < $xmax && (!layer || (d.options.layer ?? 'bottom') === layer)) {\n callback(d);\n }\n });\n }\n}\n\nclass Decoration extends DisposableStore implements IInternalDecoration {\n public readonly marker: IMarker;\n public element: HTMLElement | undefined;\n\n public readonly onRenderEmitter = this.add(new Emitter());\n public readonly onRender = this.onRenderEmitter.event;\n private readonly _onDispose = this.add(new Emitter());\n public readonly onDispose = this._onDispose.event;\n\n private _cachedBg: IColor | undefined | null = null;\n public get backgroundColorRGB(): IColor | undefined {\n if (this._cachedBg === null) {\n if (this.options.backgroundColor) {\n this._cachedBg = css.toColor(this.options.backgroundColor);\n } else {\n this._cachedBg = undefined;\n }\n }\n return this._cachedBg;\n }\n\n private _cachedFg: IColor | undefined | null = null;\n public get foregroundColorRGB(): IColor | undefined {\n if (this._cachedFg === null) {\n if (this.options.foregroundColor) {\n this._cachedFg = css.toColor(this.options.foregroundColor);\n } else {\n this._cachedFg = undefined;\n }\n }\n return this._cachedFg;\n }\n\n constructor(\n public readonly options: IDecorationOptions\n ) {\n super();\n this.marker = options.marker;\n if (this.options.overviewRulerOptions && !this.options.overviewRulerOptions.position) {\n this.options.overviewRulerOptions.position = 'full';\n }\n }\n\n public override dispose(): void {\n this._onDispose.fire();\n super.dispose();\n }\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n *\n * This was heavily inspired from microsoft/vscode's dependency injection system (MIT).\n */\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\nimport { IInstantiationService, IServiceIdentifier } from 'common/services/Services';\nimport { getServiceDependencies } from 'common/services/ServiceRegistry';\n\nexport class ServiceCollection {\n\n private _entries = new Map, any>();\n\n constructor(...entries: [IServiceIdentifier, any][]) {\n for (const [id, service] of entries) {\n this.set(id, service);\n }\n }\n\n public set(id: IServiceIdentifier, instance: T): T {\n const result = this._entries.get(id);\n this._entries.set(id, instance);\n return result;\n }\n\n public forEach(callback: (id: IServiceIdentifier, instance: any) => any): void {\n for (const [key, value] of this._entries.entries()) {\n callback(key, value);\n }\n }\n\n public has(id: IServiceIdentifier): boolean {\n return this._entries.has(id);\n }\n\n public get(id: IServiceIdentifier): T | undefined {\n return this._entries.get(id);\n }\n}\n\nexport class InstantiationService implements IInstantiationService {\n public serviceBrand: undefined;\n\n private readonly _services: ServiceCollection = new ServiceCollection();\n\n constructor() {\n this._services.set(IInstantiationService, this);\n }\n\n public setService(id: IServiceIdentifier, instance: T): void {\n this._services.set(id, instance);\n }\n\n public getService(id: IServiceIdentifier): T | undefined {\n return this._services.get(id);\n }\n\n public createInstance(ctor: any, ...args: any[]): T {\n const serviceDependencies = getServiceDependencies(ctor).sort((a, b) => a.index - b.index);\n\n const serviceArgs: any[] = [];\n for (const dependency of serviceDependencies) {\n const service = this._services.get(dependency.id);\n if (!service) {\n throw new Error(`[createInstance] ${ctor.name} depends on UNKNOWN service ${dependency.id._id}.`);\n }\n serviceArgs.push(service);\n }\n\n const firstServiceArgPos = serviceDependencies.length > 0 ? serviceDependencies[0].index : args.length;\n\n // check for argument mismatches, adjust static args if needed\n if (args.length !== firstServiceArgPos) {\n throw new Error(`[createInstance] First service dependency of ${ctor.name} at position ${firstServiceArgPos + 1} conflicts with ${args.length} static arguments`);\n }\n\n // now create the instance\n return new ctor(...[...args, ...serviceArgs]);\n }\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { Disposable } from 'vs/base/common/lifecycle';\nimport { ILogService, IOptionsService, LogLevelEnum } from 'common/services/Services';\n\ntype LogType = (message?: any, ...optionalParams: any[]) => void;\n\ninterface IConsole {\n log: LogType;\n error: LogType;\n info: LogType;\n trace: LogType;\n warn: LogType;\n}\n\n// console is available on both node.js and browser contexts but the common\n// module doesn't depend on them so we need to explicitly declare it.\ndeclare const console: IConsole;\n\nconst optionsKeyToLogLevel: { [key: string]: LogLevelEnum } = {\n trace: LogLevelEnum.TRACE,\n debug: LogLevelEnum.DEBUG,\n info: LogLevelEnum.INFO,\n warn: LogLevelEnum.WARN,\n error: LogLevelEnum.ERROR,\n off: LogLevelEnum.OFF\n};\n\nconst LOG_PREFIX = 'xterm.js: ';\n\nexport class LogService extends Disposable implements ILogService {\n public serviceBrand: any;\n\n private _logLevel: LogLevelEnum = LogLevelEnum.OFF;\n public get logLevel(): LogLevelEnum { return this._logLevel; }\n\n constructor(\n @IOptionsService private readonly _optionsService: IOptionsService\n ) {\n super();\n this._updateLogLevel();\n this._register(this._optionsService.onSpecificOptionChange('logLevel', () => this._updateLogLevel()));\n\n // For trace logging, assume the latest created log service is valid\n traceLogger = this;\n }\n\n private _updateLogLevel(): void {\n this._logLevel = optionsKeyToLogLevel[this._optionsService.rawOptions.logLevel];\n }\n\n private _evalLazyOptionalParams(optionalParams: any[]): void {\n for (let i = 0; i < optionalParams.length; i++) {\n if (typeof optionalParams[i] === 'function') {\n optionalParams[i] = optionalParams[i]();\n }\n }\n }\n\n private _log(type: LogType, message: string, optionalParams: any[]): void {\n this._evalLazyOptionalParams(optionalParams);\n type.call(console, (this._optionsService.options.logger ? '' : LOG_PREFIX) + message, ...optionalParams);\n }\n\n public trace(message: string, ...optionalParams: any[]): void {\n if (this._logLevel <= LogLevelEnum.TRACE) {\n this._log(this._optionsService.options.logger?.trace.bind(this._optionsService.options.logger) ?? console.log, message, optionalParams);\n }\n }\n\n public debug(message: string, ...optionalParams: any[]): void {\n if (this._logLevel <= LogLevelEnum.DEBUG) {\n this._log(this._optionsService.options.logger?.debug.bind(this._optionsService.options.logger) ?? console.log, message, optionalParams);\n }\n }\n\n public info(message: string, ...optionalParams: any[]): void {\n if (this._logLevel <= LogLevelEnum.INFO) {\n this._log(this._optionsService.options.logger?.info.bind(this._optionsService.options.logger) ?? console.info, message, optionalParams);\n }\n }\n\n public warn(message: string, ...optionalParams: any[]): void {\n if (this._logLevel <= LogLevelEnum.WARN) {\n this._log(this._optionsService.options.logger?.warn.bind(this._optionsService.options.logger) ?? console.warn, message, optionalParams);\n }\n }\n\n public error(message: string, ...optionalParams: any[]): void {\n if (this._logLevel <= LogLevelEnum.ERROR) {\n this._log(this._optionsService.options.logger?.error.bind(this._optionsService.options.logger) ?? console.error, message, optionalParams);\n }\n }\n}\n\nlet traceLogger: ILogService;\nexport function setTraceLogger(logger: ILogService): void {\n traceLogger = logger;\n}\n\n/**\n * A decorator that can be used to automatically log trace calls to the decorated function.\n */\nexport function traceCall(_target: any, key: string, descriptor: any): any {\n if (typeof descriptor.value !== 'function') {\n throw new Error('not supported');\n }\n const fnKey = 'value';\n const fn = descriptor.value;\n descriptor[fnKey] = function (...args: any[]) {\n // Early exit\n if (traceLogger.logLevel !== LogLevelEnum.TRACE) {\n return fn.apply(this, args);\n }\n\n traceLogger.trace(`GlyphRenderer#${fn.name}(${args.map(e => JSON.stringify(e)).join(', ')})`);\n const result = fn.apply(this, args);\n traceLogger.trace(`GlyphRenderer#${fn.name} return`, result);\n return result;\n };\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { Disposable, toDisposable } from 'vs/base/common/lifecycle';\nimport { isMac } from 'common/Platform';\nimport { CursorStyle, IDisposable } from 'common/Types';\nimport { FontWeight, IOptionsService, ITerminalOptions } from 'common/services/Services';\nimport { Emitter } from 'vs/base/common/event';\n\nexport const DEFAULT_OPTIONS: Readonly> = {\n cols: 80,\n rows: 24,\n cursorBlink: false,\n cursorStyle: 'block',\n cursorWidth: 1,\n cursorInactiveStyle: 'outline',\n customGlyphs: true,\n drawBoldTextInBrightColors: true,\n documentOverride: null,\n fastScrollModifier: 'alt',\n fastScrollSensitivity: 5,\n fontFamily: 'monospace',\n fontSize: 15,\n fontWeight: 'normal',\n fontWeightBold: 'bold',\n ignoreBracketedPasteMode: false,\n lineHeight: 1.0,\n letterSpacing: 0,\n linkHandler: null,\n logLevel: 'info',\n logger: null,\n scrollback: 1000,\n scrollOnEraseInDisplay: false,\n scrollOnUserInput: true,\n scrollSensitivity: 1,\n screenReaderMode: false,\n smoothScrollDuration: 0,\n macOptionIsMeta: false,\n macOptionClickForcesSelection: false,\n minimumContrastRatio: 1,\n disableStdin: false,\n allowProposedApi: false,\n allowTransparency: false,\n tabStopWidth: 8,\n theme: {},\n reflowCursorLine: false,\n rescaleOverlappingGlyphs: false,\n rightClickSelectsWord: isMac,\n windowOptions: {},\n windowsMode: false,\n windowsPty: {},\n wordSeparator: ' ()[]{}\\',\"`',\n altClickMovesCursor: true,\n convertEol: false,\n termName: 'xterm',\n cancelEvents: false,\n overviewRuler: {}\n};\n\nconst FONT_WEIGHT_OPTIONS: Extract[] = ['normal', 'bold', '100', '200', '300', '400', '500', '600', '700', '800', '900'];\n\nexport class OptionsService extends Disposable implements IOptionsService {\n public serviceBrand: any;\n\n public readonly rawOptions: Required;\n public options: Required;\n\n private readonly _onOptionChange = this._register(new Emitter());\n public readonly onOptionChange = this._onOptionChange.event;\n\n constructor(options: Partial) {\n super();\n // set the default value of each option\n const defaultOptions = { ...DEFAULT_OPTIONS };\n for (const key in options) {\n if (key in defaultOptions) {\n try {\n const newValue = options[key];\n defaultOptions[key] = this._sanitizeAndValidateOption(key, newValue);\n } catch (e) {\n console.error(e);\n }\n }\n }\n\n // set up getters and setters for each option\n this.rawOptions = defaultOptions;\n this.options = { ... defaultOptions };\n this._setupOptions();\n\n // Clear out options that could link outside xterm.js as they could easily cause an embedder\n // memory leak\n this._register(toDisposable(() => {\n this.rawOptions.linkHandler = null;\n this.rawOptions.documentOverride = null;\n }));\n }\n\n // eslint-disable-next-line @typescript-eslint/naming-convention\n public onSpecificOptionChange(key: T, listener: (value: ITerminalOptions[T]) => any): IDisposable {\n return this.onOptionChange(eventKey => {\n if (eventKey === key) {\n listener(this.rawOptions[key]);\n }\n });\n }\n\n // eslint-disable-next-line @typescript-eslint/naming-convention\n public onMultipleOptionChange(keys: (keyof ITerminalOptions)[], listener: () => any): IDisposable {\n return this.onOptionChange(eventKey => {\n if (keys.indexOf(eventKey) !== -1) {\n listener();\n }\n });\n }\n\n private _setupOptions(): void {\n const getter = (propName: string): any => {\n if (!(propName in DEFAULT_OPTIONS)) {\n throw new Error(`No option with key \"${propName}\"`);\n }\n return this.rawOptions[propName];\n };\n\n const setter = (propName: string, value: any): void => {\n if (!(propName in DEFAULT_OPTIONS)) {\n throw new Error(`No option with key \"${propName}\"`);\n }\n\n value = this._sanitizeAndValidateOption(propName, value);\n // Don't fire an option change event if they didn't change\n if (this.rawOptions[propName] !== value) {\n this.rawOptions[propName] = value;\n this._onOptionChange.fire(propName);\n }\n };\n\n for (const propName in this.rawOptions) {\n const desc = {\n get: getter.bind(this, propName),\n set: setter.bind(this, propName)\n };\n Object.defineProperty(this.options, propName, desc);\n }\n }\n\n private _sanitizeAndValidateOption(key: string, value: any): any {\n switch (key) {\n case 'cursorStyle':\n if (!value) {\n value = DEFAULT_OPTIONS[key];\n }\n if (!isCursorStyle(value)) {\n throw new Error(`\"${value}\" is not a valid value for ${key}`);\n }\n break;\n case 'wordSeparator':\n if (!value) {\n value = DEFAULT_OPTIONS[key];\n }\n break;\n case 'fontWeight':\n case 'fontWeightBold':\n if (typeof value === 'number' && 1 <= value && value <= 1000) {\n // already valid numeric value\n break;\n }\n value = FONT_WEIGHT_OPTIONS.includes(value) ? value : DEFAULT_OPTIONS[key];\n break;\n case 'cursorWidth':\n value = Math.floor(value);\n // Fall through for bounds check\n case 'lineHeight':\n case 'tabStopWidth':\n if (value < 1) {\n throw new Error(`${key} cannot be less than 1, value: ${value}`);\n }\n break;\n case 'minimumContrastRatio':\n value = Math.max(1, Math.min(21, Math.round(value * 10) / 10));\n break;\n case 'scrollback':\n value = Math.min(value, 4294967295);\n if (value < 0) {\n throw new Error(`${key} cannot be less than 0, value: ${value}`);\n }\n break;\n case 'fastScrollSensitivity':\n case 'scrollSensitivity':\n if (value <= 0) {\n throw new Error(`${key} cannot be less than or equal to 0, value: ${value}`);\n }\n break;\n case 'rows':\n case 'cols':\n if (!value && value !== 0) {\n throw new Error(`${key} must be numeric, value: ${value}`);\n }\n break;\n case 'windowsPty':\n value = value ?? {};\n break;\n }\n return value;\n }\n}\n\nfunction isCursorStyle(value: unknown): value is CursorStyle {\n return value === 'block' || value === 'underline' || value === 'bar';\n}\n","/**\n * Copyright (c) 2022 The xterm.js authors. All rights reserved.\n * @license MIT\n */\nimport { IBufferService, IOscLinkService } from 'common/services/Services';\nimport { IMarker, IOscLinkData } from 'common/Types';\n\nexport class OscLinkService implements IOscLinkService {\n public serviceBrand: any;\n\n private _nextId = 1;\n\n /**\n * A map of the link key to link entry. This is used to add additional lines to links with ids.\n */\n private _entriesWithId: Map = new Map();\n\n /**\n * A map of the link id to the link entry. The \"link id\" (number) which is the numberic\n * representation of a unique link should not be confused with \"id\" (string) which comes in with\n * `id=` in the OSC link's properties.\n */\n private _dataByLinkId: Map = new Map();\n\n constructor(\n @IBufferService private readonly _bufferService: IBufferService\n ) {\n }\n\n public registerLink(data: IOscLinkData): number {\n const buffer = this._bufferService.buffer;\n\n // Links with no id will only ever be registered a single time\n if (data.id === undefined) {\n const marker = buffer.addMarker(buffer.ybase + buffer.y);\n const entry: IOscLinkEntryNoId = {\n data,\n id: this._nextId++,\n lines: [marker]\n };\n marker.onDispose(() => this._removeMarkerFromLink(entry, marker));\n this._dataByLinkId.set(entry.id, entry);\n return entry.id;\n }\n\n // Add the line to the link if it already exists\n const castData = data as Required;\n const key = this._getEntryIdKey(castData);\n const match = this._entriesWithId.get(key);\n if (match) {\n this.addLineToLink(match.id, buffer.ybase + buffer.y);\n return match.id;\n }\n\n // Create the link\n const marker = buffer.addMarker(buffer.ybase + buffer.y);\n const entry: IOscLinkEntryWithId = {\n id: this._nextId++,\n key: this._getEntryIdKey(castData),\n data: castData,\n lines: [marker]\n };\n marker.onDispose(() => this._removeMarkerFromLink(entry, marker));\n this._entriesWithId.set(entry.key, entry);\n this._dataByLinkId.set(entry.id, entry);\n return entry.id;\n }\n\n public addLineToLink(linkId: number, y: number): void {\n const entry = this._dataByLinkId.get(linkId);\n if (!entry) {\n return;\n }\n if (entry.lines.every(e => e.line !== y)) {\n const marker = this._bufferService.buffer.addMarker(y);\n entry.lines.push(marker);\n marker.onDispose(() => this._removeMarkerFromLink(entry, marker));\n }\n }\n\n public getLinkData(linkId: number): IOscLinkData | undefined {\n return this._dataByLinkId.get(linkId)?.data;\n }\n\n private _getEntryIdKey(linkData: Required): string {\n return `${linkData.id};;${linkData.uri}`;\n }\n\n private _removeMarkerFromLink(entry: IOscLinkEntryNoId | IOscLinkEntryWithId, marker: IMarker): void {\n const index = entry.lines.indexOf(marker);\n if (index === -1) {\n return;\n }\n entry.lines.splice(index, 1);\n if (entry.lines.length === 0) {\n if (entry.data.id !== undefined) {\n this._entriesWithId.delete((entry as IOscLinkEntryWithId).key);\n }\n this._dataByLinkId.delete(entry.id);\n }\n }\n}\n\ninterface IOscLinkEntry {\n data: T;\n id: number;\n lines: IMarker[];\n}\n\ninterface IOscLinkEntryNoId extends IOscLinkEntry {\n}\n\ninterface IOscLinkEntryWithId extends IOscLinkEntry> {\n key: string;\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n *\n * This was heavily inspired from microsoft/vscode's dependency injection system (MIT).\n */\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\nimport { IServiceIdentifier } from 'common/services/Services';\n\nconst DI_TARGET = 'di$target';\nconst DI_DEPENDENCIES = 'di$dependencies';\n\nexport const serviceRegistry: Map> = new Map();\n\nexport function getServiceDependencies(ctor: any): { id: IServiceIdentifier, index: number, optional: boolean }[] {\n return ctor[DI_DEPENDENCIES] || [];\n}\n\nexport function createDecorator(id: string): IServiceIdentifier {\n if (serviceRegistry.has(id)) {\n return serviceRegistry.get(id)!;\n }\n\n const decorator: any = function (target: Function, key: string, index: number): any {\n if (arguments.length !== 3) {\n throw new Error('@IServiceName-decorator can only be used to decorate a parameter');\n }\n\n storeServiceDependency(decorator, target, index);\n };\n\n decorator._id = id;\n\n serviceRegistry.set(id, decorator);\n return decorator;\n}\n\nfunction storeServiceDependency(id: Function, target: Function, index: number): void {\n if ((target as any)[DI_TARGET] === target) {\n (target as any)[DI_DEPENDENCIES].push({ id, index });\n } else {\n (target as any)[DI_DEPENDENCIES] = [{ id, index }];\n (target as any)[DI_TARGET] = target;\n }\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IDecoration, IDecorationOptions, ILinkHandler, ILogger, IWindowsPty, type IOverviewRulerOptions } from '@xterm/xterm';\nimport { CoreMouseEncoding, CoreMouseEventType, CursorInactiveStyle, CursorStyle, IAttributeData, ICharset, IColor, ICoreMouseEvent, ICoreMouseProtocol, IDecPrivateModes, IDisposable, IModes, IOscLinkData, IWindowOptions } from 'common/Types';\nimport { IBuffer, IBufferSet } from 'common/buffer/Types';\nimport { createDecorator } from 'common/services/ServiceRegistry';\nimport type { Emitter, Event } from 'vs/base/common/event';\n\nexport const IBufferService = createDecorator('BufferService');\nexport interface IBufferService {\n serviceBrand: undefined;\n\n readonly cols: number;\n readonly rows: number;\n readonly buffer: IBuffer;\n readonly buffers: IBufferSet;\n isUserScrolling: boolean;\n onResize: Event;\n onScroll: Event;\n scroll(eraseAttr: IAttributeData, isWrapped?: boolean): void;\n scrollLines(disp: number, suppressScrollEvent?: boolean): void;\n resize(cols: number, rows: number): void;\n reset(): void;\n}\n\nexport interface IBufferResizeEvent {\n cols: number;\n rows: number;\n colsChanged: boolean;\n rowsChanged: boolean;\n}\n\nexport const ICoreMouseService = createDecorator('CoreMouseService');\nexport interface ICoreMouseService {\n serviceBrand: undefined;\n\n activeProtocol: string;\n activeEncoding: string;\n areMouseEventsActive: boolean;\n addProtocol(name: string, protocol: ICoreMouseProtocol): void;\n addEncoding(name: string, encoding: CoreMouseEncoding): void;\n reset(): void;\n\n /**\n * Triggers a mouse event to be sent.\n *\n * Returns true if the event passed all protocol restrictions and a report\n * was sent, otherwise false. The return value may be used to decide whether\n * the default event action in the bowser component should be omitted.\n *\n * Note: The method will change values of the given event object\n * to fullfill protocol and encoding restrictions.\n */\n triggerMouseEvent(event: ICoreMouseEvent): boolean;\n\n /**\n * Event to announce changes in mouse tracking.\n */\n onProtocolChange: Event;\n\n /**\n * Human readable version of mouse events.\n */\n explainEvents(events: CoreMouseEventType): { [event: string]: boolean };\n\n /**\n * Process wheel event taking partial scroll into account.\n */\n consumeWheelEvent(ev: WheelEvent, cellHeight?: number, dpr?: number): number;\n}\n\nexport const ICoreService = createDecorator('CoreService');\nexport interface ICoreService {\n serviceBrand: undefined;\n\n /**\n * Initially the cursor will not be visible until the first time the terminal\n * is focused.\n */\n isCursorInitialized: boolean;\n isCursorHidden: boolean;\n\n readonly modes: IModes;\n readonly decPrivateModes: IDecPrivateModes;\n\n readonly onData: Event;\n readonly onUserInput: Event;\n readonly onBinary: Event;\n readonly onRequestScrollToBottom: Event;\n\n reset(): void;\n\n /**\n * Triggers the onData event in the public API.\n * @param data The data that is being emitted.\n * @param wasUserInput Whether the data originated from the user (as opposed to\n * resulting from parsing incoming data). When true this will also:\n * - Scroll to the bottom of the buffer if option scrollOnUserInput is true.\n * - Fire the `onUserInput` event (so selection can be cleared).\n */\n triggerDataEvent(data: string, wasUserInput?: boolean): void;\n\n /**\n * Triggers the onBinary event in the public API.\n * @param data The data that is being emitted.\n */\n triggerBinaryEvent(data: string): void;\n}\n\nexport const ICharsetService = createDecorator('CharsetService');\nexport interface ICharsetService {\n serviceBrand: undefined;\n\n charset: ICharset | undefined;\n readonly glevel: number;\n\n reset(): void;\n\n /**\n * Set the G level of the terminal.\n * @param g\n */\n setgLevel(g: number): void;\n\n /**\n * Set the charset for the given G level of the terminal.\n * @param g\n * @param charset\n */\n setgCharset(g: number, charset: ICharset | undefined): void;\n}\n\nexport interface IServiceIdentifier {\n (...args: any[]): void;\n type: T;\n _id: string;\n}\n\nexport interface IBrandedService {\n serviceBrand: undefined;\n}\n\ntype GetLeadingNonServiceArgs = TArgs extends [] ? []\n : TArgs extends [...infer TFirst, infer TLast] ? TLast extends IBrandedService ? GetLeadingNonServiceArgs : TArgs\n : never;\n\nexport const IInstantiationService = createDecorator('InstantiationService');\nexport interface IInstantiationService {\n serviceBrand: undefined;\n\n setService(id: IServiceIdentifier, instance: T): void;\n getService(id: IServiceIdentifier): T | undefined;\n createInstance any, R extends InstanceType>(t: Ctor, ...args: GetLeadingNonServiceArgs>): R;\n}\n\nexport enum LogLevelEnum {\n TRACE = 0,\n DEBUG = 1,\n INFO = 2,\n WARN = 3,\n ERROR = 4,\n OFF = 5\n}\n\nexport const ILogService = createDecorator('LogService');\nexport interface ILogService {\n serviceBrand: undefined;\n\n readonly logLevel: LogLevelEnum;\n\n trace(message: any, ...optionalParams: any[]): void;\n debug(message: any, ...optionalParams: any[]): void;\n info(message: any, ...optionalParams: any[]): void;\n warn(message: any, ...optionalParams: any[]): void;\n error(message: any, ...optionalParams: any[]): void;\n}\n\nexport const IOptionsService = createDecorator('OptionsService');\nexport interface IOptionsService {\n serviceBrand: undefined;\n\n /**\n * Read only access to the raw options object, this is an internal-only fast path for accessing\n * single options without any validation as we trust TypeScript to enforce correct usage\n * internally.\n */\n readonly rawOptions: Required;\n\n /**\n * Options as exposed through the public API, this property uses getters and setters with\n * validation which makes it safer but slower. {@link rawOptions} should be used for pretty much\n * all internal usage for performance reasons.\n */\n readonly options: Required;\n\n /**\n * Adds an event listener for when any option changes.\n */\n readonly onOptionChange: Event;\n\n /**\n * Adds an event listener for when a specific option changes, this is a convenience method that is\n * preferred over {@link onOptionChange} when only a single option is being listened to.\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n onSpecificOptionChange(key: T, listener: (arg1: Required[T]) => any): IDisposable;\n\n /**\n * Adds an event listener for when a set of specific options change, this is a convenience method\n * that is preferred over {@link onOptionChange} when multiple options are being listened to and\n * handled the same way.\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n onMultipleOptionChange(keys: (keyof ITerminalOptions)[], listener: () => any): IDisposable;\n}\n\nexport type FontWeight = 'normal' | 'bold' | '100' | '200' | '300' | '400' | '500' | '600' | '700' | '800' | '900' | number;\nexport type LogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'off';\n\nexport interface ITerminalOptions {\n allowProposedApi?: boolean;\n allowTransparency?: boolean;\n altClickMovesCursor?: boolean;\n cols?: number;\n convertEol?: boolean;\n cursorBlink?: boolean;\n cursorStyle?: CursorStyle;\n cursorWidth?: number;\n cursorInactiveStyle?: CursorInactiveStyle;\n customGlyphs?: boolean;\n disableStdin?: boolean;\n documentOverride?: any | null;\n drawBoldTextInBrightColors?: boolean;\n /** @deprecated No longer supported */\n fastScrollModifier?: 'none' | 'alt' | 'ctrl' | 'shift';\n fastScrollSensitivity?: number;\n fontSize?: number;\n fontFamily?: string;\n fontWeight?: FontWeight;\n fontWeightBold?: FontWeight;\n ignoreBracketedPasteMode?: boolean;\n letterSpacing?: number;\n lineHeight?: number;\n linkHandler?: ILinkHandler | null;\n logLevel?: LogLevel;\n logger?: ILogger | null;\n macOptionIsMeta?: boolean;\n macOptionClickForcesSelection?: boolean;\n minimumContrastRatio?: number;\n reflowCursorLine?: boolean;\n rescaleOverlappingGlyphs?: boolean;\n rightClickSelectsWord?: boolean;\n rows?: number;\n screenReaderMode?: boolean;\n scrollback?: number;\n scrollOnUserInput?: boolean;\n scrollSensitivity?: number;\n smoothScrollDuration?: number;\n tabStopWidth?: number;\n theme?: ITheme;\n windowsMode?: boolean;\n windowsPty?: IWindowsPty;\n windowOptions?: IWindowOptions;\n wordSeparator?: string;\n overviewRuler?: IOverviewRulerOptions;\n scrollOnEraseInDisplay?: boolean;\n\n [key: string]: any;\n cancelEvents: boolean;\n termName: string;\n}\n\nexport interface ITheme {\n foreground?: string;\n background?: string;\n cursor?: string;\n cursorAccent?: string;\n selectionForeground?: string;\n selectionBackground?: string;\n selectionInactiveBackground?: string;\n scrollbarSliderBackground?: string;\n scrollbarSliderHoverBackground?: string;\n scrollbarSliderActiveBackground?: string;\n overviewRulerBorder?: string;\n black?: string;\n red?: string;\n green?: string;\n yellow?: string;\n blue?: string;\n magenta?: string;\n cyan?: string;\n white?: string;\n brightBlack?: string;\n brightRed?: string;\n brightGreen?: string;\n brightYellow?: string;\n brightBlue?: string;\n brightMagenta?: string;\n brightCyan?: string;\n brightWhite?: string;\n extendedAnsi?: string[];\n}\n\nexport const IOscLinkService = createDecorator('OscLinkService');\nexport interface IOscLinkService {\n serviceBrand: undefined;\n /**\n * Registers a link to the service, returning the link ID. The link data is managed by this\n * service and will be freed when this current cursor position is trimmed off the buffer.\n */\n registerLink(linkData: IOscLinkData): number;\n /**\n * Adds a line to a link if needed.\n */\n addLineToLink(linkId: number, y: number): void;\n /** Get the link data associated with a link ID. */\n getLinkData(linkId: number): IOscLinkData | undefined;\n}\n\n/*\n * Width and Grapheme_Cluster_Break properties of a character as a bit mask.\n *\n * bit 0: shouldJoin - should combine with preceding character.\n * bit 1..2: wcwidth - see UnicodeCharWidth.\n * bit 3..31: class of character (currently only 4 bits are used).\n * This is used to determined grapheme clustering - i.e. which codepoints\n * are to be combined into a single compound character.\n *\n * Use the UnicodeService static function createPropertyValue to create a\n * UnicodeCharProperties; use extractShouldJoin, extractWidth, and\n * extractCharKind to extract the components.\n */\nexport type UnicodeCharProperties = number;\n\n/**\n * Width in columns of a character.\n * In a CJK context, \"half-width\" characters (such as Latin) are width 1,\n * while \"full-width\" characters (such as Kanji) are 2 columns wide.\n * Combining characters (such as accents) are width 0.\n */\nexport type UnicodeCharWidth = 0 | 1 | 2;\n\nexport const IUnicodeService = createDecorator('UnicodeService');\nexport interface IUnicodeService {\n serviceBrand: undefined;\n /** Register an Unicode version provider. */\n register(provider: IUnicodeVersionProvider): void;\n /** Registered Unicode versions. */\n readonly versions: string[];\n /** Currently active version. */\n activeVersion: string;\n /** Event triggered, when activate version changed. */\n readonly onChange: Event;\n\n /**\n * Unicode version dependent\n */\n wcwidth(codepoint: number): UnicodeCharWidth;\n getStringCellWidth(s: string): number;\n /**\n * Return character width and type for grapheme clustering.\n * If preceding != 0, it is the return code from the previous character;\n * in that case the result specifies if the characters should be joined.\n */\n charProperties(codepoint: number, preceding: UnicodeCharProperties): UnicodeCharProperties;\n}\n\nexport interface IUnicodeVersionProvider {\n readonly version: string;\n wcwidth(ucs: number): UnicodeCharWidth;\n charProperties(codepoint: number, preceding: UnicodeCharProperties): UnicodeCharProperties;\n}\n\nexport const IDecorationService = createDecorator('DecorationService');\nexport interface IDecorationService extends IDisposable {\n serviceBrand: undefined;\n readonly decorations: IterableIterator;\n readonly onDecorationRegistered: Event;\n readonly onDecorationRemoved: Event;\n registerDecoration(decorationOptions: IDecorationOptions): IDecoration | undefined;\n reset(): void;\n /**\n * Trigger a callback over the decoration at a cell (in no particular order). This uses a callback\n * instead of an iterator as it's typically used in hot code paths.\n */\n forEachDecorationAtCell(x: number, line: number, layer: 'bottom' | 'top' | undefined, callback: (decoration: IInternalDecoration) => void): void;\n}\nexport interface IInternalDecoration extends IDecoration {\n readonly options: IDecorationOptions;\n readonly backgroundColorRGB: IColor | undefined;\n readonly foregroundColorRGB: IColor | undefined;\n readonly onRenderEmitter: Emitter;\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { UnicodeV6 } from 'common/input/UnicodeV6';\nimport { IUnicodeService, IUnicodeVersionProvider, UnicodeCharProperties, UnicodeCharWidth } from 'common/services/Services';\nimport { Emitter } from 'vs/base/common/event';\n\nexport class UnicodeService implements IUnicodeService {\n public serviceBrand: any;\n\n private _providers: {[key: string]: IUnicodeVersionProvider} = Object.create(null);\n private _active: string = '';\n private _activeProvider: IUnicodeVersionProvider;\n\n private readonly _onChange = new Emitter();\n public readonly onChange = this._onChange.event;\n\n public static extractShouldJoin(value: UnicodeCharProperties): boolean {\n return (value & 1) !== 0;\n }\n public static extractWidth(value: UnicodeCharProperties): UnicodeCharWidth {\n return ((value >> 1) & 0x3) as UnicodeCharWidth;\n }\n public static extractCharKind(value: UnicodeCharProperties): number {\n return value >> 3;\n }\n public static createPropertyValue(state: number, width: number, shouldJoin: boolean = false): UnicodeCharProperties {\n return ((state & 0xffffff) << 3) | ((width & 3) << 1) | (shouldJoin?1:0);\n }\n\n constructor() {\n const defaultProvider = new UnicodeV6();\n this.register(defaultProvider);\n this._active = defaultProvider.version;\n this._activeProvider = defaultProvider;\n }\n\n public dispose(): void {\n this._onChange.dispose();\n }\n\n public get versions(): string[] {\n return Object.keys(this._providers);\n }\n\n public get activeVersion(): string {\n return this._active;\n }\n\n public set activeVersion(version: string) {\n if (!this._providers[version]) {\n throw new Error(`unknown Unicode version \"${version}\"`);\n }\n this._active = version;\n this._activeProvider = this._providers[version];\n this._onChange.fire(version);\n }\n\n public register(provider: IUnicodeVersionProvider): void {\n this._providers[provider.version] = provider;\n }\n\n /**\n * Unicode version dependent interface.\n */\n public wcwidth(num: number): UnicodeCharWidth {\n return this._activeProvider.wcwidth(num);\n }\n\n public getStringCellWidth(s: string): number {\n let result = 0;\n let precedingInfo = 0;\n const length = s.length;\n for (let i = 0; i < length; ++i) {\n let code = s.charCodeAt(i);\n // surrogate pair first\n if (0xD800 <= code && code <= 0xDBFF) {\n if (++i >= length) {\n // this should not happen with strings retrieved from\n // Buffer.translateToString as it converts from UTF-32\n // and therefore always should contain the second part\n // for any other string we still have to handle it somehow:\n // simply treat the lonely surrogate first as a single char (UCS-2 behavior)\n return result + this.wcwidth(code);\n }\n const second = s.charCodeAt(i);\n // convert surrogate pair to high codepoint only for valid second part (UTF-16)\n // otherwise treat them independently (UCS-2 behavior)\n if (0xDC00 <= second && second <= 0xDFFF) {\n code = (code - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;\n } else {\n result += this.wcwidth(second);\n }\n }\n const currentInfo = this.charProperties(code, precedingInfo);\n let chWidth = UnicodeService.extractWidth(currentInfo);\n if (UnicodeService.extractShouldJoin(currentInfo)) {\n chWidth -= UnicodeService.extractWidth(precedingInfo);\n }\n result += chWidth;\n precedingInfo = currentInfo;\n }\n return result;\n }\n\n public charProperties(codepoint: number, preceding: UnicodeCharProperties): UnicodeCharProperties {\n return this._activeProvider.charProperties(codepoint, preceding);\n }\n}\n","\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.isAndroid = exports.isElectron = exports.isWebkitWebView = exports.isSafari = exports.isChrome = exports.isWebKit = exports.isFirefox = exports.onDidChangeFullscreen = exports.onDidChangeZoomLevel = void 0;\nexports.addMatchMediaChangeListener = addMatchMediaChangeListener;\nexports.setZoomLevel = setZoomLevel;\nexports.getZoomLevel = getZoomLevel;\nexports.getZoomFactor = getZoomFactor;\nexports.setZoomFactor = setZoomFactor;\nexports.setFullscreen = setFullscreen;\nexports.isFullscreen = isFullscreen;\nexports.isStandalone = isStandalone;\nexports.isWCOEnabled = isWCOEnabled;\nexports.getWCOBoundingRect = getWCOBoundingRect;\nconst window_1 = require(\"vs/base/browser/window\");\nconst event_1 = require(\"vs/base/common/event\");\nclass WindowManager {\n constructor() {\n // --- Zoom Level\n this.mapWindowIdToZoomLevel = new Map();\n this._onDidChangeZoomLevel = new event_1.Emitter();\n this.onDidChangeZoomLevel = this._onDidChangeZoomLevel.event;\n // --- Zoom Factor\n this.mapWindowIdToZoomFactor = new Map();\n // --- Fullscreen\n this._onDidChangeFullscreen = new event_1.Emitter();\n this.onDidChangeFullscreen = this._onDidChangeFullscreen.event;\n this.mapWindowIdToFullScreen = new Map();\n }\n static { this.INSTANCE = new WindowManager(); }\n getZoomLevel(targetWindow) {\n return this.mapWindowIdToZoomLevel.get(this.getWindowId(targetWindow)) ?? 0;\n }\n setZoomLevel(zoomLevel, targetWindow) {\n if (this.getZoomLevel(targetWindow) === zoomLevel) {\n return;\n }\n const targetWindowId = this.getWindowId(targetWindow);\n this.mapWindowIdToZoomLevel.set(targetWindowId, zoomLevel);\n this._onDidChangeZoomLevel.fire(targetWindowId);\n }\n getZoomFactor(targetWindow) {\n return this.mapWindowIdToZoomFactor.get(this.getWindowId(targetWindow)) ?? 1;\n }\n setZoomFactor(zoomFactor, targetWindow) {\n this.mapWindowIdToZoomFactor.set(this.getWindowId(targetWindow), zoomFactor);\n }\n setFullscreen(fullscreen, targetWindow) {\n if (this.isFullscreen(targetWindow) === fullscreen) {\n return;\n }\n const windowId = this.getWindowId(targetWindow);\n this.mapWindowIdToFullScreen.set(windowId, fullscreen);\n this._onDidChangeFullscreen.fire(windowId);\n }\n isFullscreen(targetWindow) {\n return !!this.mapWindowIdToFullScreen.get(this.getWindowId(targetWindow));\n }\n getWindowId(targetWindow) {\n return targetWindow.vscodeWindowId;\n }\n}\nfunction addMatchMediaChangeListener(targetWindow, query, callback) {\n if (typeof query === 'string') {\n query = targetWindow.matchMedia(query);\n }\n query.addEventListener('change', callback);\n}\n/** A zoom index, e.g. 1, 2, 3 */\nfunction setZoomLevel(zoomLevel, targetWindow) {\n WindowManager.INSTANCE.setZoomLevel(zoomLevel, targetWindow);\n}\nfunction getZoomLevel(targetWindow) {\n return WindowManager.INSTANCE.getZoomLevel(targetWindow);\n}\nexports.onDidChangeZoomLevel = WindowManager.INSTANCE.onDidChangeZoomLevel;\n/** The zoom scale for an index, e.g. 1, 1.2, 1.4 */\nfunction getZoomFactor(targetWindow) {\n return WindowManager.INSTANCE.getZoomFactor(targetWindow);\n}\nfunction setZoomFactor(zoomFactor, targetWindow) {\n WindowManager.INSTANCE.setZoomFactor(zoomFactor, targetWindow);\n}\nfunction setFullscreen(fullscreen, targetWindow) {\n WindowManager.INSTANCE.setFullscreen(fullscreen, targetWindow);\n}\nfunction isFullscreen(targetWindow) {\n return WindowManager.INSTANCE.isFullscreen(targetWindow);\n}\nexports.onDidChangeFullscreen = WindowManager.INSTANCE.onDidChangeFullscreen;\nconst userAgent = typeof navigator === 'object' ? navigator.userAgent : '';\nexports.isFirefox = (userAgent.indexOf('Firefox') >= 0);\nexports.isWebKit = (userAgent.indexOf('AppleWebKit') >= 0);\nexports.isChrome = (userAgent.indexOf('Chrome') >= 0);\nexports.isSafari = (!exports.isChrome && (userAgent.indexOf('Safari') >= 0));\nexports.isWebkitWebView = (!exports.isChrome && !exports.isSafari && exports.isWebKit);\nexports.isElectron = (userAgent.indexOf('Electron/') >= 0);\nexports.isAndroid = (userAgent.indexOf('Android') >= 0);\nlet standalone = false;\nif (typeof window_1.mainWindow.matchMedia === 'function') {\n const standaloneMatchMedia = window_1.mainWindow.matchMedia('(display-mode: standalone) or (display-mode: window-controls-overlay)');\n const fullScreenMatchMedia = window_1.mainWindow.matchMedia('(display-mode: fullscreen)');\n standalone = standaloneMatchMedia.matches;\n addMatchMediaChangeListener(window_1.mainWindow, standaloneMatchMedia, ({ matches }) => {\n // entering fullscreen would change standaloneMatchMedia.matches to false\n // if standalone is true (running as PWA) and entering fullscreen, skip this change\n if (standalone && fullScreenMatchMedia.matches) {\n return;\n }\n // otherwise update standalone (browser to PWA or PWA to browser)\n standalone = matches;\n });\n}\nfunction isStandalone() {\n return standalone;\n}\n// Visible means that the feature is enabled, not necessarily being rendered\n// e.g. visible is true even in fullscreen mode where the controls are hidden\n// See docs at https://developer.mozilla.org/en-US/docs/Web/API/WindowControlsOverlay/visible\nfunction isWCOEnabled() {\n return navigator?.windowControlsOverlay?.visible;\n}\n// Returns the bounding rect of the titlebar area if it is supported and defined\n// See docs at https://developer.mozilla.org/en-US/docs/Web/API/WindowControlsOverlay/getTitlebarAreaRect\nfunction getWCOBoundingRect() {\n return navigator?.windowControlsOverlay?.getTitlebarAreaRect();\n}\n","\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.BrowserFeatures = exports.KeyboardSupport = void 0;\nconst browser = __importStar(require(\"vs/base/browser/browser\"));\nconst window_1 = require(\"vs/base/browser/window\");\nconst platform = __importStar(require(\"vs/base/common/platform\"));\nvar KeyboardSupport;\n(function (KeyboardSupport) {\n KeyboardSupport[KeyboardSupport[\"Always\"] = 0] = \"Always\";\n KeyboardSupport[KeyboardSupport[\"FullScreen\"] = 1] = \"FullScreen\";\n KeyboardSupport[KeyboardSupport[\"None\"] = 2] = \"None\";\n})(KeyboardSupport || (exports.KeyboardSupport = KeyboardSupport = {}));\nconst safeNavigator = typeof navigator === 'object' ? navigator : {};\n/**\n * Browser feature we can support in current platform, browser and environment.\n */\nexports.BrowserFeatures = {\n clipboard: {\n writeText: (platform.isNative\n || (document.queryCommandSupported && document.queryCommandSupported('copy'))\n || !!(safeNavigator && safeNavigator.clipboard && safeNavigator.clipboard.writeText)),\n readText: (platform.isNative\n || !!(safeNavigator && safeNavigator.clipboard && safeNavigator.clipboard.readText))\n },\n keyboard: (() => {\n if (platform.isNative || browser.isStandalone()) {\n return KeyboardSupport.Always;\n }\n if (safeNavigator.keyboard || browser.isSafari) {\n return KeyboardSupport.FullScreen;\n }\n return KeyboardSupport.None;\n })(),\n // 'ontouchstart' in window always evaluates to true with typescript's modern typings. This causes `window` to be\n // `never` later in `window.navigator`. That's why we need the explicit `window as Window` cast\n touch: 'ontouchstart' in window_1.mainWindow || safeNavigator.maxTouchPoints > 0,\n pointerEvents: window_1.mainWindow.PointerEvent && ('ontouchstart' in window_1.mainWindow || navigator.maxTouchPoints > 0)\n};\n","\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar _a;\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.SafeTriangle = exports.DragAndDropObserver = exports.ModifierKeyEmitter = exports.DetectedFullscreenMode = exports.Namespace = exports.EventHelper = exports.EventType = exports.sharedMutationObserver = exports.Dimension = exports.WindowIntervalTimer = exports.scheduleAtNextAnimationFrame = exports.runAtThisOrScheduleAtNextAnimationFrame = exports.WindowIdleValue = exports.addStandardDisposableGenericMouseUpListener = exports.addStandardDisposableGenericMouseDownListener = exports.addStandardDisposableListener = exports.onDidUnregisterWindow = exports.onWillUnregisterWindow = exports.onDidRegisterWindow = exports.hasWindow = exports.getWindowById = exports.getWindowId = exports.getWindowsCount = exports.getWindows = exports.getDocument = exports.getWindow = exports.registerWindow = void 0;\nexports.clearNode = clearNode;\nexports.clearNodeRecursively = clearNodeRecursively;\nexports.addDisposableListener = addDisposableListener;\nexports.addDisposableGenericMouseDownListener = addDisposableGenericMouseDownListener;\nexports.addDisposableGenericMouseMoveListener = addDisposableGenericMouseMoveListener;\nexports.addDisposableGenericMouseUpListener = addDisposableGenericMouseUpListener;\nexports.runWhenWindowIdle = runWhenWindowIdle;\nexports.disposableWindowInterval = disposableWindowInterval;\nexports.measure = measure;\nexports.modify = modify;\nexports.addDisposableThrottledListener = addDisposableThrottledListener;\nexports.getComputedStyle = getComputedStyle;\nexports.getClientArea = getClientArea;\nexports.getTopLeftOffset = getTopLeftOffset;\nexports.size = size;\nexports.position = position;\nexports.getDomNodePagePosition = getDomNodePagePosition;\nexports.getDomNodeZoomLevel = getDomNodeZoomLevel;\nexports.getTotalWidth = getTotalWidth;\nexports.getContentWidth = getContentWidth;\nexports.getTotalScrollWidth = getTotalScrollWidth;\nexports.getContentHeight = getContentHeight;\nexports.getTotalHeight = getTotalHeight;\nexports.getLargestChildWidth = getLargestChildWidth;\nexports.isAncestor = isAncestor;\nexports.setParentFlowTo = setParentFlowTo;\nexports.isAncestorUsingFlowTo = isAncestorUsingFlowTo;\nexports.findParentWithClass = findParentWithClass;\nexports.hasParentWithClass = hasParentWithClass;\nexports.isShadowRoot = isShadowRoot;\nexports.isInShadowDOM = isInShadowDOM;\nexports.getShadowRoot = getShadowRoot;\nexports.getActiveElement = getActiveElement;\nexports.isActiveElement = isActiveElement;\nexports.isAncestorOfActiveElement = isAncestorOfActiveElement;\nexports.isActiveDocument = isActiveDocument;\nexports.getActiveDocument = getActiveDocument;\nexports.getActiveWindow = getActiveWindow;\nexports.isGlobalStylesheet = isGlobalStylesheet;\nexports.createStyleSheet2 = createStyleSheet2;\nexports.createStyleSheet = createStyleSheet;\nexports.cloneGlobalStylesheets = cloneGlobalStylesheets;\nexports.createMetaElement = createMetaElement;\nexports.createLinkElement = createLinkElement;\nexports.createCSSRule = createCSSRule;\nexports.removeCSSRulesContainingSelector = removeCSSRulesContainingSelector;\nexports.isHTMLElement = isHTMLElement;\nexports.isHTMLAnchorElement = isHTMLAnchorElement;\nexports.isHTMLSpanElement = isHTMLSpanElement;\nexports.isHTMLTextAreaElement = isHTMLTextAreaElement;\nexports.isHTMLInputElement = isHTMLInputElement;\nexports.isHTMLButtonElement = isHTMLButtonElement;\nexports.isHTMLDivElement = isHTMLDivElement;\nexports.isSVGElement = isSVGElement;\nexports.isMouseEvent = isMouseEvent;\nexports.isKeyboardEvent = isKeyboardEvent;\nexports.isPointerEvent = isPointerEvent;\nexports.isDragEvent = isDragEvent;\nexports.isEventLike = isEventLike;\nexports.saveParentsScrollTop = saveParentsScrollTop;\nexports.restoreParentsScrollTop = restoreParentsScrollTop;\nexports.trackFocus = trackFocus;\nexports.after = after;\nexports.append = append;\nexports.prepend = prepend;\nexports.reset = reset;\nexports.$ = $;\nexports.join = join;\nexports.setVisibility = setVisibility;\nexports.show = show;\nexports.hide = hide;\nexports.removeTabIndexAndUpdateFocus = removeTabIndexAndUpdateFocus;\nexports.finalHandler = finalHandler;\nexports.domContentLoaded = domContentLoaded;\nexports.computeScreenAwareSize = computeScreenAwareSize;\nexports.windowOpenNoOpener = windowOpenNoOpener;\nexports.windowOpenPopup = windowOpenPopup;\nexports.windowOpenWithSuccess = windowOpenWithSuccess;\nexports.animate = animate;\nexports.asCSSPropertyValue = asCSSPropertyValue;\nexports.asCssValueWithDefault = asCssValueWithDefault;\nexports.detectFullscreen = detectFullscreen;\nexports.multibyteAwareBtoa = multibyteAwareBtoa;\nexports.getCookieValue = getCookieValue;\nexports.h = h;\nexports.svgElem = svgElem;\nexports.copyAttributes = copyAttributes;\nexports.trackAttributes = trackAttributes;\nconst browser = __importStar(require(\"vs/base/browser/browser\"));\nconst canIUse_1 = require(\"vs/base/browser/canIUse\");\nconst keyboardEvent_1 = require(\"vs/base/browser/keyboardEvent\");\nconst mouseEvent_1 = require(\"vs/base/browser/mouseEvent\");\nconst async_1 = require(\"vs/base/common/async\");\nconst errors_1 = require(\"vs/base/common/errors\");\nconst event = __importStar(require(\"vs/base/common/event\"));\nconst keyCodes_1 = require(\"vs/base/common/keyCodes\");\nconst lifecycle_1 = require(\"vs/base/common/lifecycle\");\nconst platform = __importStar(require(\"vs/base/common/platform\"));\nconst hash_1 = require(\"vs/base/common/hash\");\nconst window_1 = require(\"vs/base/browser/window\");\nconst numbers_1 = require(\"vs/base/common/numbers\");\n//# region Multi-Window Support Utilities\n_a = (function () {\n const windows = new Map();\n (0, window_1.ensureCodeWindow)(window_1.mainWindow, 1);\n const mainWindowRegistration = { window: window_1.mainWindow, disposables: new lifecycle_1.DisposableStore() };\n windows.set(window_1.mainWindow.vscodeWindowId, mainWindowRegistration);\n const onDidRegisterWindow = new event.Emitter();\n const onDidUnregisterWindow = new event.Emitter();\n const onWillUnregisterWindow = new event.Emitter();\n function getWindowById(windowId, fallbackToMain) {\n const window = typeof windowId === 'number' ? windows.get(windowId) : undefined;\n return window ?? (fallbackToMain ? mainWindowRegistration : undefined);\n }\n return {\n onDidRegisterWindow: onDidRegisterWindow.event,\n onWillUnregisterWindow: onWillUnregisterWindow.event,\n onDidUnregisterWindow: onDidUnregisterWindow.event,\n registerWindow(window) {\n if (windows.has(window.vscodeWindowId)) {\n return lifecycle_1.Disposable.None;\n }\n const disposables = new lifecycle_1.DisposableStore();\n const registeredWindow = {\n window,\n disposables: disposables.add(new lifecycle_1.DisposableStore())\n };\n windows.set(window.vscodeWindowId, registeredWindow);\n disposables.add((0, lifecycle_1.toDisposable)(() => {\n windows.delete(window.vscodeWindowId);\n onDidUnregisterWindow.fire(window);\n }));\n disposables.add(addDisposableListener(window, exports.EventType.BEFORE_UNLOAD, () => {\n onWillUnregisterWindow.fire(window);\n }));\n onDidRegisterWindow.fire(registeredWindow);\n return disposables;\n },\n getWindows() {\n return windows.values();\n },\n getWindowsCount() {\n return windows.size;\n },\n getWindowId(targetWindow) {\n return targetWindow.vscodeWindowId;\n },\n hasWindow(windowId) {\n return windows.has(windowId);\n },\n getWindowById,\n getWindow(e) {\n const candidateNode = e;\n if (candidateNode?.ownerDocument?.defaultView) {\n return candidateNode.ownerDocument.defaultView.window;\n }\n const candidateEvent = e;\n if (candidateEvent?.view) {\n return candidateEvent.view.window;\n }\n return window_1.mainWindow;\n },\n getDocument(e) {\n const candidateNode = e;\n return (0, exports.getWindow)(candidateNode).document;\n }\n };\n})(), exports.registerWindow = _a.registerWindow, exports.getWindow = _a.getWindow, exports.getDocument = _a.getDocument, exports.getWindows = _a.getWindows, exports.getWindowsCount = _a.getWindowsCount, exports.getWindowId = _a.getWindowId, exports.getWindowById = _a.getWindowById, exports.hasWindow = _a.hasWindow, exports.onDidRegisterWindow = _a.onDidRegisterWindow, exports.onWillUnregisterWindow = _a.onWillUnregisterWindow, exports.onDidUnregisterWindow = _a.onDidUnregisterWindow;\n//#endregion\nfunction clearNode(node) {\n while (node.firstChild) {\n node.firstChild.remove();\n }\n}\nfunction clearNodeRecursively(domNode) {\n while (domNode.firstChild) {\n const element = domNode.firstChild;\n element.remove();\n clearNodeRecursively(element);\n }\n}\nclass DomListener {\n constructor(node, type, handler, options) {\n this._node = node;\n this._type = type;\n this._handler = handler;\n this._options = (options || false);\n this._node.addEventListener(this._type, this._handler, this._options);\n }\n dispose() {\n if (!this._handler) {\n // Already disposed\n return;\n }\n this._node.removeEventListener(this._type, this._handler, this._options);\n // Prevent leakers from holding on to the dom or handler func\n this._node = null;\n this._handler = null;\n }\n}\nfunction addDisposableListener(node, type, handler, useCaptureOrOptions) {\n return new DomListener(node, type, handler, useCaptureOrOptions);\n}\nfunction _wrapAsStandardMouseEvent(targetWindow, handler) {\n return function (e) {\n return handler(new mouseEvent_1.StandardMouseEvent(targetWindow, e));\n };\n}\nfunction _wrapAsStandardKeyboardEvent(handler) {\n return function (e) {\n return handler(new keyboardEvent_1.StandardKeyboardEvent(e));\n };\n}\nconst addStandardDisposableListener = function addStandardDisposableListener(node, type, handler, useCapture) {\n let wrapHandler = handler;\n if (type === 'click' || type === 'mousedown' || type === 'contextmenu') {\n wrapHandler = _wrapAsStandardMouseEvent((0, exports.getWindow)(node), handler);\n }\n else if (type === 'keydown' || type === 'keypress' || type === 'keyup') {\n wrapHandler = _wrapAsStandardKeyboardEvent(handler);\n }\n return addDisposableListener(node, type, wrapHandler, useCapture);\n};\nexports.addStandardDisposableListener = addStandardDisposableListener;\nconst addStandardDisposableGenericMouseDownListener = function addStandardDisposableListener(node, handler, useCapture) {\n const wrapHandler = _wrapAsStandardMouseEvent((0, exports.getWindow)(node), handler);\n return addDisposableGenericMouseDownListener(node, wrapHandler, useCapture);\n};\nexports.addStandardDisposableGenericMouseDownListener = addStandardDisposableGenericMouseDownListener;\nconst addStandardDisposableGenericMouseUpListener = function addStandardDisposableListener(node, handler, useCapture) {\n const wrapHandler = _wrapAsStandardMouseEvent((0, exports.getWindow)(node), handler);\n return addDisposableGenericMouseUpListener(node, wrapHandler, useCapture);\n};\nexports.addStandardDisposableGenericMouseUpListener = addStandardDisposableGenericMouseUpListener;\nfunction addDisposableGenericMouseDownListener(node, handler, useCapture) {\n return addDisposableListener(node, platform.isIOS && canIUse_1.BrowserFeatures.pointerEvents ? exports.EventType.POINTER_DOWN : exports.EventType.MOUSE_DOWN, handler, useCapture);\n}\nfunction addDisposableGenericMouseMoveListener(node, handler, useCapture) {\n return addDisposableListener(node, platform.isIOS && canIUse_1.BrowserFeatures.pointerEvents ? exports.EventType.POINTER_MOVE : exports.EventType.MOUSE_MOVE, handler, useCapture);\n}\nfunction addDisposableGenericMouseUpListener(node, handler, useCapture) {\n return addDisposableListener(node, platform.isIOS && canIUse_1.BrowserFeatures.pointerEvents ? exports.EventType.POINTER_UP : exports.EventType.MOUSE_UP, handler, useCapture);\n}\n/**\n * Execute the callback the next time the browser is idle, returning an\n * {@link IDisposable} that will cancel the callback when disposed. This wraps\n * [requestIdleCallback] so it will fallback to [setTimeout] if the environment\n * doesn't support it.\n *\n * @param targetWindow The window for which to run the idle callback\n * @param callback The callback to run when idle, this includes an\n * [IdleDeadline] that provides the time alloted for the idle callback by the\n * browser. Not respecting this deadline will result in a degraded user\n * experience.\n * @param timeout A timeout at which point to queue no longer wait for an idle\n * callback but queue it on the regular event loop (like setTimeout). Typically\n * this should not be used.\n *\n * [IdleDeadline]: https://developer.mozilla.org/en-US/docs/Web/API/IdleDeadline\n * [requestIdleCallback]: https://developer.mozilla.org/en-US/docs/Web/API/Window/requestIdleCallback\n * [setTimeout]: https://developer.mozilla.org/en-US/docs/Web/API/Window/setTimeout\n */\nfunction runWhenWindowIdle(targetWindow, callback, timeout) {\n return (0, async_1._runWhenIdle)(targetWindow, callback, timeout);\n}\n/**\n * An implementation of the \"idle-until-urgent\"-strategy as introduced\n * here: https://philipwalton.com/articles/idle-until-urgent/\n */\nclass WindowIdleValue extends async_1.AbstractIdleValue {\n constructor(targetWindow, executor) {\n super(targetWindow, executor);\n }\n}\nexports.WindowIdleValue = WindowIdleValue;\nfunction disposableWindowInterval(targetWindow, handler, interval, iterations) {\n let iteration = 0;\n const timer = targetWindow.setInterval(() => {\n iteration++;\n if ((typeof iterations === 'number' && iteration >= iterations) || handler() === true) {\n disposable.dispose();\n }\n }, interval);\n const disposable = (0, lifecycle_1.toDisposable)(() => {\n targetWindow.clearInterval(timer);\n });\n return disposable;\n}\nclass WindowIntervalTimer extends async_1.IntervalTimer {\n /**\n *\n * @param node The optional node from which the target window is determined\n */\n constructor(node) {\n super();\n this.defaultTarget = node && (0, exports.getWindow)(node);\n }\n cancelAndSet(runner, interval, targetWindow) {\n return super.cancelAndSet(runner, interval, targetWindow ?? this.defaultTarget);\n }\n}\nexports.WindowIntervalTimer = WindowIntervalTimer;\nclass AnimationFrameQueueItem {\n constructor(runner, priority = 0) {\n this._runner = runner;\n this.priority = priority;\n this._canceled = false;\n }\n dispose() {\n this._canceled = true;\n }\n execute() {\n if (this._canceled) {\n return;\n }\n try {\n this._runner();\n }\n catch (e) {\n (0, errors_1.onUnexpectedError)(e);\n }\n }\n // Sort by priority (largest to lowest)\n static sort(a, b) {\n return b.priority - a.priority;\n }\n}\n(function () {\n /**\n * The runners scheduled at the next animation frame\n */\n const NEXT_QUEUE = new Map();\n /**\n * The runners scheduled at the current animation frame\n */\n const CURRENT_QUEUE = new Map();\n /**\n * A flag to keep track if the native requestAnimationFrame was already called\n */\n const animFrameRequested = new Map();\n /**\n * A flag to indicate if currently handling a native requestAnimationFrame callback\n */\n const inAnimationFrameRunner = new Map();\n const animationFrameRunner = (targetWindowId) => {\n animFrameRequested.set(targetWindowId, false);\n const currentQueue = NEXT_QUEUE.get(targetWindowId) ?? [];\n CURRENT_QUEUE.set(targetWindowId, currentQueue);\n NEXT_QUEUE.set(targetWindowId, []);\n inAnimationFrameRunner.set(targetWindowId, true);\n while (currentQueue.length > 0) {\n currentQueue.sort(AnimationFrameQueueItem.sort);\n const top = currentQueue.shift();\n top.execute();\n }\n inAnimationFrameRunner.set(targetWindowId, false);\n };\n exports.scheduleAtNextAnimationFrame = (targetWindow, runner, priority = 0) => {\n const targetWindowId = (0, exports.getWindowId)(targetWindow);\n const item = new AnimationFrameQueueItem(runner, priority);\n let nextQueue = NEXT_QUEUE.get(targetWindowId);\n if (!nextQueue) {\n nextQueue = [];\n NEXT_QUEUE.set(targetWindowId, nextQueue);\n }\n nextQueue.push(item);\n if (!animFrameRequested.get(targetWindowId)) {\n animFrameRequested.set(targetWindowId, true);\n targetWindow.requestAnimationFrame(() => animationFrameRunner(targetWindowId));\n }\n return item;\n };\n exports.runAtThisOrScheduleAtNextAnimationFrame = (targetWindow, runner, priority) => {\n const targetWindowId = (0, exports.getWindowId)(targetWindow);\n if (inAnimationFrameRunner.get(targetWindowId)) {\n const item = new AnimationFrameQueueItem(runner, priority);\n let currentQueue = CURRENT_QUEUE.get(targetWindowId);\n if (!currentQueue) {\n currentQueue = [];\n CURRENT_QUEUE.set(targetWindowId, currentQueue);\n }\n currentQueue.push(item);\n return item;\n }\n else {\n return (0, exports.scheduleAtNextAnimationFrame)(targetWindow, runner, priority);\n }\n };\n})();\nfunction measure(targetWindow, callback) {\n return (0, exports.scheduleAtNextAnimationFrame)(targetWindow, callback, 10000 /* must be early */);\n}\nfunction modify(targetWindow, callback) {\n return (0, exports.scheduleAtNextAnimationFrame)(targetWindow, callback, -10000 /* must be late */);\n}\nconst MINIMUM_TIME_MS = 8;\nconst DEFAULT_EVENT_MERGER = function (lastEvent, currentEvent) {\n return currentEvent;\n};\nclass TimeoutThrottledDomListener extends lifecycle_1.Disposable {\n constructor(node, type, handler, eventMerger = DEFAULT_EVENT_MERGER, minimumTimeMs = MINIMUM_TIME_MS) {\n super();\n let lastEvent = null;\n let lastHandlerTime = 0;\n const timeout = this._register(new async_1.TimeoutTimer());\n const invokeHandler = () => {\n lastHandlerTime = (new Date()).getTime();\n handler(lastEvent);\n lastEvent = null;\n };\n this._register(addDisposableListener(node, type, (e) => {\n lastEvent = eventMerger(lastEvent, e);\n const elapsedTime = (new Date()).getTime() - lastHandlerTime;\n if (elapsedTime >= minimumTimeMs) {\n timeout.cancel();\n invokeHandler();\n }\n else {\n timeout.setIfNotSet(invokeHandler, minimumTimeMs - elapsedTime);\n }\n }));\n }\n}\nfunction addDisposableThrottledListener(node, type, handler, eventMerger, minimumTimeMs) {\n return new TimeoutThrottledDomListener(node, type, handler, eventMerger, minimumTimeMs);\n}\nfunction getComputedStyle(el) {\n return (0, exports.getWindow)(el).getComputedStyle(el, null);\n}\nfunction getClientArea(element, fallback) {\n const elWindow = (0, exports.getWindow)(element);\n const elDocument = elWindow.document;\n // Try with DOM clientWidth / clientHeight\n if (element !== elDocument.body) {\n return new Dimension(element.clientWidth, element.clientHeight);\n }\n // If visual view port exits and it's on mobile, it should be used instead of window innerWidth / innerHeight, or document.body.clientWidth / document.body.clientHeight\n if (platform.isIOS && elWindow?.visualViewport) {\n return new Dimension(elWindow.visualViewport.width, elWindow.visualViewport.height);\n }\n // Try innerWidth / innerHeight\n if (elWindow?.innerWidth && elWindow.innerHeight) {\n return new Dimension(elWindow.innerWidth, elWindow.innerHeight);\n }\n // Try with document.body.clientWidth / document.body.clientHeight\n if (elDocument.body && elDocument.body.clientWidth && elDocument.body.clientHeight) {\n return new Dimension(elDocument.body.clientWidth, elDocument.body.clientHeight);\n }\n // Try with document.documentElement.clientWidth / document.documentElement.clientHeight\n if (elDocument.documentElement && elDocument.documentElement.clientWidth && elDocument.documentElement.clientHeight) {\n return new Dimension(elDocument.documentElement.clientWidth, elDocument.documentElement.clientHeight);\n }\n if (fallback) {\n return getClientArea(fallback);\n }\n throw new Error('Unable to figure out browser width and height');\n}\nclass SizeUtils {\n // Adapted from WinJS\n // Converts a CSS positioning string for the specified element to pixels.\n static convertToPixels(element, value) {\n return parseFloat(value) || 0;\n }\n static getDimension(element, cssPropertyName, jsPropertyName) {\n const computedStyle = getComputedStyle(element);\n const value = computedStyle ? computedStyle.getPropertyValue(cssPropertyName) : '0';\n return SizeUtils.convertToPixels(element, value);\n }\n static getBorderLeftWidth(element) {\n return SizeUtils.getDimension(element, 'border-left-width', 'borderLeftWidth');\n }\n static getBorderRightWidth(element) {\n return SizeUtils.getDimension(element, 'border-right-width', 'borderRightWidth');\n }\n static getBorderTopWidth(element) {\n return SizeUtils.getDimension(element, 'border-top-width', 'borderTopWidth');\n }\n static getBorderBottomWidth(element) {\n return SizeUtils.getDimension(element, 'border-bottom-width', 'borderBottomWidth');\n }\n static getPaddingLeft(element) {\n return SizeUtils.getDimension(element, 'padding-left', 'paddingLeft');\n }\n static getPaddingRight(element) {\n return SizeUtils.getDimension(element, 'padding-right', 'paddingRight');\n }\n static getPaddingTop(element) {\n return SizeUtils.getDimension(element, 'padding-top', 'paddingTop');\n }\n static getPaddingBottom(element) {\n return SizeUtils.getDimension(element, 'padding-bottom', 'paddingBottom');\n }\n static getMarginLeft(element) {\n return SizeUtils.getDimension(element, 'margin-left', 'marginLeft');\n }\n static getMarginTop(element) {\n return SizeUtils.getDimension(element, 'margin-top', 'marginTop');\n }\n static getMarginRight(element) {\n return SizeUtils.getDimension(element, 'margin-right', 'marginRight');\n }\n static getMarginBottom(element) {\n return SizeUtils.getDimension(element, 'margin-bottom', 'marginBottom');\n }\n}\nclass Dimension {\n static { this.None = new Dimension(0, 0); }\n constructor(width, height) {\n this.width = width;\n this.height = height;\n }\n with(width = this.width, height = this.height) {\n if (width !== this.width || height !== this.height) {\n return new Dimension(width, height);\n }\n else {\n return this;\n }\n }\n static is(obj) {\n return typeof obj === 'object' && typeof obj.height === 'number' && typeof obj.width === 'number';\n }\n static lift(obj) {\n if (obj instanceof Dimension) {\n return obj;\n }\n else {\n return new Dimension(obj.width, obj.height);\n }\n }\n static equals(a, b) {\n if (a === b) {\n return true;\n }\n if (!a || !b) {\n return false;\n }\n return a.width === b.width && a.height === b.height;\n }\n}\nexports.Dimension = Dimension;\nfunction getTopLeftOffset(element) {\n // Adapted from WinJS.Utilities.getPosition\n // and added borders to the mix\n let offsetParent = element.offsetParent;\n let top = element.offsetTop;\n let left = element.offsetLeft;\n while ((element = element.parentNode) !== null\n && element !== element.ownerDocument.body\n && element !== element.ownerDocument.documentElement) {\n top -= element.scrollTop;\n const c = isShadowRoot(element) ? null : getComputedStyle(element);\n if (c) {\n left -= c.direction !== 'rtl' ? element.scrollLeft : -element.scrollLeft;\n }\n if (element === offsetParent) {\n left += SizeUtils.getBorderLeftWidth(element);\n top += SizeUtils.getBorderTopWidth(element);\n top += element.offsetTop;\n left += element.offsetLeft;\n offsetParent = element.offsetParent;\n }\n }\n return {\n left: left,\n top: top\n };\n}\nfunction size(element, width, height) {\n if (typeof width === 'number') {\n element.style.width = `${width}px`;\n }\n if (typeof height === 'number') {\n element.style.height = `${height}px`;\n }\n}\nfunction position(element, top, right, bottom, left, position = 'absolute') {\n if (typeof top === 'number') {\n element.style.top = `${top}px`;\n }\n if (typeof right === 'number') {\n element.style.right = `${right}px`;\n }\n if (typeof bottom === 'number') {\n element.style.bottom = `${bottom}px`;\n }\n if (typeof left === 'number') {\n element.style.left = `${left}px`;\n }\n element.style.position = position;\n}\n/**\n * Returns the position of a dom node relative to the entire page.\n */\nfunction getDomNodePagePosition(domNode) {\n const bb = domNode.getBoundingClientRect();\n const window = (0, exports.getWindow)(domNode);\n return {\n left: bb.left + window.scrollX,\n top: bb.top + window.scrollY,\n width: bb.width,\n height: bb.height\n };\n}\n/**\n * Returns the effective zoom on a given element before window zoom level is applied\n */\nfunction getDomNodeZoomLevel(domNode) {\n let testElement = domNode;\n let zoom = 1.0;\n do {\n const elementZoomLevel = getComputedStyle(testElement).zoom;\n if (elementZoomLevel !== null && elementZoomLevel !== undefined && elementZoomLevel !== '1') {\n zoom *= elementZoomLevel;\n }\n testElement = testElement.parentElement;\n } while (testElement !== null && testElement !== testElement.ownerDocument.documentElement);\n return zoom;\n}\n// Adapted from WinJS\n// Gets the width of the element, including margins.\nfunction getTotalWidth(element) {\n const margin = SizeUtils.getMarginLeft(element) + SizeUtils.getMarginRight(element);\n return element.offsetWidth + margin;\n}\nfunction getContentWidth(element) {\n const border = SizeUtils.getBorderLeftWidth(element) + SizeUtils.getBorderRightWidth(element);\n const padding = SizeUtils.getPaddingLeft(element) + SizeUtils.getPaddingRight(element);\n return element.offsetWidth - border - padding;\n}\nfunction getTotalScrollWidth(element) {\n const margin = SizeUtils.getMarginLeft(element) + SizeUtils.getMarginRight(element);\n return element.scrollWidth + margin;\n}\n// Adapted from WinJS\n// Gets the height of the content of the specified element. The content height does not include borders or padding.\nfunction getContentHeight(element) {\n const border = SizeUtils.getBorderTopWidth(element) + SizeUtils.getBorderBottomWidth(element);\n const padding = SizeUtils.getPaddingTop(element) + SizeUtils.getPaddingBottom(element);\n return element.offsetHeight - border - padding;\n}\n// Adapted from WinJS\n// Gets the height of the element, including its margins.\nfunction getTotalHeight(element) {\n const margin = SizeUtils.getMarginTop(element) + SizeUtils.getMarginBottom(element);\n return element.offsetHeight + margin;\n}\n// Gets the left coordinate of the specified element relative to the specified parent.\nfunction getRelativeLeft(element, parent) {\n if (element === null) {\n return 0;\n }\n const elementPosition = getTopLeftOffset(element);\n const parentPosition = getTopLeftOffset(parent);\n return elementPosition.left - parentPosition.left;\n}\nfunction getLargestChildWidth(parent, children) {\n const childWidths = children.map((child) => {\n return Math.max(getTotalScrollWidth(child), getTotalWidth(child)) + getRelativeLeft(child, parent) || 0;\n });\n const maxWidth = Math.max(...childWidths);\n return maxWidth;\n}\n// ----------------------------------------------------------------------------------------\nfunction isAncestor(testChild, testAncestor) {\n return Boolean(testAncestor?.contains(testChild));\n}\nconst parentFlowToDataKey = 'parentFlowToElementId';\n/**\n * Set an explicit parent to use for nodes that are not part of the\n * regular dom structure.\n */\nfunction setParentFlowTo(fromChildElement, toParentElement) {\n fromChildElement.dataset[parentFlowToDataKey] = toParentElement.id;\n}\nfunction getParentFlowToElement(node) {\n const flowToParentId = node.dataset[parentFlowToDataKey];\n if (typeof flowToParentId === 'string') {\n return node.ownerDocument.getElementById(flowToParentId);\n }\n return null;\n}\n/**\n * Check if `testAncestor` is an ancestor of `testChild`, observing the explicit\n * parents set by `setParentFlowTo`.\n */\nfunction isAncestorUsingFlowTo(testChild, testAncestor) {\n let node = testChild;\n while (node) {\n if (node === testAncestor) {\n return true;\n }\n if (isHTMLElement(node)) {\n const flowToParentElement = getParentFlowToElement(node);\n if (flowToParentElement) {\n node = flowToParentElement;\n continue;\n }\n }\n node = node.parentNode;\n }\n return false;\n}\nfunction findParentWithClass(node, clazz, stopAtClazzOrNode) {\n while (node && node.nodeType === node.ELEMENT_NODE) {\n if (node.classList.contains(clazz)) {\n return node;\n }\n if (stopAtClazzOrNode) {\n if (typeof stopAtClazzOrNode === 'string') {\n if (node.classList.contains(stopAtClazzOrNode)) {\n return null;\n }\n }\n else {\n if (node === stopAtClazzOrNode) {\n return null;\n }\n }\n }\n node = node.parentNode;\n }\n return null;\n}\nfunction hasParentWithClass(node, clazz, stopAtClazzOrNode) {\n return !!findParentWithClass(node, clazz, stopAtClazzOrNode);\n}\nfunction isShadowRoot(node) {\n return (node && !!node.host && !!node.mode);\n}\nfunction isInShadowDOM(domNode) {\n return !!getShadowRoot(domNode);\n}\nfunction getShadowRoot(domNode) {\n while (domNode.parentNode) {\n if (domNode === domNode.ownerDocument?.body) {\n // reached the body\n return null;\n }\n domNode = domNode.parentNode;\n }\n return isShadowRoot(domNode) ? domNode : null;\n}\n/**\n * Returns the active element across all child windows\n * based on document focus. Falls back to the main\n * window if no window has focus.\n */\nfunction getActiveElement() {\n let result = getActiveDocument().activeElement;\n while (result?.shadowRoot) {\n result = result.shadowRoot.activeElement;\n }\n return result;\n}\n/**\n * Returns true if the focused window active element matches\n * the provided element. Falls back to the main window if no\n * window has focus.\n */\nfunction isActiveElement(element) {\n return getActiveElement() === element;\n}\n/**\n * Returns true if the focused window active element is contained in\n * `ancestor`. Falls back to the main window if no window has focus.\n */\nfunction isAncestorOfActiveElement(ancestor) {\n return isAncestor(getActiveElement(), ancestor);\n}\n/**\n * Returns whether the element is in the active `document`. The active\n * document has focus or will be the main windows document.\n */\nfunction isActiveDocument(element) {\n return element.ownerDocument === getActiveDocument();\n}\n/**\n * Returns the active document across main and child windows.\n * Prefers the window with focus, otherwise falls back to\n * the main windows document.\n */\nfunction getActiveDocument() {\n if ((0, exports.getWindowsCount)() <= 1) {\n return window_1.mainWindow.document;\n }\n const documents = Array.from((0, exports.getWindows)()).map(({ window }) => window.document);\n return documents.find(doc => doc.hasFocus()) ?? window_1.mainWindow.document;\n}\n/**\n * Returns the active window across main and child windows.\n * Prefers the window with focus, otherwise falls back to\n * the main window.\n */\nfunction getActiveWindow() {\n const document = getActiveDocument();\n return (document.defaultView?.window ?? window_1.mainWindow);\n}\nconst globalStylesheets = new Map();\nfunction isGlobalStylesheet(node) {\n return globalStylesheets.has(node);\n}\n/**\n * A version of createStyleSheet which has a unified API to initialize/set the style content.\n */\nfunction createStyleSheet2() {\n return new WrappedStyleElement();\n}\nclass WrappedStyleElement {\n constructor() {\n this._currentCssStyle = '';\n this._styleSheet = undefined;\n }\n setStyle(cssStyle) {\n if (cssStyle === this._currentCssStyle) {\n return;\n }\n this._currentCssStyle = cssStyle;\n if (!this._styleSheet) {\n this._styleSheet = createStyleSheet(window_1.mainWindow.document.head, (s) => s.innerText = cssStyle);\n }\n else {\n this._styleSheet.innerText = cssStyle;\n }\n }\n dispose() {\n if (this._styleSheet) {\n this._styleSheet.remove();\n this._styleSheet = undefined;\n }\n }\n}\nfunction createStyleSheet(container = window_1.mainWindow.document.head, beforeAppend, disposableStore) {\n const style = document.createElement('style');\n style.type = 'text/css';\n style.media = 'screen';\n beforeAppend?.(style);\n container.appendChild(style);\n if (disposableStore) {\n disposableStore.add((0, lifecycle_1.toDisposable)(() => style.remove()));\n }\n // With as container, the stylesheet becomes global and is tracked\n // to support auxiliary windows to clone the stylesheet.\n if (container === window_1.mainWindow.document.head) {\n const globalStylesheetClones = new Set();\n globalStylesheets.set(style, globalStylesheetClones);\n for (const { window: targetWindow, disposables } of (0, exports.getWindows)()) {\n if (targetWindow === window_1.mainWindow) {\n continue; // main window is already tracked\n }\n const cloneDisposable = disposables.add(cloneGlobalStyleSheet(style, globalStylesheetClones, targetWindow));\n disposableStore?.add(cloneDisposable);\n }\n }\n return style;\n}\nfunction cloneGlobalStylesheets(targetWindow) {\n const disposables = new lifecycle_1.DisposableStore();\n for (const [globalStylesheet, clonedGlobalStylesheets] of globalStylesheets) {\n disposables.add(cloneGlobalStyleSheet(globalStylesheet, clonedGlobalStylesheets, targetWindow));\n }\n return disposables;\n}\nfunction cloneGlobalStyleSheet(globalStylesheet, globalStylesheetClones, targetWindow) {\n const disposables = new lifecycle_1.DisposableStore();\n const clone = globalStylesheet.cloneNode(true);\n targetWindow.document.head.appendChild(clone);\n disposables.add((0, lifecycle_1.toDisposable)(() => clone.remove()));\n for (const rule of getDynamicStyleSheetRules(globalStylesheet)) {\n clone.sheet?.insertRule(rule.cssText, clone.sheet?.cssRules.length);\n }\n disposables.add(exports.sharedMutationObserver.observe(globalStylesheet, disposables, { childList: true })(() => {\n clone.textContent = globalStylesheet.textContent;\n }));\n globalStylesheetClones.add(clone);\n disposables.add((0, lifecycle_1.toDisposable)(() => globalStylesheetClones.delete(clone)));\n return disposables;\n}\nexports.sharedMutationObserver = new class {\n constructor() {\n this.mutationObservers = new Map();\n }\n observe(target, disposables, options) {\n let mutationObserversPerTarget = this.mutationObservers.get(target);\n if (!mutationObserversPerTarget) {\n mutationObserversPerTarget = new Map();\n this.mutationObservers.set(target, mutationObserversPerTarget);\n }\n const optionsHash = (0, hash_1.hash)(options);\n let mutationObserverPerOptions = mutationObserversPerTarget.get(optionsHash);\n if (!mutationObserverPerOptions) {\n const onDidMutate = new event.Emitter();\n const observer = new MutationObserver(mutations => onDidMutate.fire(mutations));\n observer.observe(target, options);\n const resolvedMutationObserverPerOptions = mutationObserverPerOptions = {\n users: 1,\n observer,\n onDidMutate: onDidMutate.event\n };\n disposables.add((0, lifecycle_1.toDisposable)(() => {\n resolvedMutationObserverPerOptions.users -= 1;\n if (resolvedMutationObserverPerOptions.users === 0) {\n onDidMutate.dispose();\n observer.disconnect();\n mutationObserversPerTarget?.delete(optionsHash);\n if (mutationObserversPerTarget?.size === 0) {\n this.mutationObservers.delete(target);\n }\n }\n }));\n mutationObserversPerTarget.set(optionsHash, mutationObserverPerOptions);\n }\n else {\n mutationObserverPerOptions.users += 1;\n }\n return mutationObserverPerOptions.onDidMutate;\n }\n};\nfunction createMetaElement(container = window_1.mainWindow.document.head) {\n return createHeadElement('meta', container);\n}\nfunction createLinkElement(container = window_1.mainWindow.document.head) {\n return createHeadElement('link', container);\n}\nfunction createHeadElement(tagName, container = window_1.mainWindow.document.head) {\n const element = document.createElement(tagName);\n container.appendChild(element);\n return element;\n}\nlet _sharedStyleSheet = null;\nfunction getSharedStyleSheet() {\n if (!_sharedStyleSheet) {\n _sharedStyleSheet = createStyleSheet();\n }\n return _sharedStyleSheet;\n}\nfunction getDynamicStyleSheetRules(style) {\n if (style?.sheet?.rules) {\n // Chrome, IE\n return style.sheet.rules;\n }\n if (style?.sheet?.cssRules) {\n // FF\n return style.sheet.cssRules;\n }\n return [];\n}\nfunction createCSSRule(selector, cssText, style = getSharedStyleSheet()) {\n if (!style || !cssText) {\n return;\n }\n style.sheet?.insertRule(`${selector} {${cssText}}`, 0);\n // Apply rule also to all cloned global stylesheets\n for (const clonedGlobalStylesheet of globalStylesheets.get(style) ?? []) {\n createCSSRule(selector, cssText, clonedGlobalStylesheet);\n }\n}\nfunction removeCSSRulesContainingSelector(ruleName, style = getSharedStyleSheet()) {\n if (!style) {\n return;\n }\n const rules = getDynamicStyleSheetRules(style);\n const toDelete = [];\n for (let i = 0; i < rules.length; i++) {\n const rule = rules[i];\n if (isCSSStyleRule(rule) && rule.selectorText.indexOf(ruleName) !== -1) {\n toDelete.push(i);\n }\n }\n for (let i = toDelete.length - 1; i >= 0; i--) {\n style.sheet?.deleteRule(toDelete[i]);\n }\n // Remove rules also from all cloned global stylesheets\n for (const clonedGlobalStylesheet of globalStylesheets.get(style) ?? []) {\n removeCSSRulesContainingSelector(ruleName, clonedGlobalStylesheet);\n }\n}\nfunction isCSSStyleRule(rule) {\n return typeof rule.selectorText === 'string';\n}\nfunction isHTMLElement(e) {\n // eslint-disable-next-line no-restricted-syntax\n return e instanceof HTMLElement || e instanceof (0, exports.getWindow)(e).HTMLElement;\n}\nfunction isHTMLAnchorElement(e) {\n // eslint-disable-next-line no-restricted-syntax\n return e instanceof HTMLAnchorElement || e instanceof (0, exports.getWindow)(e).HTMLAnchorElement;\n}\nfunction isHTMLSpanElement(e) {\n // eslint-disable-next-line no-restricted-syntax\n return e instanceof HTMLSpanElement || e instanceof (0, exports.getWindow)(e).HTMLSpanElement;\n}\nfunction isHTMLTextAreaElement(e) {\n // eslint-disable-next-line no-restricted-syntax\n return e instanceof HTMLTextAreaElement || e instanceof (0, exports.getWindow)(e).HTMLTextAreaElement;\n}\nfunction isHTMLInputElement(e) {\n // eslint-disable-next-line no-restricted-syntax\n return e instanceof HTMLInputElement || e instanceof (0, exports.getWindow)(e).HTMLInputElement;\n}\nfunction isHTMLButtonElement(e) {\n // eslint-disable-next-line no-restricted-syntax\n return e instanceof HTMLButtonElement || e instanceof (0, exports.getWindow)(e).HTMLButtonElement;\n}\nfunction isHTMLDivElement(e) {\n // eslint-disable-next-line no-restricted-syntax\n return e instanceof HTMLDivElement || e instanceof (0, exports.getWindow)(e).HTMLDivElement;\n}\nfunction isSVGElement(e) {\n // eslint-disable-next-line no-restricted-syntax\n return e instanceof SVGElement || e instanceof (0, exports.getWindow)(e).SVGElement;\n}\nfunction isMouseEvent(e) {\n // eslint-disable-next-line no-restricted-syntax\n return e instanceof MouseEvent || e instanceof (0, exports.getWindow)(e).MouseEvent;\n}\nfunction isKeyboardEvent(e) {\n // eslint-disable-next-line no-restricted-syntax\n return e instanceof KeyboardEvent || e instanceof (0, exports.getWindow)(e).KeyboardEvent;\n}\nfunction isPointerEvent(e) {\n // eslint-disable-next-line no-restricted-syntax\n return e instanceof PointerEvent || e instanceof (0, exports.getWindow)(e).PointerEvent;\n}\nfunction isDragEvent(e) {\n // eslint-disable-next-line no-restricted-syntax\n return e instanceof DragEvent || e instanceof (0, exports.getWindow)(e).DragEvent;\n}\nexports.EventType = {\n // Mouse\n CLICK: 'click',\n AUXCLICK: 'auxclick',\n DBLCLICK: 'dblclick',\n MOUSE_UP: 'mouseup',\n MOUSE_DOWN: 'mousedown',\n MOUSE_OVER: 'mouseover',\n MOUSE_MOVE: 'mousemove',\n MOUSE_OUT: 'mouseout',\n MOUSE_ENTER: 'mouseenter',\n MOUSE_LEAVE: 'mouseleave',\n MOUSE_WHEEL: 'wheel',\n POINTER_UP: 'pointerup',\n POINTER_DOWN: 'pointerdown',\n POINTER_MOVE: 'pointermove',\n POINTER_LEAVE: 'pointerleave',\n CONTEXT_MENU: 'contextmenu',\n WHEEL: 'wheel',\n // Keyboard\n KEY_DOWN: 'keydown',\n KEY_PRESS: 'keypress',\n KEY_UP: 'keyup',\n // HTML Document\n LOAD: 'load',\n BEFORE_UNLOAD: 'beforeunload',\n UNLOAD: 'unload',\n PAGE_SHOW: 'pageshow',\n PAGE_HIDE: 'pagehide',\n PASTE: 'paste',\n ABORT: 'abort',\n ERROR: 'error',\n RESIZE: 'resize',\n SCROLL: 'scroll',\n FULLSCREEN_CHANGE: 'fullscreenchange',\n WK_FULLSCREEN_CHANGE: 'webkitfullscreenchange',\n // Form\n SELECT: 'select',\n CHANGE: 'change',\n SUBMIT: 'submit',\n RESET: 'reset',\n FOCUS: 'focus',\n FOCUS_IN: 'focusin',\n FOCUS_OUT: 'focusout',\n BLUR: 'blur',\n INPUT: 'input',\n // Local Storage\n STORAGE: 'storage',\n // Drag\n DRAG_START: 'dragstart',\n DRAG: 'drag',\n DRAG_ENTER: 'dragenter',\n DRAG_LEAVE: 'dragleave',\n DRAG_OVER: 'dragover',\n DROP: 'drop',\n DRAG_END: 'dragend',\n // Animation\n ANIMATION_START: browser.isWebKit ? 'webkitAnimationStart' : 'animationstart',\n ANIMATION_END: browser.isWebKit ? 'webkitAnimationEnd' : 'animationend',\n ANIMATION_ITERATION: browser.isWebKit ? 'webkitAnimationIteration' : 'animationiteration'\n};\nfunction isEventLike(obj) {\n const candidate = obj;\n return !!(candidate && typeof candidate.preventDefault === 'function' && typeof candidate.stopPropagation === 'function');\n}\nexports.EventHelper = {\n stop: (e, cancelBubble) => {\n e.preventDefault();\n if (cancelBubble) {\n e.stopPropagation();\n }\n return e;\n }\n};\nfunction saveParentsScrollTop(node) {\n const r = [];\n for (let i = 0; node && node.nodeType === node.ELEMENT_NODE; i++) {\n r[i] = node.scrollTop;\n node = node.parentNode;\n }\n return r;\n}\nfunction restoreParentsScrollTop(node, state) {\n for (let i = 0; node && node.nodeType === node.ELEMENT_NODE; i++) {\n if (node.scrollTop !== state[i]) {\n node.scrollTop = state[i];\n }\n node = node.parentNode;\n }\n}\nclass FocusTracker extends lifecycle_1.Disposable {\n static hasFocusWithin(element) {\n if (isHTMLElement(element)) {\n const shadowRoot = getShadowRoot(element);\n const activeElement = (shadowRoot ? shadowRoot.activeElement : element.ownerDocument.activeElement);\n return isAncestor(activeElement, element);\n }\n else {\n const window = element;\n return isAncestor(window.document.activeElement, window.document);\n }\n }\n constructor(element) {\n super();\n this._onDidFocus = this._register(new event.Emitter());\n this.onDidFocus = this._onDidFocus.event;\n this._onDidBlur = this._register(new event.Emitter());\n this.onDidBlur = this._onDidBlur.event;\n let hasFocus = FocusTracker.hasFocusWithin(element);\n let loosingFocus = false;\n const onFocus = () => {\n loosingFocus = false;\n if (!hasFocus) {\n hasFocus = true;\n this._onDidFocus.fire();\n }\n };\n const onBlur = () => {\n if (hasFocus) {\n loosingFocus = true;\n (isHTMLElement(element) ? (0, exports.getWindow)(element) : element).setTimeout(() => {\n if (loosingFocus) {\n loosingFocus = false;\n hasFocus = false;\n this._onDidBlur.fire();\n }\n }, 0);\n }\n };\n this._refreshStateHandler = () => {\n const currentNodeHasFocus = FocusTracker.hasFocusWithin(element);\n if (currentNodeHasFocus !== hasFocus) {\n if (hasFocus) {\n onBlur();\n }\n else {\n onFocus();\n }\n }\n };\n this._register(addDisposableListener(element, exports.EventType.FOCUS, onFocus, true));\n this._register(addDisposableListener(element, exports.EventType.BLUR, onBlur, true));\n if (isHTMLElement(element)) {\n this._register(addDisposableListener(element, exports.EventType.FOCUS_IN, () => this._refreshStateHandler()));\n this._register(addDisposableListener(element, exports.EventType.FOCUS_OUT, () => this._refreshStateHandler()));\n }\n }\n refreshState() {\n this._refreshStateHandler();\n }\n}\n/**\n * Creates a new `IFocusTracker` instance that tracks focus changes on the given `element` and its descendants.\n *\n * @param element The `HTMLElement` or `Window` to track focus changes on.\n * @returns An `IFocusTracker` instance.\n */\nfunction trackFocus(element) {\n return new FocusTracker(element);\n}\nfunction after(sibling, child) {\n sibling.after(child);\n return child;\n}\nfunction append(parent, ...children) {\n parent.append(...children);\n if (children.length === 1 && typeof children[0] !== 'string') {\n return children[0];\n }\n}\nfunction prepend(parent, child) {\n parent.insertBefore(child, parent.firstChild);\n return child;\n}\n/**\n * Removes all children from `parent` and appends `children`\n */\nfunction reset(parent, ...children) {\n parent.innerText = '';\n append(parent, ...children);\n}\nconst SELECTOR_REGEX = /([\\w\\-]+)?(#([\\w\\-]+))?((\\.([\\w\\-]+))*)/;\nvar Namespace;\n(function (Namespace) {\n Namespace[\"HTML\"] = \"http://www.w3.org/1999/xhtml\";\n Namespace[\"SVG\"] = \"http://www.w3.org/2000/svg\";\n})(Namespace || (exports.Namespace = Namespace = {}));\nfunction _$(namespace, description, attrs, ...children) {\n const match = SELECTOR_REGEX.exec(description);\n if (!match) {\n throw new Error('Bad use of emmet');\n }\n const tagName = match[1] || 'div';\n let result;\n if (namespace !== Namespace.HTML) {\n result = document.createElementNS(namespace, tagName);\n }\n else {\n result = document.createElement(tagName);\n }\n if (match[3]) {\n result.id = match[3];\n }\n if (match[4]) {\n result.className = match[4].replace(/\\./g, ' ').trim();\n }\n if (attrs) {\n Object.entries(attrs).forEach(([name, value]) => {\n if (typeof value === 'undefined') {\n return;\n }\n if (/^on\\w+$/.test(name)) {\n result[name] = value;\n }\n else if (name === 'selected') {\n if (value) {\n result.setAttribute(name, 'true');\n }\n }\n else {\n result.setAttribute(name, value);\n }\n });\n }\n result.append(...children);\n return result;\n}\nfunction $(description, attrs, ...children) {\n return _$(Namespace.HTML, description, attrs, ...children);\n}\n$.SVG = function (description, attrs, ...children) {\n return _$(Namespace.SVG, description, attrs, ...children);\n};\nfunction join(nodes, separator) {\n const result = [];\n nodes.forEach((node, index) => {\n if (index > 0) {\n if (separator instanceof Node) {\n result.push(separator.cloneNode());\n }\n else {\n result.push(document.createTextNode(separator));\n }\n }\n result.push(node);\n });\n return result;\n}\nfunction setVisibility(visible, ...elements) {\n if (visible) {\n show(...elements);\n }\n else {\n hide(...elements);\n }\n}\nfunction show(...elements) {\n for (const element of elements) {\n element.style.display = '';\n element.removeAttribute('aria-hidden');\n }\n}\nfunction hide(...elements) {\n for (const element of elements) {\n element.style.display = 'none';\n element.setAttribute('aria-hidden', 'true');\n }\n}\nfunction findParentWithAttribute(node, attribute) {\n while (node && node.nodeType === node.ELEMENT_NODE) {\n if (isHTMLElement(node) && node.hasAttribute(attribute)) {\n return node;\n }\n node = node.parentNode;\n }\n return null;\n}\nfunction removeTabIndexAndUpdateFocus(node) {\n if (!node || !node.hasAttribute('tabIndex')) {\n return;\n }\n // If we are the currently focused element and tabIndex is removed,\n // standard DOM behavior is to move focus to the element. We\n // typically never want that, rather put focus to the closest element\n // in the hierarchy of the parent DOM nodes.\n if (node.ownerDocument.activeElement === node) {\n const parentFocusable = findParentWithAttribute(node.parentElement, 'tabIndex');\n parentFocusable?.focus();\n }\n node.removeAttribute('tabindex');\n}\nfunction finalHandler(fn) {\n return e => {\n e.preventDefault();\n e.stopPropagation();\n fn(e);\n };\n}\nfunction domContentLoaded(targetWindow) {\n return new Promise(resolve => {\n const readyState = targetWindow.document.readyState;\n if (readyState === 'complete' || (targetWindow.document && targetWindow.document.body !== null)) {\n resolve(undefined);\n }\n else {\n const listener = () => {\n targetWindow.window.removeEventListener('DOMContentLoaded', listener, false);\n resolve();\n };\n targetWindow.window.addEventListener('DOMContentLoaded', listener, false);\n }\n });\n}\n/**\n * Find a value usable for a dom node size such that the likelihood that it would be\n * displayed with constant screen pixels size is as high as possible.\n *\n * e.g. We would desire for the cursors to be 2px (CSS px) wide. Under a devicePixelRatio\n * of 1.25, the cursor will be 2.5 screen pixels wide. Depending on how the dom node aligns/\"snaps\"\n * with the screen pixels, it will sometimes be rendered with 2 screen pixels, and sometimes with 3 screen pixels.\n */\nfunction computeScreenAwareSize(window, cssPx) {\n const screenPx = window.devicePixelRatio * cssPx;\n return Math.max(1, Math.floor(screenPx)) / window.devicePixelRatio;\n}\n/**\n * Open safely a new window. This is the best way to do so, but you cannot tell\n * if the window was opened or if it was blocked by the browser's popup blocker.\n * If you want to tell if the browser blocked the new window, use {@link windowOpenWithSuccess}.\n *\n * See https://github.com/microsoft/monaco-editor/issues/601\n * To protect against malicious code in the linked site, particularly phishing attempts,\n * the window.opener should be set to null to prevent the linked site from having access\n * to change the location of the current page.\n * See https://mathiasbynens.github.io/rel-noopener/\n */\nfunction windowOpenNoOpener(url) {\n // By using 'noopener' in the `windowFeatures` argument, the newly created window will\n // not be able to use `window.opener` to reach back to the current page.\n // See https://stackoverflow.com/a/46958731\n // See https://developer.mozilla.org/en-US/docs/Web/API/Window/open#noopener\n // However, this also doesn't allow us to realize if the browser blocked\n // the creation of the window.\n window_1.mainWindow.open(url, '_blank', 'noopener');\n}\n/**\n * Open a new window in a popup. This is the best way to do so, but you cannot tell\n * if the window was opened or if it was blocked by the browser's popup blocker.\n * If you want to tell if the browser blocked the new window, use {@link windowOpenWithSuccess}.\n *\n * Note: this does not set {@link window.opener} to null. This is to allow the opened popup to\n * be able to use {@link window.close} to close itself. Because of this, you should only use\n * this function on urls that you trust.\n *\n * In otherwords, you should almost always use {@link windowOpenNoOpener} instead of this function.\n */\nconst popupWidth = 780, popupHeight = 640;\nfunction windowOpenPopup(url) {\n const left = Math.floor(window_1.mainWindow.screenLeft + window_1.mainWindow.innerWidth / 2 - popupWidth / 2);\n const top = Math.floor(window_1.mainWindow.screenTop + window_1.mainWindow.innerHeight / 2 - popupHeight / 2);\n window_1.mainWindow.open(url, '_blank', `width=${popupWidth},height=${popupHeight},top=${top},left=${left}`);\n}\n/**\n * Attempts to open a window and returns whether it succeeded. This technique is\n * not appropriate in certain contexts, like for example when the JS context is\n * executing inside a sandboxed iframe. If it is not necessary to know if the\n * browser blocked the new window, use {@link windowOpenNoOpener}.\n *\n * See https://github.com/microsoft/monaco-editor/issues/601\n * See https://github.com/microsoft/monaco-editor/issues/2474\n * See https://mathiasbynens.github.io/rel-noopener/\n *\n * @param url the url to open\n * @param noOpener whether or not to set the {@link window.opener} to null. You should leave the default\n * (true) unless you trust the url that is being opened.\n * @returns boolean indicating if the {@link window.open} call succeeded\n */\nfunction windowOpenWithSuccess(url, noOpener = true) {\n const newTab = window_1.mainWindow.open();\n if (newTab) {\n if (noOpener) {\n // see `windowOpenNoOpener` for details on why this is important\n newTab.opener = null;\n }\n newTab.location.href = url;\n return true;\n }\n return false;\n}\nfunction animate(targetWindow, fn) {\n const step = () => {\n fn();\n stepDisposable = (0, exports.scheduleAtNextAnimationFrame)(targetWindow, step);\n };\n let stepDisposable = (0, exports.scheduleAtNextAnimationFrame)(targetWindow, step);\n return (0, lifecycle_1.toDisposable)(() => stepDisposable.dispose());\n}\nfunction asCSSPropertyValue(value) {\n return `'${value.replace(/'/g, '%27')}'`;\n}\nfunction asCssValueWithDefault(cssPropertyValue, dflt) {\n if (cssPropertyValue !== undefined) {\n const variableMatch = cssPropertyValue.match(/^\\s*var\\((.+)\\)$/);\n if (variableMatch) {\n const varArguments = variableMatch[1].split(',', 2);\n if (varArguments.length === 2) {\n dflt = asCssValueWithDefault(varArguments[1].trim(), dflt);\n }\n return `var(${varArguments[0]}, ${dflt})`;\n }\n return cssPropertyValue;\n }\n return dflt;\n}\nvar DetectedFullscreenMode;\n(function (DetectedFullscreenMode) {\n /**\n * The document is fullscreen, e.g. because an element\n * in the document requested to be fullscreen.\n */\n DetectedFullscreenMode[DetectedFullscreenMode[\"DOCUMENT\"] = 1] = \"DOCUMENT\";\n /**\n * The browser is fullscreen, e.g. because the user enabled\n * native window fullscreen for it.\n */\n DetectedFullscreenMode[DetectedFullscreenMode[\"BROWSER\"] = 2] = \"BROWSER\";\n})(DetectedFullscreenMode || (exports.DetectedFullscreenMode = DetectedFullscreenMode = {}));\nfunction detectFullscreen(targetWindow) {\n // Browser fullscreen: use DOM APIs to detect\n if (targetWindow.document.fullscreenElement || targetWindow.document.webkitFullscreenElement || targetWindow.document.webkitIsFullScreen) {\n return { mode: DetectedFullscreenMode.DOCUMENT, guess: false };\n }\n // There is no standard way to figure out if the browser\n // is using native fullscreen. Via checking on screen\n // height and comparing that to window height, we can guess\n // it though.\n if (targetWindow.innerHeight === targetWindow.screen.height) {\n // if the height of the window matches the screen height, we can\n // safely assume that the browser is fullscreen because no browser\n // chrome is taking height away (e.g. like toolbars).\n return { mode: DetectedFullscreenMode.BROWSER, guess: false };\n }\n if (platform.isMacintosh || platform.isLinux) {\n // macOS and Linux do not properly report `innerHeight`, only Windows does\n if (targetWindow.outerHeight === targetWindow.screen.height && targetWindow.outerWidth === targetWindow.screen.width) {\n // if the height of the browser matches the screen height, we can\n // only guess that we are in fullscreen. It is also possible that\n // the user has turned off taskbars in the OS and the browser is\n // simply able to span the entire size of the screen.\n return { mode: DetectedFullscreenMode.BROWSER, guess: true };\n }\n }\n // Not in fullscreen\n return null;\n}\n/**\n * Convert a Unicode string to a string in which each 16-bit unit occupies only one byte\n *\n * From https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/btoa\n */\nfunction toBinary(str) {\n const codeUnits = new Uint16Array(str.length);\n for (let i = 0; i < codeUnits.length; i++) {\n codeUnits[i] = str.charCodeAt(i);\n }\n let binary = '';\n const uint8array = new Uint8Array(codeUnits.buffer);\n for (let i = 0; i < uint8array.length; i++) {\n binary += String.fromCharCode(uint8array[i]);\n }\n return binary;\n}\n/**\n * Version of the global `btoa` function that handles multi-byte characters instead\n * of throwing an exception.\n */\nfunction multibyteAwareBtoa(str) {\n return btoa(toBinary(str));\n}\nclass ModifierKeyEmitter extends event.Emitter {\n constructor() {\n super();\n this._subscriptions = new lifecycle_1.DisposableStore();\n this._keyStatus = {\n altKey: false,\n shiftKey: false,\n ctrlKey: false,\n metaKey: false\n };\n this._subscriptions.add(event.Event.runAndSubscribe(exports.onDidRegisterWindow, ({ window, disposables }) => this.registerListeners(window, disposables), { window: window_1.mainWindow, disposables: this._subscriptions }));\n }\n registerListeners(window, disposables) {\n disposables.add(addDisposableListener(window, 'keydown', e => {\n if (e.defaultPrevented) {\n return;\n }\n const event = new keyboardEvent_1.StandardKeyboardEvent(e);\n // If Alt-key keydown event is repeated, ignore it #112347\n // Only known to be necessary for Alt-Key at the moment #115810\n if (event.keyCode === keyCodes_1.KeyCode.Alt && e.repeat) {\n return;\n }\n if (e.altKey && !this._keyStatus.altKey) {\n this._keyStatus.lastKeyPressed = 'alt';\n }\n else if (e.ctrlKey && !this._keyStatus.ctrlKey) {\n this._keyStatus.lastKeyPressed = 'ctrl';\n }\n else if (e.metaKey && !this._keyStatus.metaKey) {\n this._keyStatus.lastKeyPressed = 'meta';\n }\n else if (e.shiftKey && !this._keyStatus.shiftKey) {\n this._keyStatus.lastKeyPressed = 'shift';\n }\n else if (event.keyCode !== keyCodes_1.KeyCode.Alt) {\n this._keyStatus.lastKeyPressed = undefined;\n }\n else {\n return;\n }\n this._keyStatus.altKey = e.altKey;\n this._keyStatus.ctrlKey = e.ctrlKey;\n this._keyStatus.metaKey = e.metaKey;\n this._keyStatus.shiftKey = e.shiftKey;\n if (this._keyStatus.lastKeyPressed) {\n this._keyStatus.event = e;\n this.fire(this._keyStatus);\n }\n }, true));\n disposables.add(addDisposableListener(window, 'keyup', e => {\n if (e.defaultPrevented) {\n return;\n }\n if (!e.altKey && this._keyStatus.altKey) {\n this._keyStatus.lastKeyReleased = 'alt';\n }\n else if (!e.ctrlKey && this._keyStatus.ctrlKey) {\n this._keyStatus.lastKeyReleased = 'ctrl';\n }\n else if (!e.metaKey && this._keyStatus.metaKey) {\n this._keyStatus.lastKeyReleased = 'meta';\n }\n else if (!e.shiftKey && this._keyStatus.shiftKey) {\n this._keyStatus.lastKeyReleased = 'shift';\n }\n else {\n this._keyStatus.lastKeyReleased = undefined;\n }\n if (this._keyStatus.lastKeyPressed !== this._keyStatus.lastKeyReleased) {\n this._keyStatus.lastKeyPressed = undefined;\n }\n this._keyStatus.altKey = e.altKey;\n this._keyStatus.ctrlKey = e.ctrlKey;\n this._keyStatus.metaKey = e.metaKey;\n this._keyStatus.shiftKey = e.shiftKey;\n if (this._keyStatus.lastKeyReleased) {\n this._keyStatus.event = e;\n this.fire(this._keyStatus);\n }\n }, true));\n disposables.add(addDisposableListener(window.document.body, 'mousedown', () => {\n this._keyStatus.lastKeyPressed = undefined;\n }, true));\n disposables.add(addDisposableListener(window.document.body, 'mouseup', () => {\n this._keyStatus.lastKeyPressed = undefined;\n }, true));\n disposables.add(addDisposableListener(window.document.body, 'mousemove', e => {\n if (e.buttons) {\n this._keyStatus.lastKeyPressed = undefined;\n }\n }, true));\n disposables.add(addDisposableListener(window, 'blur', () => {\n this.resetKeyStatus();\n }));\n }\n get keyStatus() {\n return this._keyStatus;\n }\n get isModifierPressed() {\n return this._keyStatus.altKey || this._keyStatus.ctrlKey || this._keyStatus.metaKey || this._keyStatus.shiftKey;\n }\n /**\n * Allows to explicitly reset the key status based on more knowledge (#109062)\n */\n resetKeyStatus() {\n this.doResetKeyStatus();\n this.fire(this._keyStatus);\n }\n doResetKeyStatus() {\n this._keyStatus = {\n altKey: false,\n shiftKey: false,\n ctrlKey: false,\n metaKey: false\n };\n }\n static getInstance() {\n if (!ModifierKeyEmitter.instance) {\n ModifierKeyEmitter.instance = new ModifierKeyEmitter();\n }\n return ModifierKeyEmitter.instance;\n }\n dispose() {\n super.dispose();\n this._subscriptions.dispose();\n }\n}\nexports.ModifierKeyEmitter = ModifierKeyEmitter;\nfunction getCookieValue(name) {\n const match = document.cookie.match('(^|[^;]+)\\\\s*' + name + '\\\\s*=\\\\s*([^;]+)'); // See https://stackoverflow.com/a/25490531\n return match ? match.pop() : undefined;\n}\nclass DragAndDropObserver extends lifecycle_1.Disposable {\n constructor(element, callbacks) {\n super();\n this.element = element;\n this.callbacks = callbacks;\n // A helper to fix issues with repeated DRAG_ENTER / DRAG_LEAVE\n // calls see https://github.com/microsoft/vscode/issues/14470\n // when the element has child elements where the events are fired\n // repeadedly.\n this.counter = 0;\n // Allows to measure the duration of the drag operation.\n this.dragStartTime = 0;\n this.registerListeners();\n }\n registerListeners() {\n if (this.callbacks.onDragStart) {\n this._register(addDisposableListener(this.element, exports.EventType.DRAG_START, (e) => {\n this.callbacks.onDragStart?.(e);\n }));\n }\n if (this.callbacks.onDrag) {\n this._register(addDisposableListener(this.element, exports.EventType.DRAG, (e) => {\n this.callbacks.onDrag?.(e);\n }));\n }\n this._register(addDisposableListener(this.element, exports.EventType.DRAG_ENTER, (e) => {\n this.counter++;\n this.dragStartTime = e.timeStamp;\n this.callbacks.onDragEnter?.(e);\n }));\n this._register(addDisposableListener(this.element, exports.EventType.DRAG_OVER, (e) => {\n e.preventDefault(); // needed so that the drop event fires (https://stackoverflow.com/questions/21339924/drop-event-not-firing-in-chrome)\n this.callbacks.onDragOver?.(e, e.timeStamp - this.dragStartTime);\n }));\n this._register(addDisposableListener(this.element, exports.EventType.DRAG_LEAVE, (e) => {\n this.counter--;\n if (this.counter === 0) {\n this.dragStartTime = 0;\n this.callbacks.onDragLeave?.(e);\n }\n }));\n this._register(addDisposableListener(this.element, exports.EventType.DRAG_END, (e) => {\n this.counter = 0;\n this.dragStartTime = 0;\n this.callbacks.onDragEnd?.(e);\n }));\n this._register(addDisposableListener(this.element, exports.EventType.DROP, (e) => {\n this.counter = 0;\n this.dragStartTime = 0;\n this.callbacks.onDrop?.(e);\n }));\n }\n}\nexports.DragAndDropObserver = DragAndDropObserver;\nconst H_REGEX = /(?[\\w\\-]+)?(?:#(?[\\w\\-]+))?(?(?:\\.(?:[\\w\\-]+))*)(?:@(?(?:[\\w\\_])+))?/;\nfunction h(tag, ...args) {\n let attributes;\n let children;\n if (Array.isArray(args[0])) {\n attributes = {};\n children = args[0];\n }\n else {\n attributes = args[0] || {};\n children = args[1];\n }\n const match = H_REGEX.exec(tag);\n if (!match || !match.groups) {\n throw new Error('Bad use of h');\n }\n const tagName = match.groups['tag'] || 'div';\n const el = document.createElement(tagName);\n if (match.groups['id']) {\n el.id = match.groups['id'];\n }\n const classNames = [];\n if (match.groups['class']) {\n for (const className of match.groups['class'].split('.')) {\n if (className !== '') {\n classNames.push(className);\n }\n }\n }\n if (attributes.className !== undefined) {\n for (const className of attributes.className.split('.')) {\n if (className !== '') {\n classNames.push(className);\n }\n }\n }\n if (classNames.length > 0) {\n el.className = classNames.join(' ');\n }\n const result = {};\n if (match.groups['name']) {\n result[match.groups['name']] = el;\n }\n if (children) {\n for (const c of children) {\n if (isHTMLElement(c)) {\n el.appendChild(c);\n }\n else if (typeof c === 'string') {\n el.append(c);\n }\n else if ('root' in c) {\n Object.assign(result, c);\n el.appendChild(c.root);\n }\n }\n }\n for (const [key, value] of Object.entries(attributes)) {\n if (key === 'className') {\n continue;\n }\n else if (key === 'style') {\n for (const [cssKey, cssValue] of Object.entries(value)) {\n el.style.setProperty(camelCaseToHyphenCase(cssKey), typeof cssValue === 'number' ? cssValue + 'px' : '' + cssValue);\n }\n }\n else if (key === 'tabIndex') {\n el.tabIndex = value;\n }\n else {\n el.setAttribute(camelCaseToHyphenCase(key), value.toString());\n }\n }\n result['root'] = el;\n return result;\n}\nfunction svgElem(tag, ...args) {\n let attributes;\n let children;\n if (Array.isArray(args[0])) {\n attributes = {};\n children = args[0];\n }\n else {\n attributes = args[0] || {};\n children = args[1];\n }\n const match = H_REGEX.exec(tag);\n if (!match || !match.groups) {\n throw new Error('Bad use of h');\n }\n const tagName = match.groups['tag'] || 'div';\n const el = document.createElementNS('http://www.w3.org/2000/svg', tagName);\n if (match.groups['id']) {\n el.id = match.groups['id'];\n }\n const classNames = [];\n if (match.groups['class']) {\n for (const className of match.groups['class'].split('.')) {\n if (className !== '') {\n classNames.push(className);\n }\n }\n }\n if (attributes.className !== undefined) {\n for (const className of attributes.className.split('.')) {\n if (className !== '') {\n classNames.push(className);\n }\n }\n }\n if (classNames.length > 0) {\n el.className = classNames.join(' ');\n }\n const result = {};\n if (match.groups['name']) {\n result[match.groups['name']] = el;\n }\n if (children) {\n for (const c of children) {\n if (isHTMLElement(c)) {\n el.appendChild(c);\n }\n else if (typeof c === 'string') {\n el.append(c);\n }\n else if ('root' in c) {\n Object.assign(result, c);\n el.appendChild(c.root);\n }\n }\n }\n for (const [key, value] of Object.entries(attributes)) {\n if (key === 'className') {\n continue;\n }\n else if (key === 'style') {\n for (const [cssKey, cssValue] of Object.entries(value)) {\n el.style.setProperty(camelCaseToHyphenCase(cssKey), typeof cssValue === 'number' ? cssValue + 'px' : '' + cssValue);\n }\n }\n else if (key === 'tabIndex') {\n el.tabIndex = value;\n }\n else {\n el.setAttribute(camelCaseToHyphenCase(key), value.toString());\n }\n }\n result['root'] = el;\n return result;\n}\nfunction camelCaseToHyphenCase(str) {\n return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();\n}\nfunction copyAttributes(from, to, filter) {\n for (const { name, value } of from.attributes) {\n if (!filter || filter.includes(name)) {\n to.setAttribute(name, value);\n }\n }\n}\nfunction copyAttribute(from, to, name) {\n const value = from.getAttribute(name);\n if (value) {\n to.setAttribute(name, value);\n }\n else {\n to.removeAttribute(name);\n }\n}\nfunction trackAttributes(from, to, filter) {\n copyAttributes(from, to, filter);\n const disposables = new lifecycle_1.DisposableStore();\n disposables.add(exports.sharedMutationObserver.observe(from, disposables, { attributes: true, attributeFilter: filter })(mutations => {\n for (const mutation of mutations) {\n if (mutation.type === 'attributes' && mutation.attributeName) {\n copyAttribute(from, to, mutation.attributeName);\n }\n }\n }));\n return disposables;\n}\n/**\n * Helper for calculating the \"safe triangle\" occluded by hovers to avoid early dismissal.\n * @see https://www.smashingmagazine.com/2023/08/better-context-menus-safe-triangles/ for example\n */\nclass SafeTriangle {\n constructor(originX, originY, target) {\n this.originX = originX;\n this.originY = originY;\n // 4 triangles, 2 points (x, y) stored for each\n this.triangles = [];\n const { top, left, right, bottom } = target.getBoundingClientRect();\n const t = this.triangles;\n let i = 0;\n t[i++] = left;\n t[i++] = top;\n t[i++] = right;\n t[i++] = top;\n t[i++] = left;\n t[i++] = top;\n t[i++] = left;\n t[i++] = bottom;\n t[i++] = right;\n t[i++] = top;\n t[i++] = right;\n t[i++] = bottom;\n t[i++] = left;\n t[i++] = bottom;\n t[i++] = right;\n t[i++] = bottom;\n }\n contains(x, y) {\n const { triangles, originX, originY } = this;\n for (let i = 0; i < 4; i++) {\n if ((0, numbers_1.isPointWithinTriangle)(x, y, originX, originY, triangles[2 * i], triangles[2 * i + 1], triangles[2 * i + 2], triangles[2 * i + 3])) {\n return true;\n }\n }\n return false;\n }\n}\nexports.SafeTriangle = SafeTriangle;\n","\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.FastDomNode = void 0;\nexports.createFastDomNode = createFastDomNode;\nclass FastDomNode {\n constructor(domNode) {\n this.domNode = domNode;\n this._maxWidth = '';\n this._width = '';\n this._height = '';\n this._top = '';\n this._left = '';\n this._bottom = '';\n this._right = '';\n this._paddingTop = '';\n this._paddingLeft = '';\n this._paddingBottom = '';\n this._paddingRight = '';\n this._fontFamily = '';\n this._fontWeight = '';\n this._fontSize = '';\n this._fontStyle = '';\n this._fontFeatureSettings = '';\n this._fontVariationSettings = '';\n this._textDecoration = '';\n this._lineHeight = '';\n this._letterSpacing = '';\n this._className = '';\n this._display = '';\n this._position = '';\n this._visibility = '';\n this._color = '';\n this._backgroundColor = '';\n this._layerHint = false;\n this._contain = 'none';\n this._boxShadow = '';\n }\n setMaxWidth(_maxWidth) {\n const maxWidth = numberAsPixels(_maxWidth);\n if (this._maxWidth === maxWidth) {\n return;\n }\n this._maxWidth = maxWidth;\n this.domNode.style.maxWidth = this._maxWidth;\n }\n setWidth(_width) {\n const width = numberAsPixels(_width);\n if (this._width === width) {\n return;\n }\n this._width = width;\n this.domNode.style.width = this._width;\n }\n setHeight(_height) {\n const height = numberAsPixels(_height);\n if (this._height === height) {\n return;\n }\n this._height = height;\n this.domNode.style.height = this._height;\n }\n setTop(_top) {\n const top = numberAsPixels(_top);\n if (this._top === top) {\n return;\n }\n this._top = top;\n this.domNode.style.top = this._top;\n }\n setLeft(_left) {\n const left = numberAsPixels(_left);\n if (this._left === left) {\n return;\n }\n this._left = left;\n this.domNode.style.left = this._left;\n }\n setBottom(_bottom) {\n const bottom = numberAsPixels(_bottom);\n if (this._bottom === bottom) {\n return;\n }\n this._bottom = bottom;\n this.domNode.style.bottom = this._bottom;\n }\n setRight(_right) {\n const right = numberAsPixels(_right);\n if (this._right === right) {\n return;\n }\n this._right = right;\n this.domNode.style.right = this._right;\n }\n setPaddingTop(_paddingTop) {\n const paddingTop = numberAsPixels(_paddingTop);\n if (this._paddingTop === paddingTop) {\n return;\n }\n this._paddingTop = paddingTop;\n this.domNode.style.paddingTop = this._paddingTop;\n }\n setPaddingLeft(_paddingLeft) {\n const paddingLeft = numberAsPixels(_paddingLeft);\n if (this._paddingLeft === paddingLeft) {\n return;\n }\n this._paddingLeft = paddingLeft;\n this.domNode.style.paddingLeft = this._paddingLeft;\n }\n setPaddingBottom(_paddingBottom) {\n const paddingBottom = numberAsPixels(_paddingBottom);\n if (this._paddingBottom === paddingBottom) {\n return;\n }\n this._paddingBottom = paddingBottom;\n this.domNode.style.paddingBottom = this._paddingBottom;\n }\n setPaddingRight(_paddingRight) {\n const paddingRight = numberAsPixels(_paddingRight);\n if (this._paddingRight === paddingRight) {\n return;\n }\n this._paddingRight = paddingRight;\n this.domNode.style.paddingRight = this._paddingRight;\n }\n setFontFamily(fontFamily) {\n if (this._fontFamily === fontFamily) {\n return;\n }\n this._fontFamily = fontFamily;\n this.domNode.style.fontFamily = this._fontFamily;\n }\n setFontWeight(fontWeight) {\n if (this._fontWeight === fontWeight) {\n return;\n }\n this._fontWeight = fontWeight;\n this.domNode.style.fontWeight = this._fontWeight;\n }\n setFontSize(_fontSize) {\n const fontSize = numberAsPixels(_fontSize);\n if (this._fontSize === fontSize) {\n return;\n }\n this._fontSize = fontSize;\n this.domNode.style.fontSize = this._fontSize;\n }\n setFontStyle(fontStyle) {\n if (this._fontStyle === fontStyle) {\n return;\n }\n this._fontStyle = fontStyle;\n this.domNode.style.fontStyle = this._fontStyle;\n }\n setFontFeatureSettings(fontFeatureSettings) {\n if (this._fontFeatureSettings === fontFeatureSettings) {\n return;\n }\n this._fontFeatureSettings = fontFeatureSettings;\n this.domNode.style.fontFeatureSettings = this._fontFeatureSettings;\n }\n setFontVariationSettings(fontVariationSettings) {\n if (this._fontVariationSettings === fontVariationSettings) {\n return;\n }\n this._fontVariationSettings = fontVariationSettings;\n this.domNode.style.fontVariationSettings = this._fontVariationSettings;\n }\n setTextDecoration(textDecoration) {\n if (this._textDecoration === textDecoration) {\n return;\n }\n this._textDecoration = textDecoration;\n this.domNode.style.textDecoration = this._textDecoration;\n }\n setLineHeight(_lineHeight) {\n const lineHeight = numberAsPixels(_lineHeight);\n if (this._lineHeight === lineHeight) {\n return;\n }\n this._lineHeight = lineHeight;\n this.domNode.style.lineHeight = this._lineHeight;\n }\n setLetterSpacing(_letterSpacing) {\n const letterSpacing = numberAsPixels(_letterSpacing);\n if (this._letterSpacing === letterSpacing) {\n return;\n }\n this._letterSpacing = letterSpacing;\n this.domNode.style.letterSpacing = this._letterSpacing;\n }\n setClassName(className) {\n if (this._className === className) {\n return;\n }\n this._className = className;\n this.domNode.className = this._className;\n }\n toggleClassName(className, shouldHaveIt) {\n this.domNode.classList.toggle(className, shouldHaveIt);\n this._className = this.domNode.className;\n }\n setDisplay(display) {\n if (this._display === display) {\n return;\n }\n this._display = display;\n this.domNode.style.display = this._display;\n }\n setPosition(position) {\n if (this._position === position) {\n return;\n }\n this._position = position;\n this.domNode.style.position = this._position;\n }\n setVisibility(visibility) {\n if (this._visibility === visibility) {\n return;\n }\n this._visibility = visibility;\n this.domNode.style.visibility = this._visibility;\n }\n setColor(color) {\n if (this._color === color) {\n return;\n }\n this._color = color;\n this.domNode.style.color = this._color;\n }\n setBackgroundColor(backgroundColor) {\n if (this._backgroundColor === backgroundColor) {\n return;\n }\n this._backgroundColor = backgroundColor;\n this.domNode.style.backgroundColor = this._backgroundColor;\n }\n setLayerHinting(layerHint) {\n if (this._layerHint === layerHint) {\n return;\n }\n this._layerHint = layerHint;\n this.domNode.style.transform = this._layerHint ? 'translate3d(0px, 0px, 0px)' : '';\n }\n setBoxShadow(boxShadow) {\n if (this._boxShadow === boxShadow) {\n return;\n }\n this._boxShadow = boxShadow;\n this.domNode.style.boxShadow = boxShadow;\n }\n setContain(contain) {\n if (this._contain === contain) {\n return;\n }\n this._contain = contain;\n this.domNode.style.contain = this._contain;\n }\n setAttribute(name, value) {\n this.domNode.setAttribute(name, value);\n }\n removeAttribute(name) {\n this.domNode.removeAttribute(name);\n }\n appendChild(child) {\n this.domNode.appendChild(child.domNode);\n }\n removeChild(child) {\n this.domNode.removeChild(child.domNode);\n }\n}\nexports.FastDomNode = FastDomNode;\nfunction numberAsPixels(value) {\n return (typeof value === 'number' ? `${value}px` : value);\n}\nfunction createFastDomNode(domNode) {\n return new FastDomNode(domNode);\n}\n","\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.GlobalPointerMoveMonitor = void 0;\nconst dom = __importStar(require(\"vs/base/browser/dom\"));\nconst lifecycle_1 = require(\"vs/base/common/lifecycle\");\nclass GlobalPointerMoveMonitor {\n constructor() {\n this._hooks = new lifecycle_1.DisposableStore();\n this._pointerMoveCallback = null;\n this._onStopCallback = null;\n }\n dispose() {\n this.stopMonitoring(false);\n this._hooks.dispose();\n }\n stopMonitoring(invokeStopCallback, browserEvent) {\n if (!this.isMonitoring()) {\n // Not monitoring\n return;\n }\n // Unhook\n this._hooks.clear();\n this._pointerMoveCallback = null;\n const onStopCallback = this._onStopCallback;\n this._onStopCallback = null;\n if (invokeStopCallback && onStopCallback) {\n onStopCallback(browserEvent);\n }\n }\n isMonitoring() {\n return !!this._pointerMoveCallback;\n }\n startMonitoring(initialElement, pointerId, initialButtons, pointerMoveCallback, onStopCallback) {\n if (this.isMonitoring()) {\n this.stopMonitoring(false);\n }\n this._pointerMoveCallback = pointerMoveCallback;\n this._onStopCallback = onStopCallback;\n let eventSource = initialElement;\n try {\n initialElement.setPointerCapture(pointerId);\n this._hooks.add((0, lifecycle_1.toDisposable)(() => {\n try {\n initialElement.releasePointerCapture(pointerId);\n }\n catch (err) {\n // See https://github.com/microsoft/vscode/issues/161731\n //\n // `releasePointerCapture` sometimes fails when being invoked with the exception:\n // DOMException: Failed to execute 'releasePointerCapture' on 'Element':\n // No active pointer with the given id is found.\n //\n // There's no need to do anything in case of failure\n }\n }));\n }\n catch (err) {\n // See https://github.com/microsoft/vscode/issues/144584\n // See https://github.com/microsoft/vscode/issues/146947\n // `setPointerCapture` sometimes fails when being invoked\n // from a `mousedown` listener on macOS and Windows\n // and it always fails on Linux with the exception:\n // DOMException: Failed to execute 'setPointerCapture' on 'Element':\n // No active pointer with the given id is found.\n // In case of failure, we bind the listeners on the window\n eventSource = dom.getWindow(initialElement);\n }\n this._hooks.add(dom.addDisposableListener(eventSource, dom.EventType.POINTER_MOVE, (e) => {\n if (e.buttons !== initialButtons) {\n // Buttons state has changed in the meantime\n this.stopMonitoring(true);\n return;\n }\n e.preventDefault();\n this._pointerMoveCallback(e);\n }));\n this._hooks.add(dom.addDisposableListener(eventSource, dom.EventType.POINTER_UP, (e) => this.stopMonitoring(true)));\n }\n}\nexports.GlobalPointerMoveMonitor = GlobalPointerMoveMonitor;\n","\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.IframeUtils = void 0;\nexports.parentOriginHash = parentOriginHash;\nconst sameOriginWindowChainCache = new WeakMap();\nfunction getParentWindowIfSameOrigin(w) {\n if (!w.parent || w.parent === w) {\n return null;\n }\n // Cannot really tell if we have access to the parent window unless we try to access something in it\n try {\n const location = w.location;\n const parentLocation = w.parent.location;\n if (location.origin !== 'null' && parentLocation.origin !== 'null' && location.origin !== parentLocation.origin) {\n return null;\n }\n }\n catch (e) {\n return null;\n }\n return w.parent;\n}\nclass IframeUtils {\n /**\n * Returns a chain of embedded windows with the same origin (which can be accessed programmatically).\n * Having a chain of length 1 might mean that the current execution environment is running outside of an iframe or inside an iframe embedded in a window with a different origin.\n */\n static getSameOriginWindowChain(targetWindow) {\n let windowChainCache = sameOriginWindowChainCache.get(targetWindow);\n if (!windowChainCache) {\n windowChainCache = [];\n sameOriginWindowChainCache.set(targetWindow, windowChainCache);\n let w = targetWindow;\n let parent;\n do {\n parent = getParentWindowIfSameOrigin(w);\n if (parent) {\n windowChainCache.push({\n window: new WeakRef(w),\n iframeElement: w.frameElement || null\n });\n }\n else {\n windowChainCache.push({\n window: new WeakRef(w),\n iframeElement: null\n });\n }\n w = parent;\n } while (w);\n }\n return windowChainCache.slice(0);\n }\n /**\n * Returns the position of `childWindow` relative to `ancestorWindow`\n */\n static getPositionOfChildWindowRelativeToAncestorWindow(childWindow, ancestorWindow) {\n if (!ancestorWindow || childWindow === ancestorWindow) {\n return {\n top: 0,\n left: 0\n };\n }\n let top = 0, left = 0;\n const windowChain = this.getSameOriginWindowChain(childWindow);\n for (const windowChainEl of windowChain) {\n const windowInChain = windowChainEl.window.deref();\n top += windowInChain?.scrollY ?? 0;\n left += windowInChain?.scrollX ?? 0;\n if (windowInChain === ancestorWindow) {\n break;\n }\n if (!windowChainEl.iframeElement) {\n break;\n }\n const boundingRect = windowChainEl.iframeElement.getBoundingClientRect();\n top += boundingRect.top;\n left += boundingRect.left;\n }\n return {\n top: top,\n left: left\n };\n }\n}\nexports.IframeUtils = IframeUtils;\n/**\n * Returns a sha-256 composed of `parentOrigin` and `salt` converted to base 32\n */\nasync function parentOriginHash(parentOrigin, salt) {\n // This same code is also inlined at `src/vs/workbench/services/extensions/worker/webWorkerExtensionHostIframe.html`\n if (!crypto.subtle) {\n throw new Error(`'crypto.subtle' is not available so webviews will not work. This is likely because the editor is not running in a secure context (https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts).`);\n }\n const strData = JSON.stringify({ parentOrigin, salt });\n const encoder = new TextEncoder();\n const arrData = encoder.encode(strData);\n const hash = await crypto.subtle.digest('sha-256', arrData);\n return sha256AsBase32(hash);\n}\nfunction sha256AsBase32(bytes) {\n const array = Array.from(new Uint8Array(bytes));\n const hexArray = array.map(b => b.toString(16).padStart(2, '0')).join('');\n // sha256 has 256 bits, so we need at most ceil(lg(2^256-1)/lg(32)) = 52 chars to represent it in base 32\n return BigInt(`0x${hexArray}`).toString(32).padStart(52, '0');\n}\n","\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.StandardKeyboardEvent = void 0;\nexports.printKeyboardEvent = printKeyboardEvent;\nexports.printStandardKeyboardEvent = printStandardKeyboardEvent;\nconst browser = __importStar(require(\"vs/base/browser/browser\"));\nconst keyCodes_1 = require(\"vs/base/common/keyCodes\");\nconst keybindings_1 = require(\"vs/base/common/keybindings\");\nconst platform = __importStar(require(\"vs/base/common/platform\"));\nfunction extractKeyCode(e) {\n if (e.charCode) {\n // \"keypress\" events mostly\n const char = String.fromCharCode(e.charCode).toUpperCase();\n return keyCodes_1.KeyCodeUtils.fromString(char);\n }\n const keyCode = e.keyCode;\n // browser quirks\n if (keyCode === 3) {\n return keyCodes_1.KeyCode.PauseBreak;\n }\n else if (browser.isFirefox) {\n switch (keyCode) {\n case 59: return keyCodes_1.KeyCode.Semicolon;\n case 60:\n if (platform.isLinux) {\n return keyCodes_1.KeyCode.IntlBackslash;\n }\n break;\n case 61: return keyCodes_1.KeyCode.Equal;\n // based on: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode#numpad_keys\n case 107: return keyCodes_1.KeyCode.NumpadAdd;\n case 109: return keyCodes_1.KeyCode.NumpadSubtract;\n case 173: return keyCodes_1.KeyCode.Minus;\n case 224:\n if (platform.isMacintosh) {\n return keyCodes_1.KeyCode.Meta;\n }\n break;\n }\n }\n else if (browser.isWebKit) {\n if (platform.isMacintosh && keyCode === 93) {\n // the two meta keys in the Mac have different key codes (91 and 93)\n return keyCodes_1.KeyCode.Meta;\n }\n else if (!platform.isMacintosh && keyCode === 92) {\n return keyCodes_1.KeyCode.Meta;\n }\n }\n // cross browser keycodes:\n return keyCodes_1.EVENT_KEY_CODE_MAP[keyCode] || keyCodes_1.KeyCode.Unknown;\n}\nconst ctrlKeyMod = (platform.isMacintosh ? keyCodes_1.KeyMod.WinCtrl : keyCodes_1.KeyMod.CtrlCmd);\nconst altKeyMod = keyCodes_1.KeyMod.Alt;\nconst shiftKeyMod = keyCodes_1.KeyMod.Shift;\nconst metaKeyMod = (platform.isMacintosh ? keyCodes_1.KeyMod.CtrlCmd : keyCodes_1.KeyMod.WinCtrl);\nfunction printKeyboardEvent(e) {\n const modifiers = [];\n if (e.ctrlKey) {\n modifiers.push(`ctrl`);\n }\n if (e.shiftKey) {\n modifiers.push(`shift`);\n }\n if (e.altKey) {\n modifiers.push(`alt`);\n }\n if (e.metaKey) {\n modifiers.push(`meta`);\n }\n return `modifiers: [${modifiers.join(',')}], code: ${e.code}, keyCode: ${e.keyCode}, key: ${e.key}`;\n}\nfunction printStandardKeyboardEvent(e) {\n const modifiers = [];\n if (e.ctrlKey) {\n modifiers.push(`ctrl`);\n }\n if (e.shiftKey) {\n modifiers.push(`shift`);\n }\n if (e.altKey) {\n modifiers.push(`alt`);\n }\n if (e.metaKey) {\n modifiers.push(`meta`);\n }\n return `modifiers: [${modifiers.join(',')}], code: ${e.code}, keyCode: ${e.keyCode} ('${keyCodes_1.KeyCodeUtils.toString(e.keyCode)}')`;\n}\nclass StandardKeyboardEvent {\n constructor(source) {\n this._standardKeyboardEventBrand = true;\n const e = source;\n this.browserEvent = e;\n this.target = e.target;\n this.ctrlKey = e.ctrlKey;\n this.shiftKey = e.shiftKey;\n this.altKey = e.altKey;\n this.metaKey = e.metaKey;\n this.altGraphKey = e.getModifierState?.('AltGraph');\n this.keyCode = extractKeyCode(e);\n this.code = e.code;\n // console.info(e.type + \": keyCode: \" + e.keyCode + \", which: \" + e.which + \", charCode: \" + e.charCode + \", detail: \" + e.detail + \" ====> \" + this.keyCode + ' -- ' + KeyCode[this.keyCode]);\n this.ctrlKey = this.ctrlKey || this.keyCode === keyCodes_1.KeyCode.Ctrl;\n this.altKey = this.altKey || this.keyCode === keyCodes_1.KeyCode.Alt;\n this.shiftKey = this.shiftKey || this.keyCode === keyCodes_1.KeyCode.Shift;\n this.metaKey = this.metaKey || this.keyCode === keyCodes_1.KeyCode.Meta;\n this._asKeybinding = this._computeKeybinding();\n this._asKeyCodeChord = this._computeKeyCodeChord();\n // console.log(`code: ${e.code}, keyCode: ${e.keyCode}, key: ${e.key}`);\n }\n preventDefault() {\n if (this.browserEvent && this.browserEvent.preventDefault) {\n this.browserEvent.preventDefault();\n }\n }\n stopPropagation() {\n if (this.browserEvent && this.browserEvent.stopPropagation) {\n this.browserEvent.stopPropagation();\n }\n }\n toKeyCodeChord() {\n return this._asKeyCodeChord;\n }\n equals(other) {\n return this._asKeybinding === other;\n }\n _computeKeybinding() {\n let key = keyCodes_1.KeyCode.Unknown;\n if (this.keyCode !== keyCodes_1.KeyCode.Ctrl && this.keyCode !== keyCodes_1.KeyCode.Shift && this.keyCode !== keyCodes_1.KeyCode.Alt && this.keyCode !== keyCodes_1.KeyCode.Meta) {\n key = this.keyCode;\n }\n let result = 0;\n if (this.ctrlKey) {\n result |= ctrlKeyMod;\n }\n if (this.altKey) {\n result |= altKeyMod;\n }\n if (this.shiftKey) {\n result |= shiftKeyMod;\n }\n if (this.metaKey) {\n result |= metaKeyMod;\n }\n result |= key;\n return result;\n }\n _computeKeyCodeChord() {\n let key = keyCodes_1.KeyCode.Unknown;\n if (this.keyCode !== keyCodes_1.KeyCode.Ctrl && this.keyCode !== keyCodes_1.KeyCode.Shift && this.keyCode !== keyCodes_1.KeyCode.Alt && this.keyCode !== keyCodes_1.KeyCode.Meta) {\n key = this.keyCode;\n }\n return new keybindings_1.KeyCodeChord(this.ctrlKey, this.shiftKey, this.altKey, this.metaKey, key);\n }\n}\nexports.StandardKeyboardEvent = StandardKeyboardEvent;\n","\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.StandardWheelEvent = exports.DragMouseEvent = exports.StandardMouseEvent = void 0;\nconst browser = __importStar(require(\"vs/base/browser/browser\"));\nconst iframe_1 = require(\"vs/base/browser/iframe\");\nconst platform = __importStar(require(\"vs/base/common/platform\"));\nclass StandardMouseEvent {\n constructor(targetWindow, e) {\n this.timestamp = Date.now();\n this.browserEvent = e;\n this.leftButton = e.button === 0;\n this.middleButton = e.button === 1;\n this.rightButton = e.button === 2;\n this.buttons = e.buttons;\n this.target = e.target;\n this.detail = e.detail || 1;\n if (e.type === 'dblclick') {\n this.detail = 2;\n }\n this.ctrlKey = e.ctrlKey;\n this.shiftKey = e.shiftKey;\n this.altKey = e.altKey;\n this.metaKey = e.metaKey;\n if (typeof e.pageX === 'number') {\n this.posx = e.pageX;\n this.posy = e.pageY;\n }\n else {\n // Probably hit by MSGestureEvent\n this.posx = e.clientX + this.target.ownerDocument.body.scrollLeft + this.target.ownerDocument.documentElement.scrollLeft;\n this.posy = e.clientY + this.target.ownerDocument.body.scrollTop + this.target.ownerDocument.documentElement.scrollTop;\n }\n // Find the position of the iframe this code is executing in relative to the iframe where the event was captured.\n const iframeOffsets = iframe_1.IframeUtils.getPositionOfChildWindowRelativeToAncestorWindow(targetWindow, e.view);\n this.posx -= iframeOffsets.left;\n this.posy -= iframeOffsets.top;\n }\n preventDefault() {\n this.browserEvent.preventDefault();\n }\n stopPropagation() {\n this.browserEvent.stopPropagation();\n }\n}\nexports.StandardMouseEvent = StandardMouseEvent;\nclass DragMouseEvent extends StandardMouseEvent {\n constructor(targetWindow, e) {\n super(targetWindow, e);\n this.dataTransfer = e.dataTransfer;\n }\n}\nexports.DragMouseEvent = DragMouseEvent;\nclass StandardWheelEvent {\n constructor(e, deltaX = 0, deltaY = 0) {\n this.browserEvent = e || null;\n this.target = e ? (e.target || e.targetNode || e.srcElement) : null;\n this.deltaY = deltaY;\n this.deltaX = deltaX;\n let shouldFactorDPR = false;\n if (browser.isChrome) {\n // Chrome version >= 123 contains the fix to factor devicePixelRatio into the wheel event.\n // See https://chromium.googlesource.com/chromium/src.git/+/be51b448441ff0c9d1f17e0f25c4bf1ab3f11f61\n const chromeVersionMatch = navigator.userAgent.match(/Chrome\\/(\\d+)/);\n const chromeMajorVersion = chromeVersionMatch ? parseInt(chromeVersionMatch[1]) : 123;\n shouldFactorDPR = chromeMajorVersion <= 122;\n }\n if (e) {\n // Old (deprecated) wheel events\n const e1 = e;\n const e2 = e;\n const devicePixelRatio = e.view?.devicePixelRatio || 1;\n // vertical delta scroll\n if (typeof e1.wheelDeltaY !== 'undefined') {\n if (shouldFactorDPR) {\n // Refs https://github.com/microsoft/vscode/issues/146403#issuecomment-1854538928\n this.deltaY = e1.wheelDeltaY / (120 * devicePixelRatio);\n }\n else {\n this.deltaY = e1.wheelDeltaY / 120;\n }\n }\n else if (typeof e2.VERTICAL_AXIS !== 'undefined' && e2.axis === e2.VERTICAL_AXIS) {\n this.deltaY = -e2.detail / 3;\n }\n else if (e.type === 'wheel') {\n // Modern wheel event\n // https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent\n const ev = e;\n if (ev.deltaMode === ev.DOM_DELTA_LINE) {\n // the deltas are expressed in lines\n if (browser.isFirefox && !platform.isMacintosh) {\n this.deltaY = -e.deltaY / 3;\n }\n else {\n this.deltaY = -e.deltaY;\n }\n }\n else {\n this.deltaY = -e.deltaY / 40;\n }\n }\n // horizontal delta scroll\n if (typeof e1.wheelDeltaX !== 'undefined') {\n if (browser.isSafari && platform.isWindows) {\n this.deltaX = -(e1.wheelDeltaX / 120);\n }\n else if (shouldFactorDPR) {\n // Refs https://github.com/microsoft/vscode/issues/146403#issuecomment-1854538928\n this.deltaX = e1.wheelDeltaX / (120 * devicePixelRatio);\n }\n else {\n this.deltaX = e1.wheelDeltaX / 120;\n }\n }\n else if (typeof e2.HORIZONTAL_AXIS !== 'undefined' && e2.axis === e2.HORIZONTAL_AXIS) {\n this.deltaX = -e.detail / 3;\n }\n else if (e.type === 'wheel') {\n // Modern wheel event\n // https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent\n const ev = e;\n if (ev.deltaMode === ev.DOM_DELTA_LINE) {\n // the deltas are expressed in lines\n if (browser.isFirefox && !platform.isMacintosh) {\n this.deltaX = -e.deltaX / 3;\n }\n else {\n this.deltaX = -e.deltaX;\n }\n }\n else {\n this.deltaX = -e.deltaX / 40;\n }\n }\n // Assume a vertical scroll if nothing else worked\n if (this.deltaY === 0 && this.deltaX === 0 && e.wheelDelta) {\n if (shouldFactorDPR) {\n // Refs https://github.com/microsoft/vscode/issues/146403#issuecomment-1854538928\n this.deltaY = e.wheelDelta / (120 * devicePixelRatio);\n }\n else {\n this.deltaY = e.wheelDelta / 120;\n }\n }\n }\n }\n preventDefault() {\n this.browserEvent?.preventDefault();\n }\n stopPropagation() {\n this.browserEvent?.stopPropagation();\n }\n}\nexports.StandardWheelEvent = StandardWheelEvent;\n","\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Gesture = exports.EventType = void 0;\nconst DomUtils = __importStar(require(\"vs/base/browser/dom\"));\nconst window_1 = require(\"vs/base/browser/window\");\nconst arrays = __importStar(require(\"vs/base/common/arrays\"));\nconst decorators_1 = require(\"vs/base/common/decorators\");\nconst event_1 = require(\"vs/base/common/event\");\nconst lifecycle_1 = require(\"vs/base/common/lifecycle\");\nconst linkedList_1 = require(\"vs/base/common/linkedList\");\nvar EventType;\n(function (EventType) {\n EventType.Tap = '-xterm-gesturetap';\n EventType.Change = '-xterm-gesturechange';\n EventType.Start = '-xterm-gesturestart';\n EventType.End = '-xterm-gesturesend';\n EventType.Contextmenu = '-xterm-gesturecontextmenu';\n})(EventType || (exports.EventType = EventType = {}));\nclass Gesture extends lifecycle_1.Disposable {\n static { this.SCROLL_FRICTION = -0.005; }\n static { this.HOLD_DELAY = 700; }\n static { this.CLEAR_TAP_COUNT_TIME = 400; } // ms\n constructor() {\n super();\n this.dispatched = false;\n this.targets = new linkedList_1.LinkedList();\n this.ignoreTargets = new linkedList_1.LinkedList();\n this.activeTouches = {};\n this.handle = null;\n this._lastSetTapCountTime = 0;\n this._register(event_1.Event.runAndSubscribe(DomUtils.onDidRegisterWindow, ({ window, disposables }) => {\n disposables.add(DomUtils.addDisposableListener(window.document, 'touchstart', (e) => this.onTouchStart(e), { passive: false }));\n disposables.add(DomUtils.addDisposableListener(window.document, 'touchend', (e) => this.onTouchEnd(window, e)));\n disposables.add(DomUtils.addDisposableListener(window.document, 'touchmove', (e) => this.onTouchMove(e), { passive: false }));\n }, { window: window_1.mainWindow, disposables: this._store }));\n }\n static addTarget(element) {\n if (!Gesture.isTouchDevice()) {\n return lifecycle_1.Disposable.None;\n }\n if (!Gesture.INSTANCE) {\n Gesture.INSTANCE = (0, lifecycle_1.markAsSingleton)(new Gesture());\n }\n const remove = Gesture.INSTANCE.targets.push(element);\n return (0, lifecycle_1.toDisposable)(remove);\n }\n static ignoreTarget(element) {\n if (!Gesture.isTouchDevice()) {\n return lifecycle_1.Disposable.None;\n }\n if (!Gesture.INSTANCE) {\n Gesture.INSTANCE = (0, lifecycle_1.markAsSingleton)(new Gesture());\n }\n const remove = Gesture.INSTANCE.ignoreTargets.push(element);\n return (0, lifecycle_1.toDisposable)(remove);\n }\n static isTouchDevice() {\n // `'ontouchstart' in window` always evaluates to true with typescript's modern typings. This causes `window` to be\n // `never` later in `window.navigator`. That's why we need the explicit `window as Window` cast\n return 'ontouchstart' in window_1.mainWindow || navigator.maxTouchPoints > 0;\n }\n dispose() {\n if (this.handle) {\n this.handle.dispose();\n this.handle = null;\n }\n super.dispose();\n }\n onTouchStart(e) {\n const timestamp = Date.now(); // use Date.now() because on FF e.timeStamp is not epoch based.\n if (this.handle) {\n this.handle.dispose();\n this.handle = null;\n }\n for (let i = 0, len = e.targetTouches.length; i < len; i++) {\n const touch = e.targetTouches.item(i);\n this.activeTouches[touch.identifier] = {\n id: touch.identifier,\n initialTarget: touch.target,\n initialTimeStamp: timestamp,\n initialPageX: touch.pageX,\n initialPageY: touch.pageY,\n rollingTimestamps: [timestamp],\n rollingPageX: [touch.pageX],\n rollingPageY: [touch.pageY]\n };\n const evt = this.newGestureEvent(EventType.Start, touch.target);\n evt.pageX = touch.pageX;\n evt.pageY = touch.pageY;\n this.dispatchEvent(evt);\n }\n if (this.dispatched) {\n e.preventDefault();\n e.stopPropagation();\n this.dispatched = false;\n }\n }\n onTouchEnd(targetWindow, e) {\n const timestamp = Date.now(); // use Date.now() because on FF e.timeStamp is not epoch based.\n const activeTouchCount = Object.keys(this.activeTouches).length;\n for (let i = 0, len = e.changedTouches.length; i < len; i++) {\n const touch = e.changedTouches.item(i);\n if (!this.activeTouches.hasOwnProperty(String(touch.identifier))) {\n console.warn('move of an UNKNOWN touch', touch);\n continue;\n }\n const data = this.activeTouches[touch.identifier], holdTime = Date.now() - data.initialTimeStamp;\n if (holdTime < Gesture.HOLD_DELAY\n && Math.abs(data.initialPageX - arrays.tail(data.rollingPageX)) < 30\n && Math.abs(data.initialPageY - arrays.tail(data.rollingPageY)) < 30) {\n const evt = this.newGestureEvent(EventType.Tap, data.initialTarget);\n evt.pageX = arrays.tail(data.rollingPageX);\n evt.pageY = arrays.tail(data.rollingPageY);\n this.dispatchEvent(evt);\n }\n else if (holdTime >= Gesture.HOLD_DELAY\n && Math.abs(data.initialPageX - arrays.tail(data.rollingPageX)) < 30\n && Math.abs(data.initialPageY - arrays.tail(data.rollingPageY)) < 30) {\n const evt = this.newGestureEvent(EventType.Contextmenu, data.initialTarget);\n evt.pageX = arrays.tail(data.rollingPageX);\n evt.pageY = arrays.tail(data.rollingPageY);\n this.dispatchEvent(evt);\n }\n else if (activeTouchCount === 1) {\n const finalX = arrays.tail(data.rollingPageX);\n const finalY = arrays.tail(data.rollingPageY);\n const deltaT = arrays.tail(data.rollingTimestamps) - data.rollingTimestamps[0];\n const deltaX = finalX - data.rollingPageX[0];\n const deltaY = finalY - data.rollingPageY[0];\n // We need to get all the dispatch targets on the start of the inertia event\n const dispatchTo = [...this.targets].filter(t => data.initialTarget instanceof Node && t.contains(data.initialTarget));\n this.inertia(targetWindow, dispatchTo, timestamp, // time now\n Math.abs(deltaX) / deltaT, // speed\n deltaX > 0 ? 1 : -1, // x direction\n finalX, // x now\n Math.abs(deltaY) / deltaT, // y speed\n deltaY > 0 ? 1 : -1, // y direction\n finalY // y now\n );\n }\n this.dispatchEvent(this.newGestureEvent(EventType.End, data.initialTarget));\n // forget about this touch\n delete this.activeTouches[touch.identifier];\n }\n if (this.dispatched) {\n e.preventDefault();\n e.stopPropagation();\n this.dispatched = false;\n }\n }\n newGestureEvent(type, initialTarget) {\n const event = document.createEvent('CustomEvent');\n event.initEvent(type, false, true);\n event.initialTarget = initialTarget;\n event.tapCount = 0;\n return event;\n }\n dispatchEvent(event) {\n if (event.type === EventType.Tap) {\n const currentTime = (new Date()).getTime();\n let setTapCount = 0;\n if (currentTime - this._lastSetTapCountTime > Gesture.CLEAR_TAP_COUNT_TIME) {\n setTapCount = 1;\n }\n else {\n setTapCount = 2;\n }\n this._lastSetTapCountTime = currentTime;\n event.tapCount = setTapCount;\n }\n else if (event.type === EventType.Change || event.type === EventType.Contextmenu) {\n // tap is canceled by scrolling or context menu\n this._lastSetTapCountTime = 0;\n }\n if (event.initialTarget instanceof Node) {\n for (const ignoreTarget of this.ignoreTargets) {\n if (ignoreTarget.contains(event.initialTarget)) {\n return;\n }\n }\n const targets = [];\n for (const target of this.targets) {\n if (target.contains(event.initialTarget)) {\n let depth = 0;\n let now = event.initialTarget;\n while (now && now !== target) {\n depth++;\n now = now.parentElement;\n }\n targets.push([depth, target]);\n }\n }\n targets.sort((a, b) => a[0] - b[0]);\n for (const [_, target] of targets) {\n target.dispatchEvent(event);\n this.dispatched = true;\n }\n }\n }\n inertia(targetWindow, dispatchTo, t1, vX, dirX, x, vY, dirY, y) {\n this.handle = DomUtils.scheduleAtNextAnimationFrame(targetWindow, () => {\n const now = Date.now();\n // velocity: old speed + accel_over_time\n const deltaT = now - t1;\n let delta_pos_x = 0, delta_pos_y = 0;\n let stopped = true;\n vX += Gesture.SCROLL_FRICTION * deltaT;\n vY += Gesture.SCROLL_FRICTION * deltaT;\n if (vX > 0) {\n stopped = false;\n delta_pos_x = dirX * vX * deltaT;\n }\n if (vY > 0) {\n stopped = false;\n delta_pos_y = dirY * vY * deltaT;\n }\n // dispatch translation event\n const evt = this.newGestureEvent(EventType.Change);\n evt.translationX = delta_pos_x;\n evt.translationY = delta_pos_y;\n dispatchTo.forEach(d => d.dispatchEvent(evt));\n if (!stopped) {\n this.inertia(targetWindow, dispatchTo, now, vX, dirX, x + delta_pos_x, vY, dirY, y + delta_pos_y);\n }\n });\n }\n onTouchMove(e) {\n const timestamp = Date.now(); // use Date.now() because on FF e.timeStamp is not epoch based.\n for (let i = 0, len = e.changedTouches.length; i < len; i++) {\n const touch = e.changedTouches.item(i);\n if (!this.activeTouches.hasOwnProperty(String(touch.identifier))) {\n console.warn('end of an UNKNOWN touch', touch);\n continue;\n }\n const data = this.activeTouches[touch.identifier];\n const evt = this.newGestureEvent(EventType.Change, data.initialTarget);\n evt.translationX = touch.pageX - arrays.tail(data.rollingPageX);\n evt.translationY = touch.pageY - arrays.tail(data.rollingPageY);\n evt.pageX = touch.pageX;\n evt.pageY = touch.pageY;\n this.dispatchEvent(evt);\n // only keep a few data points, to average the final speed\n if (data.rollingPageX.length > 3) {\n data.rollingPageX.shift();\n data.rollingPageY.shift();\n data.rollingTimestamps.shift();\n }\n data.rollingPageX.push(touch.pageX);\n data.rollingPageY.push(touch.pageY);\n data.rollingTimestamps.push(timestamp);\n }\n if (this.dispatched) {\n e.preventDefault();\n e.stopPropagation();\n this.dispatched = false;\n }\n }\n}\nexports.Gesture = Gesture;\n__decorate([\n decorators_1.memoize\n], Gesture, \"isTouchDevice\", null);\n","\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.AbstractScrollbar = void 0;\nconst dom = __importStar(require(\"vs/base/browser/dom\"));\nconst fastDomNode_1 = require(\"vs/base/browser/fastDomNode\");\nconst globalPointerMoveMonitor_1 = require(\"vs/base/browser/globalPointerMoveMonitor\");\nconst scrollbarArrow_1 = require(\"vs/base/browser/ui/scrollbar/scrollbarArrow\");\nconst scrollbarVisibilityController_1 = require(\"vs/base/browser/ui/scrollbar/scrollbarVisibilityController\");\nconst widget_1 = require(\"vs/base/browser/ui/widget\");\nconst platform = __importStar(require(\"vs/base/common/platform\"));\n/**\n * The orthogonal distance to the slider at which dragging \"resets\". This implements \"snapping\"\n */\nconst POINTER_DRAG_RESET_DISTANCE = 140;\nclass AbstractScrollbar extends widget_1.Widget {\n constructor(opts) {\n super();\n this._lazyRender = opts.lazyRender;\n this._host = opts.host;\n this._scrollable = opts.scrollable;\n this._scrollByPage = opts.scrollByPage;\n this._scrollbarState = opts.scrollbarState;\n this._visibilityController = this._register(new scrollbarVisibilityController_1.ScrollbarVisibilityController(opts.visibility, 'visible scrollbar ' + opts.extraScrollbarClassName, 'invisible scrollbar ' + opts.extraScrollbarClassName));\n this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded());\n this._pointerMoveMonitor = this._register(new globalPointerMoveMonitor_1.GlobalPointerMoveMonitor());\n this._shouldRender = true;\n this.domNode = (0, fastDomNode_1.createFastDomNode)(document.createElement('div'));\n this.domNode.setAttribute('role', 'presentation');\n this.domNode.setAttribute('aria-hidden', 'true');\n this._visibilityController.setDomNode(this.domNode);\n this.domNode.setPosition('absolute');\n this._register(dom.addDisposableListener(this.domNode.domNode, dom.EventType.POINTER_DOWN, (e) => this._domNodePointerDown(e)));\n }\n // ----------------- creation\n /**\n * Creates the dom node for an arrow & adds it to the container\n */\n _createArrow(opts) {\n const arrow = this._register(new scrollbarArrow_1.ScrollbarArrow(opts));\n this.domNode.domNode.appendChild(arrow.bgDomNode);\n this.domNode.domNode.appendChild(arrow.domNode);\n }\n /**\n * Creates the slider dom node, adds it to the container & hooks up the events\n */\n _createSlider(top, left, width, height) {\n this.slider = (0, fastDomNode_1.createFastDomNode)(document.createElement('div'));\n this.slider.setClassName('slider');\n this.slider.setPosition('absolute');\n this.slider.setTop(top);\n this.slider.setLeft(left);\n if (typeof width === 'number') {\n this.slider.setWidth(width);\n }\n if (typeof height === 'number') {\n this.slider.setHeight(height);\n }\n this.slider.setLayerHinting(true);\n this.slider.setContain('strict');\n this.domNode.domNode.appendChild(this.slider.domNode);\n this._register(dom.addDisposableListener(this.slider.domNode, dom.EventType.POINTER_DOWN, (e) => {\n if (e.button === 0) {\n e.preventDefault();\n this._sliderPointerDown(e);\n }\n }));\n this.onclick(this.slider.domNode, e => {\n if (e.leftButton) {\n e.stopPropagation();\n }\n });\n }\n // ----------------- Update state\n _onElementSize(visibleSize) {\n if (this._scrollbarState.setVisibleSize(visibleSize)) {\n this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded());\n this._shouldRender = true;\n if (!this._lazyRender) {\n this.render();\n }\n }\n return this._shouldRender;\n }\n _onElementScrollSize(elementScrollSize) {\n if (this._scrollbarState.setScrollSize(elementScrollSize)) {\n this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded());\n this._shouldRender = true;\n if (!this._lazyRender) {\n this.render();\n }\n }\n return this._shouldRender;\n }\n _onElementScrollPosition(elementScrollPosition) {\n if (this._scrollbarState.setScrollPosition(elementScrollPosition)) {\n this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded());\n this._shouldRender = true;\n if (!this._lazyRender) {\n this.render();\n }\n }\n return this._shouldRender;\n }\n // ----------------- rendering\n beginReveal() {\n this._visibilityController.setShouldBeVisible(true);\n }\n beginHide() {\n this._visibilityController.setShouldBeVisible(false);\n }\n render() {\n if (!this._shouldRender) {\n return;\n }\n this._shouldRender = false;\n this._renderDomNode(this._scrollbarState.getRectangleLargeSize(), this._scrollbarState.getRectangleSmallSize());\n this._updateSlider(this._scrollbarState.getSliderSize(), this._scrollbarState.getArrowSize() + this._scrollbarState.getSliderPosition());\n }\n // ----------------- DOM events\n _domNodePointerDown(e) {\n if (e.target !== this.domNode.domNode) {\n return;\n }\n this._onPointerDown(e);\n }\n delegatePointerDown(e) {\n const domTop = this.domNode.domNode.getClientRects()[0].top;\n const sliderStart = domTop + this._scrollbarState.getSliderPosition();\n const sliderStop = domTop + this._scrollbarState.getSliderPosition() + this._scrollbarState.getSliderSize();\n const pointerPos = this._sliderPointerPosition(e);\n if (sliderStart <= pointerPos && pointerPos <= sliderStop) {\n // Act as if it was a pointer down on the slider\n if (e.button === 0) {\n e.preventDefault();\n this._sliderPointerDown(e);\n }\n }\n else {\n // Act as if it was a pointer down on the scrollbar\n this._onPointerDown(e);\n }\n }\n _onPointerDown(e) {\n let offsetX;\n let offsetY;\n if (e.target === this.domNode.domNode && typeof e.offsetX === 'number' && typeof e.offsetY === 'number') {\n offsetX = e.offsetX;\n offsetY = e.offsetY;\n }\n else {\n const domNodePosition = dom.getDomNodePagePosition(this.domNode.domNode);\n offsetX = e.pageX - domNodePosition.left;\n offsetY = e.pageY - domNodePosition.top;\n }\n const offset = this._pointerDownRelativePosition(offsetX, offsetY);\n this._setDesiredScrollPositionNow(this._scrollByPage\n ? this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(offset)\n : this._scrollbarState.getDesiredScrollPositionFromOffset(offset));\n if (e.button === 0) {\n // left button\n e.preventDefault();\n this._sliderPointerDown(e);\n }\n }\n _sliderPointerDown(e) {\n if (!e.target || !(e.target instanceof Element)) {\n return;\n }\n const initialPointerPosition = this._sliderPointerPosition(e);\n const initialPointerOrthogonalPosition = this._sliderOrthogonalPointerPosition(e);\n const initialScrollbarState = this._scrollbarState.clone();\n this.slider.toggleClassName('active', true);\n this._pointerMoveMonitor.startMonitoring(e.target, e.pointerId, e.buttons, (pointerMoveData) => {\n const pointerOrthogonalPosition = this._sliderOrthogonalPointerPosition(pointerMoveData);\n const pointerOrthogonalDelta = Math.abs(pointerOrthogonalPosition - initialPointerOrthogonalPosition);\n if (platform.isWindows && pointerOrthogonalDelta > POINTER_DRAG_RESET_DISTANCE) {\n // The pointer has wondered away from the scrollbar => reset dragging\n this._setDesiredScrollPositionNow(initialScrollbarState.getScrollPosition());\n return;\n }\n const pointerPosition = this._sliderPointerPosition(pointerMoveData);\n const pointerDelta = pointerPosition - initialPointerPosition;\n this._setDesiredScrollPositionNow(initialScrollbarState.getDesiredScrollPositionFromDelta(pointerDelta));\n }, () => {\n this.slider.toggleClassName('active', false);\n this._host.onDragEnd();\n });\n this._host.onDragStart();\n }\n _setDesiredScrollPositionNow(_desiredScrollPosition) {\n const desiredScrollPosition = {};\n this.writeScrollPosition(desiredScrollPosition, _desiredScrollPosition);\n this._scrollable.setScrollPositionNow(desiredScrollPosition);\n }\n updateScrollbarSize(scrollbarSize) {\n this._updateScrollbarSize(scrollbarSize);\n this._scrollbarState.setScrollbarSize(scrollbarSize);\n this._shouldRender = true;\n if (!this._lazyRender) {\n this.render();\n }\n }\n isNeeded() {\n return this._scrollbarState.isNeeded();\n }\n}\nexports.AbstractScrollbar = AbstractScrollbar;\n","\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.HorizontalScrollbar = void 0;\nconst abstractScrollbar_1 = require(\"vs/base/browser/ui/scrollbar/abstractScrollbar\");\nconst scrollbarState_1 = require(\"vs/base/browser/ui/scrollbar/scrollbarState\");\nconst scrollable_1 = require(\"vs/base/common/scrollable\");\nclass HorizontalScrollbar extends abstractScrollbar_1.AbstractScrollbar {\n constructor(scrollable, options, host) {\n const scrollDimensions = scrollable.getScrollDimensions();\n const scrollPosition = scrollable.getCurrentScrollPosition();\n super({\n lazyRender: options.lazyRender,\n host: host,\n scrollbarState: new scrollbarState_1.ScrollbarState((options.horizontalHasArrows ? options.arrowSize : 0), (options.horizontal === scrollable_1.ScrollbarVisibility.Hidden ? 0 : options.horizontalScrollbarSize), (options.vertical === scrollable_1.ScrollbarVisibility.Hidden ? 0 : options.verticalScrollbarSize), scrollDimensions.width, scrollDimensions.scrollWidth, scrollPosition.scrollLeft),\n visibility: options.horizontal,\n extraScrollbarClassName: 'horizontal',\n scrollable: scrollable,\n scrollByPage: options.scrollByPage\n });\n if (options.horizontalHasArrows) {\n throw new Error('horizontalHasArrows is not supported in xterm.js');\n // const arrowDelta = (options.arrowSize - ARROW_IMG_SIZE) / 2;\n // const scrollbarDelta = (options.horizontalScrollbarSize - ARROW_IMG_SIZE) / 2;\n // this._createArrow({\n // \tclassName: 'scra',\n // \ticon: Codicon.scrollbarButtonLeft,\n // \ttop: scrollbarDelta,\n // \tleft: arrowDelta,\n // \tbottom: undefined,\n // \tright: undefined,\n // \tbgWidth: options.arrowSize,\n // \tbgHeight: options.horizontalScrollbarSize,\n // \tonActivate: () => this._host.onMouseWheel(new StandardWheelEvent(null, 1, 0)),\n // });\n // this._createArrow({\n // \tclassName: 'scra',\n // \ticon: Codicon.scrollbarButtonRight,\n // \ttop: scrollbarDelta,\n // \tleft: undefined,\n // \tbottom: undefined,\n // \tright: arrowDelta,\n // \tbgWidth: options.arrowSize,\n // \tbgHeight: options.horizontalScrollbarSize,\n // \tonActivate: () => this._host.onMouseWheel(new StandardWheelEvent(null, -1, 0)),\n // });\n }\n this._createSlider(Math.floor((options.horizontalScrollbarSize - options.horizontalSliderSize) / 2), 0, undefined, options.horizontalSliderSize);\n }\n _updateSlider(sliderSize, sliderPosition) {\n this.slider.setWidth(sliderSize);\n this.slider.setLeft(sliderPosition);\n }\n _renderDomNode(largeSize, smallSize) {\n this.domNode.setWidth(largeSize);\n this.domNode.setHeight(smallSize);\n this.domNode.setLeft(0);\n this.domNode.setBottom(0);\n }\n onDidScroll(e) {\n this._shouldRender = this._onElementScrollSize(e.scrollWidth) || this._shouldRender;\n this._shouldRender = this._onElementScrollPosition(e.scrollLeft) || this._shouldRender;\n this._shouldRender = this._onElementSize(e.width) || this._shouldRender;\n return this._shouldRender;\n }\n _pointerDownRelativePosition(offsetX, offsetY) {\n return offsetX;\n }\n _sliderPointerPosition(e) {\n return e.pageX;\n }\n _sliderOrthogonalPointerPosition(e) {\n return e.pageY;\n }\n _updateScrollbarSize(size) {\n this.slider.setHeight(size);\n }\n writeScrollPosition(target, scrollPosition) {\n target.scrollLeft = scrollPosition;\n }\n updateOptions(options) {\n this.updateScrollbarSize(options.horizontal === scrollable_1.ScrollbarVisibility.Hidden ? 0 : options.horizontalScrollbarSize);\n this._scrollbarState.setOppositeScrollbarSize(options.vertical === scrollable_1.ScrollbarVisibility.Hidden ? 0 : options.verticalScrollbarSize);\n this._visibilityController.setVisibility(options.horizontal);\n this._scrollByPage = options.scrollByPage;\n }\n}\nexports.HorizontalScrollbar = HorizontalScrollbar;\n","\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.DomScrollableElement = exports.SmoothScrollableElement = exports.ScrollableElement = exports.AbstractScrollableElement = exports.MouseWheelClassifier = void 0;\nconst browser_1 = require(\"vs/base/browser/browser\");\nconst dom = __importStar(require(\"vs/base/browser/dom\"));\nconst fastDomNode_1 = require(\"vs/base/browser/fastDomNode\");\nconst mouseEvent_1 = require(\"vs/base/browser/mouseEvent\");\nconst horizontalScrollbar_1 = require(\"vs/base/browser/ui/scrollbar/horizontalScrollbar\");\nconst verticalScrollbar_1 = require(\"vs/base/browser/ui/scrollbar/verticalScrollbar\");\nconst widget_1 = require(\"vs/base/browser/ui/widget\");\nconst async_1 = require(\"vs/base/common/async\");\nconst event_1 = require(\"vs/base/common/event\");\nconst lifecycle_1 = require(\"vs/base/common/lifecycle\");\nconst platform = __importStar(require(\"vs/base/common/platform\"));\nconst scrollable_1 = require(\"vs/base/common/scrollable\");\n// import 'vs/css!./media/scrollbars';\nconst HIDE_TIMEOUT = 500;\nconst SCROLL_WHEEL_SENSITIVITY = 50;\nconst SCROLL_WHEEL_SMOOTH_SCROLL_ENABLED = true;\nclass MouseWheelClassifierItem {\n constructor(timestamp, deltaX, deltaY) {\n this.timestamp = timestamp;\n this.deltaX = deltaX;\n this.deltaY = deltaY;\n this.score = 0;\n }\n}\nclass MouseWheelClassifier {\n static { this.INSTANCE = new MouseWheelClassifier(); }\n constructor() {\n this._capacity = 5;\n this._memory = [];\n this._front = -1;\n this._rear = -1;\n }\n isPhysicalMouseWheel() {\n if (this._front === -1 && this._rear === -1) {\n // no elements\n return false;\n }\n // 0.5 * last + 0.25 * 2nd last + 0.125 * 3rd last + ...\n let remainingInfluence = 1;\n let score = 0;\n let iteration = 1;\n let index = this._rear;\n do {\n const influence = (index === this._front ? remainingInfluence : Math.pow(2, -iteration));\n remainingInfluence -= influence;\n score += this._memory[index].score * influence;\n if (index === this._front) {\n break;\n }\n index = (this._capacity + index - 1) % this._capacity;\n iteration++;\n } while (true);\n return (score <= 0.5);\n }\n acceptStandardWheelEvent(e) {\n if (browser_1.isChrome) {\n const targetWindow = dom.getWindow(e.browserEvent);\n const pageZoomFactor = (0, browser_1.getZoomFactor)(targetWindow);\n // On Chrome, the incoming delta events are multiplied with the OS zoom factor.\n // The OS zoom factor can be reverse engineered by using the device pixel ratio and the configured zoom factor into account.\n this.accept(Date.now(), e.deltaX * pageZoomFactor, e.deltaY * pageZoomFactor);\n }\n else {\n this.accept(Date.now(), e.deltaX, e.deltaY);\n }\n }\n accept(timestamp, deltaX, deltaY) {\n let previousItem = null;\n const item = new MouseWheelClassifierItem(timestamp, deltaX, deltaY);\n if (this._front === -1 && this._rear === -1) {\n this._memory[0] = item;\n this._front = 0;\n this._rear = 0;\n }\n else {\n previousItem = this._memory[this._rear];\n this._rear = (this._rear + 1) % this._capacity;\n if (this._rear === this._front) {\n // Drop oldest\n this._front = (this._front + 1) % this._capacity;\n }\n this._memory[this._rear] = item;\n }\n item.score = this._computeScore(item, previousItem);\n }\n /**\n * A score between 0 and 1 for `item`.\n * - a score towards 0 indicates that the source appears to be a physical mouse wheel\n * - a score towards 1 indicates that the source appears to be a touchpad or magic mouse, etc.\n */\n _computeScore(item, previousItem) {\n if (Math.abs(item.deltaX) > 0 && Math.abs(item.deltaY) > 0) {\n // both axes exercised => definitely not a physical mouse wheel\n return 1;\n }\n let score = 0.5;\n if (!this._isAlmostInt(item.deltaX) || !this._isAlmostInt(item.deltaY)) {\n // non-integer deltas => indicator that this is not a physical mouse wheel\n score += 0.25;\n }\n // Non-accelerating scroll => indicator that this is a physical mouse wheel\n // These can be identified by seeing whether they are the module of one another.\n if (previousItem) {\n const absDeltaX = Math.abs(item.deltaX);\n const absDeltaY = Math.abs(item.deltaY);\n const absPreviousDeltaX = Math.abs(previousItem.deltaX);\n const absPreviousDeltaY = Math.abs(previousItem.deltaY);\n // Min 1 to avoid division by zero, module 1 will still be 0.\n const minDeltaX = Math.max(Math.min(absDeltaX, absPreviousDeltaX), 1);\n const minDeltaY = Math.max(Math.min(absDeltaY, absPreviousDeltaY), 1);\n const maxDeltaX = Math.max(absDeltaX, absPreviousDeltaX);\n const maxDeltaY = Math.max(absDeltaY, absPreviousDeltaY);\n const isSameModulo = (maxDeltaX % minDeltaX === 0 && maxDeltaY % minDeltaY === 0);\n if (isSameModulo) {\n score -= 0.5;\n }\n }\n return Math.min(Math.max(score, 0), 1);\n }\n _isAlmostInt(value) {\n const delta = Math.abs(Math.round(value) - value);\n return (delta < 0.01);\n }\n}\nexports.MouseWheelClassifier = MouseWheelClassifier;\nclass AbstractScrollableElement extends widget_1.Widget {\n get options() {\n return this._options;\n }\n constructor(element, options, scrollable) {\n super();\n this._onScroll = this._register(new event_1.Emitter());\n this.onScroll = this._onScroll.event;\n this._onWillScroll = this._register(new event_1.Emitter());\n this.onWillScroll = this._onWillScroll.event;\n // HACK: xterm.js currnetly requires overflow to allow decorations to escape the container\n // element.style.overflow = 'hidden';\n this._options = resolveOptions(options);\n this._scrollable = scrollable;\n this._register(this._scrollable.onScroll((e) => {\n this._onWillScroll.fire(e);\n this._onDidScroll(e);\n this._onScroll.fire(e);\n }));\n const scrollbarHost = {\n onMouseWheel: (mouseWheelEvent) => this._onMouseWheel(mouseWheelEvent),\n onDragStart: () => this._onDragStart(),\n onDragEnd: () => this._onDragEnd(),\n };\n this._verticalScrollbar = this._register(new verticalScrollbar_1.VerticalScrollbar(this._scrollable, this._options, scrollbarHost));\n this._horizontalScrollbar = this._register(new horizontalScrollbar_1.HorizontalScrollbar(this._scrollable, this._options, scrollbarHost));\n this._domNode = document.createElement('div');\n this._domNode.className = 'xterm-scrollable-element ' + this._options.className;\n this._domNode.setAttribute('role', 'presentation');\n this._domNode.style.position = 'relative';\n // HACK: xterm.js currnetly requires overflow to allow decorations to escape the container\n // this._domNode.style.overflow = 'hidden';\n this._domNode.appendChild(element);\n this._domNode.appendChild(this._horizontalScrollbar.domNode.domNode);\n this._domNode.appendChild(this._verticalScrollbar.domNode.domNode);\n if (this._options.useShadows) {\n this._leftShadowDomNode = (0, fastDomNode_1.createFastDomNode)(document.createElement('div'));\n this._leftShadowDomNode.setClassName('shadow');\n this._domNode.appendChild(this._leftShadowDomNode.domNode);\n this._topShadowDomNode = (0, fastDomNode_1.createFastDomNode)(document.createElement('div'));\n this._topShadowDomNode.setClassName('shadow');\n this._domNode.appendChild(this._topShadowDomNode.domNode);\n this._topLeftShadowDomNode = (0, fastDomNode_1.createFastDomNode)(document.createElement('div'));\n this._topLeftShadowDomNode.setClassName('shadow');\n this._domNode.appendChild(this._topLeftShadowDomNode.domNode);\n }\n else {\n this._leftShadowDomNode = null;\n this._topShadowDomNode = null;\n this._topLeftShadowDomNode = null;\n }\n this._listenOnDomNode = this._options.listenOnDomNode || this._domNode;\n this._mouseWheelToDispose = [];\n this._setListeningToMouseWheel(this._options.handleMouseWheel);\n this.onmouseover(this._listenOnDomNode, (e) => this._onMouseOver(e));\n this.onmouseleave(this._listenOnDomNode, (e) => this._onMouseLeave(e));\n this._hideTimeout = this._register(new async_1.TimeoutTimer());\n this._isDragging = false;\n this._mouseIsOver = false;\n this._shouldRender = true;\n this._revealOnScroll = true;\n }\n dispose() {\n this._mouseWheelToDispose = (0, lifecycle_1.dispose)(this._mouseWheelToDispose);\n super.dispose();\n }\n /**\n * Get the generated 'scrollable' dom node\n */\n getDomNode() {\n return this._domNode;\n }\n getOverviewRulerLayoutInfo() {\n return {\n parent: this._domNode,\n insertBefore: this._verticalScrollbar.domNode.domNode,\n };\n }\n /**\n * Delegate a pointer down event to the vertical scrollbar.\n * This is to help with clicking somewhere else and having the scrollbar react.\n */\n delegateVerticalScrollbarPointerDown(browserEvent) {\n this._verticalScrollbar.delegatePointerDown(browserEvent);\n }\n getScrollDimensions() {\n return this._scrollable.getScrollDimensions();\n }\n setScrollDimensions(dimensions) {\n this._scrollable.setScrollDimensions(dimensions, false);\n }\n /**\n * Update the class name of the scrollable element.\n */\n updateClassName(newClassName) {\n this._options.className = newClassName;\n // Defaults are different on Macs\n if (platform.isMacintosh) {\n this._options.className += ' mac';\n }\n this._domNode.className = 'xterm-scrollable-element ' + this._options.className;\n }\n /**\n * Update configuration options for the scrollbar.\n */\n updateOptions(newOptions) {\n if (typeof newOptions.handleMouseWheel !== 'undefined') {\n this._options.handleMouseWheel = newOptions.handleMouseWheel;\n this._setListeningToMouseWheel(this._options.handleMouseWheel);\n }\n if (typeof newOptions.mouseWheelScrollSensitivity !== 'undefined') {\n this._options.mouseWheelScrollSensitivity = newOptions.mouseWheelScrollSensitivity;\n }\n if (typeof newOptions.fastScrollSensitivity !== 'undefined') {\n this._options.fastScrollSensitivity = newOptions.fastScrollSensitivity;\n }\n if (typeof newOptions.scrollPredominantAxis !== 'undefined') {\n this._options.scrollPredominantAxis = newOptions.scrollPredominantAxis;\n }\n if (typeof newOptions.horizontal !== 'undefined') {\n this._options.horizontal = newOptions.horizontal;\n }\n if (typeof newOptions.vertical !== 'undefined') {\n this._options.vertical = newOptions.vertical;\n }\n if (typeof newOptions.horizontalScrollbarSize !== 'undefined') {\n this._options.horizontalScrollbarSize = newOptions.horizontalScrollbarSize;\n }\n if (typeof newOptions.verticalScrollbarSize !== 'undefined') {\n this._options.verticalScrollbarSize = newOptions.verticalScrollbarSize;\n }\n if (typeof newOptions.scrollByPage !== 'undefined') {\n this._options.scrollByPage = newOptions.scrollByPage;\n }\n this._horizontalScrollbar.updateOptions(this._options);\n this._verticalScrollbar.updateOptions(this._options);\n if (!this._options.lazyRender) {\n this._render();\n }\n }\n setRevealOnScroll(value) {\n this._revealOnScroll = value;\n }\n delegateScrollFromMouseWheelEvent(browserEvent) {\n this._onMouseWheel(new mouseEvent_1.StandardWheelEvent(browserEvent));\n }\n // -------------------- mouse wheel scrolling --------------------\n _setListeningToMouseWheel(shouldListen) {\n const isListening = (this._mouseWheelToDispose.length > 0);\n if (isListening === shouldListen) {\n // No change\n return;\n }\n // Stop listening (if necessary)\n this._mouseWheelToDispose = (0, lifecycle_1.dispose)(this._mouseWheelToDispose);\n // Start listening (if necessary)\n if (shouldListen) {\n const onMouseWheel = (browserEvent) => {\n this._onMouseWheel(new mouseEvent_1.StandardWheelEvent(browserEvent));\n };\n this._mouseWheelToDispose.push(dom.addDisposableListener(this._listenOnDomNode, dom.EventType.MOUSE_WHEEL, onMouseWheel, { passive: false }));\n }\n }\n _onMouseWheel(e) {\n if (e.browserEvent?.defaultPrevented) {\n return;\n }\n const classifier = MouseWheelClassifier.INSTANCE;\n if (SCROLL_WHEEL_SMOOTH_SCROLL_ENABLED) {\n classifier.acceptStandardWheelEvent(e);\n }\n // useful for creating unit tests:\n // console.log(`${Date.now()}, ${e.deltaY}, ${e.deltaX}`);\n let didScroll = false;\n if (e.deltaY || e.deltaX) {\n let deltaY = e.deltaY * this._options.mouseWheelScrollSensitivity;\n let deltaX = e.deltaX * this._options.mouseWheelScrollSensitivity;\n if (this._options.scrollPredominantAxis) {\n if (this._options.scrollYToX && deltaX + deltaY === 0) {\n // when configured to map Y to X and we both see\n // no dominant axis and X and Y are competing with\n // identical values into opposite directions, we\n // ignore the delta as we cannot make a decision then\n deltaX = deltaY = 0;\n }\n else if (Math.abs(deltaY) >= Math.abs(deltaX)) {\n deltaX = 0;\n }\n else {\n deltaY = 0;\n }\n }\n if (this._options.flipAxes) {\n [deltaY, deltaX] = [deltaX, deltaY];\n }\n // Convert vertical scrolling to horizontal if shift is held, this\n // is handled at a higher level on Mac\n const shiftConvert = !platform.isMacintosh && e.browserEvent && e.browserEvent.shiftKey;\n if ((this._options.scrollYToX || shiftConvert) && !deltaX) {\n deltaX = deltaY;\n deltaY = 0;\n }\n if (e.browserEvent && e.browserEvent.altKey) {\n // fastScrolling\n deltaX = deltaX * this._options.fastScrollSensitivity;\n deltaY = deltaY * this._options.fastScrollSensitivity;\n }\n const futureScrollPosition = this._scrollable.getFutureScrollPosition();\n let desiredScrollPosition = {};\n if (deltaY) {\n const deltaScrollTop = SCROLL_WHEEL_SENSITIVITY * deltaY;\n // Here we convert values such as -0.3 to -1 or 0.3 to 1, otherwise low speed scrolling will never scroll\n const desiredScrollTop = futureScrollPosition.scrollTop - (deltaScrollTop < 0 ? Math.floor(deltaScrollTop) : Math.ceil(deltaScrollTop));\n this._verticalScrollbar.writeScrollPosition(desiredScrollPosition, desiredScrollTop);\n }\n if (deltaX) {\n const deltaScrollLeft = SCROLL_WHEEL_SENSITIVITY * deltaX;\n // Here we convert values such as -0.3 to -1 or 0.3 to 1, otherwise low speed scrolling will never scroll\n const desiredScrollLeft = futureScrollPosition.scrollLeft - (deltaScrollLeft < 0 ? Math.floor(deltaScrollLeft) : Math.ceil(deltaScrollLeft));\n this._horizontalScrollbar.writeScrollPosition(desiredScrollPosition, desiredScrollLeft);\n }\n // Check that we are scrolling towards a location which is valid\n desiredScrollPosition = this._scrollable.validateScrollPosition(desiredScrollPosition);\n if (futureScrollPosition.scrollLeft !== desiredScrollPosition.scrollLeft || futureScrollPosition.scrollTop !== desiredScrollPosition.scrollTop) {\n const canPerformSmoothScroll = (SCROLL_WHEEL_SMOOTH_SCROLL_ENABLED\n && this._options.mouseWheelSmoothScroll\n && classifier.isPhysicalMouseWheel());\n if (canPerformSmoothScroll) {\n this._scrollable.setScrollPositionSmooth(desiredScrollPosition);\n }\n else {\n this._scrollable.setScrollPositionNow(desiredScrollPosition);\n }\n didScroll = true;\n }\n }\n let consumeMouseWheel = didScroll;\n if (!consumeMouseWheel && this._options.alwaysConsumeMouseWheel) {\n consumeMouseWheel = true;\n }\n if (!consumeMouseWheel && this._options.consumeMouseWheelIfScrollbarIsNeeded && (this._verticalScrollbar.isNeeded() || this._horizontalScrollbar.isNeeded())) {\n consumeMouseWheel = true;\n }\n if (consumeMouseWheel) {\n e.preventDefault();\n e.stopPropagation();\n }\n }\n _onDidScroll(e) {\n this._shouldRender = this._horizontalScrollbar.onDidScroll(e) || this._shouldRender;\n this._shouldRender = this._verticalScrollbar.onDidScroll(e) || this._shouldRender;\n if (this._options.useShadows) {\n this._shouldRender = true;\n }\n if (this._revealOnScroll) {\n this._reveal();\n }\n if (!this._options.lazyRender) {\n this._render();\n }\n }\n /**\n * Render / mutate the DOM now.\n * Should be used together with the ctor option `lazyRender`.\n */\n renderNow() {\n if (!this._options.lazyRender) {\n throw new Error('Please use `lazyRender` together with `renderNow`!');\n }\n this._render();\n }\n _render() {\n if (!this._shouldRender) {\n return;\n }\n this._shouldRender = false;\n this._horizontalScrollbar.render();\n this._verticalScrollbar.render();\n if (this._options.useShadows) {\n const scrollState = this._scrollable.getCurrentScrollPosition();\n const enableTop = scrollState.scrollTop > 0;\n const enableLeft = scrollState.scrollLeft > 0;\n const leftClassName = (enableLeft ? ' left' : '');\n const topClassName = (enableTop ? ' top' : '');\n const topLeftClassName = (enableLeft || enableTop ? ' top-left-corner' : '');\n this._leftShadowDomNode.setClassName(`shadow${leftClassName}`);\n this._topShadowDomNode.setClassName(`shadow${topClassName}`);\n this._topLeftShadowDomNode.setClassName(`shadow${topLeftClassName}${topClassName}${leftClassName}`);\n }\n }\n // -------------------- fade in / fade out --------------------\n _onDragStart() {\n this._isDragging = true;\n this._reveal();\n }\n _onDragEnd() {\n this._isDragging = false;\n this._hide();\n }\n _onMouseLeave(e) {\n this._mouseIsOver = false;\n this._hide();\n }\n _onMouseOver(e) {\n this._mouseIsOver = true;\n this._reveal();\n }\n _reveal() {\n this._verticalScrollbar.beginReveal();\n this._horizontalScrollbar.beginReveal();\n this._scheduleHide();\n }\n _hide() {\n if (!this._mouseIsOver && !this._isDragging) {\n this._verticalScrollbar.beginHide();\n this._horizontalScrollbar.beginHide();\n }\n }\n _scheduleHide() {\n if (!this._mouseIsOver && !this._isDragging) {\n this._hideTimeout.cancelAndSet(() => this._hide(), HIDE_TIMEOUT);\n }\n }\n}\nexports.AbstractScrollableElement = AbstractScrollableElement;\nclass ScrollableElement extends AbstractScrollableElement {\n constructor(element, options) {\n options = options || {};\n options.mouseWheelSmoothScroll = false;\n const scrollable = new scrollable_1.Scrollable({\n forceIntegerValues: true,\n smoothScrollDuration: 0,\n scheduleAtNextAnimationFrame: (callback) => dom.scheduleAtNextAnimationFrame(dom.getWindow(element), callback)\n });\n super(element, options, scrollable);\n this._register(scrollable);\n }\n setScrollPosition(update) {\n this._scrollable.setScrollPositionNow(update);\n }\n getScrollPosition() {\n return this._scrollable.getCurrentScrollPosition();\n }\n}\nexports.ScrollableElement = ScrollableElement;\nclass SmoothScrollableElement extends AbstractScrollableElement {\n constructor(element, options, scrollable) {\n super(element, options, scrollable);\n }\n setScrollPosition(update) {\n if (update.reuseAnimation) {\n this._scrollable.setScrollPositionSmooth(update, update.reuseAnimation);\n }\n else {\n this._scrollable.setScrollPositionNow(update);\n }\n }\n getScrollPosition() {\n return this._scrollable.getCurrentScrollPosition();\n }\n}\nexports.SmoothScrollableElement = SmoothScrollableElement;\nclass DomScrollableElement extends AbstractScrollableElement {\n constructor(element, options) {\n options = options || {};\n options.mouseWheelSmoothScroll = false;\n const scrollable = new scrollable_1.Scrollable({\n forceIntegerValues: false, // See https://github.com/microsoft/vscode/issues/139877\n smoothScrollDuration: 0,\n scheduleAtNextAnimationFrame: (callback) => dom.scheduleAtNextAnimationFrame(dom.getWindow(element), callback)\n });\n super(element, options, scrollable);\n this._register(scrollable);\n this._element = element;\n this._register(this.onScroll((e) => {\n if (e.scrollTopChanged) {\n this._element.scrollTop = e.scrollTop;\n }\n if (e.scrollLeftChanged) {\n this._element.scrollLeft = e.scrollLeft;\n }\n }));\n this.scanDomNode();\n }\n setScrollPosition(update) {\n this._scrollable.setScrollPositionNow(update);\n }\n getScrollPosition() {\n return this._scrollable.getCurrentScrollPosition();\n }\n scanDomNode() {\n // width, scrollLeft, scrollWidth, height, scrollTop, scrollHeight\n this.setScrollDimensions({\n width: this._element.clientWidth,\n scrollWidth: this._element.scrollWidth,\n height: this._element.clientHeight,\n scrollHeight: this._element.scrollHeight\n });\n this.setScrollPosition({\n scrollLeft: this._element.scrollLeft,\n scrollTop: this._element.scrollTop,\n });\n }\n}\nexports.DomScrollableElement = DomScrollableElement;\nfunction resolveOptions(opts) {\n const result = {\n lazyRender: (typeof opts.lazyRender !== 'undefined' ? opts.lazyRender : false),\n className: (typeof opts.className !== 'undefined' ? opts.className : ''),\n useShadows: (typeof opts.useShadows !== 'undefined' ? opts.useShadows : true),\n handleMouseWheel: (typeof opts.handleMouseWheel !== 'undefined' ? opts.handleMouseWheel : true),\n flipAxes: (typeof opts.flipAxes !== 'undefined' ? opts.flipAxes : false),\n consumeMouseWheelIfScrollbarIsNeeded: (typeof opts.consumeMouseWheelIfScrollbarIsNeeded !== 'undefined' ? opts.consumeMouseWheelIfScrollbarIsNeeded : false),\n alwaysConsumeMouseWheel: (typeof opts.alwaysConsumeMouseWheel !== 'undefined' ? opts.alwaysConsumeMouseWheel : false),\n scrollYToX: (typeof opts.scrollYToX !== 'undefined' ? opts.scrollYToX : false),\n mouseWheelScrollSensitivity: (typeof opts.mouseWheelScrollSensitivity !== 'undefined' ? opts.mouseWheelScrollSensitivity : 1),\n fastScrollSensitivity: (typeof opts.fastScrollSensitivity !== 'undefined' ? opts.fastScrollSensitivity : 5),\n scrollPredominantAxis: (typeof opts.scrollPredominantAxis !== 'undefined' ? opts.scrollPredominantAxis : true),\n mouseWheelSmoothScroll: (typeof opts.mouseWheelSmoothScroll !== 'undefined' ? opts.mouseWheelSmoothScroll : true),\n arrowSize: (typeof opts.arrowSize !== 'undefined' ? opts.arrowSize : 11),\n listenOnDomNode: (typeof opts.listenOnDomNode !== 'undefined' ? opts.listenOnDomNode : null),\n horizontal: (typeof opts.horizontal !== 'undefined' ? opts.horizontal : scrollable_1.ScrollbarVisibility.Auto),\n horizontalScrollbarSize: (typeof opts.horizontalScrollbarSize !== 'undefined' ? opts.horizontalScrollbarSize : 10),\n horizontalSliderSize: (typeof opts.horizontalSliderSize !== 'undefined' ? opts.horizontalSliderSize : 0),\n horizontalHasArrows: (typeof opts.horizontalHasArrows !== 'undefined' ? opts.horizontalHasArrows : false),\n vertical: (typeof opts.vertical !== 'undefined' ? opts.vertical : scrollable_1.ScrollbarVisibility.Auto),\n verticalScrollbarSize: (typeof opts.verticalScrollbarSize !== 'undefined' ? opts.verticalScrollbarSize : 10),\n verticalHasArrows: (typeof opts.verticalHasArrows !== 'undefined' ? opts.verticalHasArrows : false),\n verticalSliderSize: (typeof opts.verticalSliderSize !== 'undefined' ? opts.verticalSliderSize : 0),\n scrollByPage: (typeof opts.scrollByPage !== 'undefined' ? opts.scrollByPage : false)\n };\n result.horizontalSliderSize = (typeof opts.horizontalSliderSize !== 'undefined' ? opts.horizontalSliderSize : result.horizontalScrollbarSize);\n result.verticalSliderSize = (typeof opts.verticalSliderSize !== 'undefined' ? opts.verticalSliderSize : result.verticalScrollbarSize);\n // Defaults are different on Macs\n if (platform.isMacintosh) {\n result.className += ' mac';\n }\n return result;\n}\n","\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ScrollbarArrow = exports.ARROW_IMG_SIZE = void 0;\nconst globalPointerMoveMonitor_1 = require(\"vs/base/browser/globalPointerMoveMonitor\");\nconst widget_1 = require(\"vs/base/browser/ui/widget\");\nconst async_1 = require(\"vs/base/common/async\");\nconst dom = __importStar(require(\"vs/base/browser/dom\"));\n/**\n * The arrow image size.\n */\nexports.ARROW_IMG_SIZE = 11;\nclass ScrollbarArrow extends widget_1.Widget {\n constructor(opts) {\n super();\n this._onActivate = opts.onActivate;\n this.bgDomNode = document.createElement('div');\n this.bgDomNode.className = 'arrow-background';\n this.bgDomNode.style.position = 'absolute';\n this.bgDomNode.style.width = opts.bgWidth + 'px';\n this.bgDomNode.style.height = opts.bgHeight + 'px';\n if (typeof opts.top !== 'undefined') {\n this.bgDomNode.style.top = '0px';\n }\n if (typeof opts.left !== 'undefined') {\n this.bgDomNode.style.left = '0px';\n }\n if (typeof opts.bottom !== 'undefined') {\n this.bgDomNode.style.bottom = '0px';\n }\n if (typeof opts.right !== 'undefined') {\n this.bgDomNode.style.right = '0px';\n }\n this.domNode = document.createElement('div');\n this.domNode.className = opts.className;\n // this.domNode.classList.add(...ThemeIcon.asClassNameArray(opts.icon));\n this.domNode.style.position = 'absolute';\n this.domNode.style.width = exports.ARROW_IMG_SIZE + 'px';\n this.domNode.style.height = exports.ARROW_IMG_SIZE + 'px';\n if (typeof opts.top !== 'undefined') {\n this.domNode.style.top = opts.top + 'px';\n }\n if (typeof opts.left !== 'undefined') {\n this.domNode.style.left = opts.left + 'px';\n }\n if (typeof opts.bottom !== 'undefined') {\n this.domNode.style.bottom = opts.bottom + 'px';\n }\n if (typeof opts.right !== 'undefined') {\n this.domNode.style.right = opts.right + 'px';\n }\n this._pointerMoveMonitor = this._register(new globalPointerMoveMonitor_1.GlobalPointerMoveMonitor());\n this._register(dom.addStandardDisposableListener(this.bgDomNode, dom.EventType.POINTER_DOWN, (e) => this._arrowPointerDown(e)));\n this._register(dom.addStandardDisposableListener(this.domNode, dom.EventType.POINTER_DOWN, (e) => this._arrowPointerDown(e)));\n this._pointerdownRepeatTimer = this._register(new dom.WindowIntervalTimer());\n this._pointerdownScheduleRepeatTimer = this._register(new async_1.TimeoutTimer());\n }\n _arrowPointerDown(e) {\n if (!e.target || !(e.target instanceof Element)) {\n return;\n }\n const scheduleRepeater = () => {\n this._pointerdownRepeatTimer.cancelAndSet(() => this._onActivate(), 1000 / 24, dom.getWindow(e));\n };\n this._onActivate();\n this._pointerdownRepeatTimer.cancel();\n this._pointerdownScheduleRepeatTimer.cancelAndSet(scheduleRepeater, 200);\n this._pointerMoveMonitor.startMonitoring(e.target, e.pointerId, e.buttons, (pointerMoveData) => { }, () => {\n this._pointerdownRepeatTimer.cancel();\n this._pointerdownScheduleRepeatTimer.cancel();\n });\n e.preventDefault();\n }\n}\nexports.ScrollbarArrow = ScrollbarArrow;\n","\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ScrollbarState = void 0;\n/**\n * The minimal size of the slider (such that it can still be clickable) -- it is artificially enlarged.\n */\nconst MINIMUM_SLIDER_SIZE = 20;\nclass ScrollbarState {\n constructor(arrowSize, scrollbarSize, oppositeScrollbarSize, visibleSize, scrollSize, scrollPosition) {\n this._scrollbarSize = Math.round(scrollbarSize);\n this._oppositeScrollbarSize = Math.round(oppositeScrollbarSize);\n this._arrowSize = Math.round(arrowSize);\n this._visibleSize = visibleSize;\n this._scrollSize = scrollSize;\n this._scrollPosition = scrollPosition;\n this._computedAvailableSize = 0;\n this._computedIsNeeded = false;\n this._computedSliderSize = 0;\n this._computedSliderRatio = 0;\n this._computedSliderPosition = 0;\n this._refreshComputedValues();\n }\n clone() {\n return new ScrollbarState(this._arrowSize, this._scrollbarSize, this._oppositeScrollbarSize, this._visibleSize, this._scrollSize, this._scrollPosition);\n }\n setVisibleSize(visibleSize) {\n const iVisibleSize = Math.round(visibleSize);\n if (this._visibleSize !== iVisibleSize) {\n this._visibleSize = iVisibleSize;\n this._refreshComputedValues();\n return true;\n }\n return false;\n }\n setScrollSize(scrollSize) {\n const iScrollSize = Math.round(scrollSize);\n if (this._scrollSize !== iScrollSize) {\n this._scrollSize = iScrollSize;\n this._refreshComputedValues();\n return true;\n }\n return false;\n }\n setScrollPosition(scrollPosition) {\n const iScrollPosition = Math.round(scrollPosition);\n if (this._scrollPosition !== iScrollPosition) {\n this._scrollPosition = iScrollPosition;\n this._refreshComputedValues();\n return true;\n }\n return false;\n }\n setScrollbarSize(scrollbarSize) {\n this._scrollbarSize = Math.round(scrollbarSize);\n }\n setOppositeScrollbarSize(oppositeScrollbarSize) {\n this._oppositeScrollbarSize = Math.round(oppositeScrollbarSize);\n }\n static _computeValues(oppositeScrollbarSize, arrowSize, visibleSize, scrollSize, scrollPosition) {\n const computedAvailableSize = Math.max(0, visibleSize - oppositeScrollbarSize);\n const computedRepresentableSize = Math.max(0, computedAvailableSize - 2 * arrowSize);\n const computedIsNeeded = (scrollSize > 0 && scrollSize > visibleSize);\n if (!computedIsNeeded) {\n // There is no need for a slider\n return {\n computedAvailableSize: Math.round(computedAvailableSize),\n computedIsNeeded: computedIsNeeded,\n computedSliderSize: Math.round(computedRepresentableSize),\n computedSliderRatio: 0,\n computedSliderPosition: 0,\n };\n }\n // We must artificially increase the size of the slider if needed, since the slider would be too small to grab with the mouse otherwise\n const computedSliderSize = Math.round(Math.max(MINIMUM_SLIDER_SIZE, Math.floor(visibleSize * computedRepresentableSize / scrollSize)));\n // The slider can move from 0 to `computedRepresentableSize` - `computedSliderSize`\n // in the same way `scrollPosition` can move from 0 to `scrollSize` - `visibleSize`.\n const computedSliderRatio = (computedRepresentableSize - computedSliderSize) / (scrollSize - visibleSize);\n const computedSliderPosition = (scrollPosition * computedSliderRatio);\n return {\n computedAvailableSize: Math.round(computedAvailableSize),\n computedIsNeeded: computedIsNeeded,\n computedSliderSize: Math.round(computedSliderSize),\n computedSliderRatio: computedSliderRatio,\n computedSliderPosition: Math.round(computedSliderPosition),\n };\n }\n _refreshComputedValues() {\n const r = ScrollbarState._computeValues(this._oppositeScrollbarSize, this._arrowSize, this._visibleSize, this._scrollSize, this._scrollPosition);\n this._computedAvailableSize = r.computedAvailableSize;\n this._computedIsNeeded = r.computedIsNeeded;\n this._computedSliderSize = r.computedSliderSize;\n this._computedSliderRatio = r.computedSliderRatio;\n this._computedSliderPosition = r.computedSliderPosition;\n }\n getArrowSize() {\n return this._arrowSize;\n }\n getScrollPosition() {\n return this._scrollPosition;\n }\n getRectangleLargeSize() {\n return this._computedAvailableSize;\n }\n getRectangleSmallSize() {\n return this._scrollbarSize;\n }\n isNeeded() {\n return this._computedIsNeeded;\n }\n getSliderSize() {\n return this._computedSliderSize;\n }\n getSliderPosition() {\n return this._computedSliderPosition;\n }\n /**\n * Compute a desired `scrollPosition` such that `offset` ends up in the center of the slider.\n * `offset` is based on the same coordinate system as the `sliderPosition`.\n */\n getDesiredScrollPositionFromOffset(offset) {\n if (!this._computedIsNeeded) {\n // no need for a slider\n return 0;\n }\n const desiredSliderPosition = offset - this._arrowSize - this._computedSliderSize / 2;\n return Math.round(desiredSliderPosition / this._computedSliderRatio);\n }\n /**\n * Compute a desired `scrollPosition` from if offset is before or after the slider position.\n * If offset is before slider, treat as a page up (or left). If after, page down (or right).\n * `offset` and `_computedSliderPosition` are based on the same coordinate system.\n * `_visibleSize` corresponds to a \"page\" of lines in the returned coordinate system.\n */\n getDesiredScrollPositionFromOffsetPaged(offset) {\n if (!this._computedIsNeeded) {\n // no need for a slider\n return 0;\n }\n const correctedOffset = offset - this._arrowSize; // compensate if has arrows\n let desiredScrollPosition = this._scrollPosition;\n if (correctedOffset < this._computedSliderPosition) {\n desiredScrollPosition -= this._visibleSize; // page up/left\n }\n else {\n desiredScrollPosition += this._visibleSize; // page down/right\n }\n return desiredScrollPosition;\n }\n /**\n * Compute a desired `scrollPosition` such that the slider moves by `delta`.\n */\n getDesiredScrollPositionFromDelta(delta) {\n if (!this._computedIsNeeded) {\n // no need for a slider\n return 0;\n }\n const desiredSliderPosition = this._computedSliderPosition + delta;\n return Math.round(desiredSliderPosition / this._computedSliderRatio);\n }\n}\nexports.ScrollbarState = ScrollbarState;\n","\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ScrollbarVisibilityController = void 0;\nconst async_1 = require(\"vs/base/common/async\");\nconst lifecycle_1 = require(\"vs/base/common/lifecycle\");\nconst scrollable_1 = require(\"vs/base/common/scrollable\");\nclass ScrollbarVisibilityController extends lifecycle_1.Disposable {\n constructor(visibility, visibleClassName, invisibleClassName) {\n super();\n this._visibility = visibility;\n this._visibleClassName = visibleClassName;\n this._invisibleClassName = invisibleClassName;\n this._domNode = null;\n this._isVisible = false;\n this._isNeeded = false;\n this._rawShouldBeVisible = false;\n this._shouldBeVisible = false;\n this._revealTimer = this._register(new async_1.TimeoutTimer());\n }\n setVisibility(visibility) {\n if (this._visibility !== visibility) {\n this._visibility = visibility;\n this._updateShouldBeVisible();\n }\n }\n // ----------------- Hide / Reveal\n setShouldBeVisible(rawShouldBeVisible) {\n this._rawShouldBeVisible = rawShouldBeVisible;\n this._updateShouldBeVisible();\n }\n _applyVisibilitySetting() {\n if (this._visibility === scrollable_1.ScrollbarVisibility.Hidden) {\n return false;\n }\n if (this._visibility === scrollable_1.ScrollbarVisibility.Visible) {\n return true;\n }\n return this._rawShouldBeVisible;\n }\n _updateShouldBeVisible() {\n const shouldBeVisible = this._applyVisibilitySetting();\n if (this._shouldBeVisible !== shouldBeVisible) {\n this._shouldBeVisible = shouldBeVisible;\n this.ensureVisibility();\n }\n }\n setIsNeeded(isNeeded) {\n if (this._isNeeded !== isNeeded) {\n this._isNeeded = isNeeded;\n this.ensureVisibility();\n }\n }\n setDomNode(domNode) {\n this._domNode = domNode;\n this._domNode.setClassName(this._invisibleClassName);\n // Now that the flags & the dom node are in a consistent state, ensure the Hidden/Visible configuration\n this.setShouldBeVisible(false);\n }\n ensureVisibility() {\n if (!this._isNeeded) {\n // Nothing to be rendered\n this._hide(false);\n return;\n }\n if (this._shouldBeVisible) {\n this._reveal();\n }\n else {\n this._hide(true);\n }\n }\n _reveal() {\n if (this._isVisible) {\n return;\n }\n this._isVisible = true;\n // The CSS animation doesn't play otherwise\n this._revealTimer.setIfNotSet(() => {\n this._domNode?.setClassName(this._visibleClassName);\n }, 0);\n }\n _hide(withFadeAway) {\n this._revealTimer.cancel();\n if (!this._isVisible) {\n return;\n }\n this._isVisible = false;\n this._domNode?.setClassName(this._invisibleClassName + (withFadeAway ? ' fade' : ''));\n }\n}\nexports.ScrollbarVisibilityController = ScrollbarVisibilityController;\n","\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.VerticalScrollbar = void 0;\nconst abstractScrollbar_1 = require(\"vs/base/browser/ui/scrollbar/abstractScrollbar\");\nconst scrollbarState_1 = require(\"vs/base/browser/ui/scrollbar/scrollbarState\");\nconst scrollable_1 = require(\"vs/base/common/scrollable\");\nclass VerticalScrollbar extends abstractScrollbar_1.AbstractScrollbar {\n constructor(scrollable, options, host) {\n const scrollDimensions = scrollable.getScrollDimensions();\n const scrollPosition = scrollable.getCurrentScrollPosition();\n super({\n lazyRender: options.lazyRender,\n host: host,\n scrollbarState: new scrollbarState_1.ScrollbarState((options.verticalHasArrows ? options.arrowSize : 0), (options.vertical === scrollable_1.ScrollbarVisibility.Hidden ? 0 : options.verticalScrollbarSize), \n // give priority to vertical scroll bar over horizontal and let it scroll all the way to the bottom\n 0, scrollDimensions.height, scrollDimensions.scrollHeight, scrollPosition.scrollTop),\n visibility: options.vertical,\n extraScrollbarClassName: 'vertical',\n scrollable: scrollable,\n scrollByPage: options.scrollByPage\n });\n if (options.verticalHasArrows) {\n throw new Error('horizontalHasArrows is not supported in xterm.js');\n // const arrowDelta = (options.arrowSize - ARROW_IMG_SIZE) / 2;\n // const scrollbarDelta = (options.verticalScrollbarSize - ARROW_IMG_SIZE) / 2;\n // this._createArrow({\n // \tclassName: 'scra',\n // \ticon: Codicon.scrollbarButtonUp,\n // \ttop: arrowDelta,\n // \tleft: scrollbarDelta,\n // \tbottom: undefined,\n // \tright: undefined,\n // \tbgWidth: options.verticalScrollbarSize,\n // \tbgHeight: options.arrowSize,\n // \tonActivate: () => this._host.onMouseWheel(new StandardWheelEvent(null, 0, 1)),\n // });\n // this._createArrow({\n // \tclassName: 'scra',\n // \ticon: Codicon.scrollbarButtonDown,\n // \ttop: undefined,\n // \tleft: scrollbarDelta,\n // \tbottom: arrowDelta,\n // \tright: undefined,\n // \tbgWidth: options.verticalScrollbarSize,\n // \tbgHeight: options.arrowSize,\n // \tonActivate: () => this._host.onMouseWheel(new StandardWheelEvent(null, 0, -1)),\n // });\n }\n this._createSlider(0, Math.floor((options.verticalScrollbarSize - options.verticalSliderSize) / 2), options.verticalSliderSize, undefined);\n }\n _updateSlider(sliderSize, sliderPosition) {\n this.slider.setHeight(sliderSize);\n this.slider.setTop(sliderPosition);\n }\n _renderDomNode(largeSize, smallSize) {\n this.domNode.setWidth(smallSize);\n this.domNode.setHeight(largeSize);\n this.domNode.setRight(0);\n this.domNode.setTop(0);\n }\n onDidScroll(e) {\n this._shouldRender = this._onElementScrollSize(e.scrollHeight) || this._shouldRender;\n this._shouldRender = this._onElementScrollPosition(e.scrollTop) || this._shouldRender;\n this._shouldRender = this._onElementSize(e.height) || this._shouldRender;\n return this._shouldRender;\n }\n _pointerDownRelativePosition(offsetX, offsetY) {\n return offsetY;\n }\n _sliderPointerPosition(e) {\n return e.pageY;\n }\n _sliderOrthogonalPointerPosition(e) {\n return e.pageX;\n }\n _updateScrollbarSize(size) {\n this.slider.setWidth(size);\n }\n writeScrollPosition(target, scrollPosition) {\n target.scrollTop = scrollPosition;\n }\n updateOptions(options) {\n this.updateScrollbarSize(options.vertical === scrollable_1.ScrollbarVisibility.Hidden ? 0 : options.verticalScrollbarSize);\n // give priority to vertical scroll bar over horizontal and let it scroll all the way to the bottom\n this._scrollbarState.setOppositeScrollbarSize(0);\n this._visibilityController.setVisibility(options.vertical);\n this._scrollByPage = options.scrollByPage;\n }\n}\nexports.VerticalScrollbar = VerticalScrollbar;\n","\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Widget = void 0;\nconst dom = __importStar(require(\"vs/base/browser/dom\"));\nconst keyboardEvent_1 = require(\"vs/base/browser/keyboardEvent\");\nconst mouseEvent_1 = require(\"vs/base/browser/mouseEvent\");\nconst touch_1 = require(\"vs/base/browser/touch\");\nconst lifecycle_1 = require(\"vs/base/common/lifecycle\");\nclass Widget extends lifecycle_1.Disposable {\n onclick(domNode, listener) {\n this._register(dom.addDisposableListener(domNode, dom.EventType.CLICK, (e) => listener(new mouseEvent_1.StandardMouseEvent(dom.getWindow(domNode), e))));\n }\n onmousedown(domNode, listener) {\n this._register(dom.addDisposableListener(domNode, dom.EventType.MOUSE_DOWN, (e) => listener(new mouseEvent_1.StandardMouseEvent(dom.getWindow(domNode), e))));\n }\n onmouseover(domNode, listener) {\n this._register(dom.addDisposableListener(domNode, dom.EventType.MOUSE_OVER, (e) => listener(new mouseEvent_1.StandardMouseEvent(dom.getWindow(domNode), e))));\n }\n onmouseleave(domNode, listener) {\n this._register(dom.addDisposableListener(domNode, dom.EventType.MOUSE_LEAVE, (e) => listener(new mouseEvent_1.StandardMouseEvent(dom.getWindow(domNode), e))));\n }\n onkeydown(domNode, listener) {\n this._register(dom.addDisposableListener(domNode, dom.EventType.KEY_DOWN, (e) => listener(new keyboardEvent_1.StandardKeyboardEvent(e))));\n }\n onkeyup(domNode, listener) {\n this._register(dom.addDisposableListener(domNode, dom.EventType.KEY_UP, (e) => listener(new keyboardEvent_1.StandardKeyboardEvent(e))));\n }\n oninput(domNode, listener) {\n this._register(dom.addDisposableListener(domNode, dom.EventType.INPUT, listener));\n }\n onblur(domNode, listener) {\n this._register(dom.addDisposableListener(domNode, dom.EventType.BLUR, listener));\n }\n onfocus(domNode, listener) {\n this._register(dom.addDisposableListener(domNode, dom.EventType.FOCUS, listener));\n }\n onchange(domNode, listener) {\n this._register(dom.addDisposableListener(domNode, dom.EventType.CHANGE, listener));\n }\n ignoreGesture(domNode) {\n return touch_1.Gesture.ignoreTarget(domNode);\n }\n}\nexports.Widget = Widget;\n","\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.mainWindow = void 0;\nexports.ensureCodeWindow = ensureCodeWindow;\nfunction ensureCodeWindow(targetWindow, fallbackWindowId) {\n}\n// eslint-disable-next-line no-restricted-globals\nexports.mainWindow = (typeof window === 'object' ? window : globalThis);\n","\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Permutation = exports.CallbackIterable = exports.ArrayQueue = exports.booleanComparator = exports.numberComparator = exports.CompareResult = void 0;\nexports.tail = tail;\nexports.tail2 = tail2;\nexports.equals = equals;\nexports.removeFastWithoutKeepingOrder = removeFastWithoutKeepingOrder;\nexports.binarySearch = binarySearch;\nexports.binarySearch2 = binarySearch2;\nexports.quickSelect = quickSelect;\nexports.groupBy = groupBy;\nexports.groupAdjacentBy = groupAdjacentBy;\nexports.forEachAdjacent = forEachAdjacent;\nexports.forEachWithNeighbors = forEachWithNeighbors;\nexports.sortedDiff = sortedDiff;\nexports.delta = delta;\nexports.top = top;\nexports.topAsync = topAsync;\nexports.coalesce = coalesce;\nexports.coalesceInPlace = coalesceInPlace;\nexports.move = move;\nexports.isFalsyOrEmpty = isFalsyOrEmpty;\nexports.isNonEmptyArray = isNonEmptyArray;\nexports.distinct = distinct;\nexports.uniqueFilter = uniqueFilter;\nexports.firstOrDefault = firstOrDefault;\nexports.lastOrDefault = lastOrDefault;\nexports.commonPrefixLength = commonPrefixLength;\nexports.range = range;\nexports.index = index;\nexports.insert = insert;\nexports.remove = remove;\nexports.arrayInsert = arrayInsert;\nexports.shuffle = shuffle;\nexports.pushToStart = pushToStart;\nexports.pushToEnd = pushToEnd;\nexports.pushMany = pushMany;\nexports.mapArrayOrNot = mapArrayOrNot;\nexports.asArray = asArray;\nexports.getRandomElement = getRandomElement;\nexports.insertInto = insertInto;\nexports.splice = splice;\nexports.compareBy = compareBy;\nexports.tieBreakComparators = tieBreakComparators;\nexports.reverseOrder = reverseOrder;\nconst errors_1 = require(\"vs/base/common/errors\");\nconst arraysFind_1 = require(\"./arraysFind\");\n/**\n * Returns the last element of an array.\n * @param array The array.\n * @param n Which element from the end (default is zero).\n */\nfunction tail(array, n = 0) {\n return array[array.length - (1 + n)];\n}\nfunction tail2(arr) {\n if (arr.length === 0) {\n throw new Error('Invalid tail call');\n }\n return [arr.slice(0, arr.length - 1), arr[arr.length - 1]];\n}\nfunction equals(one, other, itemEquals = (a, b) => a === b) {\n if (one === other) {\n return true;\n }\n if (!one || !other) {\n return false;\n }\n if (one.length !== other.length) {\n return false;\n }\n for (let i = 0, len = one.length; i < len; i++) {\n if (!itemEquals(one[i], other[i])) {\n return false;\n }\n }\n return true;\n}\n/**\n * Remove the element at `index` by replacing it with the last element. This is faster than `splice`\n * but changes the order of the array\n */\nfunction removeFastWithoutKeepingOrder(array, index) {\n const last = array.length - 1;\n if (index < last) {\n array[index] = array[last];\n }\n array.pop();\n}\n/**\n * Performs a binary search algorithm over a sorted array.\n *\n * @param array The array being searched.\n * @param key The value we search for.\n * @param comparator A function that takes two array elements and returns zero\n * if they are equal, a negative number if the first element precedes the\n * second one in the sorting order, or a positive number if the second element\n * precedes the first one.\n * @return See {@link binarySearch2}\n */\nfunction binarySearch(array, key, comparator) {\n return binarySearch2(array.length, i => comparator(array[i], key));\n}\n/**\n * Performs a binary search algorithm over a sorted collection. Useful for cases\n * when we need to perform a binary search over something that isn't actually an\n * array, and converting data to an array would defeat the use of binary search\n * in the first place.\n *\n * @param length The collection length.\n * @param compareToKey A function that takes an index of an element in the\n * collection and returns zero if the value at this index is equal to the\n * search key, a negative number if the value precedes the search key in the\n * sorting order, or a positive number if the search key precedes the value.\n * @return A non-negative index of an element, if found. If not found, the\n * result is -(n+1) (or ~n, using bitwise notation), where n is the index\n * where the key should be inserted to maintain the sorting order.\n */\nfunction binarySearch2(length, compareToKey) {\n let low = 0, high = length - 1;\n while (low <= high) {\n const mid = ((low + high) / 2) | 0;\n const comp = compareToKey(mid);\n if (comp < 0) {\n low = mid + 1;\n }\n else if (comp > 0) {\n high = mid - 1;\n }\n else {\n return mid;\n }\n }\n return -(low + 1);\n}\nfunction quickSelect(nth, data, compare) {\n nth = nth | 0;\n if (nth >= data.length) {\n throw new TypeError('invalid index');\n }\n const pivotValue = data[Math.floor(data.length * Math.random())];\n const lower = [];\n const higher = [];\n const pivots = [];\n for (const value of data) {\n const val = compare(value, pivotValue);\n if (val < 0) {\n lower.push(value);\n }\n else if (val > 0) {\n higher.push(value);\n }\n else {\n pivots.push(value);\n }\n }\n if (nth < lower.length) {\n return quickSelect(nth, lower, compare);\n }\n else if (nth < lower.length + pivots.length) {\n return pivots[0];\n }\n else {\n return quickSelect(nth - (lower.length + pivots.length), higher, compare);\n }\n}\nfunction groupBy(data, compare) {\n const result = [];\n let currentGroup = undefined;\n for (const element of data.slice(0).sort(compare)) {\n if (!currentGroup || compare(currentGroup[0], element) !== 0) {\n currentGroup = [element];\n result.push(currentGroup);\n }\n else {\n currentGroup.push(element);\n }\n }\n return result;\n}\n/**\n * Splits the given items into a list of (non-empty) groups.\n * `shouldBeGrouped` is used to decide if two consecutive items should be in the same group.\n * The order of the items is preserved.\n */\nfunction* groupAdjacentBy(items, shouldBeGrouped) {\n let currentGroup;\n let last;\n for (const item of items) {\n if (last !== undefined && shouldBeGrouped(last, item)) {\n currentGroup.push(item);\n }\n else {\n if (currentGroup) {\n yield currentGroup;\n }\n currentGroup = [item];\n }\n last = item;\n }\n if (currentGroup) {\n yield currentGroup;\n }\n}\nfunction forEachAdjacent(arr, f) {\n for (let i = 0; i <= arr.length; i++) {\n f(i === 0 ? undefined : arr[i - 1], i === arr.length ? undefined : arr[i]);\n }\n}\nfunction forEachWithNeighbors(arr, f) {\n for (let i = 0; i < arr.length; i++) {\n f(i === 0 ? undefined : arr[i - 1], arr[i], i + 1 === arr.length ? undefined : arr[i + 1]);\n }\n}\n/**\n * Diffs two *sorted* arrays and computes the splices which apply the diff.\n */\nfunction sortedDiff(before, after, compare) {\n const result = [];\n function pushSplice(start, deleteCount, toInsert) {\n if (deleteCount === 0 && toInsert.length === 0) {\n return;\n }\n const latest = result[result.length - 1];\n if (latest && latest.start + latest.deleteCount === start) {\n latest.deleteCount += deleteCount;\n latest.toInsert.push(...toInsert);\n }\n else {\n result.push({ start, deleteCount, toInsert });\n }\n }\n let beforeIdx = 0;\n let afterIdx = 0;\n while (true) {\n if (beforeIdx === before.length) {\n pushSplice(beforeIdx, 0, after.slice(afterIdx));\n break;\n }\n if (afterIdx === after.length) {\n pushSplice(beforeIdx, before.length - beforeIdx, []);\n break;\n }\n const beforeElement = before[beforeIdx];\n const afterElement = after[afterIdx];\n const n = compare(beforeElement, afterElement);\n if (n === 0) {\n // equal\n beforeIdx += 1;\n afterIdx += 1;\n }\n else if (n < 0) {\n // beforeElement is smaller -> before element removed\n pushSplice(beforeIdx, 1, []);\n beforeIdx += 1;\n }\n else if (n > 0) {\n // beforeElement is greater -> after element added\n pushSplice(beforeIdx, 0, [afterElement]);\n afterIdx += 1;\n }\n }\n return result;\n}\n/**\n * Takes two *sorted* arrays and computes their delta (removed, added elements).\n * Finishes in `Math.min(before.length, after.length)` steps.\n */\nfunction delta(before, after, compare) {\n const splices = sortedDiff(before, after, compare);\n const removed = [];\n const added = [];\n for (const splice of splices) {\n removed.push(...before.slice(splice.start, splice.start + splice.deleteCount));\n added.push(...splice.toInsert);\n }\n return { removed, added };\n}\n/**\n * Returns the top N elements from the array.\n *\n * Faster than sorting the entire array when the array is a lot larger than N.\n *\n * @param array The unsorted array.\n * @param compare A sort function for the elements.\n * @param n The number of elements to return.\n * @return The first n elements from array when sorted with compare.\n */\nfunction top(array, compare, n) {\n if (n === 0) {\n return [];\n }\n const result = array.slice(0, n).sort(compare);\n topStep(array, compare, result, n, array.length);\n return result;\n}\n/**\n * Asynchronous variant of `top()` allowing for splitting up work in batches between which the event loop can run.\n *\n * Returns the top N elements from the array.\n *\n * Faster than sorting the entire array when the array is a lot larger than N.\n *\n * @param array The unsorted array.\n * @param compare A sort function for the elements.\n * @param n The number of elements to return.\n * @param batch The number of elements to examine before yielding to the event loop.\n * @return The first n elements from array when sorted with compare.\n */\nfunction topAsync(array, compare, n, batch, token) {\n if (n === 0) {\n return Promise.resolve([]);\n }\n return new Promise((resolve, reject) => {\n (async () => {\n const o = array.length;\n const result = array.slice(0, n).sort(compare);\n for (let i = n, m = Math.min(n + batch, o); i < o; i = m, m = Math.min(m + batch, o)) {\n if (i > n) {\n await new Promise(resolve => setTimeout(resolve)); // any other delay function would starve I/O\n }\n if (token && token.isCancellationRequested) {\n throw new errors_1.CancellationError();\n }\n topStep(array, compare, result, i, m);\n }\n return result;\n })()\n .then(resolve, reject);\n });\n}\nfunction topStep(array, compare, result, i, m) {\n for (const n = result.length; i < m; i++) {\n const element = array[i];\n if (compare(element, result[n - 1]) < 0) {\n result.pop();\n const j = (0, arraysFind_1.findFirstIdxMonotonousOrArrLen)(result, e => compare(element, e) < 0);\n result.splice(j, 0, element);\n }\n }\n}\n/**\n * @returns New array with all falsy values removed. The original array IS NOT modified.\n */\nfunction coalesce(array) {\n return array.filter((e) => !!e);\n}\n/**\n * Remove all falsy values from `array`. The original array IS modified.\n */\nfunction coalesceInPlace(array) {\n let to = 0;\n for (let i = 0; i < array.length; i++) {\n if (!!array[i]) {\n array[to] = array[i];\n to += 1;\n }\n }\n array.length = to;\n}\n/**\n * @deprecated Use `Array.copyWithin` instead\n */\nfunction move(array, from, to) {\n array.splice(to, 0, array.splice(from, 1)[0]);\n}\n/**\n * @returns false if the provided object is an array and not empty.\n */\nfunction isFalsyOrEmpty(obj) {\n return !Array.isArray(obj) || obj.length === 0;\n}\nfunction isNonEmptyArray(obj) {\n return Array.isArray(obj) && obj.length > 0;\n}\n/**\n * Removes duplicates from the given array. The optional keyFn allows to specify\n * how elements are checked for equality by returning an alternate value for each.\n */\nfunction distinct(array, keyFn = value => value) {\n const seen = new Set();\n return array.filter(element => {\n const key = keyFn(element);\n if (seen.has(key)) {\n return false;\n }\n seen.add(key);\n return true;\n });\n}\nfunction uniqueFilter(keyFn) {\n const seen = new Set();\n return element => {\n const key = keyFn(element);\n if (seen.has(key)) {\n return false;\n }\n seen.add(key);\n return true;\n };\n}\nfunction firstOrDefault(array, notFoundValue) {\n return array.length > 0 ? array[0] : notFoundValue;\n}\nfunction lastOrDefault(array, notFoundValue) {\n return array.length > 0 ? array[array.length - 1] : notFoundValue;\n}\nfunction commonPrefixLength(one, other, equals = (a, b) => a === b) {\n let result = 0;\n for (let i = 0, len = Math.min(one.length, other.length); i < len && equals(one[i], other[i]); i++) {\n result++;\n }\n return result;\n}\nfunction range(arg, to) {\n let from = typeof to === 'number' ? arg : 0;\n if (typeof to === 'number') {\n from = arg;\n }\n else {\n from = 0;\n to = arg;\n }\n const result = [];\n if (from <= to) {\n for (let i = from; i < to; i++) {\n result.push(i);\n }\n }\n else {\n for (let i = from; i > to; i--) {\n result.push(i);\n }\n }\n return result;\n}\nfunction index(array, indexer, mapper) {\n return array.reduce((r, t) => {\n r[indexer(t)] = mapper ? mapper(t) : t;\n return r;\n }, Object.create(null));\n}\n/**\n * Inserts an element into an array. Returns a function which, when\n * called, will remove that element from the array.\n *\n * @deprecated In almost all cases, use a `Set` instead.\n */\nfunction insert(array, element) {\n array.push(element);\n return () => remove(array, element);\n}\n/**\n * Removes an element from an array if it can be found.\n *\n * @deprecated In almost all cases, use a `Set` instead.\n */\nfunction remove(array, element) {\n const index = array.indexOf(element);\n if (index > -1) {\n array.splice(index, 1);\n return element;\n }\n return undefined;\n}\n/**\n * Insert `insertArr` inside `target` at `insertIndex`.\n * Please don't touch unless you understand https://jsperf.com/inserting-an-array-within-an-array\n */\nfunction arrayInsert(target, insertIndex, insertArr) {\n const before = target.slice(0, insertIndex);\n const after = target.slice(insertIndex);\n return before.concat(insertArr, after);\n}\n/**\n * Uses Fisher-Yates shuffle to shuffle the given array\n */\nfunction shuffle(array, _seed) {\n let rand;\n if (typeof _seed === 'number') {\n let seed = _seed;\n // Seeded random number generator in JS. Modified from:\n // https://stackoverflow.com/questions/521295/seeding-the-random-number-generator-in-javascript\n rand = () => {\n const x = Math.sin(seed++) * 179426549; // throw away most significant digits and reduce any potential bias\n return x - Math.floor(x);\n };\n }\n else {\n rand = Math.random;\n }\n for (let i = array.length - 1; i > 0; i -= 1) {\n const j = Math.floor(rand() * (i + 1));\n const temp = array[i];\n array[i] = array[j];\n array[j] = temp;\n }\n}\n/**\n * Pushes an element to the start of the array, if found.\n */\nfunction pushToStart(arr, value) {\n const index = arr.indexOf(value);\n if (index > -1) {\n arr.splice(index, 1);\n arr.unshift(value);\n }\n}\n/**\n * Pushes an element to the end of the array, if found.\n */\nfunction pushToEnd(arr, value) {\n const index = arr.indexOf(value);\n if (index > -1) {\n arr.splice(index, 1);\n arr.push(value);\n }\n}\nfunction pushMany(arr, items) {\n for (const item of items) {\n arr.push(item);\n }\n}\nfunction mapArrayOrNot(items, fn) {\n return Array.isArray(items) ?\n items.map(fn) :\n fn(items);\n}\nfunction asArray(x) {\n return Array.isArray(x) ? x : [x];\n}\nfunction getRandomElement(arr) {\n return arr[Math.floor(Math.random() * arr.length)];\n}\n/**\n * Insert the new items in the array.\n * @param array The original array.\n * @param start The zero-based location in the array from which to start inserting elements.\n * @param newItems The items to be inserted\n */\nfunction insertInto(array, start, newItems) {\n const startIdx = getActualStartIndex(array, start);\n const originalLength = array.length;\n const newItemsLength = newItems.length;\n array.length = originalLength + newItemsLength;\n // Move the items after the start index, start from the end so that we don't overwrite any value.\n for (let i = originalLength - 1; i >= startIdx; i--) {\n array[i + newItemsLength] = array[i];\n }\n for (let i = 0; i < newItemsLength; i++) {\n array[i + startIdx] = newItems[i];\n }\n}\n/**\n * Removes elements from an array and inserts new elements in their place, returning the deleted elements. Alternative to the native Array.splice method, it\n * can only support limited number of items due to the maximum call stack size limit.\n * @param array The original array.\n * @param start The zero-based location in the array from which to start removing elements.\n * @param deleteCount The number of elements to remove.\n * @returns An array containing the elements that were deleted.\n */\nfunction splice(array, start, deleteCount, newItems) {\n const index = getActualStartIndex(array, start);\n let result = array.splice(index, deleteCount);\n if (result === undefined) {\n // see https://bugs.webkit.org/show_bug.cgi?id=261140\n result = [];\n }\n insertInto(array, index, newItems);\n return result;\n}\n/**\n * Determine the actual start index (same logic as the native splice() or slice())\n * If greater than the length of the array, start will be set to the length of the array. In this case, no element will be deleted but the method will behave as an adding function, adding as many element as item[n*] provided.\n * If negative, it will begin that many elements from the end of the array. (In this case, the origin -1, meaning -n is the index of the nth last element, and is therefore equivalent to the index of array.length - n.) If array.length + start is less than 0, it will begin from index 0.\n * @param array The target array.\n * @param start The operation index.\n */\nfunction getActualStartIndex(array, start) {\n return start < 0 ? Math.max(start + array.length, 0) : Math.min(start, array.length);\n}\nvar CompareResult;\n(function (CompareResult) {\n function isLessThan(result) {\n return result < 0;\n }\n CompareResult.isLessThan = isLessThan;\n function isLessThanOrEqual(result) {\n return result <= 0;\n }\n CompareResult.isLessThanOrEqual = isLessThanOrEqual;\n function isGreaterThan(result) {\n return result > 0;\n }\n CompareResult.isGreaterThan = isGreaterThan;\n function isNeitherLessOrGreaterThan(result) {\n return result === 0;\n }\n CompareResult.isNeitherLessOrGreaterThan = isNeitherLessOrGreaterThan;\n CompareResult.greaterThan = 1;\n CompareResult.lessThan = -1;\n CompareResult.neitherLessOrGreaterThan = 0;\n})(CompareResult || (exports.CompareResult = CompareResult = {}));\nfunction compareBy(selector, comparator) {\n return (a, b) => comparator(selector(a), selector(b));\n}\nfunction tieBreakComparators(...comparators) {\n return (item1, item2) => {\n for (const comparator of comparators) {\n const result = comparator(item1, item2);\n if (!CompareResult.isNeitherLessOrGreaterThan(result)) {\n return result;\n }\n }\n return CompareResult.neitherLessOrGreaterThan;\n };\n}\n/**\n * The natural order on numbers.\n*/\nconst numberComparator = (a, b) => a - b;\nexports.numberComparator = numberComparator;\nconst booleanComparator = (a, b) => (0, exports.numberComparator)(a ? 1 : 0, b ? 1 : 0);\nexports.booleanComparator = booleanComparator;\nfunction reverseOrder(comparator) {\n return (a, b) => -comparator(a, b);\n}\nclass ArrayQueue {\n /**\n * Constructs a queue that is backed by the given array. Runtime is O(1).\n */\n constructor(items) {\n this.items = items;\n this.firstIdx = 0;\n this.lastIdx = this.items.length - 1;\n }\n get length() {\n return this.lastIdx - this.firstIdx + 1;\n }\n /**\n * Consumes elements from the beginning of the queue as long as the predicate returns true.\n * If no elements were consumed, `null` is returned. Has a runtime of O(result.length).\n */\n takeWhile(predicate) {\n // P(k) := k <= this.lastIdx && predicate(this.items[k])\n // Find s := min { k | k >= this.firstIdx && !P(k) } and return this.data[this.firstIdx...s)\n let startIdx = this.firstIdx;\n while (startIdx < this.items.length && predicate(this.items[startIdx])) {\n startIdx++;\n }\n const result = startIdx === this.firstIdx ? null : this.items.slice(this.firstIdx, startIdx);\n this.firstIdx = startIdx;\n return result;\n }\n /**\n * Consumes elements from the end of the queue as long as the predicate returns true.\n * If no elements were consumed, `null` is returned.\n * The result has the same order as the underlying array!\n */\n takeFromEndWhile(predicate) {\n // P(k) := this.firstIdx >= k && predicate(this.items[k])\n // Find s := max { k | k <= this.lastIdx && !P(k) } and return this.data(s...this.lastIdx]\n let endIdx = this.lastIdx;\n while (endIdx >= 0 && predicate(this.items[endIdx])) {\n endIdx--;\n }\n const result = endIdx === this.lastIdx ? null : this.items.slice(endIdx + 1, this.lastIdx + 1);\n this.lastIdx = endIdx;\n return result;\n }\n peek() {\n if (this.length === 0) {\n return undefined;\n }\n return this.items[this.firstIdx];\n }\n peekLast() {\n if (this.length === 0) {\n return undefined;\n }\n return this.items[this.lastIdx];\n }\n dequeue() {\n const result = this.items[this.firstIdx];\n this.firstIdx++;\n return result;\n }\n removeLast() {\n const result = this.items[this.lastIdx];\n this.lastIdx--;\n return result;\n }\n takeCount(count) {\n const result = this.items.slice(this.firstIdx, this.firstIdx + count);\n this.firstIdx += count;\n return result;\n }\n}\nexports.ArrayQueue = ArrayQueue;\n/**\n * This class is faster than an iterator and array for lazy computed data.\n*/\nclass CallbackIterable {\n static { this.empty = new CallbackIterable(_callback => { }); }\n constructor(\n /**\n * Calls the callback for every item.\n * Stops when the callback returns false.\n */\n iterate) {\n this.iterate = iterate;\n }\n forEach(handler) {\n this.iterate(item => { handler(item); return true; });\n }\n toArray() {\n const result = [];\n this.iterate(item => { result.push(item); return true; });\n return result;\n }\n filter(predicate) {\n return new CallbackIterable(cb => this.iterate(item => predicate(item) ? cb(item) : true));\n }\n map(mapFn) {\n return new CallbackIterable(cb => this.iterate(item => cb(mapFn(item))));\n }\n some(predicate) {\n let result = false;\n this.iterate(item => { result = predicate(item); return !result; });\n return result;\n }\n findFirst(predicate) {\n let result;\n this.iterate(item => {\n if (predicate(item)) {\n result = item;\n return false;\n }\n return true;\n });\n return result;\n }\n findLast(predicate) {\n let result;\n this.iterate(item => {\n if (predicate(item)) {\n result = item;\n }\n return true;\n });\n return result;\n }\n findLastMaxBy(comparator) {\n let result;\n let first = true;\n this.iterate(item => {\n if (first || CompareResult.isGreaterThan(comparator(item, result))) {\n first = false;\n result = item;\n }\n return true;\n });\n return result;\n }\n}\nexports.CallbackIterable = CallbackIterable;\n/**\n * Represents a re-arrangement of items in an array.\n */\nclass Permutation {\n constructor(_indexMap) {\n this._indexMap = _indexMap;\n }\n /**\n * Returns a permutation that sorts the given array according to the given compare function.\n */\n static createSortPermutation(arr, compareFn) {\n const sortIndices = Array.from(arr.keys()).sort((index1, index2) => compareFn(arr[index1], arr[index2]));\n return new Permutation(sortIndices);\n }\n /**\n * Returns a new array with the elements of the given array re-arranged according to this permutation.\n */\n apply(arr) {\n return arr.map((_, index) => arr[this._indexMap[index]]);\n }\n /**\n * Returns a new permutation that undoes the re-arrangement of this permutation.\n */\n inverse() {\n const inverseIndexMap = this._indexMap.slice();\n for (let i = 0; i < this._indexMap.length; i++) {\n inverseIndexMap[this._indexMap[i]] = i;\n }\n return new Permutation(inverseIndexMap);\n }\n}\nexports.Permutation = Permutation;\n","\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.MonotonousArray = void 0;\nexports.findLast = findLast;\nexports.findLastIdx = findLastIdx;\nexports.findLastMonotonous = findLastMonotonous;\nexports.findLastIdxMonotonous = findLastIdxMonotonous;\nexports.findFirstMonotonous = findFirstMonotonous;\nexports.findFirstIdxMonotonousOrArrLen = findFirstIdxMonotonousOrArrLen;\nexports.findFirstIdxMonotonous = findFirstIdxMonotonous;\nexports.findFirstMax = findFirstMax;\nexports.findLastMax = findLastMax;\nexports.findFirstMin = findFirstMin;\nexports.findMaxIdx = findMaxIdx;\nexports.mapFindFirst = mapFindFirst;\nfunction findLast(array, predicate) {\n const idx = findLastIdx(array, predicate);\n if (idx === -1) {\n return undefined;\n }\n return array[idx];\n}\nfunction findLastIdx(array, predicate, fromIndex = array.length - 1) {\n for (let i = fromIndex; i >= 0; i--) {\n const element = array[i];\n if (predicate(element)) {\n return i;\n }\n }\n return -1;\n}\n/**\n * Finds the last item where predicate is true using binary search.\n * `predicate` must be monotonous, i.e. `arr.map(predicate)` must be like `[true, ..., true, false, ..., false]`!\n *\n * @returns `undefined` if no item matches, otherwise the last item that matches the predicate.\n */\nfunction findLastMonotonous(array, predicate) {\n const idx = findLastIdxMonotonous(array, predicate);\n return idx === -1 ? undefined : array[idx];\n}\n/**\n * Finds the last item where predicate is true using binary search.\n * `predicate` must be monotonous, i.e. `arr.map(predicate)` must be like `[true, ..., true, false, ..., false]`!\n *\n * @returns `startIdx - 1` if predicate is false for all items, otherwise the index of the last item that matches the predicate.\n */\nfunction findLastIdxMonotonous(array, predicate, startIdx = 0, endIdxEx = array.length) {\n let i = startIdx;\n let j = endIdxEx;\n while (i < j) {\n const k = Math.floor((i + j) / 2);\n if (predicate(array[k])) {\n i = k + 1;\n }\n else {\n j = k;\n }\n }\n return i - 1;\n}\n/**\n * Finds the first item where predicate is true using binary search.\n * `predicate` must be monotonous, i.e. `arr.map(predicate)` must be like `[false, ..., false, true, ..., true]`!\n *\n * @returns `undefined` if no item matches, otherwise the first item that matches the predicate.\n */\nfunction findFirstMonotonous(array, predicate) {\n const idx = findFirstIdxMonotonousOrArrLen(array, predicate);\n return idx === array.length ? undefined : array[idx];\n}\n/**\n * Finds the first item where predicate is true using binary search.\n * `predicate` must be monotonous, i.e. `arr.map(predicate)` must be like `[false, ..., false, true, ..., true]`!\n *\n * @returns `endIdxEx` if predicate is false for all items, otherwise the index of the first item that matches the predicate.\n */\nfunction findFirstIdxMonotonousOrArrLen(array, predicate, startIdx = 0, endIdxEx = array.length) {\n let i = startIdx;\n let j = endIdxEx;\n while (i < j) {\n const k = Math.floor((i + j) / 2);\n if (predicate(array[k])) {\n j = k;\n }\n else {\n i = k + 1;\n }\n }\n return i;\n}\nfunction findFirstIdxMonotonous(array, predicate, startIdx = 0, endIdxEx = array.length) {\n const idx = findFirstIdxMonotonousOrArrLen(array, predicate, startIdx, endIdxEx);\n return idx === array.length ? -1 : idx;\n}\n/**\n * Use this when\n * * You have a sorted array\n * * You query this array with a monotonous predicate to find the last item that has a certain property.\n * * You query this array multiple times with monotonous predicates that get weaker and weaker.\n */\nclass MonotonousArray {\n static { this.assertInvariants = false; }\n constructor(_array) {\n this._array = _array;\n this._findLastMonotonousLastIdx = 0;\n }\n /**\n * The predicate must be monotonous, i.e. `arr.map(predicate)` must be like `[true, ..., true, false, ..., false]`!\n * For subsequent calls, current predicate must be weaker than (or equal to) the previous predicate, i.e. more entries must be `true`.\n */\n findLastMonotonous(predicate) {\n if (MonotonousArray.assertInvariants) {\n if (this._prevFindLastPredicate) {\n for (const item of this._array) {\n if (this._prevFindLastPredicate(item) && !predicate(item)) {\n throw new Error('MonotonousArray: current predicate must be weaker than (or equal to) the previous predicate.');\n }\n }\n }\n this._prevFindLastPredicate = predicate;\n }\n const idx = findLastIdxMonotonous(this._array, predicate, this._findLastMonotonousLastIdx);\n this._findLastMonotonousLastIdx = idx + 1;\n return idx === -1 ? undefined : this._array[idx];\n }\n}\nexports.MonotonousArray = MonotonousArray;\n/**\n * Returns the first item that is equal to or greater than every other item.\n*/\nfunction findFirstMax(array, comparator) {\n if (array.length === 0) {\n return undefined;\n }\n let max = array[0];\n for (let i = 1; i < array.length; i++) {\n const item = array[i];\n if (comparator(item, max) > 0) {\n max = item;\n }\n }\n return max;\n}\n/**\n * Returns the last item that is equal to or greater than every other item.\n*/\nfunction findLastMax(array, comparator) {\n if (array.length === 0) {\n return undefined;\n }\n let max = array[0];\n for (let i = 1; i < array.length; i++) {\n const item = array[i];\n if (comparator(item, max) >= 0) {\n max = item;\n }\n }\n return max;\n}\n/**\n * Returns the first item that is equal to or less than every other item.\n*/\nfunction findFirstMin(array, comparator) {\n return findFirstMax(array, (a, b) => -comparator(a, b));\n}\nfunction findMaxIdx(array, comparator) {\n if (array.length === 0) {\n return -1;\n }\n let maxIdx = 0;\n for (let i = 1; i < array.length; i++) {\n const item = array[i];\n if (comparator(item, array[maxIdx]) > 0) {\n maxIdx = i;\n }\n }\n return maxIdx;\n}\n/**\n * Returns the first mapped value of the array which is not undefined.\n */\nfunction mapFindFirst(items, mapFn) {\n for (const value of items) {\n const mapped = mapFn(value);\n if (mapped !== undefined) {\n return mapped;\n }\n }\n return undefined;\n}\n","\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.AsyncIterableSource = exports.CancelableAsyncIterableObject = exports.AsyncIterableObject = exports.LazyStatefulPromise = exports.StatefulPromise = exports.Promises = exports.DeferredPromise = exports.IntervalCounter = exports.TaskSequentializer = exports.GlobalIdleValue = exports.AbstractIdleValue = exports._runWhenIdle = exports.runWhenGlobalIdle = exports.ThrottledWorker = exports.RunOnceWorker = exports.ProcessTimeRunOnceScheduler = exports.RunOnceScheduler = exports.IntervalTimer = exports.TimeoutTimer = exports.LimitedQueue = exports.Queue = exports.Limiter = exports.AutoOpenBarrier = exports.Barrier = exports.ThrottledDelayer = exports.Delayer = exports.SequencerByKey = exports.Sequencer = exports.Throttler = void 0;\nexports.isThenable = isThenable;\nexports.createCancelablePromise = createCancelablePromise;\nexports.raceCancellation = raceCancellation;\nexports.raceCancellationError = raceCancellationError;\nexports.raceCancellablePromises = raceCancellablePromises;\nexports.raceTimeout = raceTimeout;\nexports.asPromise = asPromise;\nexports.promiseWithResolvers = promiseWithResolvers;\nexports.timeout = timeout;\nexports.disposableTimeout = disposableTimeout;\nexports.sequence = sequence;\nexports.first = first;\nexports.firstParallel = firstParallel;\nexports.retry = retry;\nexports.createCancelableAsyncIterable = createCancelableAsyncIterable;\nconst cancellation_1 = require(\"vs/base/common/cancellation\");\nconst errors_1 = require(\"vs/base/common/errors\");\nconst event_1 = require(\"vs/base/common/event\");\nconst lifecycle_1 = require(\"vs/base/common/lifecycle\");\nconst platform_1 = require(\"vs/base/common/platform\");\nconst symbols_1 = require(\"./symbols\");\nconst lazy_1 = require(\"vs/base/common/lazy\");\nfunction isThenable(obj) {\n return !!obj && typeof obj.then === 'function';\n}\nfunction createCancelablePromise(callback) {\n const source = new cancellation_1.CancellationTokenSource();\n const thenable = callback(source.token);\n const promise = new Promise((resolve, reject) => {\n const subscription = source.token.onCancellationRequested(() => {\n subscription.dispose();\n reject(new errors_1.CancellationError());\n });\n Promise.resolve(thenable).then(value => {\n subscription.dispose();\n source.dispose();\n resolve(value);\n }, err => {\n subscription.dispose();\n source.dispose();\n reject(err);\n });\n });\n return new class {\n cancel() {\n source.cancel();\n source.dispose();\n }\n then(resolve, reject) {\n return promise.then(resolve, reject);\n }\n catch(reject) {\n return this.then(undefined, reject);\n }\n finally(onfinally) {\n return promise.finally(onfinally);\n }\n };\n}\nfunction raceCancellation(promise, token, defaultValue) {\n return new Promise((resolve, reject) => {\n const ref = token.onCancellationRequested(() => {\n ref.dispose();\n resolve(defaultValue);\n });\n promise.then(resolve, reject).finally(() => ref.dispose());\n });\n}\n/**\n * Returns a promise that rejects with an {@CancellationError} as soon as the passed token is cancelled.\n * @see {@link raceCancellation}\n */\nfunction raceCancellationError(promise, token) {\n return new Promise((resolve, reject) => {\n const ref = token.onCancellationRequested(() => {\n ref.dispose();\n reject(new errors_1.CancellationError());\n });\n promise.then(resolve, reject).finally(() => ref.dispose());\n });\n}\n/**\n * Returns as soon as one of the promises resolves or rejects and cancels remaining promises\n */\nasync function raceCancellablePromises(cancellablePromises) {\n let resolvedPromiseIndex = -1;\n const promises = cancellablePromises.map((promise, index) => promise.then(result => { resolvedPromiseIndex = index; return result; }));\n try {\n const result = await Promise.race(promises);\n return result;\n }\n finally {\n cancellablePromises.forEach((cancellablePromise, index) => {\n if (index !== resolvedPromiseIndex) {\n cancellablePromise.cancel();\n }\n });\n }\n}\nfunction raceTimeout(promise, timeout, onTimeout) {\n let promiseResolve = undefined;\n const timer = setTimeout(() => {\n promiseResolve?.(undefined);\n onTimeout?.();\n }, timeout);\n return Promise.race([\n promise.finally(() => clearTimeout(timer)),\n new Promise(resolve => promiseResolve = resolve)\n ]);\n}\nfunction asPromise(callback) {\n return new Promise((resolve, reject) => {\n const item = callback();\n if (isThenable(item)) {\n item.then(resolve, reject);\n }\n else {\n resolve(item);\n }\n });\n}\n/**\n * Creates and returns a new promise, plus its `resolve` and `reject` callbacks.\n *\n * Replace with standardized [`Promise.withResolvers`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/withResolvers) once it is supported\n */\nfunction promiseWithResolvers() {\n let resolve;\n let reject;\n const promise = new Promise((res, rej) => {\n resolve = res;\n reject = rej;\n });\n return { promise, resolve: resolve, reject: reject };\n}\n/**\n * A helper to prevent accumulation of sequential async tasks.\n *\n * Imagine a mail man with the sole task of delivering letters. As soon as\n * a letter submitted for delivery, he drives to the destination, delivers it\n * and returns to his base. Imagine that during the trip, N more letters were submitted.\n * When the mail man returns, he picks those N letters and delivers them all in a\n * single trip. Even though N+1 submissions occurred, only 2 deliveries were made.\n *\n * The throttler implements this via the queue() method, by providing it a task\n * factory. Following the example:\n *\n * \t\tconst throttler = new Throttler();\n * \t\tconst letters = [];\n *\n * \t\tfunction deliver() {\n * \t\t\tconst lettersToDeliver = letters;\n * \t\t\tletters = [];\n * \t\t\treturn makeTheTrip(lettersToDeliver);\n * \t\t}\n *\n * \t\tfunction onLetterReceived(l) {\n * \t\t\tletters.push(l);\n * \t\t\tthrottler.queue(deliver);\n * \t\t}\n */\nclass Throttler {\n constructor() {\n this.isDisposed = false;\n this.activePromise = null;\n this.queuedPromise = null;\n this.queuedPromiseFactory = null;\n }\n queue(promiseFactory) {\n if (this.isDisposed) {\n return Promise.reject(new Error('Throttler is disposed'));\n }\n if (this.activePromise) {\n this.queuedPromiseFactory = promiseFactory;\n if (!this.queuedPromise) {\n const onComplete = () => {\n this.queuedPromise = null;\n if (this.isDisposed) {\n return;\n }\n const result = this.queue(this.queuedPromiseFactory);\n this.queuedPromiseFactory = null;\n return result;\n };\n this.queuedPromise = new Promise(resolve => {\n this.activePromise.then(onComplete, onComplete).then(resolve);\n });\n }\n return new Promise((resolve, reject) => {\n this.queuedPromise.then(resolve, reject);\n });\n }\n this.activePromise = promiseFactory();\n return new Promise((resolve, reject) => {\n this.activePromise.then((result) => {\n this.activePromise = null;\n resolve(result);\n }, (err) => {\n this.activePromise = null;\n reject(err);\n });\n });\n }\n dispose() {\n this.isDisposed = true;\n }\n}\nexports.Throttler = Throttler;\nclass Sequencer {\n constructor() {\n this.current = Promise.resolve(null);\n }\n queue(promiseTask) {\n return this.current = this.current.then(() => promiseTask(), () => promiseTask());\n }\n}\nexports.Sequencer = Sequencer;\nclass SequencerByKey {\n constructor() {\n this.promiseMap = new Map();\n }\n queue(key, promiseTask) {\n const runningPromise = this.promiseMap.get(key) ?? Promise.resolve();\n const newPromise = runningPromise\n .catch(() => { })\n .then(promiseTask)\n .finally(() => {\n if (this.promiseMap.get(key) === newPromise) {\n this.promiseMap.delete(key);\n }\n });\n this.promiseMap.set(key, newPromise);\n return newPromise;\n }\n}\nexports.SequencerByKey = SequencerByKey;\nconst timeoutDeferred = (timeout, fn) => {\n let scheduled = true;\n const handle = setTimeout(() => {\n scheduled = false;\n fn();\n }, timeout);\n return {\n isTriggered: () => scheduled,\n dispose: () => {\n clearTimeout(handle);\n scheduled = false;\n },\n };\n};\nconst microtaskDeferred = (fn) => {\n let scheduled = true;\n queueMicrotask(() => {\n if (scheduled) {\n scheduled = false;\n fn();\n }\n });\n return {\n isTriggered: () => scheduled,\n dispose: () => { scheduled = false; },\n };\n};\n/**\n * A helper to delay (debounce) execution of a task that is being requested often.\n *\n * Following the throttler, now imagine the mail man wants to optimize the number of\n * trips proactively. The trip itself can be long, so he decides not to make the trip\n * as soon as a letter is submitted. Instead he waits a while, in case more\n * letters are submitted. After said waiting period, if no letters were submitted, he\n * decides to make the trip. Imagine that N more letters were submitted after the first\n * one, all within a short period of time between each other. Even though N+1\n * submissions occurred, only 1 delivery was made.\n *\n * The delayer offers this behavior via the trigger() method, into which both the task\n * to be executed and the waiting period (delay) must be passed in as arguments. Following\n * the example:\n *\n * \t\tconst delayer = new Delayer(WAITING_PERIOD);\n * \t\tconst letters = [];\n *\n * \t\tfunction letterReceived(l) {\n * \t\t\tletters.push(l);\n * \t\t\tdelayer.trigger(() => { return makeTheTrip(); });\n * \t\t}\n */\nclass Delayer {\n constructor(defaultDelay) {\n this.defaultDelay = defaultDelay;\n this.deferred = null;\n this.completionPromise = null;\n this.doResolve = null;\n this.doReject = null;\n this.task = null;\n }\n trigger(task, delay = this.defaultDelay) {\n this.task = task;\n this.cancelTimeout();\n if (!this.completionPromise) {\n this.completionPromise = new Promise((resolve, reject) => {\n this.doResolve = resolve;\n this.doReject = reject;\n }).then(() => {\n this.completionPromise = null;\n this.doResolve = null;\n if (this.task) {\n const task = this.task;\n this.task = null;\n return task();\n }\n return undefined;\n });\n }\n const fn = () => {\n this.deferred = null;\n this.doResolve?.(null);\n };\n this.deferred = delay === symbols_1.MicrotaskDelay ? microtaskDeferred(fn) : timeoutDeferred(delay, fn);\n return this.completionPromise;\n }\n isTriggered() {\n return !!this.deferred?.isTriggered();\n }\n cancel() {\n this.cancelTimeout();\n if (this.completionPromise) {\n this.doReject?.(new errors_1.CancellationError());\n this.completionPromise = null;\n }\n }\n cancelTimeout() {\n this.deferred?.dispose();\n this.deferred = null;\n }\n dispose() {\n this.cancel();\n }\n}\nexports.Delayer = Delayer;\n/**\n * A helper to delay execution of a task that is being requested often, while\n * preventing accumulation of consecutive executions, while the task runs.\n *\n * The mail man is clever and waits for a certain amount of time, before going\n * out to deliver letters. While the mail man is going out, more letters arrive\n * and can only be delivered once he is back. Once he is back the mail man will\n * do one more trip to deliver the letters that have accumulated while he was out.\n */\nclass ThrottledDelayer {\n constructor(defaultDelay) {\n this.delayer = new Delayer(defaultDelay);\n this.throttler = new Throttler();\n }\n trigger(promiseFactory, delay) {\n return this.delayer.trigger(() => this.throttler.queue(promiseFactory), delay);\n }\n isTriggered() {\n return this.delayer.isTriggered();\n }\n cancel() {\n this.delayer.cancel();\n }\n dispose() {\n this.delayer.dispose();\n this.throttler.dispose();\n }\n}\nexports.ThrottledDelayer = ThrottledDelayer;\n/**\n * A barrier that is initially closed and then becomes opened permanently.\n */\nclass Barrier {\n constructor() {\n this._isOpen = false;\n this._promise = new Promise((c, e) => {\n this._completePromise = c;\n });\n }\n isOpen() {\n return this._isOpen;\n }\n open() {\n this._isOpen = true;\n this._completePromise(true);\n }\n wait() {\n return this._promise;\n }\n}\nexports.Barrier = Barrier;\n/**\n * A barrier that is initially closed and then becomes opened permanently after a certain period of\n * time or when open is called explicitly\n */\nclass AutoOpenBarrier extends Barrier {\n constructor(autoOpenTimeMs) {\n super();\n this._timeout = setTimeout(() => this.open(), autoOpenTimeMs);\n }\n open() {\n clearTimeout(this._timeout);\n super.open();\n }\n}\nexports.AutoOpenBarrier = AutoOpenBarrier;\nfunction timeout(millis, token) {\n if (!token) {\n return createCancelablePromise(token => timeout(millis, token));\n }\n return new Promise((resolve, reject) => {\n const handle = setTimeout(() => {\n disposable.dispose();\n resolve();\n }, millis);\n const disposable = token.onCancellationRequested(() => {\n clearTimeout(handle);\n disposable.dispose();\n reject(new errors_1.CancellationError());\n });\n });\n}\n/**\n * Creates a timeout that can be disposed using its returned value.\n * @param handler The timeout handler.\n * @param timeout An optional timeout in milliseconds.\n * @param store An optional {@link DisposableStore} that will have the timeout disposable managed automatically.\n *\n * @example\n * const store = new DisposableStore;\n * // Call the timeout after 1000ms at which point it will be automatically\n * // evicted from the store.\n * const timeoutDisposable = disposableTimeout(() => {}, 1000, store);\n *\n * if (foo) {\n * // Cancel the timeout and evict it from store.\n * timeoutDisposable.dispose();\n * }\n */\nfunction disposableTimeout(handler, timeout = 0, store) {\n const timer = setTimeout(() => {\n handler();\n if (store) {\n disposable.dispose();\n }\n }, timeout);\n const disposable = (0, lifecycle_1.toDisposable)(() => {\n clearTimeout(timer);\n store?.deleteAndLeak(disposable);\n });\n store?.add(disposable);\n return disposable;\n}\n/**\n * Runs the provided list of promise factories in sequential order. The returned\n * promise will complete to an array of results from each promise.\n */\nfunction sequence(promiseFactories) {\n const results = [];\n let index = 0;\n const len = promiseFactories.length;\n function next() {\n return index < len ? promiseFactories[index++]() : null;\n }\n function thenHandler(result) {\n if (result !== undefined && result !== null) {\n results.push(result);\n }\n const n = next();\n if (n) {\n return n.then(thenHandler);\n }\n return Promise.resolve(results);\n }\n return Promise.resolve(null).then(thenHandler);\n}\nfunction first(promiseFactories, shouldStop = t => !!t, defaultValue = null) {\n let index = 0;\n const len = promiseFactories.length;\n const loop = () => {\n if (index >= len) {\n return Promise.resolve(defaultValue);\n }\n const factory = promiseFactories[index++];\n const promise = Promise.resolve(factory());\n return promise.then(result => {\n if (shouldStop(result)) {\n return Promise.resolve(result);\n }\n return loop();\n });\n };\n return loop();\n}\nfunction firstParallel(promiseList, shouldStop = t => !!t, defaultValue = null) {\n if (promiseList.length === 0) {\n return Promise.resolve(defaultValue);\n }\n let todo = promiseList.length;\n const finish = () => {\n todo = -1;\n for (const promise of promiseList) {\n promise.cancel?.();\n }\n };\n return new Promise((resolve, reject) => {\n for (const promise of promiseList) {\n promise.then(result => {\n if (--todo >= 0 && shouldStop(result)) {\n finish();\n resolve(result);\n }\n else if (todo === 0) {\n resolve(defaultValue);\n }\n })\n .catch(err => {\n if (--todo >= 0) {\n finish();\n reject(err);\n }\n });\n }\n });\n}\n/**\n * A helper to queue N promises and run them all with a max degree of parallelism. The helper\n * ensures that at any time no more than M promises are running at the same time.\n */\nclass Limiter {\n constructor(maxDegreeOfParalellism) {\n this._size = 0;\n this._isDisposed = false;\n this.maxDegreeOfParalellism = maxDegreeOfParalellism;\n this.outstandingPromises = [];\n this.runningPromises = 0;\n this._onDrained = new event_1.Emitter();\n }\n /**\n *\n * @returns A promise that resolved when all work is done (onDrained) or when\n * there is nothing to do\n */\n whenIdle() {\n return this.size > 0\n ? event_1.Event.toPromise(this.onDrained)\n : Promise.resolve();\n }\n get onDrained() {\n return this._onDrained.event;\n }\n get size() {\n return this._size;\n }\n queue(factory) {\n if (this._isDisposed) {\n throw new Error('Object has been disposed');\n }\n this._size++;\n return new Promise((c, e) => {\n this.outstandingPromises.push({ factory, c, e });\n this.consume();\n });\n }\n consume() {\n while (this.outstandingPromises.length && this.runningPromises < this.maxDegreeOfParalellism) {\n const iLimitedTask = this.outstandingPromises.shift();\n this.runningPromises++;\n const promise = iLimitedTask.factory();\n promise.then(iLimitedTask.c, iLimitedTask.e);\n promise.then(() => this.consumed(), () => this.consumed());\n }\n }\n consumed() {\n if (this._isDisposed) {\n return;\n }\n this.runningPromises--;\n if (--this._size === 0) {\n this._onDrained.fire();\n }\n if (this.outstandingPromises.length > 0) {\n this.consume();\n }\n }\n clear() {\n if (this._isDisposed) {\n throw new Error('Object has been disposed');\n }\n this.outstandingPromises.length = 0;\n this._size = this.runningPromises;\n }\n dispose() {\n this._isDisposed = true;\n this.outstandingPromises.length = 0; // stop further processing\n this._size = 0;\n this._onDrained.dispose();\n }\n}\nexports.Limiter = Limiter;\n/**\n * A queue is handles one promise at a time and guarantees that at any time only one promise is executing.\n */\nclass Queue extends Limiter {\n constructor() {\n super(1);\n }\n}\nexports.Queue = Queue;\n/**\n * Same as `Queue`, ensures that only 1 task is executed at the same time. The difference to `Queue` is that\n * there is only 1 task about to be scheduled next. As such, calling `queue` while a task is executing will\n * replace the currently queued task until it executes.\n *\n * As such, the returned promise may not be from the factory that is passed in but from the next factory that\n * is running after having called `queue`.\n */\nclass LimitedQueue {\n constructor() {\n this.sequentializer = new TaskSequentializer();\n this.tasks = 0;\n }\n queue(factory) {\n if (!this.sequentializer.isRunning()) {\n return this.sequentializer.run(this.tasks++, factory());\n }\n return this.sequentializer.queue(() => {\n return this.sequentializer.run(this.tasks++, factory());\n });\n }\n}\nexports.LimitedQueue = LimitedQueue;\nclass TimeoutTimer {\n constructor(runner, timeout) {\n this._isDisposed = false;\n this._token = -1;\n if (typeof runner === 'function' && typeof timeout === 'number') {\n this.setIfNotSet(runner, timeout);\n }\n }\n dispose() {\n this.cancel();\n this._isDisposed = true;\n }\n cancel() {\n if (this._token !== -1) {\n clearTimeout(this._token);\n this._token = -1;\n }\n }\n cancelAndSet(runner, timeout) {\n if (this._isDisposed) {\n throw new errors_1.BugIndicatingError(`Calling 'cancelAndSet' on a disposed TimeoutTimer`);\n }\n this.cancel();\n this._token = setTimeout(() => {\n this._token = -1;\n runner();\n }, timeout);\n }\n setIfNotSet(runner, timeout) {\n if (this._isDisposed) {\n throw new errors_1.BugIndicatingError(`Calling 'setIfNotSet' on a disposed TimeoutTimer`);\n }\n if (this._token !== -1) {\n // timer is already set\n return;\n }\n this._token = setTimeout(() => {\n this._token = -1;\n runner();\n }, timeout);\n }\n}\nexports.TimeoutTimer = TimeoutTimer;\nclass IntervalTimer {\n constructor() {\n this.disposable = undefined;\n this.isDisposed = false;\n }\n cancel() {\n this.disposable?.dispose();\n this.disposable = undefined;\n }\n cancelAndSet(runner, interval, context = globalThis) {\n if (this.isDisposed) {\n throw new errors_1.BugIndicatingError(`Calling 'cancelAndSet' on a disposed IntervalTimer`);\n }\n this.cancel();\n const handle = context.setInterval(() => {\n runner();\n }, interval);\n this.disposable = (0, lifecycle_1.toDisposable)(() => {\n context.clearInterval(handle);\n this.disposable = undefined;\n });\n }\n dispose() {\n this.cancel();\n this.isDisposed = true;\n }\n}\nexports.IntervalTimer = IntervalTimer;\nclass RunOnceScheduler {\n constructor(runner, delay) {\n this.timeoutToken = -1;\n this.runner = runner;\n this.timeout = delay;\n this.timeoutHandler = this.onTimeout.bind(this);\n }\n /**\n * Dispose RunOnceScheduler\n */\n dispose() {\n this.cancel();\n this.runner = null;\n }\n /**\n * Cancel current scheduled runner (if any).\n */\n cancel() {\n if (this.isScheduled()) {\n clearTimeout(this.timeoutToken);\n this.timeoutToken = -1;\n }\n }\n /**\n * Cancel previous runner (if any) & schedule a new runner.\n */\n schedule(delay = this.timeout) {\n this.cancel();\n this.timeoutToken = setTimeout(this.timeoutHandler, delay);\n }\n get delay() {\n return this.timeout;\n }\n set delay(value) {\n this.timeout = value;\n }\n /**\n * Returns true if scheduled.\n */\n isScheduled() {\n return this.timeoutToken !== -1;\n }\n flush() {\n if (this.isScheduled()) {\n this.cancel();\n this.doRun();\n }\n }\n onTimeout() {\n this.timeoutToken = -1;\n if (this.runner) {\n this.doRun();\n }\n }\n doRun() {\n this.runner?.();\n }\n}\nexports.RunOnceScheduler = RunOnceScheduler;\n/**\n * Same as `RunOnceScheduler`, but doesn't count the time spent in sleep mode.\n * > **NOTE**: Only offers 1s resolution.\n *\n * When calling `setTimeout` with 3hrs, and putting the computer immediately to sleep\n * for 8hrs, `setTimeout` will fire **as soon as the computer wakes from sleep**. But\n * this scheduler will execute 3hrs **after waking the computer from sleep**.\n */\nclass ProcessTimeRunOnceScheduler {\n constructor(runner, delay) {\n if (delay % 1000 !== 0) {\n console.warn(`ProcessTimeRunOnceScheduler resolution is 1s, ${delay}ms is not a multiple of 1000ms.`);\n }\n this.runner = runner;\n this.timeout = delay;\n this.counter = 0;\n this.intervalToken = -1;\n this.intervalHandler = this.onInterval.bind(this);\n }\n dispose() {\n this.cancel();\n this.runner = null;\n }\n cancel() {\n if (this.isScheduled()) {\n clearInterval(this.intervalToken);\n this.intervalToken = -1;\n }\n }\n /**\n * Cancel previous runner (if any) & schedule a new runner.\n */\n schedule(delay = this.timeout) {\n if (delay % 1000 !== 0) {\n console.warn(`ProcessTimeRunOnceScheduler resolution is 1s, ${delay}ms is not a multiple of 1000ms.`);\n }\n this.cancel();\n this.counter = Math.ceil(delay / 1000);\n this.intervalToken = setInterval(this.intervalHandler, 1000);\n }\n /**\n * Returns true if scheduled.\n */\n isScheduled() {\n return this.intervalToken !== -1;\n }\n onInterval() {\n this.counter--;\n if (this.counter > 0) {\n // still need to wait\n return;\n }\n // time elapsed\n clearInterval(this.intervalToken);\n this.intervalToken = -1;\n this.runner?.();\n }\n}\nexports.ProcessTimeRunOnceScheduler = ProcessTimeRunOnceScheduler;\nclass RunOnceWorker extends RunOnceScheduler {\n constructor(runner, timeout) {\n super(runner, timeout);\n this.units = [];\n }\n work(unit) {\n this.units.push(unit);\n if (!this.isScheduled()) {\n this.schedule();\n }\n }\n doRun() {\n const units = this.units;\n this.units = [];\n this.runner?.(units);\n }\n dispose() {\n this.units = [];\n super.dispose();\n }\n}\nexports.RunOnceWorker = RunOnceWorker;\n/**\n * The `ThrottledWorker` will accept units of work `T`\n * to handle. The contract is:\n * * there is a maximum of units the worker can handle at once (via `maxWorkChunkSize`)\n * * there is a maximum of units the worker will keep in memory for processing (via `maxBufferedWork`)\n * * after having handled `maxWorkChunkSize` units, the worker needs to rest (via `throttleDelay`)\n */\nclass ThrottledWorker extends lifecycle_1.Disposable {\n constructor(options, handler) {\n super();\n this.options = options;\n this.handler = handler;\n this.pendingWork = [];\n this.throttler = this._register(new lifecycle_1.MutableDisposable());\n this.disposed = false;\n }\n /**\n * The number of work units that are pending to be processed.\n */\n get pending() { return this.pendingWork.length; }\n /**\n * Add units to be worked on. Use `pending` to figure out\n * how many units are not yet processed after this method\n * was called.\n *\n * @returns whether the work was accepted or not. If the\n * worker is disposed, it will not accept any more work.\n * If the number of pending units would become larger\n * than `maxPendingWork`, more work will also not be accepted.\n */\n work(units) {\n if (this.disposed) {\n return false; // work not accepted: disposed\n }\n // Check for reaching maximum of pending work\n if (typeof this.options.maxBufferedWork === 'number') {\n // Throttled: simple check if pending + units exceeds max pending\n if (this.throttler.value) {\n if (this.pending + units.length > this.options.maxBufferedWork) {\n return false; // work not accepted: too much pending work\n }\n }\n // Unthrottled: same as throttled, but account for max chunk getting\n // worked on directly without being pending\n else {\n if (this.pending + units.length - this.options.maxWorkChunkSize > this.options.maxBufferedWork) {\n return false; // work not accepted: too much pending work\n }\n }\n }\n // Add to pending units first\n for (const unit of units) {\n this.pendingWork.push(unit);\n }\n // If not throttled, start working directly\n // Otherwise, when the throttle delay has\n // past, pending work will be worked again.\n if (!this.throttler.value) {\n this.doWork();\n }\n return true; // work accepted\n }\n doWork() {\n // Extract chunk to handle and handle it\n this.handler(this.pendingWork.splice(0, this.options.maxWorkChunkSize));\n // If we have remaining work, schedule it after a delay\n if (this.pendingWork.length > 0) {\n this.throttler.value = new RunOnceScheduler(() => {\n this.throttler.clear();\n this.doWork();\n }, this.options.throttleDelay);\n this.throttler.value.schedule();\n }\n }\n dispose() {\n super.dispose();\n this.disposed = true;\n }\n}\nexports.ThrottledWorker = ThrottledWorker;\n(function () {\n if (typeof globalThis.requestIdleCallback !== 'function' || typeof globalThis.cancelIdleCallback !== 'function') {\n exports._runWhenIdle = (_targetWindow, runner) => {\n (0, platform_1.setTimeout0)(() => {\n if (disposed) {\n return;\n }\n const end = Date.now() + 15; // one frame at 64fps\n const deadline = {\n didTimeout: true,\n timeRemaining() {\n return Math.max(0, end - Date.now());\n }\n };\n runner(Object.freeze(deadline));\n });\n let disposed = false;\n return {\n dispose() {\n if (disposed) {\n return;\n }\n disposed = true;\n }\n };\n };\n }\n else {\n exports._runWhenIdle = (targetWindow, runner, timeout) => {\n const handle = targetWindow.requestIdleCallback(runner, typeof timeout === 'number' ? { timeout } : undefined);\n let disposed = false;\n return {\n dispose() {\n if (disposed) {\n return;\n }\n disposed = true;\n targetWindow.cancelIdleCallback(handle);\n }\n };\n };\n }\n exports.runWhenGlobalIdle = (runner) => (0, exports._runWhenIdle)(globalThis, runner);\n})();\nclass AbstractIdleValue {\n constructor(targetWindow, executor) {\n this._didRun = false;\n this._executor = () => {\n try {\n this._value = executor();\n }\n catch (err) {\n this._error = err;\n }\n finally {\n this._didRun = true;\n }\n };\n this._handle = (0, exports._runWhenIdle)(targetWindow, () => this._executor());\n }\n dispose() {\n this._handle.dispose();\n }\n get value() {\n if (!this._didRun) {\n this._handle.dispose();\n this._executor();\n }\n if (this._error) {\n throw this._error;\n }\n return this._value;\n }\n get isInitialized() {\n return this._didRun;\n }\n}\nexports.AbstractIdleValue = AbstractIdleValue;\n/**\n * An `IdleValue` that always uses the current window (which might be throttled or inactive)\n *\n * **Note** that there is `dom.ts#WindowIdleValue` which is better suited when running inside a browser\n * context\n */\nclass GlobalIdleValue extends AbstractIdleValue {\n constructor(executor) {\n super(globalThis, executor);\n }\n}\nexports.GlobalIdleValue = GlobalIdleValue;\n//#endregion\nasync function retry(task, delay, retries) {\n let lastError;\n for (let i = 0; i < retries; i++) {\n try {\n return await task();\n }\n catch (error) {\n lastError = error;\n await timeout(delay);\n }\n }\n throw lastError;\n}\n/**\n * @deprecated use `LimitedQueue` instead for an easier to use API\n */\nclass TaskSequentializer {\n isRunning(taskId) {\n if (typeof taskId === 'number') {\n return this._running?.taskId === taskId;\n }\n return !!this._running;\n }\n get running() {\n return this._running?.promise;\n }\n cancelRunning() {\n this._running?.cancel();\n }\n run(taskId, promise, onCancel) {\n this._running = { taskId, cancel: () => onCancel?.(), promise };\n promise.then(() => this.doneRunning(taskId), () => this.doneRunning(taskId));\n return promise;\n }\n doneRunning(taskId) {\n if (this._running && taskId === this._running.taskId) {\n // only set running to done if the promise finished that is associated with that taskId\n this._running = undefined;\n // schedule the queued task now that we are free if we have any\n this.runQueued();\n }\n }\n runQueued() {\n if (this._queued) {\n const queued = this._queued;\n this._queued = undefined;\n // Run queued task and complete on the associated promise\n queued.run().then(queued.promiseResolve, queued.promiseReject);\n }\n }\n /**\n * Note: the promise to schedule as next run MUST itself call `run`.\n * Otherwise, this sequentializer will report `false` for `isRunning`\n * even when this task is running. Missing this detail means that\n * suddenly multiple tasks will run in parallel.\n */\n queue(run) {\n // this is our first queued task, so we create associated promise with it\n // so that we can return a promise that completes when the task has\n // completed.\n if (!this._queued) {\n const { promise, resolve: promiseResolve, reject: promiseReject } = promiseWithResolvers();\n this._queued = {\n run,\n promise,\n promiseResolve: promiseResolve,\n promiseReject: promiseReject\n };\n }\n // we have a previous queued task, just overwrite it\n else {\n this._queued.run = run;\n }\n return this._queued.promise;\n }\n hasQueued() {\n return !!this._queued;\n }\n async join() {\n return this._queued?.promise ?? this._running?.promise;\n }\n}\nexports.TaskSequentializer = TaskSequentializer;\n//#endregion\n//#region\n/**\n * The `IntervalCounter` allows to count the number\n * of calls to `increment()` over a duration of\n * `interval`. This utility can be used to conditionally\n * throttle a frequent task when a certain threshold\n * is reached.\n */\nclass IntervalCounter {\n constructor(interval, nowFn = () => Date.now()) {\n this.interval = interval;\n this.nowFn = nowFn;\n this.lastIncrementTime = 0;\n this.value = 0;\n }\n increment() {\n const now = this.nowFn();\n // We are outside of the range of `interval` and as such\n // start counting from 0 and remember the time\n if (now - this.lastIncrementTime > this.interval) {\n this.lastIncrementTime = now;\n this.value = 0;\n }\n this.value++;\n return this.value;\n }\n}\nexports.IntervalCounter = IntervalCounter;\nvar DeferredOutcome;\n(function (DeferredOutcome) {\n DeferredOutcome[DeferredOutcome[\"Resolved\"] = 0] = \"Resolved\";\n DeferredOutcome[DeferredOutcome[\"Rejected\"] = 1] = \"Rejected\";\n})(DeferredOutcome || (DeferredOutcome = {}));\n/**\n * Creates a promise whose resolution or rejection can be controlled imperatively.\n */\nclass DeferredPromise {\n get isRejected() {\n return this.outcome?.outcome === DeferredOutcome.Rejected;\n }\n get isResolved() {\n return this.outcome?.outcome === DeferredOutcome.Resolved;\n }\n get isSettled() {\n return !!this.outcome;\n }\n get value() {\n return this.outcome?.outcome === DeferredOutcome.Resolved ? this.outcome?.value : undefined;\n }\n constructor() {\n this.p = new Promise((c, e) => {\n this.completeCallback = c;\n this.errorCallback = e;\n });\n }\n complete(value) {\n return new Promise(resolve => {\n this.completeCallback(value);\n this.outcome = { outcome: DeferredOutcome.Resolved, value };\n resolve();\n });\n }\n error(err) {\n return new Promise(resolve => {\n this.errorCallback(err);\n this.outcome = { outcome: DeferredOutcome.Rejected, value: err };\n resolve();\n });\n }\n cancel() {\n return this.error(new errors_1.CancellationError());\n }\n}\nexports.DeferredPromise = DeferredPromise;\n//#endregion\n//#region Promises\nvar Promises;\n(function (Promises) {\n /**\n * A drop-in replacement for `Promise.all` with the only difference\n * that the method awaits every promise to either fulfill or reject.\n *\n * Similar to `Promise.all`, only the first error will be returned\n * if any.\n */\n async function settled(promises) {\n let firstError = undefined;\n const result = await Promise.all(promises.map(promise => promise.then(value => value, error => {\n if (!firstError) {\n firstError = error;\n }\n return undefined; // do not rethrow so that other promises can settle\n })));\n if (typeof firstError !== 'undefined') {\n throw firstError;\n }\n return result; // cast is needed and protected by the `throw` above\n }\n Promises.settled = settled;\n /**\n * A helper to create a new `Promise` with a body that is a promise\n * itself. By default, an error that raises from the async body will\n * end up as a unhandled rejection, so this utility properly awaits the\n * body and rejects the promise as a normal promise does without async\n * body.\n *\n * This method should only be used in rare cases where otherwise `async`\n * cannot be used (e.g. when callbacks are involved that require this).\n */\n function withAsyncBody(bodyFn) {\n // eslint-disable-next-line no-async-promise-executor\n return new Promise(async (resolve, reject) => {\n try {\n await bodyFn(resolve, reject);\n }\n catch (error) {\n reject(error);\n }\n });\n }\n Promises.withAsyncBody = withAsyncBody;\n})(Promises || (exports.Promises = Promises = {}));\nclass StatefulPromise {\n get value() { return this._value; }\n get error() { return this._error; }\n get isResolved() { return this._isResolved; }\n constructor(promise) {\n this._value = undefined;\n this._error = undefined;\n this._isResolved = false;\n this.promise = promise.then(value => {\n this._value = value;\n this._isResolved = true;\n return value;\n }, error => {\n this._error = error;\n this._isResolved = true;\n throw error;\n });\n }\n /**\n * Returns the resolved value.\n * Throws if the promise is not resolved yet.\n */\n requireValue() {\n if (!this._isResolved) {\n throw new errors_1.BugIndicatingError('Promise is not resolved yet');\n }\n if (this._error) {\n throw this._error;\n }\n return this._value;\n }\n}\nexports.StatefulPromise = StatefulPromise;\nclass LazyStatefulPromise {\n constructor(_compute) {\n this._compute = _compute;\n this._promise = new lazy_1.Lazy(() => new StatefulPromise(this._compute()));\n }\n /**\n * Returns the resolved value.\n * Throws if the promise is not resolved yet.\n */\n requireValue() {\n return this._promise.value.requireValue();\n }\n /**\n * Returns the promise (and triggers a computation of the promise if not yet done so).\n */\n getPromise() {\n return this._promise.value.promise;\n }\n /**\n * Reads the current value without triggering a computation of the promise.\n */\n get currentValue() {\n return this._promise.rawValue?.value;\n }\n}\nexports.LazyStatefulPromise = LazyStatefulPromise;\n//#endregion\n//#region\nvar AsyncIterableSourceState;\n(function (AsyncIterableSourceState) {\n AsyncIterableSourceState[AsyncIterableSourceState[\"Initial\"] = 0] = \"Initial\";\n AsyncIterableSourceState[AsyncIterableSourceState[\"DoneOK\"] = 1] = \"DoneOK\";\n AsyncIterableSourceState[AsyncIterableSourceState[\"DoneError\"] = 2] = \"DoneError\";\n})(AsyncIterableSourceState || (AsyncIterableSourceState = {}));\n/**\n * A rich implementation for an `AsyncIterable`.\n */\nclass AsyncIterableObject {\n static fromArray(items) {\n return new AsyncIterableObject((writer) => {\n writer.emitMany(items);\n });\n }\n static fromPromise(promise) {\n return new AsyncIterableObject(async (emitter) => {\n emitter.emitMany(await promise);\n });\n }\n static fromPromises(promises) {\n return new AsyncIterableObject(async (emitter) => {\n await Promise.all(promises.map(async (p) => emitter.emitOne(await p)));\n });\n }\n static merge(iterables) {\n return new AsyncIterableObject(async (emitter) => {\n await Promise.all(iterables.map(async (iterable) => {\n for await (const item of iterable) {\n emitter.emitOne(item);\n }\n }));\n });\n }\n static { this.EMPTY = AsyncIterableObject.fromArray([]); }\n constructor(executor, onReturn) {\n this._state = AsyncIterableSourceState.Initial;\n this._results = [];\n this._error = null;\n this._onReturn = onReturn;\n this._onStateChanged = new event_1.Emitter();\n queueMicrotask(async () => {\n const writer = {\n emitOne: (item) => this.emitOne(item),\n emitMany: (items) => this.emitMany(items),\n reject: (error) => this.reject(error)\n };\n try {\n await Promise.resolve(executor(writer));\n this.resolve();\n }\n catch (err) {\n this.reject(err);\n }\n finally {\n writer.emitOne = undefined;\n writer.emitMany = undefined;\n writer.reject = undefined;\n }\n });\n }\n [Symbol.asyncIterator]() {\n let i = 0;\n return {\n next: async () => {\n do {\n if (this._state === AsyncIterableSourceState.DoneError) {\n throw this._error;\n }\n if (i < this._results.length) {\n return { done: false, value: this._results[i++] };\n }\n if (this._state === AsyncIterableSourceState.DoneOK) {\n return { done: true, value: undefined };\n }\n await event_1.Event.toPromise(this._onStateChanged.event);\n } while (true);\n },\n return: async () => {\n this._onReturn?.();\n return { done: true, value: undefined };\n }\n };\n }\n static map(iterable, mapFn) {\n return new AsyncIterableObject(async (emitter) => {\n for await (const item of iterable) {\n emitter.emitOne(mapFn(item));\n }\n });\n }\n map(mapFn) {\n return AsyncIterableObject.map(this, mapFn);\n }\n static filter(iterable, filterFn) {\n return new AsyncIterableObject(async (emitter) => {\n for await (const item of iterable) {\n if (filterFn(item)) {\n emitter.emitOne(item);\n }\n }\n });\n }\n filter(filterFn) {\n return AsyncIterableObject.filter(this, filterFn);\n }\n static coalesce(iterable) {\n return AsyncIterableObject.filter(iterable, item => !!item);\n }\n coalesce() {\n return AsyncIterableObject.coalesce(this);\n }\n static async toPromise(iterable) {\n const result = [];\n for await (const item of iterable) {\n result.push(item);\n }\n return result;\n }\n toPromise() {\n return AsyncIterableObject.toPromise(this);\n }\n /**\n * The value will be appended at the end.\n *\n * **NOTE** If `resolve()` or `reject()` have already been called, this method has no effect.\n */\n emitOne(value) {\n if (this._state !== AsyncIterableSourceState.Initial) {\n return;\n }\n // it is important to add new values at the end,\n // as we may have iterators already running on the array\n this._results.push(value);\n this._onStateChanged.fire();\n }\n /**\n * The values will be appended at the end.\n *\n * **NOTE** If `resolve()` or `reject()` have already been called, this method has no effect.\n */\n emitMany(values) {\n if (this._state !== AsyncIterableSourceState.Initial) {\n return;\n }\n // it is important to add new values at the end,\n // as we may have iterators already running on the array\n this._results = this._results.concat(values);\n this._onStateChanged.fire();\n }\n /**\n * Calling `resolve()` will mark the result array as complete.\n *\n * **NOTE** `resolve()` must be called, otherwise all consumers of this iterable will hang indefinitely, similar to a non-resolved promise.\n * **NOTE** If `resolve()` or `reject()` have already been called, this method has no effect.\n */\n resolve() {\n if (this._state !== AsyncIterableSourceState.Initial) {\n return;\n }\n this._state = AsyncIterableSourceState.DoneOK;\n this._onStateChanged.fire();\n }\n /**\n * Writing an error will permanently invalidate this iterable.\n * The current users will receive an error thrown, as will all future users.\n *\n * **NOTE** If `resolve()` or `reject()` have already been called, this method has no effect.\n */\n reject(error) {\n if (this._state !== AsyncIterableSourceState.Initial) {\n return;\n }\n this._state = AsyncIterableSourceState.DoneError;\n this._error = error;\n this._onStateChanged.fire();\n }\n}\nexports.AsyncIterableObject = AsyncIterableObject;\nclass CancelableAsyncIterableObject extends AsyncIterableObject {\n constructor(_source, executor) {\n super(executor);\n this._source = _source;\n }\n cancel() {\n this._source.cancel();\n }\n}\nexports.CancelableAsyncIterableObject = CancelableAsyncIterableObject;\nfunction createCancelableAsyncIterable(callback) {\n const source = new cancellation_1.CancellationTokenSource();\n const innerIterable = callback(source.token);\n return new CancelableAsyncIterableObject(source, async (emitter) => {\n const subscription = source.token.onCancellationRequested(() => {\n subscription.dispose();\n source.dispose();\n emitter.reject(new errors_1.CancellationError());\n });\n try {\n for await (const item of innerIterable) {\n if (source.token.isCancellationRequested) {\n // canceled in the meantime\n return;\n }\n emitter.emitOne(item);\n }\n subscription.dispose();\n source.dispose();\n }\n catch (err) {\n subscription.dispose();\n source.dispose();\n emitter.reject(err);\n }\n });\n}\nclass AsyncIterableSource {\n /**\n *\n * @param onReturn A function that will be called when consuming the async iterable\n * has finished by the consumer, e.g the for-await-loop has be existed (break, return) early.\n * This is NOT called when resolving this source by its owner.\n */\n constructor(onReturn) {\n this._deferred = new DeferredPromise();\n this._asyncIterable = new AsyncIterableObject(emitter => {\n if (earlyError) {\n emitter.reject(earlyError);\n return;\n }\n if (earlyItems) {\n emitter.emitMany(earlyItems);\n }\n this._errorFn = (error) => emitter.reject(error);\n this._emitFn = (item) => emitter.emitOne(item);\n return this._deferred.p;\n }, onReturn);\n let earlyError;\n let earlyItems;\n this._emitFn = (item) => {\n if (!earlyItems) {\n earlyItems = [];\n }\n earlyItems.push(item);\n };\n this._errorFn = (error) => {\n if (!earlyError) {\n earlyError = error;\n }\n };\n }\n get asyncIterable() {\n return this._asyncIterable;\n }\n resolve() {\n this._deferred.complete();\n }\n reject(error) {\n this._errorFn(error);\n this._deferred.complete();\n }\n emitOne(item) {\n this._emitFn(item);\n }\n}\nexports.AsyncIterableSource = AsyncIterableSource;\n//#endregion\n","\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.CancellationTokenSource = exports.CancellationToken = void 0;\nexports.cancelOnDispose = cancelOnDispose;\nconst event_1 = require(\"vs/base/common/event\");\nconst shortcutEvent = Object.freeze(function (callback, context) {\n const handle = setTimeout(callback.bind(context), 0);\n return { dispose() { clearTimeout(handle); } };\n});\nvar CancellationToken;\n(function (CancellationToken) {\n function isCancellationToken(thing) {\n if (thing === CancellationToken.None || thing === CancellationToken.Cancelled) {\n return true;\n }\n if (thing instanceof MutableToken) {\n return true;\n }\n if (!thing || typeof thing !== 'object') {\n return false;\n }\n return typeof thing.isCancellationRequested === 'boolean'\n && typeof thing.onCancellationRequested === 'function';\n }\n CancellationToken.isCancellationToken = isCancellationToken;\n CancellationToken.None = Object.freeze({\n isCancellationRequested: false,\n onCancellationRequested: event_1.Event.None\n });\n CancellationToken.Cancelled = Object.freeze({\n isCancellationRequested: true,\n onCancellationRequested: shortcutEvent\n });\n})(CancellationToken || (exports.CancellationToken = CancellationToken = {}));\nclass MutableToken {\n constructor() {\n this._isCancelled = false;\n this._emitter = null;\n }\n cancel() {\n if (!this._isCancelled) {\n this._isCancelled = true;\n if (this._emitter) {\n this._emitter.fire(undefined);\n this.dispose();\n }\n }\n }\n get isCancellationRequested() {\n return this._isCancelled;\n }\n get onCancellationRequested() {\n if (this._isCancelled) {\n return shortcutEvent;\n }\n if (!this._emitter) {\n this._emitter = new event_1.Emitter();\n }\n return this._emitter.event;\n }\n dispose() {\n if (this._emitter) {\n this._emitter.dispose();\n this._emitter = null;\n }\n }\n}\nclass CancellationTokenSource {\n constructor(parent) {\n this._token = undefined;\n this._parentListener = undefined;\n this._parentListener = parent && parent.onCancellationRequested(this.cancel, this);\n }\n get token() {\n if (!this._token) {\n // be lazy and create the token only when\n // actually needed\n this._token = new MutableToken();\n }\n return this._token;\n }\n cancel() {\n if (!this._token) {\n // save an object by returning the default\n // cancelled token when cancellation happens\n // before someone asks for the token\n this._token = CancellationToken.Cancelled;\n }\n else if (this._token instanceof MutableToken) {\n // actually cancel\n this._token.cancel();\n }\n }\n dispose(cancel = false) {\n if (cancel) {\n this.cancel();\n }\n this._parentListener?.dispose();\n if (!this._token) {\n // ensure to initialize with an empty token if we had none\n this._token = CancellationToken.None;\n }\n else if (this._token instanceof MutableToken) {\n // actually dispose\n this._token.dispose();\n }\n }\n}\nexports.CancellationTokenSource = CancellationTokenSource;\nfunction cancelOnDispose(store) {\n const source = new CancellationTokenSource();\n store.add({ dispose() { source.cancel(); } });\n return source.token;\n}\n","\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.CharCode = void 0;\n// Names from https://blog.codinghorror.com/ascii-pronunciation-rules-for-programmers/\n/**\n * An inlined enum containing useful character codes (to be used with String.charCodeAt).\n * Please leave the const keyword such that it gets inlined when compiled to JavaScript!\n */\nvar CharCode;\n(function (CharCode) {\n CharCode[CharCode[\"Null\"] = 0] = \"Null\";\n /**\n * The `\\b` character.\n */\n CharCode[CharCode[\"Backspace\"] = 8] = \"Backspace\";\n /**\n * The `\\t` character.\n */\n CharCode[CharCode[\"Tab\"] = 9] = \"Tab\";\n /**\n * The `\\n` character.\n */\n CharCode[CharCode[\"LineFeed\"] = 10] = \"LineFeed\";\n /**\n * The `\\r` character.\n */\n CharCode[CharCode[\"CarriageReturn\"] = 13] = \"CarriageReturn\";\n CharCode[CharCode[\"Space\"] = 32] = \"Space\";\n /**\n * The `!` character.\n */\n CharCode[CharCode[\"ExclamationMark\"] = 33] = \"ExclamationMark\";\n /**\n * The `\"` character.\n */\n CharCode[CharCode[\"DoubleQuote\"] = 34] = \"DoubleQuote\";\n /**\n * The `#` character.\n */\n CharCode[CharCode[\"Hash\"] = 35] = \"Hash\";\n /**\n * The `$` character.\n */\n CharCode[CharCode[\"DollarSign\"] = 36] = \"DollarSign\";\n /**\n * The `%` character.\n */\n CharCode[CharCode[\"PercentSign\"] = 37] = \"PercentSign\";\n /**\n * The `&` character.\n */\n CharCode[CharCode[\"Ampersand\"] = 38] = \"Ampersand\";\n /**\n * The `'` character.\n */\n CharCode[CharCode[\"SingleQuote\"] = 39] = \"SingleQuote\";\n /**\n * The `(` character.\n */\n CharCode[CharCode[\"OpenParen\"] = 40] = \"OpenParen\";\n /**\n * The `)` character.\n */\n CharCode[CharCode[\"CloseParen\"] = 41] = \"CloseParen\";\n /**\n * The `*` character.\n */\n CharCode[CharCode[\"Asterisk\"] = 42] = \"Asterisk\";\n /**\n * The `+` character.\n */\n CharCode[CharCode[\"Plus\"] = 43] = \"Plus\";\n /**\n * The `,` character.\n */\n CharCode[CharCode[\"Comma\"] = 44] = \"Comma\";\n /**\n * The `-` character.\n */\n CharCode[CharCode[\"Dash\"] = 45] = \"Dash\";\n /**\n * The `.` character.\n */\n CharCode[CharCode[\"Period\"] = 46] = \"Period\";\n /**\n * The `/` character.\n */\n CharCode[CharCode[\"Slash\"] = 47] = \"Slash\";\n CharCode[CharCode[\"Digit0\"] = 48] = \"Digit0\";\n CharCode[CharCode[\"Digit1\"] = 49] = \"Digit1\";\n CharCode[CharCode[\"Digit2\"] = 50] = \"Digit2\";\n CharCode[CharCode[\"Digit3\"] = 51] = \"Digit3\";\n CharCode[CharCode[\"Digit4\"] = 52] = \"Digit4\";\n CharCode[CharCode[\"Digit5\"] = 53] = \"Digit5\";\n CharCode[CharCode[\"Digit6\"] = 54] = \"Digit6\";\n CharCode[CharCode[\"Digit7\"] = 55] = \"Digit7\";\n CharCode[CharCode[\"Digit8\"] = 56] = \"Digit8\";\n CharCode[CharCode[\"Digit9\"] = 57] = \"Digit9\";\n /**\n * The `:` character.\n */\n CharCode[CharCode[\"Colon\"] = 58] = \"Colon\";\n /**\n * The `;` character.\n */\n CharCode[CharCode[\"Semicolon\"] = 59] = \"Semicolon\";\n /**\n * The `<` character.\n */\n CharCode[CharCode[\"LessThan\"] = 60] = \"LessThan\";\n /**\n * The `=` character.\n */\n CharCode[CharCode[\"Equals\"] = 61] = \"Equals\";\n /**\n * The `>` character.\n */\n CharCode[CharCode[\"GreaterThan\"] = 62] = \"GreaterThan\";\n /**\n * The `?` character.\n */\n CharCode[CharCode[\"QuestionMark\"] = 63] = \"QuestionMark\";\n /**\n * The `@` character.\n */\n CharCode[CharCode[\"AtSign\"] = 64] = \"AtSign\";\n CharCode[CharCode[\"A\"] = 65] = \"A\";\n CharCode[CharCode[\"B\"] = 66] = \"B\";\n CharCode[CharCode[\"C\"] = 67] = \"C\";\n CharCode[CharCode[\"D\"] = 68] = \"D\";\n CharCode[CharCode[\"E\"] = 69] = \"E\";\n CharCode[CharCode[\"F\"] = 70] = \"F\";\n CharCode[CharCode[\"G\"] = 71] = \"G\";\n CharCode[CharCode[\"H\"] = 72] = \"H\";\n CharCode[CharCode[\"I\"] = 73] = \"I\";\n CharCode[CharCode[\"J\"] = 74] = \"J\";\n CharCode[CharCode[\"K\"] = 75] = \"K\";\n CharCode[CharCode[\"L\"] = 76] = \"L\";\n CharCode[CharCode[\"M\"] = 77] = \"M\";\n CharCode[CharCode[\"N\"] = 78] = \"N\";\n CharCode[CharCode[\"O\"] = 79] = \"O\";\n CharCode[CharCode[\"P\"] = 80] = \"P\";\n CharCode[CharCode[\"Q\"] = 81] = \"Q\";\n CharCode[CharCode[\"R\"] = 82] = \"R\";\n CharCode[CharCode[\"S\"] = 83] = \"S\";\n CharCode[CharCode[\"T\"] = 84] = \"T\";\n CharCode[CharCode[\"U\"] = 85] = \"U\";\n CharCode[CharCode[\"V\"] = 86] = \"V\";\n CharCode[CharCode[\"W\"] = 87] = \"W\";\n CharCode[CharCode[\"X\"] = 88] = \"X\";\n CharCode[CharCode[\"Y\"] = 89] = \"Y\";\n CharCode[CharCode[\"Z\"] = 90] = \"Z\";\n /**\n * The `[` character.\n */\n CharCode[CharCode[\"OpenSquareBracket\"] = 91] = \"OpenSquareBracket\";\n /**\n * The `\\` character.\n */\n CharCode[CharCode[\"Backslash\"] = 92] = \"Backslash\";\n /**\n * The `]` character.\n */\n CharCode[CharCode[\"CloseSquareBracket\"] = 93] = \"CloseSquareBracket\";\n /**\n * The `^` character.\n */\n CharCode[CharCode[\"Caret\"] = 94] = \"Caret\";\n /**\n * The `_` character.\n */\n CharCode[CharCode[\"Underline\"] = 95] = \"Underline\";\n /**\n * The ``(`)`` character.\n */\n CharCode[CharCode[\"BackTick\"] = 96] = \"BackTick\";\n CharCode[CharCode[\"a\"] = 97] = \"a\";\n CharCode[CharCode[\"b\"] = 98] = \"b\";\n CharCode[CharCode[\"c\"] = 99] = \"c\";\n CharCode[CharCode[\"d\"] = 100] = \"d\";\n CharCode[CharCode[\"e\"] = 101] = \"e\";\n CharCode[CharCode[\"f\"] = 102] = \"f\";\n CharCode[CharCode[\"g\"] = 103] = \"g\";\n CharCode[CharCode[\"h\"] = 104] = \"h\";\n CharCode[CharCode[\"i\"] = 105] = \"i\";\n CharCode[CharCode[\"j\"] = 106] = \"j\";\n CharCode[CharCode[\"k\"] = 107] = \"k\";\n CharCode[CharCode[\"l\"] = 108] = \"l\";\n CharCode[CharCode[\"m\"] = 109] = \"m\";\n CharCode[CharCode[\"n\"] = 110] = \"n\";\n CharCode[CharCode[\"o\"] = 111] = \"o\";\n CharCode[CharCode[\"p\"] = 112] = \"p\";\n CharCode[CharCode[\"q\"] = 113] = \"q\";\n CharCode[CharCode[\"r\"] = 114] = \"r\";\n CharCode[CharCode[\"s\"] = 115] = \"s\";\n CharCode[CharCode[\"t\"] = 116] = \"t\";\n CharCode[CharCode[\"u\"] = 117] = \"u\";\n CharCode[CharCode[\"v\"] = 118] = \"v\";\n CharCode[CharCode[\"w\"] = 119] = \"w\";\n CharCode[CharCode[\"x\"] = 120] = \"x\";\n CharCode[CharCode[\"y\"] = 121] = \"y\";\n CharCode[CharCode[\"z\"] = 122] = \"z\";\n /**\n * The `{` character.\n */\n CharCode[CharCode[\"OpenCurlyBrace\"] = 123] = \"OpenCurlyBrace\";\n /**\n * The `|` character.\n */\n CharCode[CharCode[\"Pipe\"] = 124] = \"Pipe\";\n /**\n * The `}` character.\n */\n CharCode[CharCode[\"CloseCurlyBrace\"] = 125] = \"CloseCurlyBrace\";\n /**\n * The `~` character.\n */\n CharCode[CharCode[\"Tilde\"] = 126] = \"Tilde\";\n /**\n * The   (no-break space) character.\n * Unicode Character 'NO-BREAK SPACE' (U+00A0)\n */\n CharCode[CharCode[\"NoBreakSpace\"] = 160] = \"NoBreakSpace\";\n CharCode[CharCode[\"U_Combining_Grave_Accent\"] = 768] = \"U_Combining_Grave_Accent\";\n CharCode[CharCode[\"U_Combining_Acute_Accent\"] = 769] = \"U_Combining_Acute_Accent\";\n CharCode[CharCode[\"U_Combining_Circumflex_Accent\"] = 770] = \"U_Combining_Circumflex_Accent\";\n CharCode[CharCode[\"U_Combining_Tilde\"] = 771] = \"U_Combining_Tilde\";\n CharCode[CharCode[\"U_Combining_Macron\"] = 772] = \"U_Combining_Macron\";\n CharCode[CharCode[\"U_Combining_Overline\"] = 773] = \"U_Combining_Overline\";\n CharCode[CharCode[\"U_Combining_Breve\"] = 774] = \"U_Combining_Breve\";\n CharCode[CharCode[\"U_Combining_Dot_Above\"] = 775] = \"U_Combining_Dot_Above\";\n CharCode[CharCode[\"U_Combining_Diaeresis\"] = 776] = \"U_Combining_Diaeresis\";\n CharCode[CharCode[\"U_Combining_Hook_Above\"] = 777] = \"U_Combining_Hook_Above\";\n CharCode[CharCode[\"U_Combining_Ring_Above\"] = 778] = \"U_Combining_Ring_Above\";\n CharCode[CharCode[\"U_Combining_Double_Acute_Accent\"] = 779] = \"U_Combining_Double_Acute_Accent\";\n CharCode[CharCode[\"U_Combining_Caron\"] = 780] = \"U_Combining_Caron\";\n CharCode[CharCode[\"U_Combining_Vertical_Line_Above\"] = 781] = \"U_Combining_Vertical_Line_Above\";\n CharCode[CharCode[\"U_Combining_Double_Vertical_Line_Above\"] = 782] = \"U_Combining_Double_Vertical_Line_Above\";\n CharCode[CharCode[\"U_Combining_Double_Grave_Accent\"] = 783] = \"U_Combining_Double_Grave_Accent\";\n CharCode[CharCode[\"U_Combining_Candrabindu\"] = 784] = \"U_Combining_Candrabindu\";\n CharCode[CharCode[\"U_Combining_Inverted_Breve\"] = 785] = \"U_Combining_Inverted_Breve\";\n CharCode[CharCode[\"U_Combining_Turned_Comma_Above\"] = 786] = \"U_Combining_Turned_Comma_Above\";\n CharCode[CharCode[\"U_Combining_Comma_Above\"] = 787] = \"U_Combining_Comma_Above\";\n CharCode[CharCode[\"U_Combining_Reversed_Comma_Above\"] = 788] = \"U_Combining_Reversed_Comma_Above\";\n CharCode[CharCode[\"U_Combining_Comma_Above_Right\"] = 789] = \"U_Combining_Comma_Above_Right\";\n CharCode[CharCode[\"U_Combining_Grave_Accent_Below\"] = 790] = \"U_Combining_Grave_Accent_Below\";\n CharCode[CharCode[\"U_Combining_Acute_Accent_Below\"] = 791] = \"U_Combining_Acute_Accent_Below\";\n CharCode[CharCode[\"U_Combining_Left_Tack_Below\"] = 792] = \"U_Combining_Left_Tack_Below\";\n CharCode[CharCode[\"U_Combining_Right_Tack_Below\"] = 793] = \"U_Combining_Right_Tack_Below\";\n CharCode[CharCode[\"U_Combining_Left_Angle_Above\"] = 794] = \"U_Combining_Left_Angle_Above\";\n CharCode[CharCode[\"U_Combining_Horn\"] = 795] = \"U_Combining_Horn\";\n CharCode[CharCode[\"U_Combining_Left_Half_Ring_Below\"] = 796] = \"U_Combining_Left_Half_Ring_Below\";\n CharCode[CharCode[\"U_Combining_Up_Tack_Below\"] = 797] = \"U_Combining_Up_Tack_Below\";\n CharCode[CharCode[\"U_Combining_Down_Tack_Below\"] = 798] = \"U_Combining_Down_Tack_Below\";\n CharCode[CharCode[\"U_Combining_Plus_Sign_Below\"] = 799] = \"U_Combining_Plus_Sign_Below\";\n CharCode[CharCode[\"U_Combining_Minus_Sign_Below\"] = 800] = \"U_Combining_Minus_Sign_Below\";\n CharCode[CharCode[\"U_Combining_Palatalized_Hook_Below\"] = 801] = \"U_Combining_Palatalized_Hook_Below\";\n CharCode[CharCode[\"U_Combining_Retroflex_Hook_Below\"] = 802] = \"U_Combining_Retroflex_Hook_Below\";\n CharCode[CharCode[\"U_Combining_Dot_Below\"] = 803] = \"U_Combining_Dot_Below\";\n CharCode[CharCode[\"U_Combining_Diaeresis_Below\"] = 804] = \"U_Combining_Diaeresis_Below\";\n CharCode[CharCode[\"U_Combining_Ring_Below\"] = 805] = \"U_Combining_Ring_Below\";\n CharCode[CharCode[\"U_Combining_Comma_Below\"] = 806] = \"U_Combining_Comma_Below\";\n CharCode[CharCode[\"U_Combining_Cedilla\"] = 807] = \"U_Combining_Cedilla\";\n CharCode[CharCode[\"U_Combining_Ogonek\"] = 808] = \"U_Combining_Ogonek\";\n CharCode[CharCode[\"U_Combining_Vertical_Line_Below\"] = 809] = \"U_Combining_Vertical_Line_Below\";\n CharCode[CharCode[\"U_Combining_Bridge_Below\"] = 810] = \"U_Combining_Bridge_Below\";\n CharCode[CharCode[\"U_Combining_Inverted_Double_Arch_Below\"] = 811] = \"U_Combining_Inverted_Double_Arch_Below\";\n CharCode[CharCode[\"U_Combining_Caron_Below\"] = 812] = \"U_Combining_Caron_Below\";\n CharCode[CharCode[\"U_Combining_Circumflex_Accent_Below\"] = 813] = \"U_Combining_Circumflex_Accent_Below\";\n CharCode[CharCode[\"U_Combining_Breve_Below\"] = 814] = \"U_Combining_Breve_Below\";\n CharCode[CharCode[\"U_Combining_Inverted_Breve_Below\"] = 815] = \"U_Combining_Inverted_Breve_Below\";\n CharCode[CharCode[\"U_Combining_Tilde_Below\"] = 816] = \"U_Combining_Tilde_Below\";\n CharCode[CharCode[\"U_Combining_Macron_Below\"] = 817] = \"U_Combining_Macron_Below\";\n CharCode[CharCode[\"U_Combining_Low_Line\"] = 818] = \"U_Combining_Low_Line\";\n CharCode[CharCode[\"U_Combining_Double_Low_Line\"] = 819] = \"U_Combining_Double_Low_Line\";\n CharCode[CharCode[\"U_Combining_Tilde_Overlay\"] = 820] = \"U_Combining_Tilde_Overlay\";\n CharCode[CharCode[\"U_Combining_Short_Stroke_Overlay\"] = 821] = \"U_Combining_Short_Stroke_Overlay\";\n CharCode[CharCode[\"U_Combining_Long_Stroke_Overlay\"] = 822] = \"U_Combining_Long_Stroke_Overlay\";\n CharCode[CharCode[\"U_Combining_Short_Solidus_Overlay\"] = 823] = \"U_Combining_Short_Solidus_Overlay\";\n CharCode[CharCode[\"U_Combining_Long_Solidus_Overlay\"] = 824] = \"U_Combining_Long_Solidus_Overlay\";\n CharCode[CharCode[\"U_Combining_Right_Half_Ring_Below\"] = 825] = \"U_Combining_Right_Half_Ring_Below\";\n CharCode[CharCode[\"U_Combining_Inverted_Bridge_Below\"] = 826] = \"U_Combining_Inverted_Bridge_Below\";\n CharCode[CharCode[\"U_Combining_Square_Below\"] = 827] = \"U_Combining_Square_Below\";\n CharCode[CharCode[\"U_Combining_Seagull_Below\"] = 828] = \"U_Combining_Seagull_Below\";\n CharCode[CharCode[\"U_Combining_X_Above\"] = 829] = \"U_Combining_X_Above\";\n CharCode[CharCode[\"U_Combining_Vertical_Tilde\"] = 830] = \"U_Combining_Vertical_Tilde\";\n CharCode[CharCode[\"U_Combining_Double_Overline\"] = 831] = \"U_Combining_Double_Overline\";\n CharCode[CharCode[\"U_Combining_Grave_Tone_Mark\"] = 832] = \"U_Combining_Grave_Tone_Mark\";\n CharCode[CharCode[\"U_Combining_Acute_Tone_Mark\"] = 833] = \"U_Combining_Acute_Tone_Mark\";\n CharCode[CharCode[\"U_Combining_Greek_Perispomeni\"] = 834] = \"U_Combining_Greek_Perispomeni\";\n CharCode[CharCode[\"U_Combining_Greek_Koronis\"] = 835] = \"U_Combining_Greek_Koronis\";\n CharCode[CharCode[\"U_Combining_Greek_Dialytika_Tonos\"] = 836] = \"U_Combining_Greek_Dialytika_Tonos\";\n CharCode[CharCode[\"U_Combining_Greek_Ypogegrammeni\"] = 837] = \"U_Combining_Greek_Ypogegrammeni\";\n CharCode[CharCode[\"U_Combining_Bridge_Above\"] = 838] = \"U_Combining_Bridge_Above\";\n CharCode[CharCode[\"U_Combining_Equals_Sign_Below\"] = 839] = \"U_Combining_Equals_Sign_Below\";\n CharCode[CharCode[\"U_Combining_Double_Vertical_Line_Below\"] = 840] = \"U_Combining_Double_Vertical_Line_Below\";\n CharCode[CharCode[\"U_Combining_Left_Angle_Below\"] = 841] = \"U_Combining_Left_Angle_Below\";\n CharCode[CharCode[\"U_Combining_Not_Tilde_Above\"] = 842] = \"U_Combining_Not_Tilde_Above\";\n CharCode[CharCode[\"U_Combining_Homothetic_Above\"] = 843] = \"U_Combining_Homothetic_Above\";\n CharCode[CharCode[\"U_Combining_Almost_Equal_To_Above\"] = 844] = \"U_Combining_Almost_Equal_To_Above\";\n CharCode[CharCode[\"U_Combining_Left_Right_Arrow_Below\"] = 845] = \"U_Combining_Left_Right_Arrow_Below\";\n CharCode[CharCode[\"U_Combining_Upwards_Arrow_Below\"] = 846] = \"U_Combining_Upwards_Arrow_Below\";\n CharCode[CharCode[\"U_Combining_Grapheme_Joiner\"] = 847] = \"U_Combining_Grapheme_Joiner\";\n CharCode[CharCode[\"U_Combining_Right_Arrowhead_Above\"] = 848] = \"U_Combining_Right_Arrowhead_Above\";\n CharCode[CharCode[\"U_Combining_Left_Half_Ring_Above\"] = 849] = \"U_Combining_Left_Half_Ring_Above\";\n CharCode[CharCode[\"U_Combining_Fermata\"] = 850] = \"U_Combining_Fermata\";\n CharCode[CharCode[\"U_Combining_X_Below\"] = 851] = \"U_Combining_X_Below\";\n CharCode[CharCode[\"U_Combining_Left_Arrowhead_Below\"] = 852] = \"U_Combining_Left_Arrowhead_Below\";\n CharCode[CharCode[\"U_Combining_Right_Arrowhead_Below\"] = 853] = \"U_Combining_Right_Arrowhead_Below\";\n CharCode[CharCode[\"U_Combining_Right_Arrowhead_And_Up_Arrowhead_Below\"] = 854] = \"U_Combining_Right_Arrowhead_And_Up_Arrowhead_Below\";\n CharCode[CharCode[\"U_Combining_Right_Half_Ring_Above\"] = 855] = \"U_Combining_Right_Half_Ring_Above\";\n CharCode[CharCode[\"U_Combining_Dot_Above_Right\"] = 856] = \"U_Combining_Dot_Above_Right\";\n CharCode[CharCode[\"U_Combining_Asterisk_Below\"] = 857] = \"U_Combining_Asterisk_Below\";\n CharCode[CharCode[\"U_Combining_Double_Ring_Below\"] = 858] = \"U_Combining_Double_Ring_Below\";\n CharCode[CharCode[\"U_Combining_Zigzag_Above\"] = 859] = \"U_Combining_Zigzag_Above\";\n CharCode[CharCode[\"U_Combining_Double_Breve_Below\"] = 860] = \"U_Combining_Double_Breve_Below\";\n CharCode[CharCode[\"U_Combining_Double_Breve\"] = 861] = \"U_Combining_Double_Breve\";\n CharCode[CharCode[\"U_Combining_Double_Macron\"] = 862] = \"U_Combining_Double_Macron\";\n CharCode[CharCode[\"U_Combining_Double_Macron_Below\"] = 863] = \"U_Combining_Double_Macron_Below\";\n CharCode[CharCode[\"U_Combining_Double_Tilde\"] = 864] = \"U_Combining_Double_Tilde\";\n CharCode[CharCode[\"U_Combining_Double_Inverted_Breve\"] = 865] = \"U_Combining_Double_Inverted_Breve\";\n CharCode[CharCode[\"U_Combining_Double_Rightwards_Arrow_Below\"] = 866] = \"U_Combining_Double_Rightwards_Arrow_Below\";\n CharCode[CharCode[\"U_Combining_Latin_Small_Letter_A\"] = 867] = \"U_Combining_Latin_Small_Letter_A\";\n CharCode[CharCode[\"U_Combining_Latin_Small_Letter_E\"] = 868] = \"U_Combining_Latin_Small_Letter_E\";\n CharCode[CharCode[\"U_Combining_Latin_Small_Letter_I\"] = 869] = \"U_Combining_Latin_Small_Letter_I\";\n CharCode[CharCode[\"U_Combining_Latin_Small_Letter_O\"] = 870] = \"U_Combining_Latin_Small_Letter_O\";\n CharCode[CharCode[\"U_Combining_Latin_Small_Letter_U\"] = 871] = \"U_Combining_Latin_Small_Letter_U\";\n CharCode[CharCode[\"U_Combining_Latin_Small_Letter_C\"] = 872] = \"U_Combining_Latin_Small_Letter_C\";\n CharCode[CharCode[\"U_Combining_Latin_Small_Letter_D\"] = 873] = \"U_Combining_Latin_Small_Letter_D\";\n CharCode[CharCode[\"U_Combining_Latin_Small_Letter_H\"] = 874] = \"U_Combining_Latin_Small_Letter_H\";\n CharCode[CharCode[\"U_Combining_Latin_Small_Letter_M\"] = 875] = \"U_Combining_Latin_Small_Letter_M\";\n CharCode[CharCode[\"U_Combining_Latin_Small_Letter_R\"] = 876] = \"U_Combining_Latin_Small_Letter_R\";\n CharCode[CharCode[\"U_Combining_Latin_Small_Letter_T\"] = 877] = \"U_Combining_Latin_Small_Letter_T\";\n CharCode[CharCode[\"U_Combining_Latin_Small_Letter_V\"] = 878] = \"U_Combining_Latin_Small_Letter_V\";\n CharCode[CharCode[\"U_Combining_Latin_Small_Letter_X\"] = 879] = \"U_Combining_Latin_Small_Letter_X\";\n /**\n * Unicode Character 'LINE SEPARATOR' (U+2028)\n * http://www.fileformat.info/info/unicode/char/2028/index.htm\n */\n CharCode[CharCode[\"LINE_SEPARATOR\"] = 8232] = \"LINE_SEPARATOR\";\n /**\n * Unicode Character 'PARAGRAPH SEPARATOR' (U+2029)\n * http://www.fileformat.info/info/unicode/char/2029/index.htm\n */\n CharCode[CharCode[\"PARAGRAPH_SEPARATOR\"] = 8233] = \"PARAGRAPH_SEPARATOR\";\n /**\n * Unicode Character 'NEXT LINE' (U+0085)\n * http://www.fileformat.info/info/unicode/char/0085/index.htm\n */\n CharCode[CharCode[\"NEXT_LINE\"] = 133] = \"NEXT_LINE\";\n // http://www.fileformat.info/info/unicode/category/Sk/list.htm\n CharCode[CharCode[\"U_CIRCUMFLEX\"] = 94] = \"U_CIRCUMFLEX\";\n CharCode[CharCode[\"U_GRAVE_ACCENT\"] = 96] = \"U_GRAVE_ACCENT\";\n CharCode[CharCode[\"U_DIAERESIS\"] = 168] = \"U_DIAERESIS\";\n CharCode[CharCode[\"U_MACRON\"] = 175] = \"U_MACRON\";\n CharCode[CharCode[\"U_ACUTE_ACCENT\"] = 180] = \"U_ACUTE_ACCENT\";\n CharCode[CharCode[\"U_CEDILLA\"] = 184] = \"U_CEDILLA\";\n CharCode[CharCode[\"U_MODIFIER_LETTER_LEFT_ARROWHEAD\"] = 706] = \"U_MODIFIER_LETTER_LEFT_ARROWHEAD\";\n CharCode[CharCode[\"U_MODIFIER_LETTER_RIGHT_ARROWHEAD\"] = 707] = \"U_MODIFIER_LETTER_RIGHT_ARROWHEAD\";\n CharCode[CharCode[\"U_MODIFIER_LETTER_UP_ARROWHEAD\"] = 708] = \"U_MODIFIER_LETTER_UP_ARROWHEAD\";\n CharCode[CharCode[\"U_MODIFIER_LETTER_DOWN_ARROWHEAD\"] = 709] = \"U_MODIFIER_LETTER_DOWN_ARROWHEAD\";\n CharCode[CharCode[\"U_MODIFIER_LETTER_CENTRED_RIGHT_HALF_RING\"] = 722] = \"U_MODIFIER_LETTER_CENTRED_RIGHT_HALF_RING\";\n CharCode[CharCode[\"U_MODIFIER_LETTER_CENTRED_LEFT_HALF_RING\"] = 723] = \"U_MODIFIER_LETTER_CENTRED_LEFT_HALF_RING\";\n CharCode[CharCode[\"U_MODIFIER_LETTER_UP_TACK\"] = 724] = \"U_MODIFIER_LETTER_UP_TACK\";\n CharCode[CharCode[\"U_MODIFIER_LETTER_DOWN_TACK\"] = 725] = \"U_MODIFIER_LETTER_DOWN_TACK\";\n CharCode[CharCode[\"U_MODIFIER_LETTER_PLUS_SIGN\"] = 726] = \"U_MODIFIER_LETTER_PLUS_SIGN\";\n CharCode[CharCode[\"U_MODIFIER_LETTER_MINUS_SIGN\"] = 727] = \"U_MODIFIER_LETTER_MINUS_SIGN\";\n CharCode[CharCode[\"U_BREVE\"] = 728] = \"U_BREVE\";\n CharCode[CharCode[\"U_DOT_ABOVE\"] = 729] = \"U_DOT_ABOVE\";\n CharCode[CharCode[\"U_RING_ABOVE\"] = 730] = \"U_RING_ABOVE\";\n CharCode[CharCode[\"U_OGONEK\"] = 731] = \"U_OGONEK\";\n CharCode[CharCode[\"U_SMALL_TILDE\"] = 732] = \"U_SMALL_TILDE\";\n CharCode[CharCode[\"U_DOUBLE_ACUTE_ACCENT\"] = 733] = \"U_DOUBLE_ACUTE_ACCENT\";\n CharCode[CharCode[\"U_MODIFIER_LETTER_RHOTIC_HOOK\"] = 734] = \"U_MODIFIER_LETTER_RHOTIC_HOOK\";\n CharCode[CharCode[\"U_MODIFIER_LETTER_CROSS_ACCENT\"] = 735] = \"U_MODIFIER_LETTER_CROSS_ACCENT\";\n CharCode[CharCode[\"U_MODIFIER_LETTER_EXTRA_HIGH_TONE_BAR\"] = 741] = \"U_MODIFIER_LETTER_EXTRA_HIGH_TONE_BAR\";\n CharCode[CharCode[\"U_MODIFIER_LETTER_HIGH_TONE_BAR\"] = 742] = \"U_MODIFIER_LETTER_HIGH_TONE_BAR\";\n CharCode[CharCode[\"U_MODIFIER_LETTER_MID_TONE_BAR\"] = 743] = \"U_MODIFIER_LETTER_MID_TONE_BAR\";\n CharCode[CharCode[\"U_MODIFIER_LETTER_LOW_TONE_BAR\"] = 744] = \"U_MODIFIER_LETTER_LOW_TONE_BAR\";\n CharCode[CharCode[\"U_MODIFIER_LETTER_EXTRA_LOW_TONE_BAR\"] = 745] = \"U_MODIFIER_LETTER_EXTRA_LOW_TONE_BAR\";\n CharCode[CharCode[\"U_MODIFIER_LETTER_YIN_DEPARTING_TONE_MARK\"] = 746] = \"U_MODIFIER_LETTER_YIN_DEPARTING_TONE_MARK\";\n CharCode[CharCode[\"U_MODIFIER_LETTER_YANG_DEPARTING_TONE_MARK\"] = 747] = \"U_MODIFIER_LETTER_YANG_DEPARTING_TONE_MARK\";\n CharCode[CharCode[\"U_MODIFIER_LETTER_UNASPIRATED\"] = 749] = \"U_MODIFIER_LETTER_UNASPIRATED\";\n CharCode[CharCode[\"U_MODIFIER_LETTER_LOW_DOWN_ARROWHEAD\"] = 751] = \"U_MODIFIER_LETTER_LOW_DOWN_ARROWHEAD\";\n CharCode[CharCode[\"U_MODIFIER_LETTER_LOW_UP_ARROWHEAD\"] = 752] = \"U_MODIFIER_LETTER_LOW_UP_ARROWHEAD\";\n CharCode[CharCode[\"U_MODIFIER_LETTER_LOW_LEFT_ARROWHEAD\"] = 753] = \"U_MODIFIER_LETTER_LOW_LEFT_ARROWHEAD\";\n CharCode[CharCode[\"U_MODIFIER_LETTER_LOW_RIGHT_ARROWHEAD\"] = 754] = \"U_MODIFIER_LETTER_LOW_RIGHT_ARROWHEAD\";\n CharCode[CharCode[\"U_MODIFIER_LETTER_LOW_RING\"] = 755] = \"U_MODIFIER_LETTER_LOW_RING\";\n CharCode[CharCode[\"U_MODIFIER_LETTER_MIDDLE_GRAVE_ACCENT\"] = 756] = \"U_MODIFIER_LETTER_MIDDLE_GRAVE_ACCENT\";\n CharCode[CharCode[\"U_MODIFIER_LETTER_MIDDLE_DOUBLE_GRAVE_ACCENT\"] = 757] = \"U_MODIFIER_LETTER_MIDDLE_DOUBLE_GRAVE_ACCENT\";\n CharCode[CharCode[\"U_MODIFIER_LETTER_MIDDLE_DOUBLE_ACUTE_ACCENT\"] = 758] = \"U_MODIFIER_LETTER_MIDDLE_DOUBLE_ACUTE_ACCENT\";\n CharCode[CharCode[\"U_MODIFIER_LETTER_LOW_TILDE\"] = 759] = \"U_MODIFIER_LETTER_LOW_TILDE\";\n CharCode[CharCode[\"U_MODIFIER_LETTER_RAISED_COLON\"] = 760] = \"U_MODIFIER_LETTER_RAISED_COLON\";\n CharCode[CharCode[\"U_MODIFIER_LETTER_BEGIN_HIGH_TONE\"] = 761] = \"U_MODIFIER_LETTER_BEGIN_HIGH_TONE\";\n CharCode[CharCode[\"U_MODIFIER_LETTER_END_HIGH_TONE\"] = 762] = \"U_MODIFIER_LETTER_END_HIGH_TONE\";\n CharCode[CharCode[\"U_MODIFIER_LETTER_BEGIN_LOW_TONE\"] = 763] = \"U_MODIFIER_LETTER_BEGIN_LOW_TONE\";\n CharCode[CharCode[\"U_MODIFIER_LETTER_END_LOW_TONE\"] = 764] = \"U_MODIFIER_LETTER_END_LOW_TONE\";\n CharCode[CharCode[\"U_MODIFIER_LETTER_SHELF\"] = 765] = \"U_MODIFIER_LETTER_SHELF\";\n CharCode[CharCode[\"U_MODIFIER_LETTER_OPEN_SHELF\"] = 766] = \"U_MODIFIER_LETTER_OPEN_SHELF\";\n CharCode[CharCode[\"U_MODIFIER_LETTER_LOW_LEFT_ARROW\"] = 767] = \"U_MODIFIER_LETTER_LOW_LEFT_ARROW\";\n CharCode[CharCode[\"U_GREEK_LOWER_NUMERAL_SIGN\"] = 885] = \"U_GREEK_LOWER_NUMERAL_SIGN\";\n CharCode[CharCode[\"U_GREEK_TONOS\"] = 900] = \"U_GREEK_TONOS\";\n CharCode[CharCode[\"U_GREEK_DIALYTIKA_TONOS\"] = 901] = \"U_GREEK_DIALYTIKA_TONOS\";\n CharCode[CharCode[\"U_GREEK_KORONIS\"] = 8125] = \"U_GREEK_KORONIS\";\n CharCode[CharCode[\"U_GREEK_PSILI\"] = 8127] = \"U_GREEK_PSILI\";\n CharCode[CharCode[\"U_GREEK_PERISPOMENI\"] = 8128] = \"U_GREEK_PERISPOMENI\";\n CharCode[CharCode[\"U_GREEK_DIALYTIKA_AND_PERISPOMENI\"] = 8129] = \"U_GREEK_DIALYTIKA_AND_PERISPOMENI\";\n CharCode[CharCode[\"U_GREEK_PSILI_AND_VARIA\"] = 8141] = \"U_GREEK_PSILI_AND_VARIA\";\n CharCode[CharCode[\"U_GREEK_PSILI_AND_OXIA\"] = 8142] = \"U_GREEK_PSILI_AND_OXIA\";\n CharCode[CharCode[\"U_GREEK_PSILI_AND_PERISPOMENI\"] = 8143] = \"U_GREEK_PSILI_AND_PERISPOMENI\";\n CharCode[CharCode[\"U_GREEK_DASIA_AND_VARIA\"] = 8157] = \"U_GREEK_DASIA_AND_VARIA\";\n CharCode[CharCode[\"U_GREEK_DASIA_AND_OXIA\"] = 8158] = \"U_GREEK_DASIA_AND_OXIA\";\n CharCode[CharCode[\"U_GREEK_DASIA_AND_PERISPOMENI\"] = 8159] = \"U_GREEK_DASIA_AND_PERISPOMENI\";\n CharCode[CharCode[\"U_GREEK_DIALYTIKA_AND_VARIA\"] = 8173] = \"U_GREEK_DIALYTIKA_AND_VARIA\";\n CharCode[CharCode[\"U_GREEK_DIALYTIKA_AND_OXIA\"] = 8174] = \"U_GREEK_DIALYTIKA_AND_OXIA\";\n CharCode[CharCode[\"U_GREEK_VARIA\"] = 8175] = \"U_GREEK_VARIA\";\n CharCode[CharCode[\"U_GREEK_OXIA\"] = 8189] = \"U_GREEK_OXIA\";\n CharCode[CharCode[\"U_GREEK_DASIA\"] = 8190] = \"U_GREEK_DASIA\";\n CharCode[CharCode[\"U_IDEOGRAPHIC_FULL_STOP\"] = 12290] = \"U_IDEOGRAPHIC_FULL_STOP\";\n CharCode[CharCode[\"U_LEFT_CORNER_BRACKET\"] = 12300] = \"U_LEFT_CORNER_BRACKET\";\n CharCode[CharCode[\"U_RIGHT_CORNER_BRACKET\"] = 12301] = \"U_RIGHT_CORNER_BRACKET\";\n CharCode[CharCode[\"U_LEFT_BLACK_LENTICULAR_BRACKET\"] = 12304] = \"U_LEFT_BLACK_LENTICULAR_BRACKET\";\n CharCode[CharCode[\"U_RIGHT_BLACK_LENTICULAR_BRACKET\"] = 12305] = \"U_RIGHT_BLACK_LENTICULAR_BRACKET\";\n CharCode[CharCode[\"U_OVERLINE\"] = 8254] = \"U_OVERLINE\";\n /**\n * UTF-8 BOM\n * Unicode Character 'ZERO WIDTH NO-BREAK SPACE' (U+FEFF)\n * http://www.fileformat.info/info/unicode/char/feff/index.htm\n */\n CharCode[CharCode[\"UTF8_BOM\"] = 65279] = \"UTF8_BOM\";\n CharCode[CharCode[\"U_FULLWIDTH_SEMICOLON\"] = 65307] = \"U_FULLWIDTH_SEMICOLON\";\n CharCode[CharCode[\"U_FULLWIDTH_COMMA\"] = 65292] = \"U_FULLWIDTH_COMMA\";\n})(CharCode || (exports.CharCode = CharCode = {}));\n","\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nvar _a;\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.SetWithKey = void 0;\nexports.groupBy = groupBy;\nexports.diffSets = diffSets;\nexports.diffMaps = diffMaps;\nexports.intersection = intersection;\n/**\n * Groups the collection into a dictionary based on the provided\n * group function.\n */\nfunction groupBy(data, groupFn) {\n const result = Object.create(null);\n for (const element of data) {\n const key = groupFn(element);\n let target = result[key];\n if (!target) {\n target = result[key] = [];\n }\n target.push(element);\n }\n return result;\n}\nfunction diffSets(before, after) {\n const removed = [];\n const added = [];\n for (const element of before) {\n if (!after.has(element)) {\n removed.push(element);\n }\n }\n for (const element of after) {\n if (!before.has(element)) {\n added.push(element);\n }\n }\n return { removed, added };\n}\nfunction diffMaps(before, after) {\n const removed = [];\n const added = [];\n for (const [index, value] of before) {\n if (!after.has(index)) {\n removed.push(value);\n }\n }\n for (const [index, value] of after) {\n if (!before.has(index)) {\n added.push(value);\n }\n }\n return { removed, added };\n}\n/**\n * Computes the intersection of two sets.\n *\n * @param setA - The first set.\n * @param setB - The second iterable.\n * @returns A new set containing the elements that are in both `setA` and `setB`.\n */\nfunction intersection(setA, setB) {\n const result = new Set();\n for (const elem of setB) {\n if (setA.has(elem)) {\n result.add(elem);\n }\n }\n return result;\n}\nclass SetWithKey {\n static { _a = Symbol.toStringTag; }\n constructor(values, toKey) {\n this.toKey = toKey;\n this._map = new Map();\n this[_a] = 'SetWithKey';\n for (const value of values) {\n this.add(value);\n }\n }\n get size() {\n return this._map.size;\n }\n add(value) {\n const key = this.toKey(value);\n this._map.set(key, value);\n return this;\n }\n delete(value) {\n return this._map.delete(this.toKey(value));\n }\n has(value) {\n return this._map.has(this.toKey(value));\n }\n *entries() {\n for (const entry of this._map.values()) {\n yield [entry, entry];\n }\n }\n keys() {\n return this.values();\n }\n *values() {\n for (const entry of this._map.values()) {\n yield entry;\n }\n }\n clear() {\n this._map.clear();\n }\n forEach(callbackfn, thisArg) {\n this._map.forEach(entry => callbackfn.call(thisArg, entry, entry, this));\n }\n [Symbol.iterator]() {\n return this.values();\n }\n}\nexports.SetWithKey = SetWithKey;\n","\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.memoize = memoize;\nexports.debounce = debounce;\nexports.throttle = throttle;\nfunction createDecorator(mapFn) {\n return (target, key, descriptor) => {\n let fnKey = null;\n let fn = null;\n if (typeof descriptor.value === 'function') {\n fnKey = 'value';\n fn = descriptor.value;\n }\n else if (typeof descriptor.get === 'function') {\n fnKey = 'get';\n fn = descriptor.get;\n }\n if (!fn) {\n throw new Error('not supported');\n }\n descriptor[fnKey] = mapFn(fn, key);\n };\n}\nfunction memoize(_target, key, descriptor) {\n let fnKey = null;\n let fn = null;\n if (typeof descriptor.value === 'function') {\n fnKey = 'value';\n fn = descriptor.value;\n if (fn.length !== 0) {\n console.warn('Memoize should only be used in functions with zero parameters');\n }\n }\n else if (typeof descriptor.get === 'function') {\n fnKey = 'get';\n fn = descriptor.get;\n }\n if (!fn) {\n throw new Error('not supported');\n }\n const memoizeKey = `$memoize$${key}`;\n descriptor[fnKey] = function (...args) {\n if (!this.hasOwnProperty(memoizeKey)) {\n Object.defineProperty(this, memoizeKey, {\n configurable: false,\n enumerable: false,\n writable: false,\n value: fn.apply(this, args)\n });\n }\n return this[memoizeKey];\n };\n}\nfunction debounce(delay, reducer, initialValueProvider) {\n return createDecorator((fn, key) => {\n const timerKey = `$debounce$${key}`;\n const resultKey = `$debounce$result$${key}`;\n return function (...args) {\n if (!this[resultKey]) {\n this[resultKey] = initialValueProvider ? initialValueProvider() : undefined;\n }\n clearTimeout(this[timerKey]);\n if (reducer) {\n this[resultKey] = reducer(this[resultKey], ...args);\n args = [this[resultKey]];\n }\n this[timerKey] = setTimeout(() => {\n fn.apply(this, args);\n this[resultKey] = initialValueProvider ? initialValueProvider() : undefined;\n }, delay);\n };\n });\n}\nfunction throttle(delay, reducer, initialValueProvider) {\n return createDecorator((fn, key) => {\n const timerKey = `$throttle$timer$${key}`;\n const resultKey = `$throttle$result$${key}`;\n const lastRunKey = `$throttle$lastRun$${key}`;\n const pendingKey = `$throttle$pending$${key}`;\n return function (...args) {\n if (!this[resultKey]) {\n this[resultKey] = initialValueProvider ? initialValueProvider() : undefined;\n }\n if (this[lastRunKey] === null || this[lastRunKey] === undefined) {\n this[lastRunKey] = -Number.MAX_VALUE;\n }\n if (reducer) {\n this[resultKey] = reducer(this[resultKey], ...args);\n }\n if (this[pendingKey]) {\n return;\n }\n const nextTime = this[lastRunKey] + delay;\n if (nextTime <= Date.now()) {\n this[lastRunKey] = Date.now();\n fn.apply(this, [this[resultKey]]);\n this[resultKey] = initialValueProvider ? initialValueProvider() : undefined;\n }\n else {\n this[pendingKey] = true;\n this[timerKey] = setTimeout(() => {\n this[pendingKey] = false;\n this[lastRunKey] = Date.now();\n fn.apply(this, [this[resultKey]]);\n this[resultKey] = initialValueProvider ? initialValueProvider() : undefined;\n }, nextTime - Date.now());\n }\n };\n });\n}\n","\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.BugIndicatingError = exports.ErrorNoTelemetry = exports.ExpectedError = exports.NotSupportedError = exports.NotImplementedError = exports.ReadonlyError = exports.CancellationError = exports.errorHandler = exports.ErrorHandler = void 0;\nexports.setUnexpectedErrorHandler = setUnexpectedErrorHandler;\nexports.isSigPipeError = isSigPipeError;\nexports.onUnexpectedError = onUnexpectedError;\nexports.onUnexpectedExternalError = onUnexpectedExternalError;\nexports.transformErrorForSerialization = transformErrorForSerialization;\nexports.transformErrorFromSerialization = transformErrorFromSerialization;\nexports.isCancellationError = isCancellationError;\nexports.canceled = canceled;\nexports.illegalArgument = illegalArgument;\nexports.illegalState = illegalState;\nexports.getErrorMessage = getErrorMessage;\n// Avoid circular dependency on EventEmitter by implementing a subset of the interface.\nclass ErrorHandler {\n constructor() {\n this.listeners = [];\n this.unexpectedErrorHandler = function (e) {\n setTimeout(() => {\n if (e.stack) {\n if (ErrorNoTelemetry.isErrorNoTelemetry(e)) {\n throw new ErrorNoTelemetry(e.message + '\\n\\n' + e.stack);\n }\n throw new Error(e.message + '\\n\\n' + e.stack);\n }\n throw e;\n }, 0);\n };\n }\n addListener(listener) {\n this.listeners.push(listener);\n return () => {\n this._removeListener(listener);\n };\n }\n emit(e) {\n this.listeners.forEach((listener) => {\n listener(e);\n });\n }\n _removeListener(listener) {\n this.listeners.splice(this.listeners.indexOf(listener), 1);\n }\n setUnexpectedErrorHandler(newUnexpectedErrorHandler) {\n this.unexpectedErrorHandler = newUnexpectedErrorHandler;\n }\n getUnexpectedErrorHandler() {\n return this.unexpectedErrorHandler;\n }\n onUnexpectedError(e) {\n this.unexpectedErrorHandler(e);\n this.emit(e);\n }\n // For external errors, we don't want the listeners to be called\n onUnexpectedExternalError(e) {\n this.unexpectedErrorHandler(e);\n }\n}\nexports.ErrorHandler = ErrorHandler;\nexports.errorHandler = new ErrorHandler();\n/** @skipMangle */\nfunction setUnexpectedErrorHandler(newUnexpectedErrorHandler) {\n exports.errorHandler.setUnexpectedErrorHandler(newUnexpectedErrorHandler);\n}\n/**\n * Returns if the error is a SIGPIPE error. SIGPIPE errors should generally be\n * logged at most once, to avoid a loop.\n *\n * @see https://github.com/microsoft/vscode-remote-release/issues/6481\n */\nfunction isSigPipeError(e) {\n if (!e || typeof e !== 'object') {\n return false;\n }\n const cast = e;\n return cast.code === 'EPIPE' && cast.syscall?.toUpperCase() === 'WRITE';\n}\nfunction onUnexpectedError(e) {\n // ignore errors from cancelled promises\n if (!isCancellationError(e)) {\n exports.errorHandler.onUnexpectedError(e);\n }\n return undefined;\n}\nfunction onUnexpectedExternalError(e) {\n // ignore errors from cancelled promises\n if (!isCancellationError(e)) {\n exports.errorHandler.onUnexpectedExternalError(e);\n }\n return undefined;\n}\nfunction transformErrorForSerialization(error) {\n if (error instanceof Error) {\n const { name, message } = error;\n const stack = error.stacktrace || error.stack;\n return {\n $isError: true,\n name,\n message,\n stack,\n noTelemetry: ErrorNoTelemetry.isErrorNoTelemetry(error)\n };\n }\n // return as is\n return error;\n}\nfunction transformErrorFromSerialization(data) {\n let error;\n if (data.noTelemetry) {\n error = new ErrorNoTelemetry();\n }\n else {\n error = new Error();\n error.name = data.name;\n }\n error.message = data.message;\n error.stack = data.stack;\n return error;\n}\nconst canceledName = 'Canceled';\n/**\n * Checks if the given error is a promise in canceled state\n */\nfunction isCancellationError(error) {\n if (error instanceof CancellationError) {\n return true;\n }\n return error instanceof Error && error.name === canceledName && error.message === canceledName;\n}\n// !!!IMPORTANT!!!\n// Do NOT change this class because it is also used as an API-type.\nclass CancellationError extends Error {\n constructor() {\n super(canceledName);\n this.name = this.message;\n }\n}\nexports.CancellationError = CancellationError;\n/**\n * @deprecated use {@link CancellationError `new CancellationError()`} instead\n */\nfunction canceled() {\n const error = new Error(canceledName);\n error.name = error.message;\n return error;\n}\nfunction illegalArgument(name) {\n if (name) {\n return new Error(`Illegal argument: ${name}`);\n }\n else {\n return new Error('Illegal argument');\n }\n}\nfunction illegalState(name) {\n if (name) {\n return new Error(`Illegal state: ${name}`);\n }\n else {\n return new Error('Illegal state');\n }\n}\nclass ReadonlyError extends TypeError {\n constructor(name) {\n super(name ? `${name} is read-only and cannot be changed` : 'Cannot change read-only property');\n }\n}\nexports.ReadonlyError = ReadonlyError;\nfunction getErrorMessage(err) {\n if (!err) {\n return 'Error';\n }\n if (err.message) {\n return err.message;\n }\n if (err.stack) {\n return err.stack.split('\\n')[0];\n }\n return String(err);\n}\nclass NotImplementedError extends Error {\n constructor(message) {\n super('NotImplemented');\n if (message) {\n this.message = message;\n }\n }\n}\nexports.NotImplementedError = NotImplementedError;\nclass NotSupportedError extends Error {\n constructor(message) {\n super('NotSupported');\n if (message) {\n this.message = message;\n }\n }\n}\nexports.NotSupportedError = NotSupportedError;\nclass ExpectedError extends Error {\n constructor() {\n super(...arguments);\n this.isExpected = true;\n }\n}\nexports.ExpectedError = ExpectedError;\n/**\n * Error that when thrown won't be logged in telemetry as an unhandled error.\n */\nclass ErrorNoTelemetry extends Error {\n constructor(msg) {\n super(msg);\n this.name = 'CodeExpectedError';\n }\n static fromError(err) {\n if (err instanceof ErrorNoTelemetry) {\n return err;\n }\n const result = new ErrorNoTelemetry();\n result.message = err.message;\n result.stack = err.stack;\n return result;\n }\n static isErrorNoTelemetry(err) {\n return err.name === 'CodeExpectedError';\n }\n}\nexports.ErrorNoTelemetry = ErrorNoTelemetry;\n/**\n * This error indicates a bug.\n * Do not throw this for invalid user input.\n * Only catch this error to recover gracefully from bugs.\n */\nclass BugIndicatingError extends Error {\n constructor(message) {\n super(message || 'An unexpected bug occurred.');\n Object.setPrototypeOf(this, BugIndicatingError.prototype);\n // Because we know for sure only buggy code throws this,\n // we definitely want to break here and fix the bug.\n // eslint-disable-next-line no-debugger\n // debugger;\n }\n}\nexports.BugIndicatingError = BugIndicatingError;\n","\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ValueWithChangeEvent = exports.Relay = exports.EventBufferer = exports.DynamicListEventMultiplexer = exports.EventMultiplexer = exports.MicrotaskEmitter = exports.DebounceEmitter = exports.PauseableEmitter = exports.AsyncEmitter = exports.createEventDeliveryQueue = exports.Emitter = exports.ListenerRefusalError = exports.ListenerLeakError = exports.EventProfiling = exports.Event = void 0;\nexports.setGlobalLeakWarningThreshold = setGlobalLeakWarningThreshold;\nconst errors_1 = require(\"vs/base/common/errors\");\nconst functional_1 = require(\"vs/base/common/functional\");\nconst lifecycle_1 = require(\"vs/base/common/lifecycle\");\nconst linkedList_1 = require(\"vs/base/common/linkedList\");\nconst stopwatch_1 = require(\"vs/base/common/stopwatch\");\n// -----------------------------------------------------------------------------------------------------------------------\n// Uncomment the next line to print warnings whenever a listener is GC'ed without having been disposed. This is a LEAK.\n// -----------------------------------------------------------------------------------------------------------------------\nconst _enableListenerGCedWarning = false;\n// -----------------------------------------------------------------------------------------------------------------------\n// Uncomment the next line to print warnings whenever an emitter with listeners is disposed. That is a sign of code smell.\n// -----------------------------------------------------------------------------------------------------------------------\nconst _enableDisposeWithListenerWarning = false;\n// -----------------------------------------------------------------------------------------------------------------------\n// Uncomment the next line to print warnings whenever a snapshotted event is used repeatedly without cleanup.\n// See https://github.com/microsoft/vscode/issues/142851\n// -----------------------------------------------------------------------------------------------------------------------\nconst _enableSnapshotPotentialLeakWarning = false;\nvar Event;\n(function (Event) {\n Event.None = () => lifecycle_1.Disposable.None;\n function _addLeakageTraceLogic(options) {\n if (_enableSnapshotPotentialLeakWarning) {\n const { onDidAddListener: origListenerDidAdd } = options;\n const stack = Stacktrace.create();\n let count = 0;\n options.onDidAddListener = () => {\n if (++count === 2) {\n console.warn('snapshotted emitter LIKELY used public and SHOULD HAVE BEEN created with DisposableStore. snapshotted here');\n stack.print();\n }\n origListenerDidAdd?.();\n };\n }\n }\n /**\n * Given an event, returns another event which debounces calls and defers the listeners to a later task via a shared\n * `setTimeout`. The event is converted into a signal (`Event`) to avoid additional object creation as a\n * result of merging events and to try prevent race conditions that could arise when using related deferred and\n * non-deferred events.\n *\n * This is useful for deferring non-critical work (eg. general UI updates) to ensure it does not block critical work\n * (eg. latency of keypress to text rendered).\n *\n * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned\n * event is accessible to \"third parties\", e.g the event is a public property. Otherwise a leaked listener on the\n * returned event causes this utility to leak a listener on the original event.\n *\n * @param event The event source for the new event.\n * @param disposable A disposable store to add the new EventEmitter to.\n */\n function defer(event, disposable) {\n return debounce(event, () => void 0, 0, undefined, true, undefined, disposable);\n }\n Event.defer = defer;\n /**\n * Given an event, returns another event which only fires once.\n *\n * @param event The event source for the new event.\n */\n function once(event) {\n return (listener, thisArgs = null, disposables) => {\n // we need this, in case the event fires during the listener call\n let didFire = false;\n let result = undefined;\n result = event(e => {\n if (didFire) {\n return;\n }\n else if (result) {\n result.dispose();\n }\n else {\n didFire = true;\n }\n return listener.call(thisArgs, e);\n }, null, disposables);\n if (didFire) {\n result.dispose();\n }\n return result;\n };\n }\n Event.once = once;\n /**\n * Maps an event of one type into an event of another type using a mapping function, similar to how\n * `Array.prototype.map` works.\n *\n * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned\n * event is accessible to \"third parties\", e.g the event is a public property. Otherwise a leaked listener on the\n * returned event causes this utility to leak a listener on the original event.\n *\n * @param event The event source for the new event.\n * @param map The mapping function.\n * @param disposable A disposable store to add the new EventEmitter to.\n */\n function map(event, map, disposable) {\n return snapshot((listener, thisArgs = null, disposables) => event(i => listener.call(thisArgs, map(i)), null, disposables), disposable);\n }\n Event.map = map;\n /**\n * Wraps an event in another event that performs some function on the event object before firing.\n *\n * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned\n * event is accessible to \"third parties\", e.g the event is a public property. Otherwise a leaked listener on the\n * returned event causes this utility to leak a listener on the original event.\n *\n * @param event The event source for the new event.\n * @param each The function to perform on the event object.\n * @param disposable A disposable store to add the new EventEmitter to.\n */\n function forEach(event, each, disposable) {\n return snapshot((listener, thisArgs = null, disposables) => event(i => { each(i); listener.call(thisArgs, i); }, null, disposables), disposable);\n }\n Event.forEach = forEach;\n function filter(event, filter, disposable) {\n return snapshot((listener, thisArgs = null, disposables) => event(e => filter(e) && listener.call(thisArgs, e), null, disposables), disposable);\n }\n Event.filter = filter;\n /**\n * Given an event, returns the same event but typed as `Event`.\n */\n function signal(event) {\n return event;\n }\n Event.signal = signal;\n function any(...events) {\n return (listener, thisArgs = null, disposables) => {\n const disposable = (0, lifecycle_1.combinedDisposable)(...events.map(event => event(e => listener.call(thisArgs, e))));\n return addAndReturnDisposable(disposable, disposables);\n };\n }\n Event.any = any;\n /**\n * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned\n * event is accessible to \"third parties\", e.g the event is a public property. Otherwise a leaked listener on the\n * returned event causes this utility to leak a listener on the original event.\n */\n function reduce(event, merge, initial, disposable) {\n let output = initial;\n return map(event, e => {\n output = merge(output, e);\n return output;\n }, disposable);\n }\n Event.reduce = reduce;\n function snapshot(event, disposable) {\n let listener;\n const options = {\n onWillAddFirstListener() {\n listener = event(emitter.fire, emitter);\n },\n onDidRemoveLastListener() {\n listener?.dispose();\n }\n };\n if (!disposable) {\n _addLeakageTraceLogic(options);\n }\n const emitter = new Emitter(options);\n disposable?.add(emitter);\n return emitter.event;\n }\n /**\n * Adds the IDisposable to the store if it's set, and returns it. Useful to\n * Event function implementation.\n */\n function addAndReturnDisposable(d, store) {\n if (store instanceof Array) {\n store.push(d);\n }\n else if (store) {\n store.add(d);\n }\n return d;\n }\n function debounce(event, merge, delay = 100, leading = false, flushOnListenerRemove = false, leakWarningThreshold, disposable) {\n let subscription;\n let output = undefined;\n let handle = undefined;\n let numDebouncedCalls = 0;\n let doFire;\n const options = {\n leakWarningThreshold,\n onWillAddFirstListener() {\n subscription = event(cur => {\n numDebouncedCalls++;\n output = merge(output, cur);\n if (leading && !handle) {\n emitter.fire(output);\n output = undefined;\n }\n doFire = () => {\n const _output = output;\n output = undefined;\n handle = undefined;\n if (!leading || numDebouncedCalls > 1) {\n emitter.fire(_output);\n }\n numDebouncedCalls = 0;\n };\n if (typeof delay === 'number') {\n clearTimeout(handle);\n handle = setTimeout(doFire, delay);\n }\n else {\n if (handle === undefined) {\n handle = 0;\n queueMicrotask(doFire);\n }\n }\n });\n },\n onWillRemoveListener() {\n if (flushOnListenerRemove && numDebouncedCalls > 0) {\n doFire?.();\n }\n },\n onDidRemoveLastListener() {\n doFire = undefined;\n subscription.dispose();\n }\n };\n if (!disposable) {\n _addLeakageTraceLogic(options);\n }\n const emitter = new Emitter(options);\n disposable?.add(emitter);\n return emitter.event;\n }\n Event.debounce = debounce;\n /**\n * Debounces an event, firing after some delay (default=0) with an array of all event original objects.\n *\n * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned\n * event is accessible to \"third parties\", e.g the event is a public property. Otherwise a leaked listener on the\n * returned event causes this utility to leak a listener on the original event.\n */\n function accumulate(event, delay = 0, disposable) {\n return Event.debounce(event, (last, e) => {\n if (!last) {\n return [e];\n }\n last.push(e);\n return last;\n }, delay, undefined, true, undefined, disposable);\n }\n Event.accumulate = accumulate;\n /**\n * Filters an event such that some condition is _not_ met more than once in a row, effectively ensuring duplicate\n * event objects from different sources do not fire the same event object.\n *\n * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned\n * event is accessible to \"third parties\", e.g the event is a public property. Otherwise a leaked listener on the\n * returned event causes this utility to leak a listener on the original event.\n *\n * @param event The event source for the new event.\n * @param equals The equality condition.\n * @param disposable A disposable store to add the new EventEmitter to.\n *\n * @example\n * ```\n * // Fire only one time when a single window is opened or focused\n * Event.latch(Event.any(onDidOpenWindow, onDidFocusWindow))\n * ```\n */\n function latch(event, equals = (a, b) => a === b, disposable) {\n let firstCall = true;\n let cache;\n return filter(event, value => {\n const shouldEmit = firstCall || !equals(value, cache);\n firstCall = false;\n cache = value;\n return shouldEmit;\n }, disposable);\n }\n Event.latch = latch;\n /**\n * Splits an event whose parameter is a union type into 2 separate events for each type in the union.\n *\n * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned\n * event is accessible to \"third parties\", e.g the event is a public property. Otherwise a leaked listener on the\n * returned event causes this utility to leak a listener on the original event.\n *\n * @example\n * ```\n * const event = new EventEmitter().event;\n * const [numberEvent, undefinedEvent] = Event.split(event, isUndefined);\n * ```\n *\n * @param event The event source for the new event.\n * @param isT A function that determines what event is of the first type.\n * @param disposable A disposable store to add the new EventEmitter to.\n */\n function split(event, isT, disposable) {\n return [\n Event.filter(event, isT, disposable),\n Event.filter(event, e => !isT(e), disposable),\n ];\n }\n Event.split = split;\n /**\n * Buffers an event until it has a listener attached.\n *\n * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned\n * event is accessible to \"third parties\", e.g the event is a public property. Otherwise a leaked listener on the\n * returned event causes this utility to leak a listener on the original event.\n *\n * @param event The event source for the new event.\n * @param flushAfterTimeout Determines whether to flush the buffer after a timeout immediately or after a\n * `setTimeout` when the first event listener is added.\n * @param _buffer Internal: A source event array used for tests.\n *\n * @example\n * ```\n * // Start accumulating events, when the first listener is attached, flush\n * // the event after a timeout such that multiple listeners attached before\n * // the timeout would receive the event\n * this.onInstallExtension = Event.buffer(service.onInstallExtension, true);\n * ```\n */\n function buffer(event, flushAfterTimeout = false, _buffer = [], disposable) {\n let buffer = _buffer.slice();\n let listener = event(e => {\n if (buffer) {\n buffer.push(e);\n }\n else {\n emitter.fire(e);\n }\n });\n if (disposable) {\n disposable.add(listener);\n }\n const flush = () => {\n buffer?.forEach(e => emitter.fire(e));\n buffer = null;\n };\n const emitter = new Emitter({\n onWillAddFirstListener() {\n if (!listener) {\n listener = event(e => emitter.fire(e));\n if (disposable) {\n disposable.add(listener);\n }\n }\n },\n onDidAddFirstListener() {\n if (buffer) {\n if (flushAfterTimeout) {\n setTimeout(flush);\n }\n else {\n flush();\n }\n }\n },\n onDidRemoveLastListener() {\n if (listener) {\n listener.dispose();\n }\n listener = null;\n }\n });\n if (disposable) {\n disposable.add(emitter);\n }\n return emitter.event;\n }\n Event.buffer = buffer;\n /**\n * Wraps the event in an {@link IChainableEvent}, allowing a more functional programming style.\n *\n * @example\n * ```\n * // Normal\n * const onEnterPressNormal = Event.filter(\n * Event.map(onKeyPress.event, e => new StandardKeyboardEvent(e)),\n * e.keyCode === KeyCode.Enter\n * ).event;\n *\n * // Using chain\n * const onEnterPressChain = Event.chain(onKeyPress.event, $ => $\n * .map(e => new StandardKeyboardEvent(e))\n * .filter(e => e.keyCode === KeyCode.Enter)\n * );\n * ```\n */\n function chain(event, sythensize) {\n const fn = (listener, thisArgs, disposables) => {\n const cs = sythensize(new ChainableSynthesis());\n return event(function (value) {\n const result = cs.evaluate(value);\n if (result !== HaltChainable) {\n listener.call(thisArgs, result);\n }\n }, undefined, disposables);\n };\n return fn;\n }\n Event.chain = chain;\n const HaltChainable = Symbol('HaltChainable');\n class ChainableSynthesis {\n constructor() {\n this.steps = [];\n }\n map(fn) {\n this.steps.push(fn);\n return this;\n }\n forEach(fn) {\n this.steps.push(v => {\n fn(v);\n return v;\n });\n return this;\n }\n filter(fn) {\n this.steps.push(v => fn(v) ? v : HaltChainable);\n return this;\n }\n reduce(merge, initial) {\n let last = initial;\n this.steps.push(v => {\n last = merge(last, v);\n return last;\n });\n return this;\n }\n latch(equals = (a, b) => a === b) {\n let firstCall = true;\n let cache;\n this.steps.push(value => {\n const shouldEmit = firstCall || !equals(value, cache);\n firstCall = false;\n cache = value;\n return shouldEmit ? value : HaltChainable;\n });\n return this;\n }\n evaluate(value) {\n for (const step of this.steps) {\n value = step(value);\n if (value === HaltChainable) {\n break;\n }\n }\n return value;\n }\n }\n /**\n * Creates an {@link Event} from a node event emitter.\n */\n function fromNodeEventEmitter(emitter, eventName, map = id => id) {\n const fn = (...args) => result.fire(map(...args));\n const onFirstListenerAdd = () => emitter.on(eventName, fn);\n const onLastListenerRemove = () => emitter.removeListener(eventName, fn);\n const result = new Emitter({ onWillAddFirstListener: onFirstListenerAdd, onDidRemoveLastListener: onLastListenerRemove });\n return result.event;\n }\n Event.fromNodeEventEmitter = fromNodeEventEmitter;\n /**\n * Creates an {@link Event} from a DOM event emitter.\n */\n function fromDOMEventEmitter(emitter, eventName, map = id => id) {\n const fn = (...args) => result.fire(map(...args));\n const onFirstListenerAdd = () => emitter.addEventListener(eventName, fn);\n const onLastListenerRemove = () => emitter.removeEventListener(eventName, fn);\n const result = new Emitter({ onWillAddFirstListener: onFirstListenerAdd, onDidRemoveLastListener: onLastListenerRemove });\n return result.event;\n }\n Event.fromDOMEventEmitter = fromDOMEventEmitter;\n /**\n * Creates a promise out of an event, using the {@link Event.once} helper.\n */\n function toPromise(event) {\n return new Promise(resolve => once(event)(resolve));\n }\n Event.toPromise = toPromise;\n /**\n * Creates an event out of a promise that fires once when the promise is\n * resolved with the result of the promise or `undefined`.\n */\n function fromPromise(promise) {\n const result = new Emitter();\n promise.then(res => {\n result.fire(res);\n }, () => {\n result.fire(undefined);\n }).finally(() => {\n result.dispose();\n });\n return result.event;\n }\n Event.fromPromise = fromPromise;\n /**\n * A convenience function for forwarding an event to another emitter which\n * improves readability.allows Event.forward(event, emitter) instead of `event(e => emitter.fire(e))`.\n * @param from The event to forward.\n * @param to The emitter to forward the event to.\n * @example\n * Event.forward(event, emitter);\n * // equivalent to\n * event(e => emitter.fire(e));\n * // equivalent to\n * event(emitter.fire, emitter);\n */\n function forward(from, to) {\n return from(e => to.fire(e));\n }\n Event.forward = forward;\n function runAndSubscribe(event, handler, initial) {\n handler(initial);\n return event(e => handler(e));\n }\n Event.runAndSubscribe = runAndSubscribe;\n class EmitterObserver {\n constructor(_observable, store) {\n this._observable = _observable;\n this._counter = 0;\n this._hasChanged = false;\n const options = {\n onWillAddFirstListener: () => {\n _observable.addObserver(this);\n },\n onDidRemoveLastListener: () => {\n _observable.removeObserver(this);\n }\n };\n if (!store) {\n _addLeakageTraceLogic(options);\n }\n this.emitter = new Emitter(options);\n if (store) {\n store.add(this.emitter);\n }\n }\n beginUpdate(_observable) {\n // assert(_observable === this.obs);\n this._counter++;\n }\n handlePossibleChange(_observable) {\n // assert(_observable === this.obs);\n }\n handleChange(_observable, _change) {\n // assert(_observable === this.obs);\n this._hasChanged = true;\n }\n endUpdate(_observable) {\n // assert(_observable === this.obs);\n this._counter--;\n if (this._counter === 0) {\n this._observable.reportChanges();\n if (this._hasChanged) {\n this._hasChanged = false;\n this.emitter.fire(this._observable.get());\n }\n }\n }\n }\n /**\n * Creates an event emitter that is fired when the observable changes.\n * Each listeners subscribes to the emitter.\n */\n function fromObservable(obs, store) {\n const observer = new EmitterObserver(obs, store);\n return observer.emitter.event;\n }\n Event.fromObservable = fromObservable;\n /**\n * Each listener is attached to the observable directly.\n */\n function fromObservableLight(observable) {\n return (listener, thisArgs, disposables) => {\n let count = 0;\n let didChange = false;\n const observer = {\n beginUpdate() {\n count++;\n },\n endUpdate() {\n count--;\n if (count === 0) {\n observable.reportChanges();\n if (didChange) {\n didChange = false;\n listener.call(thisArgs);\n }\n }\n },\n handlePossibleChange() {\n // noop\n },\n handleChange() {\n didChange = true;\n }\n };\n observable.addObserver(observer);\n observable.reportChanges();\n const disposable = {\n dispose() {\n observable.removeObserver(observer);\n }\n };\n if (disposables instanceof lifecycle_1.DisposableStore) {\n disposables.add(disposable);\n }\n else if (Array.isArray(disposables)) {\n disposables.push(disposable);\n }\n return disposable;\n };\n }\n Event.fromObservableLight = fromObservableLight;\n})(Event || (exports.Event = Event = {}));\nclass EventProfiling {\n static { this.all = new Set(); }\n static { this._idPool = 0; }\n constructor(name) {\n this.listenerCount = 0;\n this.invocationCount = 0;\n this.elapsedOverall = 0;\n this.durations = [];\n this.name = `${name}_${EventProfiling._idPool++}`;\n EventProfiling.all.add(this);\n }\n start(listenerCount) {\n this._stopWatch = new stopwatch_1.StopWatch();\n this.listenerCount = listenerCount;\n }\n stop() {\n if (this._stopWatch) {\n const elapsed = this._stopWatch.elapsed();\n this.durations.push(elapsed);\n this.elapsedOverall += elapsed;\n this.invocationCount += 1;\n this._stopWatch = undefined;\n }\n }\n}\nexports.EventProfiling = EventProfiling;\nlet _globalLeakWarningThreshold = -1;\nfunction setGlobalLeakWarningThreshold(n) {\n const oldValue = _globalLeakWarningThreshold;\n _globalLeakWarningThreshold = n;\n return {\n dispose() {\n _globalLeakWarningThreshold = oldValue;\n }\n };\n}\nclass LeakageMonitor {\n static { this._idPool = 1; }\n constructor(_errorHandler, threshold, name = (LeakageMonitor._idPool++).toString(16).padStart(3, '0')) {\n this._errorHandler = _errorHandler;\n this.threshold = threshold;\n this.name = name;\n this._warnCountdown = 0;\n }\n dispose() {\n this._stacks?.clear();\n }\n check(stack, listenerCount) {\n const threshold = this.threshold;\n if (threshold <= 0 || listenerCount < threshold) {\n return undefined;\n }\n if (!this._stacks) {\n this._stacks = new Map();\n }\n const count = (this._stacks.get(stack.value) || 0);\n this._stacks.set(stack.value, count + 1);\n this._warnCountdown -= 1;\n if (this._warnCountdown <= 0) {\n // only warn on first exceed and then every time the limit\n // is exceeded by 50% again\n this._warnCountdown = threshold * 0.5;\n const [topStack, topCount] = this.getMostFrequentStack();\n const message = `[${this.name}] potential listener LEAK detected, having ${listenerCount} listeners already. MOST frequent listener (${topCount}):`;\n console.warn(message);\n console.warn(topStack);\n const error = new ListenerLeakError(message, topStack);\n this._errorHandler(error);\n }\n return () => {\n const count = (this._stacks.get(stack.value) || 0);\n this._stacks.set(stack.value, count - 1);\n };\n }\n getMostFrequentStack() {\n if (!this._stacks) {\n return undefined;\n }\n let topStack;\n let topCount = 0;\n for (const [stack, count] of this._stacks) {\n if (!topStack || topCount < count) {\n topStack = [stack, count];\n topCount = count;\n }\n }\n return topStack;\n }\n}\nclass Stacktrace {\n static create() {\n const err = new Error();\n return new Stacktrace(err.stack ?? '');\n }\n constructor(value) {\n this.value = value;\n }\n print() {\n console.warn(this.value.split('\\n').slice(2).join('\\n'));\n }\n}\n// error that is logged when going over the configured listener threshold\nclass ListenerLeakError extends Error {\n constructor(message, stack) {\n super(message);\n this.name = 'ListenerLeakError';\n this.stack = stack;\n }\n}\nexports.ListenerLeakError = ListenerLeakError;\n// SEVERE error that is logged when having gone way over the configured listener\n// threshold so that the emitter refuses to accept more listeners\nclass ListenerRefusalError extends Error {\n constructor(message, stack) {\n super(message);\n this.name = 'ListenerRefusalError';\n this.stack = stack;\n }\n}\nexports.ListenerRefusalError = ListenerRefusalError;\nlet id = 0;\nclass UniqueContainer {\n constructor(value) {\n this.value = value;\n this.id = id++;\n }\n}\nconst compactionThreshold = 2;\nconst forEachListener = (listeners, fn) => {\n if (listeners instanceof UniqueContainer) {\n fn(listeners);\n }\n else {\n for (let i = 0; i < listeners.length; i++) {\n const l = listeners[i];\n if (l) {\n fn(l);\n }\n }\n }\n};\nlet _listenerFinalizers;\nif (_enableListenerGCedWarning) {\n const leaks = [];\n setInterval(() => {\n if (leaks.length === 0) {\n return;\n }\n console.warn('[LEAKING LISTENERS] GC\\'ed these listeners that were NOT yet disposed:');\n console.warn(leaks.join('\\n'));\n leaks.length = 0;\n }, 3000);\n _listenerFinalizers = new FinalizationRegistry(heldValue => {\n if (typeof heldValue === 'string') {\n leaks.push(heldValue);\n }\n });\n}\n/**\n * The Emitter can be used to expose an Event to the public\n * to fire it from the insides.\n * Sample:\n class Document {\n\n private readonly _onDidChange = new Emitter<(value:string)=>any>();\n\n public onDidChange = this._onDidChange.event;\n\n // getter-style\n // get onDidChange(): Event<(value:string)=>any> {\n // \treturn this._onDidChange.event;\n // }\n\n private _doIt() {\n //...\n this._onDidChange.fire(value);\n }\n }\n */\nclass Emitter {\n constructor(options) {\n this._size = 0;\n this._options = options;\n this._leakageMon = (_globalLeakWarningThreshold > 0 || this._options?.leakWarningThreshold)\n ? new LeakageMonitor(options?.onListenerError ?? errors_1.onUnexpectedError, this._options?.leakWarningThreshold ?? _globalLeakWarningThreshold) :\n undefined;\n this._perfMon = this._options?._profName ? new EventProfiling(this._options._profName) : undefined;\n this._deliveryQueue = this._options?.deliveryQueue;\n }\n dispose() {\n if (!this._disposed) {\n this._disposed = true;\n // It is bad to have listeners at the time of disposing an emitter, it is worst to have listeners keep the emitter\n // alive via the reference that's embedded in their disposables. Therefore we loop over all remaining listeners and\n // unset their subscriptions/disposables. Looping and blaming remaining listeners is done on next tick because the\n // the following programming pattern is very popular:\n //\n // const someModel = this._disposables.add(new ModelObject()); // (1) create and register model\n // this._disposables.add(someModel.onDidChange(() => { ... }); // (2) subscribe and register model-event listener\n // ...later...\n // this._disposables.dispose(); disposes (1) then (2): don't warn after (1) but after the \"overall dispose\" is done\n if (this._deliveryQueue?.current === this) {\n this._deliveryQueue.reset();\n }\n if (this._listeners) {\n if (_enableDisposeWithListenerWarning) {\n const listeners = this._listeners;\n queueMicrotask(() => {\n forEachListener(listeners, l => l.stack?.print());\n });\n }\n this._listeners = undefined;\n this._size = 0;\n }\n this._options?.onDidRemoveLastListener?.();\n this._leakageMon?.dispose();\n }\n }\n /**\n * For the public to allow to subscribe\n * to events from this Emitter\n */\n get event() {\n this._event ??= (callback, thisArgs, disposables) => {\n if (this._leakageMon && this._size > this._leakageMon.threshold ** 2) {\n const message = `[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;\n console.warn(message);\n const tuple = this._leakageMon.getMostFrequentStack() ?? ['UNKNOWN stack', -1];\n const error = new ListenerRefusalError(`${message}. HINT: Stack shows most frequent listener (${tuple[1]}-times)`, tuple[0]);\n const errorHandler = this._options?.onListenerError || errors_1.onUnexpectedError;\n errorHandler(error);\n return lifecycle_1.Disposable.None;\n }\n if (this._disposed) {\n // todo: should we warn if a listener is added to a disposed emitter? This happens often\n return lifecycle_1.Disposable.None;\n }\n if (thisArgs) {\n callback = callback.bind(thisArgs);\n }\n const contained = new UniqueContainer(callback);\n let removeMonitor;\n let stack;\n if (this._leakageMon && this._size >= Math.ceil(this._leakageMon.threshold * 0.2)) {\n // check and record this emitter for potential leakage\n contained.stack = Stacktrace.create();\n removeMonitor = this._leakageMon.check(contained.stack, this._size + 1);\n }\n if (_enableDisposeWithListenerWarning) {\n contained.stack = stack ?? Stacktrace.create();\n }\n if (!this._listeners) {\n this._options?.onWillAddFirstListener?.(this);\n this._listeners = contained;\n this._options?.onDidAddFirstListener?.(this);\n }\n else if (this._listeners instanceof UniqueContainer) {\n this._deliveryQueue ??= new EventDeliveryQueuePrivate();\n this._listeners = [this._listeners, contained];\n }\n else {\n this._listeners.push(contained);\n }\n this._size++;\n const result = (0, lifecycle_1.toDisposable)(() => {\n _listenerFinalizers?.unregister(result);\n removeMonitor?.();\n this._removeListener(contained);\n });\n if (disposables instanceof lifecycle_1.DisposableStore) {\n disposables.add(result);\n }\n else if (Array.isArray(disposables)) {\n disposables.push(result);\n }\n if (_listenerFinalizers) {\n const stack = new Error().stack.split('\\n').slice(2, 3).join('\\n').trim();\n const match = /(file:|vscode-file:\\/\\/vscode-app)?(\\/[^:]*:\\d+:\\d+)/.exec(stack);\n _listenerFinalizers.register(result, match?.[2] ?? stack, result);\n }\n return result;\n };\n return this._event;\n }\n _removeListener(listener) {\n this._options?.onWillRemoveListener?.(this);\n if (!this._listeners) {\n return; // expected if a listener gets disposed\n }\n if (this._size === 1) {\n this._listeners = undefined;\n this._options?.onDidRemoveLastListener?.(this);\n this._size = 0;\n return;\n }\n // size > 1 which requires that listeners be a list:\n const listeners = this._listeners;\n const index = listeners.indexOf(listener);\n if (index === -1) {\n console.log('disposed?', this._disposed);\n console.log('size?', this._size);\n console.log('arr?', JSON.stringify(this._listeners));\n throw new Error('Attempted to dispose unknown listener');\n }\n this._size--;\n listeners[index] = undefined;\n const adjustDeliveryQueue = this._deliveryQueue.current === this;\n if (this._size * compactionThreshold <= listeners.length) {\n let n = 0;\n for (let i = 0; i < listeners.length; i++) {\n if (listeners[i]) {\n listeners[n++] = listeners[i];\n }\n else if (adjustDeliveryQueue) {\n this._deliveryQueue.end--;\n if (n < this._deliveryQueue.i) {\n this._deliveryQueue.i--;\n }\n }\n }\n listeners.length = n;\n }\n }\n _deliver(listener, value) {\n if (!listener) {\n return;\n }\n const errorHandler = this._options?.onListenerError || errors_1.onUnexpectedError;\n if (!errorHandler) {\n listener.value(value);\n return;\n }\n try {\n listener.value(value);\n }\n catch (e) {\n errorHandler(e);\n }\n }\n /** Delivers items in the queue. Assumes the queue is ready to go. */\n _deliverQueue(dq) {\n const listeners = dq.current._listeners;\n while (dq.i < dq.end) {\n // important: dq.i is incremented before calling deliver() because it might reenter deliverQueue()\n this._deliver(listeners[dq.i++], dq.value);\n }\n dq.reset();\n }\n /**\n * To be kept private to fire an event to\n * subscribers\n */\n fire(event) {\n if (this._deliveryQueue?.current) {\n this._deliverQueue(this._deliveryQueue);\n this._perfMon?.stop(); // last fire() will have starting perfmon, stop it before starting the next dispatch\n }\n this._perfMon?.start(this._size);\n if (!this._listeners) {\n // no-op\n }\n else if (this._listeners instanceof UniqueContainer) {\n this._deliver(this._listeners, event);\n }\n else {\n const dq = this._deliveryQueue;\n dq.enqueue(this, event, this._listeners.length);\n this._deliverQueue(dq);\n }\n this._perfMon?.stop();\n }\n hasListeners() {\n return this._size > 0;\n }\n}\nexports.Emitter = Emitter;\nconst createEventDeliveryQueue = () => new EventDeliveryQueuePrivate();\nexports.createEventDeliveryQueue = createEventDeliveryQueue;\nclass EventDeliveryQueuePrivate {\n constructor() {\n /**\n * Index in current's listener list.\n */\n this.i = -1;\n /**\n * The last index in the listener's list to deliver.\n */\n this.end = 0;\n }\n enqueue(emitter, value, end) {\n this.i = 0;\n this.end = end;\n this.current = emitter;\n this.value = value;\n }\n reset() {\n this.i = this.end; // force any current emission loop to stop, mainly for during dispose\n this.current = undefined;\n this.value = undefined;\n }\n}\nclass AsyncEmitter extends Emitter {\n async fireAsync(data, token, promiseJoin) {\n if (!this._listeners) {\n return;\n }\n if (!this._asyncDeliveryQueue) {\n this._asyncDeliveryQueue = new linkedList_1.LinkedList();\n }\n forEachListener(this._listeners, listener => this._asyncDeliveryQueue.push([listener.value, data]));\n while (this._asyncDeliveryQueue.size > 0 && !token.isCancellationRequested) {\n const [listener, data] = this._asyncDeliveryQueue.shift();\n const thenables = [];\n const event = {\n ...data,\n token,\n waitUntil: (p) => {\n if (Object.isFrozen(thenables)) {\n throw new Error('waitUntil can NOT be called asynchronous');\n }\n if (promiseJoin) {\n p = promiseJoin(p, listener);\n }\n thenables.push(p);\n }\n };\n try {\n listener(event);\n }\n catch (e) {\n (0, errors_1.onUnexpectedError)(e);\n continue;\n }\n // freeze thenables-collection to enforce sync-calls to\n // wait until and then wait for all thenables to resolve\n Object.freeze(thenables);\n await Promise.allSettled(thenables).then(values => {\n for (const value of values) {\n if (value.status === 'rejected') {\n (0, errors_1.onUnexpectedError)(value.reason);\n }\n }\n });\n }\n }\n}\nexports.AsyncEmitter = AsyncEmitter;\nclass PauseableEmitter extends Emitter {\n get isPaused() {\n return this._isPaused !== 0;\n }\n constructor(options) {\n super(options);\n this._isPaused = 0;\n this._eventQueue = new linkedList_1.LinkedList();\n this._mergeFn = options?.merge;\n }\n pause() {\n this._isPaused++;\n }\n resume() {\n if (this._isPaused !== 0 && --this._isPaused === 0) {\n if (this._mergeFn) {\n // use the merge function to create a single composite\n // event. make a copy in case firing pauses this emitter\n if (this._eventQueue.size > 0) {\n const events = Array.from(this._eventQueue);\n this._eventQueue.clear();\n super.fire(this._mergeFn(events));\n }\n }\n else {\n // no merging, fire each event individually and test\n // that this emitter isn't paused halfway through\n while (!this._isPaused && this._eventQueue.size !== 0) {\n super.fire(this._eventQueue.shift());\n }\n }\n }\n }\n fire(event) {\n if (this._size) {\n if (this._isPaused !== 0) {\n this._eventQueue.push(event);\n }\n else {\n super.fire(event);\n }\n }\n }\n}\nexports.PauseableEmitter = PauseableEmitter;\nclass DebounceEmitter extends PauseableEmitter {\n constructor(options) {\n super(options);\n this._delay = options.delay ?? 100;\n }\n fire(event) {\n if (!this._handle) {\n this.pause();\n this._handle = setTimeout(() => {\n this._handle = undefined;\n this.resume();\n }, this._delay);\n }\n super.fire(event);\n }\n}\nexports.DebounceEmitter = DebounceEmitter;\n/**\n * An emitter which queue all events and then process them at the\n * end of the event loop.\n */\nclass MicrotaskEmitter extends Emitter {\n constructor(options) {\n super(options);\n this._queuedEvents = [];\n this._mergeFn = options?.merge;\n }\n fire(event) {\n if (!this.hasListeners()) {\n return;\n }\n this._queuedEvents.push(event);\n if (this._queuedEvents.length === 1) {\n queueMicrotask(() => {\n if (this._mergeFn) {\n super.fire(this._mergeFn(this._queuedEvents));\n }\n else {\n this._queuedEvents.forEach(e => super.fire(e));\n }\n this._queuedEvents = [];\n });\n }\n }\n}\nexports.MicrotaskEmitter = MicrotaskEmitter;\n/**\n * An event emitter that multiplexes many events into a single event.\n *\n * @example Listen to the `onData` event of all `Thing`s, dynamically adding and removing `Thing`s\n * to the multiplexer as needed.\n *\n * ```typescript\n * const anythingDataMultiplexer = new EventMultiplexer<{ data: string }>();\n *\n * const thingListeners = DisposableMap();\n *\n * thingService.onDidAddThing(thing => {\n * thingListeners.set(thing, anythingDataMultiplexer.add(thing.onData);\n * });\n * thingService.onDidRemoveThing(thing => {\n * thingListeners.deleteAndDispose(thing);\n * });\n *\n * anythingDataMultiplexer.event(e => {\n * console.log('Something fired data ' + e.data)\n * });\n * ```\n */\nclass EventMultiplexer {\n constructor() {\n this.hasListeners = false;\n this.events = [];\n this.emitter = new Emitter({\n onWillAddFirstListener: () => this.onFirstListenerAdd(),\n onDidRemoveLastListener: () => this.onLastListenerRemove()\n });\n }\n get event() {\n return this.emitter.event;\n }\n add(event) {\n const e = { event: event, listener: null };\n this.events.push(e);\n if (this.hasListeners) {\n this.hook(e);\n }\n const dispose = () => {\n if (this.hasListeners) {\n this.unhook(e);\n }\n const idx = this.events.indexOf(e);\n this.events.splice(idx, 1);\n };\n return (0, lifecycle_1.toDisposable)((0, functional_1.createSingleCallFunction)(dispose));\n }\n onFirstListenerAdd() {\n this.hasListeners = true;\n this.events.forEach(e => this.hook(e));\n }\n onLastListenerRemove() {\n this.hasListeners = false;\n this.events.forEach(e => this.unhook(e));\n }\n hook(e) {\n e.listener = e.event(r => this.emitter.fire(r));\n }\n unhook(e) {\n e.listener?.dispose();\n e.listener = null;\n }\n dispose() {\n this.emitter.dispose();\n for (const e of this.events) {\n e.listener?.dispose();\n }\n this.events = [];\n }\n}\nexports.EventMultiplexer = EventMultiplexer;\nclass DynamicListEventMultiplexer {\n constructor(items, onAddItem, onRemoveItem, getEvent) {\n this._store = new lifecycle_1.DisposableStore();\n const multiplexer = this._store.add(new EventMultiplexer());\n const itemListeners = this._store.add(new lifecycle_1.DisposableMap());\n function addItem(instance) {\n itemListeners.set(instance, multiplexer.add(getEvent(instance)));\n }\n // Existing items\n for (const instance of items) {\n addItem(instance);\n }\n // Added items\n this._store.add(onAddItem(instance => {\n addItem(instance);\n }));\n // Removed items\n this._store.add(onRemoveItem(instance => {\n itemListeners.deleteAndDispose(instance);\n }));\n this.event = multiplexer.event;\n }\n dispose() {\n this._store.dispose();\n }\n}\nexports.DynamicListEventMultiplexer = DynamicListEventMultiplexer;\n/**\n * The EventBufferer is useful in situations in which you want\n * to delay firing your events during some code.\n * You can wrap that code and be sure that the event will not\n * be fired during that wrap.\n *\n * ```\n * const emitter: Emitter;\n * const delayer = new EventDelayer();\n * const delayedEvent = delayer.wrapEvent(emitter.event);\n *\n * delayedEvent(console.log);\n *\n * delayer.bufferEvents(() => {\n * emitter.fire(); // event will not be fired yet\n * });\n *\n * // event will only be fired at this point\n * ```\n */\nclass EventBufferer {\n constructor() {\n this.data = [];\n }\n wrapEvent(event, reduce, initial) {\n return (listener, thisArgs, disposables) => {\n return event(i => {\n const data = this.data[this.data.length - 1];\n // Non-reduce scenario\n if (!reduce) {\n // Buffering case\n if (data) {\n data.buffers.push(() => listener.call(thisArgs, i));\n }\n else {\n // Not buffering case\n listener.call(thisArgs, i);\n }\n return;\n }\n // Reduce scenario\n const reduceData = data;\n // Not buffering case\n if (!reduceData) {\n // TODO: Is there a way to cache this reduce call for all listeners?\n listener.call(thisArgs, reduce(initial, i));\n return;\n }\n // Buffering case\n reduceData.items ??= [];\n reduceData.items.push(i);\n if (reduceData.buffers.length === 0) {\n // Include a single buffered function that will reduce all events when we're done buffering events\n data.buffers.push(() => {\n // cache the reduced result so that the value can be shared across all listeners\n reduceData.reducedResult ??= initial\n ? reduceData.items.reduce(reduce, initial)\n : reduceData.items.reduce(reduce);\n listener.call(thisArgs, reduceData.reducedResult);\n });\n }\n }, undefined, disposables);\n };\n }\n bufferEvents(fn) {\n const data = { buffers: new Array() };\n this.data.push(data);\n const r = fn();\n this.data.pop();\n data.buffers.forEach(flush => flush());\n return r;\n }\n}\nexports.EventBufferer = EventBufferer;\n/**\n * A Relay is an event forwarder which functions as a replugabble event pipe.\n * Once created, you can connect an input event to it and it will simply forward\n * events from that input event through its own `event` property. The `input`\n * can be changed at any point in time.\n */\nclass Relay {\n constructor() {\n this.listening = false;\n this.inputEvent = Event.None;\n this.inputEventListener = lifecycle_1.Disposable.None;\n this.emitter = new Emitter({\n onDidAddFirstListener: () => {\n this.listening = true;\n this.inputEventListener = this.inputEvent(this.emitter.fire, this.emitter);\n },\n onDidRemoveLastListener: () => {\n this.listening = false;\n this.inputEventListener.dispose();\n }\n });\n this.event = this.emitter.event;\n }\n set input(event) {\n this.inputEvent = event;\n if (this.listening) {\n this.inputEventListener.dispose();\n this.inputEventListener = event(this.emitter.fire, this.emitter);\n }\n }\n dispose() {\n this.inputEventListener.dispose();\n this.emitter.dispose();\n }\n}\nexports.Relay = Relay;\nclass ValueWithChangeEvent {\n static const(value) {\n return new ConstValueWithChangeEvent(value);\n }\n constructor(_value) {\n this._value = _value;\n this._onDidChange = new Emitter();\n this.onDidChange = this._onDidChange.event;\n }\n get value() {\n return this._value;\n }\n set value(value) {\n if (value !== this._value) {\n this._value = value;\n this._onDidChange.fire(undefined);\n }\n }\n}\nexports.ValueWithChangeEvent = ValueWithChangeEvent;\nclass ConstValueWithChangeEvent {\n constructor(value) {\n this.value = value;\n this.onDidChange = Event.None;\n }\n}\n","\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.createSingleCallFunction = createSingleCallFunction;\n/**\n * Given a function, returns a function that is only calling that function once.\n */\nfunction createSingleCallFunction(fn, fnDidRunCallback) {\n const _this = this;\n let didCall = false;\n let result;\n return function () {\n if (didCall) {\n return result;\n }\n didCall = true;\n if (fnDidRunCallback) {\n try {\n result = fn.apply(_this, arguments);\n }\n finally {\n fnDidRunCallback();\n }\n }\n else {\n result = fn.apply(_this, arguments);\n }\n return result;\n };\n}\n","\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.StringSHA1 = exports.Hasher = void 0;\nexports.hash = hash;\nexports.doHash = doHash;\nexports.numberHash = numberHash;\nexports.stringHash = stringHash;\nexports.toHexString = toHexString;\nconst strings = __importStar(require(\"vs/base/common/strings\"));\n/**\n * Return a hash value for an object.\n */\nfunction hash(obj) {\n return doHash(obj, 0);\n}\nfunction doHash(obj, hashVal) {\n switch (typeof obj) {\n case 'object':\n if (obj === null) {\n return numberHash(349, hashVal);\n }\n else if (Array.isArray(obj)) {\n return arrayHash(obj, hashVal);\n }\n return objectHash(obj, hashVal);\n case 'string':\n return stringHash(obj, hashVal);\n case 'boolean':\n return booleanHash(obj, hashVal);\n case 'number':\n return numberHash(obj, hashVal);\n case 'undefined':\n return numberHash(937, hashVal);\n default:\n return numberHash(617, hashVal);\n }\n}\nfunction numberHash(val, initialHashVal) {\n return (((initialHashVal << 5) - initialHashVal) + val) | 0; // hashVal * 31 + ch, keep as int32\n}\nfunction booleanHash(b, initialHashVal) {\n return numberHash(b ? 433 : 863, initialHashVal);\n}\nfunction stringHash(s, hashVal) {\n hashVal = numberHash(149417, hashVal);\n for (let i = 0, length = s.length; i < length; i++) {\n hashVal = numberHash(s.charCodeAt(i), hashVal);\n }\n return hashVal;\n}\nfunction arrayHash(arr, initialHashVal) {\n initialHashVal = numberHash(104579, initialHashVal);\n return arr.reduce((hashVal, item) => doHash(item, hashVal), initialHashVal);\n}\nfunction objectHash(obj, initialHashVal) {\n initialHashVal = numberHash(181387, initialHashVal);\n return Object.keys(obj).sort().reduce((hashVal, key) => {\n hashVal = stringHash(key, hashVal);\n return doHash(obj[key], hashVal);\n }, initialHashVal);\n}\nclass Hasher {\n constructor() {\n this._value = 0;\n }\n get value() {\n return this._value;\n }\n hash(obj) {\n this._value = doHash(obj, this._value);\n return this._value;\n }\n}\nexports.Hasher = Hasher;\nvar SHA1Constant;\n(function (SHA1Constant) {\n SHA1Constant[SHA1Constant[\"BLOCK_SIZE\"] = 64] = \"BLOCK_SIZE\";\n SHA1Constant[SHA1Constant[\"UNICODE_REPLACEMENT\"] = 65533] = \"UNICODE_REPLACEMENT\";\n})(SHA1Constant || (SHA1Constant = {}));\nfunction leftRotate(value, bits, totalBits = 32) {\n // delta + bits = totalBits\n const delta = totalBits - bits;\n // All ones, expect `delta` zeros aligned to the right\n const mask = ~((1 << delta) - 1);\n // Join (value left-shifted `bits` bits) with (masked value right-shifted `delta` bits)\n return ((value << bits) | ((mask & value) >>> delta)) >>> 0;\n}\nfunction fill(dest, index = 0, count = dest.byteLength, value = 0) {\n for (let i = 0; i < count; i++) {\n dest[index + i] = value;\n }\n}\nfunction leftPad(value, length, char = '0') {\n while (value.length < length) {\n value = char + value;\n }\n return value;\n}\nfunction toHexString(bufferOrValue, bitsize = 32) {\n if (bufferOrValue instanceof ArrayBuffer) {\n return Array.from(new Uint8Array(bufferOrValue)).map(b => b.toString(16).padStart(2, '0')).join('');\n }\n return leftPad((bufferOrValue >>> 0).toString(16), bitsize / 4);\n}\n/**\n * A SHA1 implementation that works with strings and does not allocate.\n */\nclass StringSHA1 {\n static { this._bigBlock32 = new DataView(new ArrayBuffer(320)); } // 80 * 4 = 320\n constructor() {\n this._h0 = 0x67452301;\n this._h1 = 0xEFCDAB89;\n this._h2 = 0x98BADCFE;\n this._h3 = 0x10325476;\n this._h4 = 0xC3D2E1F0;\n this._buff = new Uint8Array(SHA1Constant.BLOCK_SIZE + 3 /* to fit any utf-8 */);\n this._buffDV = new DataView(this._buff.buffer);\n this._buffLen = 0;\n this._totalLen = 0;\n this._leftoverHighSurrogate = 0;\n this._finished = false;\n }\n update(str) {\n const strLen = str.length;\n if (strLen === 0) {\n return;\n }\n const buff = this._buff;\n let buffLen = this._buffLen;\n let leftoverHighSurrogate = this._leftoverHighSurrogate;\n let charCode;\n let offset;\n if (leftoverHighSurrogate !== 0) {\n charCode = leftoverHighSurrogate;\n offset = -1;\n leftoverHighSurrogate = 0;\n }\n else {\n charCode = str.charCodeAt(0);\n offset = 0;\n }\n while (true) {\n let codePoint = charCode;\n if (strings.isHighSurrogate(charCode)) {\n if (offset + 1 < strLen) {\n const nextCharCode = str.charCodeAt(offset + 1);\n if (strings.isLowSurrogate(nextCharCode)) {\n offset++;\n codePoint = strings.computeCodePoint(charCode, nextCharCode);\n }\n else {\n // illegal => unicode replacement character\n codePoint = SHA1Constant.UNICODE_REPLACEMENT;\n }\n }\n else {\n // last character is a surrogate pair\n leftoverHighSurrogate = charCode;\n break;\n }\n }\n else if (strings.isLowSurrogate(charCode)) {\n // illegal => unicode replacement character\n codePoint = SHA1Constant.UNICODE_REPLACEMENT;\n }\n buffLen = this._push(buff, buffLen, codePoint);\n offset++;\n if (offset < strLen) {\n charCode = str.charCodeAt(offset);\n }\n else {\n break;\n }\n }\n this._buffLen = buffLen;\n this._leftoverHighSurrogate = leftoverHighSurrogate;\n }\n _push(buff, buffLen, codePoint) {\n if (codePoint < 0x0080) {\n buff[buffLen++] = codePoint;\n }\n else if (codePoint < 0x0800) {\n buff[buffLen++] = 0b11000000 | ((codePoint & 0b00000000000000000000011111000000) >>> 6);\n buff[buffLen++] = 0b10000000 | ((codePoint & 0b00000000000000000000000000111111) >>> 0);\n }\n else if (codePoint < 0x10000) {\n buff[buffLen++] = 0b11100000 | ((codePoint & 0b00000000000000001111000000000000) >>> 12);\n buff[buffLen++] = 0b10000000 | ((codePoint & 0b00000000000000000000111111000000) >>> 6);\n buff[buffLen++] = 0b10000000 | ((codePoint & 0b00000000000000000000000000111111) >>> 0);\n }\n else {\n buff[buffLen++] = 0b11110000 | ((codePoint & 0b00000000000111000000000000000000) >>> 18);\n buff[buffLen++] = 0b10000000 | ((codePoint & 0b00000000000000111111000000000000) >>> 12);\n buff[buffLen++] = 0b10000000 | ((codePoint & 0b00000000000000000000111111000000) >>> 6);\n buff[buffLen++] = 0b10000000 | ((codePoint & 0b00000000000000000000000000111111) >>> 0);\n }\n if (buffLen >= SHA1Constant.BLOCK_SIZE) {\n this._step();\n buffLen -= SHA1Constant.BLOCK_SIZE;\n this._totalLen += SHA1Constant.BLOCK_SIZE;\n // take last 3 in case of UTF8 overflow\n buff[0] = buff[SHA1Constant.BLOCK_SIZE + 0];\n buff[1] = buff[SHA1Constant.BLOCK_SIZE + 1];\n buff[2] = buff[SHA1Constant.BLOCK_SIZE + 2];\n }\n return buffLen;\n }\n digest() {\n if (!this._finished) {\n this._finished = true;\n if (this._leftoverHighSurrogate) {\n // illegal => unicode replacement character\n this._leftoverHighSurrogate = 0;\n this._buffLen = this._push(this._buff, this._buffLen, SHA1Constant.UNICODE_REPLACEMENT);\n }\n this._totalLen += this._buffLen;\n this._wrapUp();\n }\n return toHexString(this._h0) + toHexString(this._h1) + toHexString(this._h2) + toHexString(this._h3) + toHexString(this._h4);\n }\n _wrapUp() {\n this._buff[this._buffLen++] = 0x80;\n fill(this._buff, this._buffLen);\n if (this._buffLen > 56) {\n this._step();\n fill(this._buff);\n }\n // this will fit because the mantissa can cover up to 52 bits\n const ml = 8 * this._totalLen;\n this._buffDV.setUint32(56, Math.floor(ml / 4294967296), false);\n this._buffDV.setUint32(60, ml % 4294967296, false);\n this._step();\n }\n _step() {\n const bigBlock32 = StringSHA1._bigBlock32;\n const data = this._buffDV;\n for (let j = 0; j < 64 /* 16*4 */; j += 4) {\n bigBlock32.setUint32(j, data.getUint32(j, false), false);\n }\n for (let j = 64; j < 320 /* 80*4 */; j += 4) {\n bigBlock32.setUint32(j, leftRotate((bigBlock32.getUint32(j - 12, false) ^ bigBlock32.getUint32(j - 32, false) ^ bigBlock32.getUint32(j - 56, false) ^ bigBlock32.getUint32(j - 64, false)), 1), false);\n }\n let a = this._h0;\n let b = this._h1;\n let c = this._h2;\n let d = this._h3;\n let e = this._h4;\n let f, k;\n let temp;\n for (let j = 0; j < 80; j++) {\n if (j < 20) {\n f = (b & c) | ((~b) & d);\n k = 0x5A827999;\n }\n else if (j < 40) {\n f = b ^ c ^ d;\n k = 0x6ED9EBA1;\n }\n else if (j < 60) {\n f = (b & c) | (b & d) | (c & d);\n k = 0x8F1BBCDC;\n }\n else {\n f = b ^ c ^ d;\n k = 0xCA62C1D6;\n }\n temp = (leftRotate(a, 5) + f + e + k + bigBlock32.getUint32(j * 4, false)) & 0xffffffff;\n e = d;\n d = c;\n c = leftRotate(b, 30);\n b = a;\n a = temp;\n }\n this._h0 = (this._h0 + a) & 0xffffffff;\n this._h1 = (this._h1 + b) & 0xffffffff;\n this._h2 = (this._h2 + c) & 0xffffffff;\n this._h3 = (this._h3 + d) & 0xffffffff;\n this._h4 = (this._h4 + e) & 0xffffffff;\n }\n}\nexports.StringSHA1 = StringSHA1;\n","\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Iterable = void 0;\nvar Iterable;\n(function (Iterable) {\n function is(thing) {\n return thing && typeof thing === 'object' && typeof thing[Symbol.iterator] === 'function';\n }\n Iterable.is = is;\n const _empty = Object.freeze([]);\n function empty() {\n return _empty;\n }\n Iterable.empty = empty;\n function* single(element) {\n yield element;\n }\n Iterable.single = single;\n function wrap(iterableOrElement) {\n if (is(iterableOrElement)) {\n return iterableOrElement;\n }\n else {\n return single(iterableOrElement);\n }\n }\n Iterable.wrap = wrap;\n function from(iterable) {\n return iterable || _empty;\n }\n Iterable.from = from;\n function* reverse(array) {\n for (let i = array.length - 1; i >= 0; i--) {\n yield array[i];\n }\n }\n Iterable.reverse = reverse;\n function isEmpty(iterable) {\n return !iterable || iterable[Symbol.iterator]().next().done === true;\n }\n Iterable.isEmpty = isEmpty;\n function first(iterable) {\n return iterable[Symbol.iterator]().next().value;\n }\n Iterable.first = first;\n function some(iterable, predicate) {\n let i = 0;\n for (const element of iterable) {\n if (predicate(element, i++)) {\n return true;\n }\n }\n return false;\n }\n Iterable.some = some;\n function find(iterable, predicate) {\n for (const element of iterable) {\n if (predicate(element)) {\n return element;\n }\n }\n return undefined;\n }\n Iterable.find = find;\n function* filter(iterable, predicate) {\n for (const element of iterable) {\n if (predicate(element)) {\n yield element;\n }\n }\n }\n Iterable.filter = filter;\n function* map(iterable, fn) {\n let index = 0;\n for (const element of iterable) {\n yield fn(element, index++);\n }\n }\n Iterable.map = map;\n function* flatMap(iterable, fn) {\n let index = 0;\n for (const element of iterable) {\n yield* fn(element, index++);\n }\n }\n Iterable.flatMap = flatMap;\n function* concat(...iterables) {\n for (const iterable of iterables) {\n yield* iterable;\n }\n }\n Iterable.concat = concat;\n function reduce(iterable, reducer, initialValue) {\n let value = initialValue;\n for (const element of iterable) {\n value = reducer(value, element);\n }\n return value;\n }\n Iterable.reduce = reduce;\n /**\n * Returns an iterable slice of the array, with the same semantics as `array.slice()`.\n */\n function* slice(arr, from, to = arr.length) {\n if (from < 0) {\n from += arr.length;\n }\n if (to < 0) {\n to += arr.length;\n }\n else if (to > arr.length) {\n to = arr.length;\n }\n for (; from < to; from++) {\n yield arr[from];\n }\n }\n Iterable.slice = slice;\n /**\n * Consumes `atMost` elements from iterable and returns the consumed elements,\n * and an iterable for the rest of the elements.\n */\n function consume(iterable, atMost = Number.POSITIVE_INFINITY) {\n const consumed = [];\n if (atMost === 0) {\n return [consumed, iterable];\n }\n const iterator = iterable[Symbol.iterator]();\n for (let i = 0; i < atMost; i++) {\n const next = iterator.next();\n if (next.done) {\n return [consumed, Iterable.empty()];\n }\n consumed.push(next.value);\n }\n return [consumed, { [Symbol.iterator]() { return iterator; } }];\n }\n Iterable.consume = consume;\n async function asyncToArray(iterable) {\n const result = [];\n for await (const item of iterable) {\n result.push(item);\n }\n return Promise.resolve(result);\n }\n Iterable.asyncToArray = asyncToArray;\n})(Iterable || (exports.Iterable = Iterable = {}));\n","\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.KeyMod = exports.KeyCodeUtils = exports.ScanCodeUtils = exports.NATIVE_WINDOWS_KEY_CODE_TO_KEY_CODE = exports.EVENT_KEY_CODE_MAP = exports.ScanCode = exports.KeyCode = void 0;\nexports.KeyChord = KeyChord;\n/**\n * Virtual Key Codes, the value does not hold any inherent meaning.\n * Inspired somewhat from https://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx\n * But these are \"more general\", as they should work across browsers & OS`s.\n */\nvar KeyCode;\n(function (KeyCode) {\n KeyCode[KeyCode[\"DependsOnKbLayout\"] = -1] = \"DependsOnKbLayout\";\n /**\n * Placed first to cover the 0 value of the enum.\n */\n KeyCode[KeyCode[\"Unknown\"] = 0] = \"Unknown\";\n KeyCode[KeyCode[\"Backspace\"] = 1] = \"Backspace\";\n KeyCode[KeyCode[\"Tab\"] = 2] = \"Tab\";\n KeyCode[KeyCode[\"Enter\"] = 3] = \"Enter\";\n KeyCode[KeyCode[\"Shift\"] = 4] = \"Shift\";\n KeyCode[KeyCode[\"Ctrl\"] = 5] = \"Ctrl\";\n KeyCode[KeyCode[\"Alt\"] = 6] = \"Alt\";\n KeyCode[KeyCode[\"PauseBreak\"] = 7] = \"PauseBreak\";\n KeyCode[KeyCode[\"CapsLock\"] = 8] = \"CapsLock\";\n KeyCode[KeyCode[\"Escape\"] = 9] = \"Escape\";\n KeyCode[KeyCode[\"Space\"] = 10] = \"Space\";\n KeyCode[KeyCode[\"PageUp\"] = 11] = \"PageUp\";\n KeyCode[KeyCode[\"PageDown\"] = 12] = \"PageDown\";\n KeyCode[KeyCode[\"End\"] = 13] = \"End\";\n KeyCode[KeyCode[\"Home\"] = 14] = \"Home\";\n KeyCode[KeyCode[\"LeftArrow\"] = 15] = \"LeftArrow\";\n KeyCode[KeyCode[\"UpArrow\"] = 16] = \"UpArrow\";\n KeyCode[KeyCode[\"RightArrow\"] = 17] = \"RightArrow\";\n KeyCode[KeyCode[\"DownArrow\"] = 18] = \"DownArrow\";\n KeyCode[KeyCode[\"Insert\"] = 19] = \"Insert\";\n KeyCode[KeyCode[\"Delete\"] = 20] = \"Delete\";\n KeyCode[KeyCode[\"Digit0\"] = 21] = \"Digit0\";\n KeyCode[KeyCode[\"Digit1\"] = 22] = \"Digit1\";\n KeyCode[KeyCode[\"Digit2\"] = 23] = \"Digit2\";\n KeyCode[KeyCode[\"Digit3\"] = 24] = \"Digit3\";\n KeyCode[KeyCode[\"Digit4\"] = 25] = \"Digit4\";\n KeyCode[KeyCode[\"Digit5\"] = 26] = \"Digit5\";\n KeyCode[KeyCode[\"Digit6\"] = 27] = \"Digit6\";\n KeyCode[KeyCode[\"Digit7\"] = 28] = \"Digit7\";\n KeyCode[KeyCode[\"Digit8\"] = 29] = \"Digit8\";\n KeyCode[KeyCode[\"Digit9\"] = 30] = \"Digit9\";\n KeyCode[KeyCode[\"KeyA\"] = 31] = \"KeyA\";\n KeyCode[KeyCode[\"KeyB\"] = 32] = \"KeyB\";\n KeyCode[KeyCode[\"KeyC\"] = 33] = \"KeyC\";\n KeyCode[KeyCode[\"KeyD\"] = 34] = \"KeyD\";\n KeyCode[KeyCode[\"KeyE\"] = 35] = \"KeyE\";\n KeyCode[KeyCode[\"KeyF\"] = 36] = \"KeyF\";\n KeyCode[KeyCode[\"KeyG\"] = 37] = \"KeyG\";\n KeyCode[KeyCode[\"KeyH\"] = 38] = \"KeyH\";\n KeyCode[KeyCode[\"KeyI\"] = 39] = \"KeyI\";\n KeyCode[KeyCode[\"KeyJ\"] = 40] = \"KeyJ\";\n KeyCode[KeyCode[\"KeyK\"] = 41] = \"KeyK\";\n KeyCode[KeyCode[\"KeyL\"] = 42] = \"KeyL\";\n KeyCode[KeyCode[\"KeyM\"] = 43] = \"KeyM\";\n KeyCode[KeyCode[\"KeyN\"] = 44] = \"KeyN\";\n KeyCode[KeyCode[\"KeyO\"] = 45] = \"KeyO\";\n KeyCode[KeyCode[\"KeyP\"] = 46] = \"KeyP\";\n KeyCode[KeyCode[\"KeyQ\"] = 47] = \"KeyQ\";\n KeyCode[KeyCode[\"KeyR\"] = 48] = \"KeyR\";\n KeyCode[KeyCode[\"KeyS\"] = 49] = \"KeyS\";\n KeyCode[KeyCode[\"KeyT\"] = 50] = \"KeyT\";\n KeyCode[KeyCode[\"KeyU\"] = 51] = \"KeyU\";\n KeyCode[KeyCode[\"KeyV\"] = 52] = \"KeyV\";\n KeyCode[KeyCode[\"KeyW\"] = 53] = \"KeyW\";\n KeyCode[KeyCode[\"KeyX\"] = 54] = \"KeyX\";\n KeyCode[KeyCode[\"KeyY\"] = 55] = \"KeyY\";\n KeyCode[KeyCode[\"KeyZ\"] = 56] = \"KeyZ\";\n KeyCode[KeyCode[\"Meta\"] = 57] = \"Meta\";\n KeyCode[KeyCode[\"ContextMenu\"] = 58] = \"ContextMenu\";\n KeyCode[KeyCode[\"F1\"] = 59] = \"F1\";\n KeyCode[KeyCode[\"F2\"] = 60] = \"F2\";\n KeyCode[KeyCode[\"F3\"] = 61] = \"F3\";\n KeyCode[KeyCode[\"F4\"] = 62] = \"F4\";\n KeyCode[KeyCode[\"F5\"] = 63] = \"F5\";\n KeyCode[KeyCode[\"F6\"] = 64] = \"F6\";\n KeyCode[KeyCode[\"F7\"] = 65] = \"F7\";\n KeyCode[KeyCode[\"F8\"] = 66] = \"F8\";\n KeyCode[KeyCode[\"F9\"] = 67] = \"F9\";\n KeyCode[KeyCode[\"F10\"] = 68] = \"F10\";\n KeyCode[KeyCode[\"F11\"] = 69] = \"F11\";\n KeyCode[KeyCode[\"F12\"] = 70] = \"F12\";\n KeyCode[KeyCode[\"F13\"] = 71] = \"F13\";\n KeyCode[KeyCode[\"F14\"] = 72] = \"F14\";\n KeyCode[KeyCode[\"F15\"] = 73] = \"F15\";\n KeyCode[KeyCode[\"F16\"] = 74] = \"F16\";\n KeyCode[KeyCode[\"F17\"] = 75] = \"F17\";\n KeyCode[KeyCode[\"F18\"] = 76] = \"F18\";\n KeyCode[KeyCode[\"F19\"] = 77] = \"F19\";\n KeyCode[KeyCode[\"F20\"] = 78] = \"F20\";\n KeyCode[KeyCode[\"F21\"] = 79] = \"F21\";\n KeyCode[KeyCode[\"F22\"] = 80] = \"F22\";\n KeyCode[KeyCode[\"F23\"] = 81] = \"F23\";\n KeyCode[KeyCode[\"F24\"] = 82] = \"F24\";\n KeyCode[KeyCode[\"NumLock\"] = 83] = \"NumLock\";\n KeyCode[KeyCode[\"ScrollLock\"] = 84] = \"ScrollLock\";\n /**\n * Used for miscellaneous characters; it can vary by keyboard.\n * For the US standard keyboard, the ';:' key\n */\n KeyCode[KeyCode[\"Semicolon\"] = 85] = \"Semicolon\";\n /**\n * For any country/region, the '+' key\n * For the US standard keyboard, the '=+' key\n */\n KeyCode[KeyCode[\"Equal\"] = 86] = \"Equal\";\n /**\n * For any country/region, the ',' key\n * For the US standard keyboard, the ',<' key\n */\n KeyCode[KeyCode[\"Comma\"] = 87] = \"Comma\";\n /**\n * For any country/region, the '-' key\n * For the US standard keyboard, the '-_' key\n */\n KeyCode[KeyCode[\"Minus\"] = 88] = \"Minus\";\n /**\n * For any country/region, the '.' key\n * For the US standard keyboard, the '.>' key\n */\n KeyCode[KeyCode[\"Period\"] = 89] = \"Period\";\n /**\n * Used for miscellaneous characters; it can vary by keyboard.\n * For the US standard keyboard, the '/?' key\n */\n KeyCode[KeyCode[\"Slash\"] = 90] = \"Slash\";\n /**\n * Used for miscellaneous characters; it can vary by keyboard.\n * For the US standard keyboard, the '`~' key\n */\n KeyCode[KeyCode[\"Backquote\"] = 91] = \"Backquote\";\n /**\n * Used for miscellaneous characters; it can vary by keyboard.\n * For the US standard keyboard, the '[{' key\n */\n KeyCode[KeyCode[\"BracketLeft\"] = 92] = \"BracketLeft\";\n /**\n * Used for miscellaneous characters; it can vary by keyboard.\n * For the US standard keyboard, the '\\|' key\n */\n KeyCode[KeyCode[\"Backslash\"] = 93] = \"Backslash\";\n /**\n * Used for miscellaneous characters; it can vary by keyboard.\n * For the US standard keyboard, the ']}' key\n */\n KeyCode[KeyCode[\"BracketRight\"] = 94] = \"BracketRight\";\n /**\n * Used for miscellaneous characters; it can vary by keyboard.\n * For the US standard keyboard, the ''\"' key\n */\n KeyCode[KeyCode[\"Quote\"] = 95] = \"Quote\";\n /**\n * Used for miscellaneous characters; it can vary by keyboard.\n */\n KeyCode[KeyCode[\"OEM_8\"] = 96] = \"OEM_8\";\n /**\n * Either the angle bracket key or the backslash key on the RT 102-key keyboard.\n */\n KeyCode[KeyCode[\"IntlBackslash\"] = 97] = \"IntlBackslash\";\n KeyCode[KeyCode[\"Numpad0\"] = 98] = \"Numpad0\";\n KeyCode[KeyCode[\"Numpad1\"] = 99] = \"Numpad1\";\n KeyCode[KeyCode[\"Numpad2\"] = 100] = \"Numpad2\";\n KeyCode[KeyCode[\"Numpad3\"] = 101] = \"Numpad3\";\n KeyCode[KeyCode[\"Numpad4\"] = 102] = \"Numpad4\";\n KeyCode[KeyCode[\"Numpad5\"] = 103] = \"Numpad5\";\n KeyCode[KeyCode[\"Numpad6\"] = 104] = \"Numpad6\";\n KeyCode[KeyCode[\"Numpad7\"] = 105] = \"Numpad7\";\n KeyCode[KeyCode[\"Numpad8\"] = 106] = \"Numpad8\";\n KeyCode[KeyCode[\"Numpad9\"] = 107] = \"Numpad9\";\n KeyCode[KeyCode[\"NumpadMultiply\"] = 108] = \"NumpadMultiply\";\n KeyCode[KeyCode[\"NumpadAdd\"] = 109] = \"NumpadAdd\";\n KeyCode[KeyCode[\"NUMPAD_SEPARATOR\"] = 110] = \"NUMPAD_SEPARATOR\";\n KeyCode[KeyCode[\"NumpadSubtract\"] = 111] = \"NumpadSubtract\";\n KeyCode[KeyCode[\"NumpadDecimal\"] = 112] = \"NumpadDecimal\";\n KeyCode[KeyCode[\"NumpadDivide\"] = 113] = \"NumpadDivide\";\n /**\n * Cover all key codes when IME is processing input.\n */\n KeyCode[KeyCode[\"KEY_IN_COMPOSITION\"] = 114] = \"KEY_IN_COMPOSITION\";\n KeyCode[KeyCode[\"ABNT_C1\"] = 115] = \"ABNT_C1\";\n KeyCode[KeyCode[\"ABNT_C2\"] = 116] = \"ABNT_C2\";\n KeyCode[KeyCode[\"AudioVolumeMute\"] = 117] = \"AudioVolumeMute\";\n KeyCode[KeyCode[\"AudioVolumeUp\"] = 118] = \"AudioVolumeUp\";\n KeyCode[KeyCode[\"AudioVolumeDown\"] = 119] = \"AudioVolumeDown\";\n KeyCode[KeyCode[\"BrowserSearch\"] = 120] = \"BrowserSearch\";\n KeyCode[KeyCode[\"BrowserHome\"] = 121] = \"BrowserHome\";\n KeyCode[KeyCode[\"BrowserBack\"] = 122] = \"BrowserBack\";\n KeyCode[KeyCode[\"BrowserForward\"] = 123] = \"BrowserForward\";\n KeyCode[KeyCode[\"MediaTrackNext\"] = 124] = \"MediaTrackNext\";\n KeyCode[KeyCode[\"MediaTrackPrevious\"] = 125] = \"MediaTrackPrevious\";\n KeyCode[KeyCode[\"MediaStop\"] = 126] = \"MediaStop\";\n KeyCode[KeyCode[\"MediaPlayPause\"] = 127] = \"MediaPlayPause\";\n KeyCode[KeyCode[\"LaunchMediaPlayer\"] = 128] = \"LaunchMediaPlayer\";\n KeyCode[KeyCode[\"LaunchMail\"] = 129] = \"LaunchMail\";\n KeyCode[KeyCode[\"LaunchApp2\"] = 130] = \"LaunchApp2\";\n /**\n * VK_CLEAR, 0x0C, CLEAR key\n */\n KeyCode[KeyCode[\"Clear\"] = 131] = \"Clear\";\n /**\n * Placed last to cover the length of the enum.\n * Please do not depend on this value!\n */\n KeyCode[KeyCode[\"MAX_VALUE\"] = 132] = \"MAX_VALUE\";\n})(KeyCode || (exports.KeyCode = KeyCode = {}));\n/**\n * keyboardEvent.code\n */\nvar ScanCode;\n(function (ScanCode) {\n ScanCode[ScanCode[\"DependsOnKbLayout\"] = -1] = \"DependsOnKbLayout\";\n ScanCode[ScanCode[\"None\"] = 0] = \"None\";\n ScanCode[ScanCode[\"Hyper\"] = 1] = \"Hyper\";\n ScanCode[ScanCode[\"Super\"] = 2] = \"Super\";\n ScanCode[ScanCode[\"Fn\"] = 3] = \"Fn\";\n ScanCode[ScanCode[\"FnLock\"] = 4] = \"FnLock\";\n ScanCode[ScanCode[\"Suspend\"] = 5] = \"Suspend\";\n ScanCode[ScanCode[\"Resume\"] = 6] = \"Resume\";\n ScanCode[ScanCode[\"Turbo\"] = 7] = \"Turbo\";\n ScanCode[ScanCode[\"Sleep\"] = 8] = \"Sleep\";\n ScanCode[ScanCode[\"WakeUp\"] = 9] = \"WakeUp\";\n ScanCode[ScanCode[\"KeyA\"] = 10] = \"KeyA\";\n ScanCode[ScanCode[\"KeyB\"] = 11] = \"KeyB\";\n ScanCode[ScanCode[\"KeyC\"] = 12] = \"KeyC\";\n ScanCode[ScanCode[\"KeyD\"] = 13] = \"KeyD\";\n ScanCode[ScanCode[\"KeyE\"] = 14] = \"KeyE\";\n ScanCode[ScanCode[\"KeyF\"] = 15] = \"KeyF\";\n ScanCode[ScanCode[\"KeyG\"] = 16] = \"KeyG\";\n ScanCode[ScanCode[\"KeyH\"] = 17] = \"KeyH\";\n ScanCode[ScanCode[\"KeyI\"] = 18] = \"KeyI\";\n ScanCode[ScanCode[\"KeyJ\"] = 19] = \"KeyJ\";\n ScanCode[ScanCode[\"KeyK\"] = 20] = \"KeyK\";\n ScanCode[ScanCode[\"KeyL\"] = 21] = \"KeyL\";\n ScanCode[ScanCode[\"KeyM\"] = 22] = \"KeyM\";\n ScanCode[ScanCode[\"KeyN\"] = 23] = \"KeyN\";\n ScanCode[ScanCode[\"KeyO\"] = 24] = \"KeyO\";\n ScanCode[ScanCode[\"KeyP\"] = 25] = \"KeyP\";\n ScanCode[ScanCode[\"KeyQ\"] = 26] = \"KeyQ\";\n ScanCode[ScanCode[\"KeyR\"] = 27] = \"KeyR\";\n ScanCode[ScanCode[\"KeyS\"] = 28] = \"KeyS\";\n ScanCode[ScanCode[\"KeyT\"] = 29] = \"KeyT\";\n ScanCode[ScanCode[\"KeyU\"] = 30] = \"KeyU\";\n ScanCode[ScanCode[\"KeyV\"] = 31] = \"KeyV\";\n ScanCode[ScanCode[\"KeyW\"] = 32] = \"KeyW\";\n ScanCode[ScanCode[\"KeyX\"] = 33] = \"KeyX\";\n ScanCode[ScanCode[\"KeyY\"] = 34] = \"KeyY\";\n ScanCode[ScanCode[\"KeyZ\"] = 35] = \"KeyZ\";\n ScanCode[ScanCode[\"Digit1\"] = 36] = \"Digit1\";\n ScanCode[ScanCode[\"Digit2\"] = 37] = \"Digit2\";\n ScanCode[ScanCode[\"Digit3\"] = 38] = \"Digit3\";\n ScanCode[ScanCode[\"Digit4\"] = 39] = \"Digit4\";\n ScanCode[ScanCode[\"Digit5\"] = 40] = \"Digit5\";\n ScanCode[ScanCode[\"Digit6\"] = 41] = \"Digit6\";\n ScanCode[ScanCode[\"Digit7\"] = 42] = \"Digit7\";\n ScanCode[ScanCode[\"Digit8\"] = 43] = \"Digit8\";\n ScanCode[ScanCode[\"Digit9\"] = 44] = \"Digit9\";\n ScanCode[ScanCode[\"Digit0\"] = 45] = \"Digit0\";\n ScanCode[ScanCode[\"Enter\"] = 46] = \"Enter\";\n ScanCode[ScanCode[\"Escape\"] = 47] = \"Escape\";\n ScanCode[ScanCode[\"Backspace\"] = 48] = \"Backspace\";\n ScanCode[ScanCode[\"Tab\"] = 49] = \"Tab\";\n ScanCode[ScanCode[\"Space\"] = 50] = \"Space\";\n ScanCode[ScanCode[\"Minus\"] = 51] = \"Minus\";\n ScanCode[ScanCode[\"Equal\"] = 52] = \"Equal\";\n ScanCode[ScanCode[\"BracketLeft\"] = 53] = \"BracketLeft\";\n ScanCode[ScanCode[\"BracketRight\"] = 54] = \"BracketRight\";\n ScanCode[ScanCode[\"Backslash\"] = 55] = \"Backslash\";\n ScanCode[ScanCode[\"IntlHash\"] = 56] = \"IntlHash\";\n ScanCode[ScanCode[\"Semicolon\"] = 57] = \"Semicolon\";\n ScanCode[ScanCode[\"Quote\"] = 58] = \"Quote\";\n ScanCode[ScanCode[\"Backquote\"] = 59] = \"Backquote\";\n ScanCode[ScanCode[\"Comma\"] = 60] = \"Comma\";\n ScanCode[ScanCode[\"Period\"] = 61] = \"Period\";\n ScanCode[ScanCode[\"Slash\"] = 62] = \"Slash\";\n ScanCode[ScanCode[\"CapsLock\"] = 63] = \"CapsLock\";\n ScanCode[ScanCode[\"F1\"] = 64] = \"F1\";\n ScanCode[ScanCode[\"F2\"] = 65] = \"F2\";\n ScanCode[ScanCode[\"F3\"] = 66] = \"F3\";\n ScanCode[ScanCode[\"F4\"] = 67] = \"F4\";\n ScanCode[ScanCode[\"F5\"] = 68] = \"F5\";\n ScanCode[ScanCode[\"F6\"] = 69] = \"F6\";\n ScanCode[ScanCode[\"F7\"] = 70] = \"F7\";\n ScanCode[ScanCode[\"F8\"] = 71] = \"F8\";\n ScanCode[ScanCode[\"F9\"] = 72] = \"F9\";\n ScanCode[ScanCode[\"F10\"] = 73] = \"F10\";\n ScanCode[ScanCode[\"F11\"] = 74] = \"F11\";\n ScanCode[ScanCode[\"F12\"] = 75] = \"F12\";\n ScanCode[ScanCode[\"PrintScreen\"] = 76] = \"PrintScreen\";\n ScanCode[ScanCode[\"ScrollLock\"] = 77] = \"ScrollLock\";\n ScanCode[ScanCode[\"Pause\"] = 78] = \"Pause\";\n ScanCode[ScanCode[\"Insert\"] = 79] = \"Insert\";\n ScanCode[ScanCode[\"Home\"] = 80] = \"Home\";\n ScanCode[ScanCode[\"PageUp\"] = 81] = \"PageUp\";\n ScanCode[ScanCode[\"Delete\"] = 82] = \"Delete\";\n ScanCode[ScanCode[\"End\"] = 83] = \"End\";\n ScanCode[ScanCode[\"PageDown\"] = 84] = \"PageDown\";\n ScanCode[ScanCode[\"ArrowRight\"] = 85] = \"ArrowRight\";\n ScanCode[ScanCode[\"ArrowLeft\"] = 86] = \"ArrowLeft\";\n ScanCode[ScanCode[\"ArrowDown\"] = 87] = \"ArrowDown\";\n ScanCode[ScanCode[\"ArrowUp\"] = 88] = \"ArrowUp\";\n ScanCode[ScanCode[\"NumLock\"] = 89] = \"NumLock\";\n ScanCode[ScanCode[\"NumpadDivide\"] = 90] = \"NumpadDivide\";\n ScanCode[ScanCode[\"NumpadMultiply\"] = 91] = \"NumpadMultiply\";\n ScanCode[ScanCode[\"NumpadSubtract\"] = 92] = \"NumpadSubtract\";\n ScanCode[ScanCode[\"NumpadAdd\"] = 93] = \"NumpadAdd\";\n ScanCode[ScanCode[\"NumpadEnter\"] = 94] = \"NumpadEnter\";\n ScanCode[ScanCode[\"Numpad1\"] = 95] = \"Numpad1\";\n ScanCode[ScanCode[\"Numpad2\"] = 96] = \"Numpad2\";\n ScanCode[ScanCode[\"Numpad3\"] = 97] = \"Numpad3\";\n ScanCode[ScanCode[\"Numpad4\"] = 98] = \"Numpad4\";\n ScanCode[ScanCode[\"Numpad5\"] = 99] = \"Numpad5\";\n ScanCode[ScanCode[\"Numpad6\"] = 100] = \"Numpad6\";\n ScanCode[ScanCode[\"Numpad7\"] = 101] = \"Numpad7\";\n ScanCode[ScanCode[\"Numpad8\"] = 102] = \"Numpad8\";\n ScanCode[ScanCode[\"Numpad9\"] = 103] = \"Numpad9\";\n ScanCode[ScanCode[\"Numpad0\"] = 104] = \"Numpad0\";\n ScanCode[ScanCode[\"NumpadDecimal\"] = 105] = \"NumpadDecimal\";\n ScanCode[ScanCode[\"IntlBackslash\"] = 106] = \"IntlBackslash\";\n ScanCode[ScanCode[\"ContextMenu\"] = 107] = \"ContextMenu\";\n ScanCode[ScanCode[\"Power\"] = 108] = \"Power\";\n ScanCode[ScanCode[\"NumpadEqual\"] = 109] = \"NumpadEqual\";\n ScanCode[ScanCode[\"F13\"] = 110] = \"F13\";\n ScanCode[ScanCode[\"F14\"] = 111] = \"F14\";\n ScanCode[ScanCode[\"F15\"] = 112] = \"F15\";\n ScanCode[ScanCode[\"F16\"] = 113] = \"F16\";\n ScanCode[ScanCode[\"F17\"] = 114] = \"F17\";\n ScanCode[ScanCode[\"F18\"] = 115] = \"F18\";\n ScanCode[ScanCode[\"F19\"] = 116] = \"F19\";\n ScanCode[ScanCode[\"F20\"] = 117] = \"F20\";\n ScanCode[ScanCode[\"F21\"] = 118] = \"F21\";\n ScanCode[ScanCode[\"F22\"] = 119] = \"F22\";\n ScanCode[ScanCode[\"F23\"] = 120] = \"F23\";\n ScanCode[ScanCode[\"F24\"] = 121] = \"F24\";\n ScanCode[ScanCode[\"Open\"] = 122] = \"Open\";\n ScanCode[ScanCode[\"Help\"] = 123] = \"Help\";\n ScanCode[ScanCode[\"Select\"] = 124] = \"Select\";\n ScanCode[ScanCode[\"Again\"] = 125] = \"Again\";\n ScanCode[ScanCode[\"Undo\"] = 126] = \"Undo\";\n ScanCode[ScanCode[\"Cut\"] = 127] = \"Cut\";\n ScanCode[ScanCode[\"Copy\"] = 128] = \"Copy\";\n ScanCode[ScanCode[\"Paste\"] = 129] = \"Paste\";\n ScanCode[ScanCode[\"Find\"] = 130] = \"Find\";\n ScanCode[ScanCode[\"AudioVolumeMute\"] = 131] = \"AudioVolumeMute\";\n ScanCode[ScanCode[\"AudioVolumeUp\"] = 132] = \"AudioVolumeUp\";\n ScanCode[ScanCode[\"AudioVolumeDown\"] = 133] = \"AudioVolumeDown\";\n ScanCode[ScanCode[\"NumpadComma\"] = 134] = \"NumpadComma\";\n ScanCode[ScanCode[\"IntlRo\"] = 135] = \"IntlRo\";\n ScanCode[ScanCode[\"KanaMode\"] = 136] = \"KanaMode\";\n ScanCode[ScanCode[\"IntlYen\"] = 137] = \"IntlYen\";\n ScanCode[ScanCode[\"Convert\"] = 138] = \"Convert\";\n ScanCode[ScanCode[\"NonConvert\"] = 139] = \"NonConvert\";\n ScanCode[ScanCode[\"Lang1\"] = 140] = \"Lang1\";\n ScanCode[ScanCode[\"Lang2\"] = 141] = \"Lang2\";\n ScanCode[ScanCode[\"Lang3\"] = 142] = \"Lang3\";\n ScanCode[ScanCode[\"Lang4\"] = 143] = \"Lang4\";\n ScanCode[ScanCode[\"Lang5\"] = 144] = \"Lang5\";\n ScanCode[ScanCode[\"Abort\"] = 145] = \"Abort\";\n ScanCode[ScanCode[\"Props\"] = 146] = \"Props\";\n ScanCode[ScanCode[\"NumpadParenLeft\"] = 147] = \"NumpadParenLeft\";\n ScanCode[ScanCode[\"NumpadParenRight\"] = 148] = \"NumpadParenRight\";\n ScanCode[ScanCode[\"NumpadBackspace\"] = 149] = \"NumpadBackspace\";\n ScanCode[ScanCode[\"NumpadMemoryStore\"] = 150] = \"NumpadMemoryStore\";\n ScanCode[ScanCode[\"NumpadMemoryRecall\"] = 151] = \"NumpadMemoryRecall\";\n ScanCode[ScanCode[\"NumpadMemoryClear\"] = 152] = \"NumpadMemoryClear\";\n ScanCode[ScanCode[\"NumpadMemoryAdd\"] = 153] = \"NumpadMemoryAdd\";\n ScanCode[ScanCode[\"NumpadMemorySubtract\"] = 154] = \"NumpadMemorySubtract\";\n ScanCode[ScanCode[\"NumpadClear\"] = 155] = \"NumpadClear\";\n ScanCode[ScanCode[\"NumpadClearEntry\"] = 156] = \"NumpadClearEntry\";\n ScanCode[ScanCode[\"ControlLeft\"] = 157] = \"ControlLeft\";\n ScanCode[ScanCode[\"ShiftLeft\"] = 158] = \"ShiftLeft\";\n ScanCode[ScanCode[\"AltLeft\"] = 159] = \"AltLeft\";\n ScanCode[ScanCode[\"MetaLeft\"] = 160] = \"MetaLeft\";\n ScanCode[ScanCode[\"ControlRight\"] = 161] = \"ControlRight\";\n ScanCode[ScanCode[\"ShiftRight\"] = 162] = \"ShiftRight\";\n ScanCode[ScanCode[\"AltRight\"] = 163] = \"AltRight\";\n ScanCode[ScanCode[\"MetaRight\"] = 164] = \"MetaRight\";\n ScanCode[ScanCode[\"BrightnessUp\"] = 165] = \"BrightnessUp\";\n ScanCode[ScanCode[\"BrightnessDown\"] = 166] = \"BrightnessDown\";\n ScanCode[ScanCode[\"MediaPlay\"] = 167] = \"MediaPlay\";\n ScanCode[ScanCode[\"MediaRecord\"] = 168] = \"MediaRecord\";\n ScanCode[ScanCode[\"MediaFastForward\"] = 169] = \"MediaFastForward\";\n ScanCode[ScanCode[\"MediaRewind\"] = 170] = \"MediaRewind\";\n ScanCode[ScanCode[\"MediaTrackNext\"] = 171] = \"MediaTrackNext\";\n ScanCode[ScanCode[\"MediaTrackPrevious\"] = 172] = \"MediaTrackPrevious\";\n ScanCode[ScanCode[\"MediaStop\"] = 173] = \"MediaStop\";\n ScanCode[ScanCode[\"Eject\"] = 174] = \"Eject\";\n ScanCode[ScanCode[\"MediaPlayPause\"] = 175] = \"MediaPlayPause\";\n ScanCode[ScanCode[\"MediaSelect\"] = 176] = \"MediaSelect\";\n ScanCode[ScanCode[\"LaunchMail\"] = 177] = \"LaunchMail\";\n ScanCode[ScanCode[\"LaunchApp2\"] = 178] = \"LaunchApp2\";\n ScanCode[ScanCode[\"LaunchApp1\"] = 179] = \"LaunchApp1\";\n ScanCode[ScanCode[\"SelectTask\"] = 180] = \"SelectTask\";\n ScanCode[ScanCode[\"LaunchScreenSaver\"] = 181] = \"LaunchScreenSaver\";\n ScanCode[ScanCode[\"BrowserSearch\"] = 182] = \"BrowserSearch\";\n ScanCode[ScanCode[\"BrowserHome\"] = 183] = \"BrowserHome\";\n ScanCode[ScanCode[\"BrowserBack\"] = 184] = \"BrowserBack\";\n ScanCode[ScanCode[\"BrowserForward\"] = 185] = \"BrowserForward\";\n ScanCode[ScanCode[\"BrowserStop\"] = 186] = \"BrowserStop\";\n ScanCode[ScanCode[\"BrowserRefresh\"] = 187] = \"BrowserRefresh\";\n ScanCode[ScanCode[\"BrowserFavorites\"] = 188] = \"BrowserFavorites\";\n ScanCode[ScanCode[\"ZoomToggle\"] = 189] = \"ZoomToggle\";\n ScanCode[ScanCode[\"MailReply\"] = 190] = \"MailReply\";\n ScanCode[ScanCode[\"MailForward\"] = 191] = \"MailForward\";\n ScanCode[ScanCode[\"MailSend\"] = 192] = \"MailSend\";\n ScanCode[ScanCode[\"MAX_VALUE\"] = 193] = \"MAX_VALUE\";\n})(ScanCode || (exports.ScanCode = ScanCode = {}));\nclass KeyCodeStrMap {\n constructor() {\n this._keyCodeToStr = [];\n this._strToKeyCode = Object.create(null);\n }\n define(keyCode, str) {\n this._keyCodeToStr[keyCode] = str;\n this._strToKeyCode[str.toLowerCase()] = keyCode;\n }\n keyCodeToStr(keyCode) {\n return this._keyCodeToStr[keyCode];\n }\n strToKeyCode(str) {\n return this._strToKeyCode[str.toLowerCase()] || KeyCode.Unknown;\n }\n}\nconst uiMap = new KeyCodeStrMap();\nconst userSettingsUSMap = new KeyCodeStrMap();\nconst userSettingsGeneralMap = new KeyCodeStrMap();\nexports.EVENT_KEY_CODE_MAP = new Array(230);\nexports.NATIVE_WINDOWS_KEY_CODE_TO_KEY_CODE = {};\nconst scanCodeIntToStr = [];\nconst scanCodeStrToInt = Object.create(null);\nconst scanCodeLowerCaseStrToInt = Object.create(null);\nexports.ScanCodeUtils = {\n lowerCaseToEnum: (scanCode) => scanCodeLowerCaseStrToInt[scanCode] || ScanCode.None,\n toEnum: (scanCode) => scanCodeStrToInt[scanCode] || ScanCode.None,\n toString: (scanCode) => scanCodeIntToStr[scanCode] || 'None'\n};\nvar KeyCodeUtils;\n(function (KeyCodeUtils) {\n function toString(keyCode) {\n return uiMap.keyCodeToStr(keyCode);\n }\n KeyCodeUtils.toString = toString;\n function fromString(key) {\n return uiMap.strToKeyCode(key);\n }\n KeyCodeUtils.fromString = fromString;\n function toUserSettingsUS(keyCode) {\n return userSettingsUSMap.keyCodeToStr(keyCode);\n }\n KeyCodeUtils.toUserSettingsUS = toUserSettingsUS;\n function toUserSettingsGeneral(keyCode) {\n return userSettingsGeneralMap.keyCodeToStr(keyCode);\n }\n KeyCodeUtils.toUserSettingsGeneral = toUserSettingsGeneral;\n function fromUserSettings(key) {\n return userSettingsUSMap.strToKeyCode(key) || userSettingsGeneralMap.strToKeyCode(key);\n }\n KeyCodeUtils.fromUserSettings = fromUserSettings;\n function toElectronAccelerator(keyCode) {\n if (keyCode >= KeyCode.Numpad0 && keyCode <= KeyCode.NumpadDivide) {\n // [Electron Accelerators] Electron is able to parse numpad keys, but unfortunately it\n // renders them just as regular keys in menus. For example, num0 is rendered as \"0\",\n // numdiv is rendered as \"/\", numsub is rendered as \"-\".\n //\n // This can lead to incredible confusion, as it makes numpad based keybindings indistinguishable\n // from keybindings based on regular keys.\n //\n // We therefore need to fall back to custom rendering for numpad keys.\n return null;\n }\n switch (keyCode) {\n case KeyCode.UpArrow:\n return 'Up';\n case KeyCode.DownArrow:\n return 'Down';\n case KeyCode.LeftArrow:\n return 'Left';\n case KeyCode.RightArrow:\n return 'Right';\n }\n return uiMap.keyCodeToStr(keyCode);\n }\n KeyCodeUtils.toElectronAccelerator = toElectronAccelerator;\n})(KeyCodeUtils || (exports.KeyCodeUtils = KeyCodeUtils = {}));\nvar KeyMod;\n(function (KeyMod) {\n KeyMod[KeyMod[\"CtrlCmd\"] = 2048] = \"CtrlCmd\";\n KeyMod[KeyMod[\"Shift\"] = 1024] = \"Shift\";\n KeyMod[KeyMod[\"Alt\"] = 512] = \"Alt\";\n KeyMod[KeyMod[\"WinCtrl\"] = 256] = \"WinCtrl\";\n})(KeyMod || (exports.KeyMod = KeyMod = {}));\nfunction KeyChord(firstPart, secondPart) {\n const chordPart = ((secondPart & 0x0000FFFF) << 16) >>> 0;\n return (firstPart | chordPart) >>> 0;\n}\n","\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ResolvedKeybinding = exports.ResolvedChord = exports.Keybinding = exports.ScanCodeChord = exports.KeyCodeChord = void 0;\nexports.decodeKeybinding = decodeKeybinding;\nexports.createSimpleKeybinding = createSimpleKeybinding;\nconst errors_1 = require(\"vs/base/common/errors\");\nconst keyCodes_1 = require(\"vs/base/common/keyCodes\");\nconst platform_1 = require(\"vs/base/common/platform\");\n/**\n * Binary encoding strategy:\n * ```\n * 1111 11\n * 5432 1098 7654 3210\n * ---- CSAW KKKK KKKK\n * C = bit 11 = ctrlCmd flag\n * S = bit 10 = shift flag\n * A = bit 9 = alt flag\n * W = bit 8 = winCtrl flag\n * K = bits 0-7 = key code\n * ```\n */\nvar BinaryKeybindingsMask;\n(function (BinaryKeybindingsMask) {\n BinaryKeybindingsMask[BinaryKeybindingsMask[\"CtrlCmd\"] = 2048] = \"CtrlCmd\";\n BinaryKeybindingsMask[BinaryKeybindingsMask[\"Shift\"] = 1024] = \"Shift\";\n BinaryKeybindingsMask[BinaryKeybindingsMask[\"Alt\"] = 512] = \"Alt\";\n BinaryKeybindingsMask[BinaryKeybindingsMask[\"WinCtrl\"] = 256] = \"WinCtrl\";\n BinaryKeybindingsMask[BinaryKeybindingsMask[\"KeyCode\"] = 255] = \"KeyCode\";\n})(BinaryKeybindingsMask || (BinaryKeybindingsMask = {}));\nfunction decodeKeybinding(keybinding, OS) {\n if (typeof keybinding === 'number') {\n if (keybinding === 0) {\n return null;\n }\n const firstChord = (keybinding & 0x0000FFFF) >>> 0;\n const secondChord = (keybinding & 0xFFFF0000) >>> 16;\n if (secondChord !== 0) {\n return new Keybinding([\n createSimpleKeybinding(firstChord, OS),\n createSimpleKeybinding(secondChord, OS)\n ]);\n }\n return new Keybinding([createSimpleKeybinding(firstChord, OS)]);\n }\n else {\n const chords = [];\n for (let i = 0; i < keybinding.length; i++) {\n chords.push(createSimpleKeybinding(keybinding[i], OS));\n }\n return new Keybinding(chords);\n }\n}\nfunction createSimpleKeybinding(keybinding, OS) {\n const ctrlCmd = (keybinding & BinaryKeybindingsMask.CtrlCmd ? true : false);\n const winCtrl = (keybinding & BinaryKeybindingsMask.WinCtrl ? true : false);\n const ctrlKey = (OS === platform_1.OperatingSystem.Macintosh ? winCtrl : ctrlCmd);\n const shiftKey = (keybinding & BinaryKeybindingsMask.Shift ? true : false);\n const altKey = (keybinding & BinaryKeybindingsMask.Alt ? true : false);\n const metaKey = (OS === platform_1.OperatingSystem.Macintosh ? ctrlCmd : winCtrl);\n const keyCode = (keybinding & BinaryKeybindingsMask.KeyCode);\n return new KeyCodeChord(ctrlKey, shiftKey, altKey, metaKey, keyCode);\n}\n/**\n * Represents a chord which uses the `keyCode` field of keyboard events.\n * A chord is a combination of keys pressed simultaneously.\n */\nclass KeyCodeChord {\n constructor(ctrlKey, shiftKey, altKey, metaKey, keyCode) {\n this.ctrlKey = ctrlKey;\n this.shiftKey = shiftKey;\n this.altKey = altKey;\n this.metaKey = metaKey;\n this.keyCode = keyCode;\n }\n equals(other) {\n return (other instanceof KeyCodeChord\n && this.ctrlKey === other.ctrlKey\n && this.shiftKey === other.shiftKey\n && this.altKey === other.altKey\n && this.metaKey === other.metaKey\n && this.keyCode === other.keyCode);\n }\n getHashCode() {\n const ctrl = this.ctrlKey ? '1' : '0';\n const shift = this.shiftKey ? '1' : '0';\n const alt = this.altKey ? '1' : '0';\n const meta = this.metaKey ? '1' : '0';\n return `K${ctrl}${shift}${alt}${meta}${this.keyCode}`;\n }\n isModifierKey() {\n return (this.keyCode === keyCodes_1.KeyCode.Unknown\n || this.keyCode === keyCodes_1.KeyCode.Ctrl\n || this.keyCode === keyCodes_1.KeyCode.Meta\n || this.keyCode === keyCodes_1.KeyCode.Alt\n || this.keyCode === keyCodes_1.KeyCode.Shift);\n }\n toKeybinding() {\n return new Keybinding([this]);\n }\n /**\n * Does this keybinding refer to the key code of a modifier and it also has the modifier flag?\n */\n isDuplicateModifierCase() {\n return ((this.ctrlKey && this.keyCode === keyCodes_1.KeyCode.Ctrl)\n || (this.shiftKey && this.keyCode === keyCodes_1.KeyCode.Shift)\n || (this.altKey && this.keyCode === keyCodes_1.KeyCode.Alt)\n || (this.metaKey && this.keyCode === keyCodes_1.KeyCode.Meta));\n }\n}\nexports.KeyCodeChord = KeyCodeChord;\n/**\n * Represents a chord which uses the `code` field of keyboard events.\n * A chord is a combination of keys pressed simultaneously.\n */\nclass ScanCodeChord {\n constructor(ctrlKey, shiftKey, altKey, metaKey, scanCode) {\n this.ctrlKey = ctrlKey;\n this.shiftKey = shiftKey;\n this.altKey = altKey;\n this.metaKey = metaKey;\n this.scanCode = scanCode;\n }\n equals(other) {\n return (other instanceof ScanCodeChord\n && this.ctrlKey === other.ctrlKey\n && this.shiftKey === other.shiftKey\n && this.altKey === other.altKey\n && this.metaKey === other.metaKey\n && this.scanCode === other.scanCode);\n }\n getHashCode() {\n const ctrl = this.ctrlKey ? '1' : '0';\n const shift = this.shiftKey ? '1' : '0';\n const alt = this.altKey ? '1' : '0';\n const meta = this.metaKey ? '1' : '0';\n return `S${ctrl}${shift}${alt}${meta}${this.scanCode}`;\n }\n /**\n * Does this keybinding refer to the key code of a modifier and it also has the modifier flag?\n */\n isDuplicateModifierCase() {\n return ((this.ctrlKey && (this.scanCode === keyCodes_1.ScanCode.ControlLeft || this.scanCode === keyCodes_1.ScanCode.ControlRight))\n || (this.shiftKey && (this.scanCode === keyCodes_1.ScanCode.ShiftLeft || this.scanCode === keyCodes_1.ScanCode.ShiftRight))\n || (this.altKey && (this.scanCode === keyCodes_1.ScanCode.AltLeft || this.scanCode === keyCodes_1.ScanCode.AltRight))\n || (this.metaKey && (this.scanCode === keyCodes_1.ScanCode.MetaLeft || this.scanCode === keyCodes_1.ScanCode.MetaRight)));\n }\n}\nexports.ScanCodeChord = ScanCodeChord;\n/**\n * A keybinding is a sequence of chords.\n */\nclass Keybinding {\n constructor(chords) {\n if (chords.length === 0) {\n throw (0, errors_1.illegalArgument)(`chords`);\n }\n this.chords = chords;\n }\n getHashCode() {\n let result = '';\n for (let i = 0, len = this.chords.length; i < len; i++) {\n if (i !== 0) {\n result += ';';\n }\n result += this.chords[i].getHashCode();\n }\n return result;\n }\n equals(other) {\n if (other === null) {\n return false;\n }\n if (this.chords.length !== other.chords.length) {\n return false;\n }\n for (let i = 0; i < this.chords.length; i++) {\n if (!this.chords[i].equals(other.chords[i])) {\n return false;\n }\n }\n return true;\n }\n}\nexports.Keybinding = Keybinding;\nclass ResolvedChord {\n constructor(ctrlKey, shiftKey, altKey, metaKey, keyLabel, keyAriaLabel) {\n this.ctrlKey = ctrlKey;\n this.shiftKey = shiftKey;\n this.altKey = altKey;\n this.metaKey = metaKey;\n this.keyLabel = keyLabel;\n this.keyAriaLabel = keyAriaLabel;\n }\n}\nexports.ResolvedChord = ResolvedChord;\n/**\n * A resolved keybinding. Consists of one or multiple chords.\n */\nclass ResolvedKeybinding {\n}\nexports.ResolvedKeybinding = ResolvedKeybinding;\n","\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Lazy = void 0;\nclass Lazy {\n constructor(executor) {\n this.executor = executor;\n this._didRun = false;\n }\n /**\n * True if the lazy value has been resolved.\n */\n get hasValue() { return this._didRun; }\n /**\n * Get the wrapped value.\n *\n * This will force evaluation of the lazy value if it has not been resolved yet. Lazy values are only\n * resolved once. `getValue` will re-throw exceptions that are hit while resolving the value\n */\n get value() {\n if (!this._didRun) {\n try {\n this._value = this.executor();\n }\n catch (err) {\n this._error = err;\n }\n finally {\n this._didRun = true;\n }\n }\n if (this._error) {\n throw this._error;\n }\n return this._value;\n }\n /**\n * Get the wrapped value without forcing evaluation.\n */\n get rawValue() { return this._value; }\n}\nexports.Lazy = Lazy;\n","\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.DisposableMap = exports.ImmortalReference = exports.AsyncReferenceCollection = exports.ReferenceCollection = exports.SafeDisposable = exports.RefCountedDisposable = exports.MandatoryMutableDisposable = exports.MutableDisposable = exports.Disposable = exports.DisposableStore = exports.DisposableTracker = void 0;\nexports.setDisposableTracker = setDisposableTracker;\nexports.trackDisposable = trackDisposable;\nexports.markAsDisposed = markAsDisposed;\nexports.markAsSingleton = markAsSingleton;\nexports.isDisposable = isDisposable;\nexports.dispose = dispose;\nexports.disposeIfDisposable = disposeIfDisposable;\nexports.combinedDisposable = combinedDisposable;\nexports.toDisposable = toDisposable;\nexports.disposeOnReturn = disposeOnReturn;\nconst arrays_1 = require(\"vs/base/common/arrays\");\nconst collections_1 = require(\"vs/base/common/collections\");\nconst map_1 = require(\"./map\");\nconst functional_1 = require(\"vs/base/common/functional\");\nconst iterator_1 = require(\"vs/base/common/iterator\");\n// #region Disposable Tracking\n/**\n * Enables logging of potentially leaked disposables.\n *\n * A disposable is considered leaked if it is not disposed or not registered as the child of\n * another disposable. This tracking is very simple an only works for classes that either\n * extend Disposable or use a DisposableStore. This means there are a lot of false positives.\n */\nconst TRACK_DISPOSABLES = false;\nlet disposableTracker = null;\nclass DisposableTracker {\n constructor() {\n this.livingDisposables = new Map();\n }\n static { this.idx = 0; }\n getDisposableData(d) {\n let val = this.livingDisposables.get(d);\n if (!val) {\n val = { parent: null, source: null, isSingleton: false, value: d, idx: DisposableTracker.idx++ };\n this.livingDisposables.set(d, val);\n }\n return val;\n }\n trackDisposable(d) {\n const data = this.getDisposableData(d);\n if (!data.source) {\n data.source =\n new Error().stack;\n }\n }\n setParent(child, parent) {\n const data = this.getDisposableData(child);\n data.parent = parent;\n }\n markAsDisposed(x) {\n this.livingDisposables.delete(x);\n }\n markAsSingleton(disposable) {\n this.getDisposableData(disposable).isSingleton = true;\n }\n getRootParent(data, cache) {\n const cacheValue = cache.get(data);\n if (cacheValue) {\n return cacheValue;\n }\n const result = data.parent ? this.getRootParent(this.getDisposableData(data.parent), cache) : data;\n cache.set(data, result);\n return result;\n }\n getTrackedDisposables() {\n const rootParentCache = new Map();\n const leaking = [...this.livingDisposables.entries()]\n .filter(([, v]) => v.source !== null && !this.getRootParent(v, rootParentCache).isSingleton)\n .flatMap(([k]) => k);\n return leaking;\n }\n computeLeakingDisposables(maxReported = 10, preComputedLeaks) {\n let uncoveredLeakingObjs;\n if (preComputedLeaks) {\n uncoveredLeakingObjs = preComputedLeaks;\n }\n else {\n const rootParentCache = new Map();\n const leakingObjects = [...this.livingDisposables.values()]\n .filter((info) => info.source !== null && !this.getRootParent(info, rootParentCache).isSingleton);\n if (leakingObjects.length === 0) {\n return;\n }\n const leakingObjsSet = new Set(leakingObjects.map(o => o.value));\n // Remove all objects that are a child of other leaking objects. Assumes there are no cycles.\n uncoveredLeakingObjs = leakingObjects.filter(l => {\n return !(l.parent && leakingObjsSet.has(l.parent));\n });\n if (uncoveredLeakingObjs.length === 0) {\n throw new Error('There are cyclic diposable chains!');\n }\n }\n if (!uncoveredLeakingObjs) {\n return undefined;\n }\n function getStackTracePath(leaking) {\n function removePrefix(array, linesToRemove) {\n while (array.length > 0 && linesToRemove.some(regexp => typeof regexp === 'string' ? regexp === array[0] : array[0].match(regexp))) {\n array.shift();\n }\n }\n const lines = leaking.source.split('\\n').map(p => p.trim().replace('at ', '')).filter(l => l !== '');\n removePrefix(lines, ['Error', /^trackDisposable \\(.*\\)$/, /^DisposableTracker.trackDisposable \\(.*\\)$/]);\n return lines.reverse();\n }\n const stackTraceStarts = new map_1.SetMap();\n for (const leaking of uncoveredLeakingObjs) {\n const stackTracePath = getStackTracePath(leaking);\n for (let i = 0; i <= stackTracePath.length; i++) {\n stackTraceStarts.add(stackTracePath.slice(0, i).join('\\n'), leaking);\n }\n }\n // Put earlier leaks first\n uncoveredLeakingObjs.sort((0, arrays_1.compareBy)(l => l.idx, arrays_1.numberComparator));\n let message = '';\n let i = 0;\n for (const leaking of uncoveredLeakingObjs.slice(0, maxReported)) {\n i++;\n const stackTracePath = getStackTracePath(leaking);\n const stackTraceFormattedLines = [];\n for (let i = 0; i < stackTracePath.length; i++) {\n let line = stackTracePath[i];\n const starts = stackTraceStarts.get(stackTracePath.slice(0, i + 1).join('\\n'));\n line = `(shared with ${starts.size}/${uncoveredLeakingObjs.length} leaks) at ${line}`;\n const prevStarts = stackTraceStarts.get(stackTracePath.slice(0, i).join('\\n'));\n const continuations = (0, collections_1.groupBy)([...prevStarts].map(d => getStackTracePath(d)[i]), v => v);\n delete continuations[stackTracePath[i]];\n for (const [cont, set] of Object.entries(continuations)) {\n stackTraceFormattedLines.unshift(` - stacktraces of ${set.length} other leaks continue with ${cont}`);\n }\n stackTraceFormattedLines.unshift(line);\n }\n message += `\\n\\n\\n==================== Leaking disposable ${i}/${uncoveredLeakingObjs.length}: ${leaking.value.constructor.name} ====================\\n${stackTraceFormattedLines.join('\\n')}\\n============================================================\\n\\n`;\n }\n if (uncoveredLeakingObjs.length > maxReported) {\n message += `\\n\\n\\n... and ${uncoveredLeakingObjs.length - maxReported} more leaking disposables\\n\\n`;\n }\n return { leaks: uncoveredLeakingObjs, details: message };\n }\n}\nexports.DisposableTracker = DisposableTracker;\nfunction setDisposableTracker(tracker) {\n disposableTracker = tracker;\n}\nif (TRACK_DISPOSABLES) {\n const __is_disposable_tracked__ = '__is_disposable_tracked__';\n setDisposableTracker(new class {\n trackDisposable(x) {\n const stack = new Error('Potentially leaked disposable').stack;\n setTimeout(() => {\n if (!x[__is_disposable_tracked__]) {\n console.log(stack);\n }\n }, 3000);\n }\n setParent(child, parent) {\n if (child && child !== Disposable.None) {\n try {\n child[__is_disposable_tracked__] = true;\n }\n catch {\n // noop\n }\n }\n }\n markAsDisposed(disposable) {\n if (disposable && disposable !== Disposable.None) {\n try {\n disposable[__is_disposable_tracked__] = true;\n }\n catch {\n // noop\n }\n }\n }\n markAsSingleton(disposable) { }\n });\n}\nfunction trackDisposable(x) {\n disposableTracker?.trackDisposable(x);\n return x;\n}\nfunction markAsDisposed(disposable) {\n disposableTracker?.markAsDisposed(disposable);\n}\nfunction setParentOfDisposable(child, parent) {\n disposableTracker?.setParent(child, parent);\n}\nfunction setParentOfDisposables(children, parent) {\n if (!disposableTracker) {\n return;\n }\n for (const child of children) {\n disposableTracker.setParent(child, parent);\n }\n}\n/**\n * Indicates that the given object is a singleton which does not need to be disposed.\n*/\nfunction markAsSingleton(singleton) {\n disposableTracker?.markAsSingleton(singleton);\n return singleton;\n}\n/**\n * Check if `thing` is {@link IDisposable disposable}.\n */\nfunction isDisposable(thing) {\n return typeof thing === 'object' && thing !== null && typeof thing.dispose === 'function' && thing.dispose.length === 0;\n}\nfunction dispose(arg) {\n if (iterator_1.Iterable.is(arg)) {\n const errors = [];\n for (const d of arg) {\n if (d) {\n try {\n d.dispose();\n }\n catch (e) {\n errors.push(e);\n }\n }\n }\n if (errors.length === 1) {\n throw errors[0];\n }\n else if (errors.length > 1) {\n throw new AggregateError(errors, 'Encountered errors while disposing of store');\n }\n return Array.isArray(arg) ? [] : arg;\n }\n else if (arg) {\n arg.dispose();\n return arg;\n }\n}\nfunction disposeIfDisposable(disposables) {\n for (const d of disposables) {\n if (isDisposable(d)) {\n d.dispose();\n }\n }\n return [];\n}\n/**\n * Combine multiple disposable values into a single {@link IDisposable}.\n */\nfunction combinedDisposable(...disposables) {\n const parent = toDisposable(() => dispose(disposables));\n setParentOfDisposables(disposables, parent);\n return parent;\n}\n/**\n * Turn a function that implements dispose into an {@link IDisposable}.\n *\n * @param fn Clean up function, guaranteed to be called only **once**.\n */\nfunction toDisposable(fn) {\n const self = trackDisposable({\n dispose: (0, functional_1.createSingleCallFunction)(() => {\n markAsDisposed(self);\n fn();\n })\n });\n return self;\n}\n/**\n * Manages a collection of disposable values.\n *\n * This is the preferred way to manage multiple disposables. A `DisposableStore` is safer to work with than an\n * `IDisposable[]` as it considers edge cases, such as registering the same value multiple times or adding an item to a\n * store that has already been disposed of.\n */\nclass DisposableStore {\n static { this.DISABLE_DISPOSED_WARNING = false; }\n constructor() {\n this._toDispose = new Set();\n this._isDisposed = false;\n trackDisposable(this);\n }\n /**\n * Dispose of all registered disposables and mark this object as disposed.\n *\n * Any future disposables added to this object will be disposed of on `add`.\n */\n dispose() {\n if (this._isDisposed) {\n return;\n }\n markAsDisposed(this);\n this._isDisposed = true;\n this.clear();\n }\n /**\n * @return `true` if this object has been disposed of.\n */\n get isDisposed() {\n return this._isDisposed;\n }\n /**\n * Dispose of all registered disposables but do not mark this object as disposed.\n */\n clear() {\n if (this._toDispose.size === 0) {\n return;\n }\n try {\n dispose(this._toDispose);\n }\n finally {\n this._toDispose.clear();\n }\n }\n /**\n * Add a new {@link IDisposable disposable} to the collection.\n */\n add(o) {\n if (!o) {\n return o;\n }\n if (o === this) {\n throw new Error('Cannot register a disposable on itself!');\n }\n setParentOfDisposable(o, this);\n if (this._isDisposed) {\n if (!DisposableStore.DISABLE_DISPOSED_WARNING) {\n console.warn(new Error('Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!').stack);\n }\n }\n else {\n this._toDispose.add(o);\n }\n return o;\n }\n /**\n * Deletes a disposable from store and disposes of it. This will not throw or warn and proceed to dispose the\n * disposable even when the disposable is not part in the store.\n */\n delete(o) {\n if (!o) {\n return;\n }\n if (o === this) {\n throw new Error('Cannot dispose a disposable on itself!');\n }\n this._toDispose.delete(o);\n o.dispose();\n }\n /**\n * Deletes the value from the store, but does not dispose it.\n */\n deleteAndLeak(o) {\n if (!o) {\n return;\n }\n if (this._toDispose.has(o)) {\n this._toDispose.delete(o);\n setParentOfDisposable(o, null);\n }\n }\n}\nexports.DisposableStore = DisposableStore;\n/**\n * Abstract base class for a {@link IDisposable disposable} object.\n *\n * Subclasses can {@linkcode _register} disposables that will be automatically cleaned up when this object is disposed of.\n */\nclass Disposable {\n /**\n * A disposable that does nothing when it is disposed of.\n *\n * TODO: This should not be a static property.\n */\n static { this.None = Object.freeze({ dispose() { } }); }\n constructor() {\n this._store = new DisposableStore();\n trackDisposable(this);\n setParentOfDisposable(this._store, this);\n }\n dispose() {\n markAsDisposed(this);\n this._store.dispose();\n }\n /**\n * Adds `o` to the collection of disposables managed by this object.\n */\n _register(o) {\n if (o === this) {\n throw new Error('Cannot register a disposable on itself!');\n }\n return this._store.add(o);\n }\n}\nexports.Disposable = Disposable;\n/**\n * Manages the lifecycle of a disposable value that may be changed.\n *\n * This ensures that when the disposable value is changed, the previously held disposable is disposed of. You can\n * also register a `MutableDisposable` on a `Disposable` to ensure it is automatically cleaned up.\n */\nclass MutableDisposable {\n constructor() {\n this._isDisposed = false;\n trackDisposable(this);\n }\n get value() {\n return this._isDisposed ? undefined : this._value;\n }\n set value(value) {\n if (this._isDisposed || value === this._value) {\n return;\n }\n this._value?.dispose();\n if (value) {\n setParentOfDisposable(value, this);\n }\n this._value = value;\n }\n /**\n * Resets the stored value and disposed of the previously stored value.\n */\n clear() {\n this.value = undefined;\n }\n dispose() {\n this._isDisposed = true;\n markAsDisposed(this);\n this._value?.dispose();\n this._value = undefined;\n }\n /**\n * Clears the value, but does not dispose it.\n * The old value is returned.\n */\n clearAndLeak() {\n const oldValue = this._value;\n this._value = undefined;\n if (oldValue) {\n setParentOfDisposable(oldValue, null);\n }\n return oldValue;\n }\n}\nexports.MutableDisposable = MutableDisposable;\n/**\n * Manages the lifecycle of a disposable value that may be changed like {@link MutableDisposable}, but the value must\n * exist and cannot be undefined.\n */\nclass MandatoryMutableDisposable {\n constructor(initialValue) {\n this._disposable = new MutableDisposable();\n this._isDisposed = false;\n this._disposable.value = initialValue;\n }\n get value() {\n return this._disposable.value;\n }\n set value(value) {\n if (this._isDisposed || value === this._disposable.value) {\n return;\n }\n this._disposable.value = value;\n }\n dispose() {\n this._isDisposed = true;\n this._disposable.dispose();\n }\n}\nexports.MandatoryMutableDisposable = MandatoryMutableDisposable;\nclass RefCountedDisposable {\n constructor(_disposable) {\n this._disposable = _disposable;\n this._counter = 1;\n }\n acquire() {\n this._counter++;\n return this;\n }\n release() {\n if (--this._counter === 0) {\n this._disposable.dispose();\n }\n return this;\n }\n}\nexports.RefCountedDisposable = RefCountedDisposable;\n/**\n * A safe disposable can be `unset` so that a leaked reference (listener)\n * can be cut-off.\n */\nclass SafeDisposable {\n constructor() {\n this.dispose = () => { };\n this.unset = () => { };\n this.isset = () => false;\n trackDisposable(this);\n }\n set(fn) {\n let callback = fn;\n this.unset = () => callback = undefined;\n this.isset = () => callback !== undefined;\n this.dispose = () => {\n if (callback) {\n callback();\n callback = undefined;\n markAsDisposed(this);\n }\n };\n return this;\n }\n}\nexports.SafeDisposable = SafeDisposable;\nclass ReferenceCollection {\n constructor() {\n this.references = new Map();\n }\n acquire(key, ...args) {\n let reference = this.references.get(key);\n if (!reference) {\n reference = { counter: 0, object: this.createReferencedObject(key, ...args) };\n this.references.set(key, reference);\n }\n const { object } = reference;\n const dispose = (0, functional_1.createSingleCallFunction)(() => {\n if (--reference.counter === 0) {\n this.destroyReferencedObject(key, reference.object);\n this.references.delete(key);\n }\n });\n reference.counter++;\n return { object, dispose };\n }\n}\nexports.ReferenceCollection = ReferenceCollection;\n/**\n * Unwraps a reference collection of promised values. Makes sure\n * references are disposed whenever promises get rejected.\n */\nclass AsyncReferenceCollection {\n constructor(referenceCollection) {\n this.referenceCollection = referenceCollection;\n }\n async acquire(key, ...args) {\n const ref = this.referenceCollection.acquire(key, ...args);\n try {\n const object = await ref.object;\n return {\n object,\n dispose: () => ref.dispose()\n };\n }\n catch (error) {\n ref.dispose();\n throw error;\n }\n }\n}\nexports.AsyncReferenceCollection = AsyncReferenceCollection;\nclass ImmortalReference {\n constructor(object) {\n this.object = object;\n }\n dispose() { }\n}\nexports.ImmortalReference = ImmortalReference;\nfunction disposeOnReturn(fn) {\n const store = new DisposableStore();\n try {\n fn(store);\n }\n finally {\n store.dispose();\n }\n}\n/**\n * A map the manages the lifecycle of the values that it stores.\n */\nclass DisposableMap {\n constructor() {\n this._store = new Map();\n this._isDisposed = false;\n trackDisposable(this);\n }\n /**\n * Disposes of all stored values and mark this object as disposed.\n *\n * Trying to use this object after it has been disposed of is an error.\n */\n dispose() {\n markAsDisposed(this);\n this._isDisposed = true;\n this.clearAndDisposeAll();\n }\n /**\n * Disposes of all stored values and clear the map, but DO NOT mark this object as disposed.\n */\n clearAndDisposeAll() {\n if (!this._store.size) {\n return;\n }\n try {\n dispose(this._store.values());\n }\n finally {\n this._store.clear();\n }\n }\n has(key) {\n return this._store.has(key);\n }\n get size() {\n return this._store.size;\n }\n get(key) {\n return this._store.get(key);\n }\n set(key, value, skipDisposeOnOverwrite = false) {\n if (this._isDisposed) {\n console.warn(new Error('Trying to add a disposable to a DisposableMap that has already been disposed of. The added object will be leaked!').stack);\n }\n if (!skipDisposeOnOverwrite) {\n this._store.get(key)?.dispose();\n }\n this._store.set(key, value);\n }\n /**\n * Delete the value stored for `key` from this map and also dispose of it.\n */\n deleteAndDispose(key) {\n this._store.get(key)?.dispose();\n this._store.delete(key);\n }\n /**\n * Delete the value stored for `key` from this map but return it. The caller is\n * responsible for disposing of the value.\n */\n deleteAndLeak(key) {\n const value = this._store.get(key);\n this._store.delete(key);\n return value;\n }\n keys() {\n return this._store.keys();\n }\n values() {\n return this._store.values();\n }\n [Symbol.iterator]() {\n return this._store[Symbol.iterator]();\n }\n}\nexports.DisposableMap = DisposableMap;\n","\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.LinkedList = void 0;\nclass Node {\n static { this.Undefined = new Node(undefined); }\n constructor(element) {\n this.element = element;\n this.next = Node.Undefined;\n this.prev = Node.Undefined;\n }\n}\nclass LinkedList {\n constructor() {\n this._first = Node.Undefined;\n this._last = Node.Undefined;\n this._size = 0;\n }\n get size() {\n return this._size;\n }\n isEmpty() {\n return this._first === Node.Undefined;\n }\n clear() {\n let node = this._first;\n while (node !== Node.Undefined) {\n const next = node.next;\n node.prev = Node.Undefined;\n node.next = Node.Undefined;\n node = next;\n }\n this._first = Node.Undefined;\n this._last = Node.Undefined;\n this._size = 0;\n }\n unshift(element) {\n return this._insert(element, false);\n }\n push(element) {\n return this._insert(element, true);\n }\n _insert(element, atTheEnd) {\n const newNode = new Node(element);\n if (this._first === Node.Undefined) {\n this._first = newNode;\n this._last = newNode;\n }\n else if (atTheEnd) {\n // push\n const oldLast = this._last;\n this._last = newNode;\n newNode.prev = oldLast;\n oldLast.next = newNode;\n }\n else {\n // unshift\n const oldFirst = this._first;\n this._first = newNode;\n newNode.next = oldFirst;\n oldFirst.prev = newNode;\n }\n this._size += 1;\n let didRemove = false;\n return () => {\n if (!didRemove) {\n didRemove = true;\n this._remove(newNode);\n }\n };\n }\n shift() {\n if (this._first === Node.Undefined) {\n return undefined;\n }\n else {\n const res = this._first.element;\n this._remove(this._first);\n return res;\n }\n }\n pop() {\n if (this._last === Node.Undefined) {\n return undefined;\n }\n else {\n const res = this._last.element;\n this._remove(this._last);\n return res;\n }\n }\n _remove(node) {\n if (node.prev !== Node.Undefined && node.next !== Node.Undefined) {\n // middle\n const anchor = node.prev;\n anchor.next = node.next;\n node.next.prev = anchor;\n }\n else if (node.prev === Node.Undefined && node.next === Node.Undefined) {\n // only node\n this._first = Node.Undefined;\n this._last = Node.Undefined;\n }\n else if (node.next === Node.Undefined) {\n // last\n this._last = this._last.prev;\n this._last.next = Node.Undefined;\n }\n else if (node.prev === Node.Undefined) {\n // first\n this._first = this._first.next;\n this._first.prev = Node.Undefined;\n }\n // done\n this._size -= 1;\n }\n *[Symbol.iterator]() {\n let node = this._first;\n while (node !== Node.Undefined) {\n yield node.element;\n node = node.next;\n }\n }\n}\nexports.LinkedList = LinkedList;\n","\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.SetMap = exports.BidirectionalMap = exports.CounterSet = exports.Touch = void 0;\nexports.getOrSet = getOrSet;\nexports.mapToString = mapToString;\nexports.setToString = setToString;\nexports.mapsStrictEqualIgnoreOrder = mapsStrictEqualIgnoreOrder;\nfunction getOrSet(map, key, value) {\n let result = map.get(key);\n if (result === undefined) {\n result = value;\n map.set(key, result);\n }\n return result;\n}\nfunction mapToString(map) {\n const entries = [];\n map.forEach((value, key) => {\n entries.push(`${key} => ${value}`);\n });\n return `Map(${map.size}) {${entries.join(', ')}}`;\n}\nfunction setToString(set) {\n const entries = [];\n set.forEach(value => {\n entries.push(value);\n });\n return `Set(${set.size}) {${entries.join(', ')}}`;\n}\nvar Touch;\n(function (Touch) {\n Touch[Touch[\"None\"] = 0] = \"None\";\n Touch[Touch[\"AsOld\"] = 1] = \"AsOld\";\n Touch[Touch[\"AsNew\"] = 2] = \"AsNew\";\n})(Touch || (exports.Touch = Touch = {}));\nclass CounterSet {\n constructor() {\n this.map = new Map();\n }\n add(value) {\n this.map.set(value, (this.map.get(value) || 0) + 1);\n return this;\n }\n delete(value) {\n let counter = this.map.get(value) || 0;\n if (counter === 0) {\n return false;\n }\n counter--;\n if (counter === 0) {\n this.map.delete(value);\n }\n else {\n this.map.set(value, counter);\n }\n return true;\n }\n has(value) {\n return this.map.has(value);\n }\n}\nexports.CounterSet = CounterSet;\n/**\n * A map that allows access both by keys and values.\n * **NOTE**: values need to be unique.\n */\nclass BidirectionalMap {\n constructor(entries) {\n this._m1 = new Map();\n this._m2 = new Map();\n if (entries) {\n for (const [key, value] of entries) {\n this.set(key, value);\n }\n }\n }\n clear() {\n this._m1.clear();\n this._m2.clear();\n }\n set(key, value) {\n this._m1.set(key, value);\n this._m2.set(value, key);\n }\n get(key) {\n return this._m1.get(key);\n }\n getKey(value) {\n return this._m2.get(value);\n }\n delete(key) {\n const value = this._m1.get(key);\n if (value === undefined) {\n return false;\n }\n this._m1.delete(key);\n this._m2.delete(value);\n return true;\n }\n forEach(callbackfn, thisArg) {\n this._m1.forEach((value, key) => {\n callbackfn.call(thisArg, value, key, this);\n });\n }\n keys() {\n return this._m1.keys();\n }\n values() {\n return this._m1.values();\n }\n}\nexports.BidirectionalMap = BidirectionalMap;\nclass SetMap {\n constructor() {\n this.map = new Map();\n }\n add(key, value) {\n let values = this.map.get(key);\n if (!values) {\n values = new Set();\n this.map.set(key, values);\n }\n values.add(value);\n }\n delete(key, value) {\n const values = this.map.get(key);\n if (!values) {\n return;\n }\n values.delete(value);\n if (values.size === 0) {\n this.map.delete(key);\n }\n }\n forEach(key, fn) {\n const values = this.map.get(key);\n if (!values) {\n return;\n }\n values.forEach(fn);\n }\n get(key) {\n const values = this.map.get(key);\n if (!values) {\n return new Set();\n }\n return values;\n }\n}\nexports.SetMap = SetMap;\nfunction mapsStrictEqualIgnoreOrder(a, b) {\n if (a === b) {\n return true;\n }\n if (a.size !== b.size) {\n return false;\n }\n for (const [key, value] of a) {\n if (!b.has(key) || b.get(key) !== value) {\n return false;\n }\n }\n for (const [key] of b) {\n if (!a.has(key)) {\n return false;\n }\n }\n return true;\n}\n","\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.SlidingWindowAverage = exports.MovingAverage = exports.Counter = void 0;\nexports.clamp = clamp;\nexports.rot = rot;\nexports.isPointWithinTriangle = isPointWithinTriangle;\nfunction clamp(value, min, max) {\n return Math.min(Math.max(value, min), max);\n}\nfunction rot(index, modulo) {\n return (modulo + (index % modulo)) % modulo;\n}\nclass Counter {\n constructor() {\n this._next = 0;\n }\n getNext() {\n return this._next++;\n }\n}\nexports.Counter = Counter;\nclass MovingAverage {\n constructor() {\n this._n = 1;\n this._val = 0;\n }\n update(value) {\n this._val = this._val + (value - this._val) / this._n;\n this._n += 1;\n return this._val;\n }\n get value() {\n return this._val;\n }\n}\nexports.MovingAverage = MovingAverage;\nclass SlidingWindowAverage {\n constructor(size) {\n this._n = 0;\n this._val = 0;\n this._values = [];\n this._index = 0;\n this._sum = 0;\n this._values = new Array(size);\n this._values.fill(0, 0, size);\n }\n update(value) {\n const oldValue = this._values[this._index];\n this._values[this._index] = value;\n this._index = (this._index + 1) % this._values.length;\n this._sum -= oldValue;\n this._sum += value;\n if (this._n < this._values.length) {\n this._n += 1;\n }\n this._val = this._sum / this._n;\n return this._val;\n }\n get value() {\n return this._val;\n }\n}\nexports.SlidingWindowAverage = SlidingWindowAverage;\n/** Returns whether the point is within the triangle formed by the following 6 x/y point pairs */\nfunction isPointWithinTriangle(x, y, ax, ay, bx, by, cx, cy) {\n const v0x = cx - ax;\n const v0y = cy - ay;\n const v1x = bx - ax;\n const v1y = by - ay;\n const v2x = x - ax;\n const v2y = y - ay;\n const dot00 = v0x * v0x + v0y * v0y;\n const dot01 = v0x * v1x + v0y * v1y;\n const dot02 = v0x * v2x + v0y * v2y;\n const dot11 = v1x * v1x + v1y * v1y;\n const dot12 = v1x * v2x + v1y * v2y;\n const invDenom = 1 / (dot00 * dot11 - dot01 * dot01);\n const u = (dot11 * dot02 - dot01 * dot12) * invDenom;\n const v = (dot00 * dot12 - dot01 * dot02) * invDenom;\n return u >= 0 && v >= 0 && u + v < 1;\n}\n","\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.isAndroid = exports.isEdge = exports.isSafari = exports.isFirefox = exports.isChrome = exports.OS = exports.OperatingSystem = exports.setTimeout0 = exports.setTimeout0IsFaster = exports.translationsConfigFile = exports.platformLocale = exports.locale = exports.Language = exports.language = exports.userAgent = exports.platform = exports.isCI = exports.isMobile = exports.isIOS = exports.webWorkerOrigin = exports.isWebWorker = exports.isWeb = exports.isElectron = exports.isNative = exports.isLinuxSnap = exports.isLinux = exports.isMacintosh = exports.isWindows = exports.Platform = exports.LANGUAGE_DEFAULT = void 0;\nexports.PlatformToString = PlatformToString;\nexports.isLittleEndian = isLittleEndian;\nexports.isBigSurOrNewer = isBigSurOrNewer;\nexports.LANGUAGE_DEFAULT = 'en';\nlet _isWindows = false;\nlet _isMacintosh = false;\nlet _isLinux = false;\nlet _isLinuxSnap = false;\nlet _isNative = false;\nlet _isWeb = false;\nlet _isElectron = false;\nlet _isIOS = false;\nlet _isCI = false;\nlet _isMobile = false;\nlet _locale = undefined;\nlet _language = exports.LANGUAGE_DEFAULT;\nlet _platformLocale = exports.LANGUAGE_DEFAULT;\nlet _translationsConfigFile = undefined;\nlet _userAgent = undefined;\nconst $globalThis = globalThis;\nlet nodeProcess = undefined;\nif (typeof $globalThis.vscode !== 'undefined' && typeof $globalThis.vscode.process !== 'undefined') {\n // Native environment (sandboxed)\n nodeProcess = $globalThis.vscode.process;\n}\nelse if (typeof process !== 'undefined' && typeof process?.versions?.node === 'string') {\n // Native environment (non-sandboxed)\n nodeProcess = process;\n}\nconst isElectronProcess = typeof nodeProcess?.versions?.electron === 'string';\nconst isElectronRenderer = isElectronProcess && nodeProcess?.type === 'renderer';\n// Native environment\nif (typeof nodeProcess === 'object') {\n _isWindows = (nodeProcess.platform === 'win32');\n _isMacintosh = (nodeProcess.platform === 'darwin');\n _isLinux = (nodeProcess.platform === 'linux');\n _isLinuxSnap = _isLinux && !!nodeProcess.env['SNAP'] && !!nodeProcess.env['SNAP_REVISION'];\n _isElectron = isElectronProcess;\n _isCI = !!nodeProcess.env['CI'] || !!nodeProcess.env['BUILD_ARTIFACTSTAGINGDIRECTORY'];\n _locale = exports.LANGUAGE_DEFAULT;\n _language = exports.LANGUAGE_DEFAULT;\n const rawNlsConfig = nodeProcess.env['VSCODE_NLS_CONFIG'];\n if (rawNlsConfig) {\n try {\n const nlsConfig = JSON.parse(rawNlsConfig);\n _locale = nlsConfig.userLocale;\n _platformLocale = nlsConfig.osLocale;\n _language = nlsConfig.resolvedLanguage || exports.LANGUAGE_DEFAULT;\n _translationsConfigFile = nlsConfig.languagePack?.translationsConfigFile;\n }\n catch (e) {\n }\n }\n _isNative = true;\n}\n// Web environment\nelse if (typeof navigator === 'object' && !isElectronRenderer) {\n _userAgent = navigator.userAgent;\n _isWindows = _userAgent.indexOf('Windows') >= 0;\n _isMacintosh = _userAgent.indexOf('Macintosh') >= 0;\n _isIOS = (_userAgent.indexOf('Macintosh') >= 0 || _userAgent.indexOf('iPad') >= 0 || _userAgent.indexOf('iPhone') >= 0) && !!navigator.maxTouchPoints && navigator.maxTouchPoints > 0;\n _isLinux = _userAgent.indexOf('Linux') >= 0;\n _isMobile = _userAgent?.indexOf('Mobi') >= 0;\n _isWeb = true;\n // VSCODE_GLOBALS: NLS\n _language = globalThis._VSCODE_NLS_LANGUAGE || exports.LANGUAGE_DEFAULT;\n _locale = navigator.language.toLowerCase();\n _platformLocale = _locale;\n}\n// Unknown environment\nelse {\n console.error('Unable to resolve platform.');\n}\nvar Platform;\n(function (Platform) {\n Platform[Platform[\"Web\"] = 0] = \"Web\";\n Platform[Platform[\"Mac\"] = 1] = \"Mac\";\n Platform[Platform[\"Linux\"] = 2] = \"Linux\";\n Platform[Platform[\"Windows\"] = 3] = \"Windows\";\n})(Platform || (exports.Platform = Platform = {}));\nfunction PlatformToString(platform) {\n switch (platform) {\n case Platform.Web: return 'Web';\n case Platform.Mac: return 'Mac';\n case Platform.Linux: return 'Linux';\n case Platform.Windows: return 'Windows';\n }\n}\nlet _platform = Platform.Web;\nif (_isMacintosh) {\n _platform = Platform.Mac;\n}\nelse if (_isWindows) {\n _platform = Platform.Windows;\n}\nelse if (_isLinux) {\n _platform = Platform.Linux;\n}\nexports.isWindows = _isWindows;\nexports.isMacintosh = _isMacintosh;\nexports.isLinux = _isLinux;\nexports.isLinuxSnap = _isLinuxSnap;\nexports.isNative = _isNative;\nexports.isElectron = _isElectron;\nexports.isWeb = _isWeb;\nexports.isWebWorker = (_isWeb && typeof $globalThis.importScripts === 'function');\nexports.webWorkerOrigin = exports.isWebWorker ? $globalThis.origin : undefined;\nexports.isIOS = _isIOS;\nexports.isMobile = _isMobile;\n/**\n * Whether we run inside a CI environment, such as\n * GH actions or Azure Pipelines.\n */\nexports.isCI = _isCI;\nexports.platform = _platform;\nexports.userAgent = _userAgent;\n/**\n * The language used for the user interface. The format of\n * the string is all lower case (e.g. zh-tw for Traditional\n * Chinese or de for German)\n */\nexports.language = _language;\nvar Language;\n(function (Language) {\n function value() {\n return exports.language;\n }\n Language.value = value;\n function isDefaultVariant() {\n if (exports.language.length === 2) {\n return exports.language === 'en';\n }\n else if (exports.language.length >= 3) {\n return exports.language[0] === 'e' && exports.language[1] === 'n' && exports.language[2] === '-';\n }\n else {\n return false;\n }\n }\n Language.isDefaultVariant = isDefaultVariant;\n function isDefault() {\n return exports.language === 'en';\n }\n Language.isDefault = isDefault;\n})(Language || (exports.Language = Language = {}));\n/**\n * Desktop: The OS locale or the locale specified by --locale or `argv.json`.\n * Web: matches `platformLocale`.\n *\n * The UI is not necessarily shown in the provided locale.\n */\nexports.locale = _locale;\n/**\n * This will always be set to the OS/browser's locale regardless of\n * what was specified otherwise. The format of the string is all\n * lower case (e.g. zh-tw for Traditional Chinese). The UI is not\n * necessarily shown in the provided locale.\n */\nexports.platformLocale = _platformLocale;\n/**\n * The translations that are available through language packs.\n */\nexports.translationsConfigFile = _translationsConfigFile;\nexports.setTimeout0IsFaster = (typeof $globalThis.postMessage === 'function' && !$globalThis.importScripts);\n/**\n * See https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#:~:text=than%204%2C%20then-,set%20timeout%20to%204,-.\n *\n * Works similarly to `setTimeout(0)` but doesn't suffer from the 4ms artificial delay\n * that browsers set when the nesting level is > 5.\n */\nexports.setTimeout0 = (() => {\n if (exports.setTimeout0IsFaster) {\n const pending = [];\n $globalThis.addEventListener('message', (e) => {\n if (e.data && e.data.vscodeScheduleAsyncWork) {\n for (let i = 0, len = pending.length; i < len; i++) {\n const candidate = pending[i];\n if (candidate.id === e.data.vscodeScheduleAsyncWork) {\n pending.splice(i, 1);\n candidate.callback();\n return;\n }\n }\n }\n });\n let lastId = 0;\n return (callback) => {\n const myId = ++lastId;\n pending.push({\n id: myId,\n callback: callback\n });\n $globalThis.postMessage({ vscodeScheduleAsyncWork: myId }, '*');\n };\n }\n return (callback) => setTimeout(callback);\n})();\nvar OperatingSystem;\n(function (OperatingSystem) {\n OperatingSystem[OperatingSystem[\"Windows\"] = 1] = \"Windows\";\n OperatingSystem[OperatingSystem[\"Macintosh\"] = 2] = \"Macintosh\";\n OperatingSystem[OperatingSystem[\"Linux\"] = 3] = \"Linux\";\n})(OperatingSystem || (exports.OperatingSystem = OperatingSystem = {}));\nexports.OS = (_isMacintosh || _isIOS ? OperatingSystem.Macintosh : (_isWindows ? OperatingSystem.Windows : OperatingSystem.Linux));\nlet _isLittleEndian = true;\nlet _isLittleEndianComputed = false;\nfunction isLittleEndian() {\n if (!_isLittleEndianComputed) {\n _isLittleEndianComputed = true;\n const test = new Uint8Array(2);\n test[0] = 1;\n test[1] = 2;\n const view = new Uint16Array(test.buffer);\n _isLittleEndian = (view[0] === (2 << 8) + 1);\n }\n return _isLittleEndian;\n}\nexports.isChrome = !!(exports.userAgent && exports.userAgent.indexOf('Chrome') >= 0);\nexports.isFirefox = !!(exports.userAgent && exports.userAgent.indexOf('Firefox') >= 0);\nexports.isSafari = !!(!exports.isChrome && (exports.userAgent && exports.userAgent.indexOf('Safari') >= 0));\nexports.isEdge = !!(exports.userAgent && exports.userAgent.indexOf('Edg/') >= 0);\nexports.isAndroid = !!(exports.userAgent && exports.userAgent.indexOf('Android') >= 0);\nfunction isBigSurOrNewer(osVersion) {\n return parseFloat(osVersion) >= 20;\n}\n","\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.SmoothScrollingOperation = exports.SmoothScrollingUpdate = exports.Scrollable = exports.ScrollState = exports.ScrollbarVisibility = void 0;\nconst event_1 = require(\"vs/base/common/event\");\nconst lifecycle_1 = require(\"vs/base/common/lifecycle\");\nvar ScrollbarVisibility;\n(function (ScrollbarVisibility) {\n ScrollbarVisibility[ScrollbarVisibility[\"Auto\"] = 1] = \"Auto\";\n ScrollbarVisibility[ScrollbarVisibility[\"Hidden\"] = 2] = \"Hidden\";\n ScrollbarVisibility[ScrollbarVisibility[\"Visible\"] = 3] = \"Visible\";\n})(ScrollbarVisibility || (exports.ScrollbarVisibility = ScrollbarVisibility = {}));\nclass ScrollState {\n constructor(_forceIntegerValues, width, scrollWidth, scrollLeft, height, scrollHeight, scrollTop) {\n this._forceIntegerValues = _forceIntegerValues;\n this._scrollStateBrand = undefined;\n if (this._forceIntegerValues) {\n width = width | 0;\n scrollWidth = scrollWidth | 0;\n scrollLeft = scrollLeft | 0;\n height = height | 0;\n scrollHeight = scrollHeight | 0;\n scrollTop = scrollTop | 0;\n }\n this.rawScrollLeft = scrollLeft; // before validation\n this.rawScrollTop = scrollTop; // before validation\n if (width < 0) {\n width = 0;\n }\n if (scrollLeft + width > scrollWidth) {\n scrollLeft = scrollWidth - width;\n }\n if (scrollLeft < 0) {\n scrollLeft = 0;\n }\n if (height < 0) {\n height = 0;\n }\n if (scrollTop + height > scrollHeight) {\n scrollTop = scrollHeight - height;\n }\n if (scrollTop < 0) {\n scrollTop = 0;\n }\n this.width = width;\n this.scrollWidth = scrollWidth;\n this.scrollLeft = scrollLeft;\n this.height = height;\n this.scrollHeight = scrollHeight;\n this.scrollTop = scrollTop;\n }\n equals(other) {\n return (this.rawScrollLeft === other.rawScrollLeft\n && this.rawScrollTop === other.rawScrollTop\n && this.width === other.width\n && this.scrollWidth === other.scrollWidth\n && this.scrollLeft === other.scrollLeft\n && this.height === other.height\n && this.scrollHeight === other.scrollHeight\n && this.scrollTop === other.scrollTop);\n }\n withScrollDimensions(update, useRawScrollPositions) {\n return new ScrollState(this._forceIntegerValues, (typeof update.width !== 'undefined' ? update.width : this.width), (typeof update.scrollWidth !== 'undefined' ? update.scrollWidth : this.scrollWidth), useRawScrollPositions ? this.rawScrollLeft : this.scrollLeft, (typeof update.height !== 'undefined' ? update.height : this.height), (typeof update.scrollHeight !== 'undefined' ? update.scrollHeight : this.scrollHeight), useRawScrollPositions ? this.rawScrollTop : this.scrollTop);\n }\n withScrollPosition(update) {\n return new ScrollState(this._forceIntegerValues, this.width, this.scrollWidth, (typeof update.scrollLeft !== 'undefined' ? update.scrollLeft : this.rawScrollLeft), this.height, this.scrollHeight, (typeof update.scrollTop !== 'undefined' ? update.scrollTop : this.rawScrollTop));\n }\n createScrollEvent(previous, inSmoothScrolling) {\n const widthChanged = (this.width !== previous.width);\n const scrollWidthChanged = (this.scrollWidth !== previous.scrollWidth);\n const scrollLeftChanged = (this.scrollLeft !== previous.scrollLeft);\n const heightChanged = (this.height !== previous.height);\n const scrollHeightChanged = (this.scrollHeight !== previous.scrollHeight);\n const scrollTopChanged = (this.scrollTop !== previous.scrollTop);\n return {\n inSmoothScrolling: inSmoothScrolling,\n oldWidth: previous.width,\n oldScrollWidth: previous.scrollWidth,\n oldScrollLeft: previous.scrollLeft,\n width: this.width,\n scrollWidth: this.scrollWidth,\n scrollLeft: this.scrollLeft,\n oldHeight: previous.height,\n oldScrollHeight: previous.scrollHeight,\n oldScrollTop: previous.scrollTop,\n height: this.height,\n scrollHeight: this.scrollHeight,\n scrollTop: this.scrollTop,\n widthChanged: widthChanged,\n scrollWidthChanged: scrollWidthChanged,\n scrollLeftChanged: scrollLeftChanged,\n heightChanged: heightChanged,\n scrollHeightChanged: scrollHeightChanged,\n scrollTopChanged: scrollTopChanged,\n };\n }\n}\nexports.ScrollState = ScrollState;\nclass Scrollable extends lifecycle_1.Disposable {\n constructor(options) {\n super();\n this._scrollableBrand = undefined;\n this._onScroll = this._register(new event_1.Emitter());\n this.onScroll = this._onScroll.event;\n this._smoothScrollDuration = options.smoothScrollDuration;\n this._scheduleAtNextAnimationFrame = options.scheduleAtNextAnimationFrame;\n this._state = new ScrollState(options.forceIntegerValues, 0, 0, 0, 0, 0, 0);\n this._smoothScrolling = null;\n }\n dispose() {\n if (this._smoothScrolling) {\n this._smoothScrolling.dispose();\n this._smoothScrolling = null;\n }\n super.dispose();\n }\n setSmoothScrollDuration(smoothScrollDuration) {\n this._smoothScrollDuration = smoothScrollDuration;\n }\n validateScrollPosition(scrollPosition) {\n return this._state.withScrollPosition(scrollPosition);\n }\n getScrollDimensions() {\n return this._state;\n }\n setScrollDimensions(dimensions, useRawScrollPositions) {\n const newState = this._state.withScrollDimensions(dimensions, useRawScrollPositions);\n this._setState(newState, Boolean(this._smoothScrolling));\n // Validate outstanding animated scroll position target\n this._smoothScrolling?.acceptScrollDimensions(this._state);\n }\n /**\n * Returns the final scroll position that the instance will have once the smooth scroll animation concludes.\n * If no scroll animation is occurring, it will return the current scroll position instead.\n */\n getFutureScrollPosition() {\n if (this._smoothScrolling) {\n return this._smoothScrolling.to;\n }\n return this._state;\n }\n /**\n * Returns the current scroll position.\n * Note: This result might be an intermediate scroll position, as there might be an ongoing smooth scroll animation.\n */\n getCurrentScrollPosition() {\n return this._state;\n }\n setScrollPositionNow(update) {\n // no smooth scrolling requested\n const newState = this._state.withScrollPosition(update);\n // Terminate any outstanding smooth scrolling\n if (this._smoothScrolling) {\n this._smoothScrolling.dispose();\n this._smoothScrolling = null;\n }\n this._setState(newState, false);\n }\n setScrollPositionSmooth(update, reuseAnimation) {\n if (this._smoothScrollDuration === 0) {\n // Smooth scrolling not supported.\n return this.setScrollPositionNow(update);\n }\n if (this._smoothScrolling) {\n // Combine our pending scrollLeft/scrollTop with incoming scrollLeft/scrollTop\n update = {\n scrollLeft: (typeof update.scrollLeft === 'undefined' ? this._smoothScrolling.to.scrollLeft : update.scrollLeft),\n scrollTop: (typeof update.scrollTop === 'undefined' ? this._smoothScrolling.to.scrollTop : update.scrollTop)\n };\n // Validate `update`\n const validTarget = this._state.withScrollPosition(update);\n if (this._smoothScrolling.to.scrollLeft === validTarget.scrollLeft && this._smoothScrolling.to.scrollTop === validTarget.scrollTop) {\n // No need to interrupt or extend the current animation since we're going to the same place\n return;\n }\n let newSmoothScrolling;\n if (reuseAnimation) {\n newSmoothScrolling = new SmoothScrollingOperation(this._smoothScrolling.from, validTarget, this._smoothScrolling.startTime, this._smoothScrolling.duration);\n }\n else {\n newSmoothScrolling = this._smoothScrolling.combine(this._state, validTarget, this._smoothScrollDuration);\n }\n this._smoothScrolling.dispose();\n this._smoothScrolling = newSmoothScrolling;\n }\n else {\n // Validate `update`\n const validTarget = this._state.withScrollPosition(update);\n this._smoothScrolling = SmoothScrollingOperation.start(this._state, validTarget, this._smoothScrollDuration);\n }\n // Begin smooth scrolling animation\n this._smoothScrolling.animationFrameDisposable = this._scheduleAtNextAnimationFrame(() => {\n if (!this._smoothScrolling) {\n return;\n }\n this._smoothScrolling.animationFrameDisposable = null;\n this._performSmoothScrolling();\n });\n }\n hasPendingScrollAnimation() {\n return Boolean(this._smoothScrolling);\n }\n _performSmoothScrolling() {\n if (!this._smoothScrolling) {\n return;\n }\n const update = this._smoothScrolling.tick();\n const newState = this._state.withScrollPosition(update);\n this._setState(newState, true);\n if (!this._smoothScrolling) {\n // Looks like someone canceled the smooth scrolling\n // from the scroll event handler\n return;\n }\n if (update.isDone) {\n this._smoothScrolling.dispose();\n this._smoothScrolling = null;\n return;\n }\n // Continue smooth scrolling animation\n this._smoothScrolling.animationFrameDisposable = this._scheduleAtNextAnimationFrame(() => {\n if (!this._smoothScrolling) {\n return;\n }\n this._smoothScrolling.animationFrameDisposable = null;\n this._performSmoothScrolling();\n });\n }\n _setState(newState, inSmoothScrolling) {\n const oldState = this._state;\n if (oldState.equals(newState)) {\n // no change\n return;\n }\n this._state = newState;\n this._onScroll.fire(this._state.createScrollEvent(oldState, inSmoothScrolling));\n }\n}\nexports.Scrollable = Scrollable;\nclass SmoothScrollingUpdate {\n constructor(scrollLeft, scrollTop, isDone) {\n this.scrollLeft = scrollLeft;\n this.scrollTop = scrollTop;\n this.isDone = isDone;\n }\n}\nexports.SmoothScrollingUpdate = SmoothScrollingUpdate;\nfunction createEaseOutCubic(from, to) {\n const delta = to - from;\n return function (completion) {\n return from + delta * easeOutCubic(completion);\n };\n}\nfunction createComposed(a, b, cut) {\n return function (completion) {\n if (completion < cut) {\n return a(completion / cut);\n }\n return b((completion - cut) / (1 - cut));\n };\n}\nclass SmoothScrollingOperation {\n constructor(from, to, startTime, duration) {\n this.from = from;\n this.to = to;\n this.duration = duration;\n this.startTime = startTime;\n this.animationFrameDisposable = null;\n this._initAnimations();\n }\n _initAnimations() {\n this.scrollLeft = this._initAnimation(this.from.scrollLeft, this.to.scrollLeft, this.to.width);\n this.scrollTop = this._initAnimation(this.from.scrollTop, this.to.scrollTop, this.to.height);\n }\n _initAnimation(from, to, viewportSize) {\n const delta = Math.abs(from - to);\n if (delta > 2.5 * viewportSize) {\n let stop1, stop2;\n if (from < to) {\n // scroll to 75% of the viewportSize\n stop1 = from + 0.75 * viewportSize;\n stop2 = to - 0.75 * viewportSize;\n }\n else {\n stop1 = from - 0.75 * viewportSize;\n stop2 = to + 0.75 * viewportSize;\n }\n return createComposed(createEaseOutCubic(from, stop1), createEaseOutCubic(stop2, to), 0.33);\n }\n return createEaseOutCubic(from, to);\n }\n dispose() {\n if (this.animationFrameDisposable !== null) {\n this.animationFrameDisposable.dispose();\n this.animationFrameDisposable = null;\n }\n }\n acceptScrollDimensions(state) {\n this.to = state.withScrollPosition(this.to);\n this._initAnimations();\n }\n tick() {\n return this._tick(Date.now());\n }\n _tick(now) {\n const completion = (now - this.startTime) / this.duration;\n if (completion < 1) {\n const newScrollLeft = this.scrollLeft(completion);\n const newScrollTop = this.scrollTop(completion);\n return new SmoothScrollingUpdate(newScrollLeft, newScrollTop, false);\n }\n return new SmoothScrollingUpdate(this.to.scrollLeft, this.to.scrollTop, true);\n }\n combine(from, to, duration) {\n return SmoothScrollingOperation.start(from, to, duration);\n }\n static start(from, to, duration) {\n // +10 / -10 : pretend the animation already started for a quicker response to a scroll request\n duration = duration + 10;\n const startTime = Date.now() - 10;\n return new SmoothScrollingOperation(from, to, startTime, duration);\n }\n}\nexports.SmoothScrollingOperation = SmoothScrollingOperation;\nfunction easeInCubic(t) {\n return Math.pow(t, 3);\n}\nfunction easeOutCubic(t) {\n return 1 - easeInCubic(1 - t);\n}\n","\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.StopWatch = void 0;\nconst hasPerformanceNow = (globalThis.performance && typeof globalThis.performance.now === 'function');\nclass StopWatch {\n static create(highResolution) {\n return new StopWatch(highResolution);\n }\n constructor(highResolution) {\n this._now = hasPerformanceNow && highResolution === false ? Date.now : globalThis.performance.now.bind(globalThis.performance);\n this._startTime = this._now();\n this._stopTime = -1;\n }\n stop() {\n this._stopTime = this._now();\n }\n reset() {\n this._startTime = this._now();\n this._stopTime = -1;\n }\n elapsed() {\n if (this._stopTime !== -1) {\n return this._stopTime - this._startTime;\n }\n return this._now() - this._startTime;\n }\n}\nexports.StopWatch = StopWatch;\n","\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.noBreakWhitespace = exports.CodePointIterator = void 0;\nexports.isFalsyOrWhitespace = isFalsyOrWhitespace;\nexports.format = format;\nexports.format2 = format2;\nexports.htmlAttributeEncodeValue = htmlAttributeEncodeValue;\nexports.escape = escape;\nexports.escapeRegExpCharacters = escapeRegExpCharacters;\nexports.count = count;\nexports.truncate = truncate;\nexports.truncateMiddle = truncateMiddle;\nexports.trim = trim;\nexports.ltrim = ltrim;\nexports.rtrim = rtrim;\nexports.convertSimple2RegExpPattern = convertSimple2RegExpPattern;\nexports.stripWildcards = stripWildcards;\nexports.createRegExp = createRegExp;\nexports.regExpLeadsToEndlessLoop = regExpLeadsToEndlessLoop;\nexports.splitLines = splitLines;\nexports.splitLinesIncludeSeparators = splitLinesIncludeSeparators;\nexports.firstNonWhitespaceIndex = firstNonWhitespaceIndex;\nexports.getLeadingWhitespace = getLeadingWhitespace;\nexports.lastNonWhitespaceIndex = lastNonWhitespaceIndex;\nexports.replaceAsync = replaceAsync;\nexports.compare = compare;\nexports.compareSubstring = compareSubstring;\nexports.compareIgnoreCase = compareIgnoreCase;\nexports.compareSubstringIgnoreCase = compareSubstringIgnoreCase;\nexports.isAsciiDigit = isAsciiDigit;\nexports.isLowerAsciiLetter = isLowerAsciiLetter;\nexports.isUpperAsciiLetter = isUpperAsciiLetter;\nexports.equalsIgnoreCase = equalsIgnoreCase;\nexports.startsWithIgnoreCase = startsWithIgnoreCase;\nexports.commonPrefixLength = commonPrefixLength;\nexports.commonSuffixLength = commonSuffixLength;\nexports.isHighSurrogate = isHighSurrogate;\nexports.isLowSurrogate = isLowSurrogate;\nexports.computeCodePoint = computeCodePoint;\nexports.getNextCodePoint = getNextCodePoint;\nconst charCode_1 = require(\"vs/base/common/charCode\");\nconst uint_1 = require(\"vs/base/common/uint\");\nfunction isFalsyOrWhitespace(str) {\n if (!str || typeof str !== 'string') {\n return true;\n }\n return str.trim().length === 0;\n}\nconst _formatRegexp = /{(\\d+)}/g;\n/**\n * Helper to produce a string with a variable number of arguments. Insert variable segments\n * into the string using the {n} notation where N is the index of the argument following the string.\n * @param value string to which formatting is applied\n * @param args replacements for {n}-entries\n */\nfunction format(value, ...args) {\n if (args.length === 0) {\n return value;\n }\n return value.replace(_formatRegexp, function (match, group) {\n const idx = parseInt(group, 10);\n return isNaN(idx) || idx < 0 || idx >= args.length ?\n match :\n args[idx];\n });\n}\nconst _format2Regexp = /{([^}]+)}/g;\n/**\n * Helper to create a string from a template and a string record.\n * Similar to `format` but with objects instead of positional arguments.\n */\nfunction format2(template, values) {\n if (Object.keys(values).length === 0) {\n return template;\n }\n return template.replace(_format2Regexp, (match, group) => (values[group] ?? match));\n}\n/**\n * Encodes the given value so that it can be used as literal value in html attributes.\n *\n * In other words, computes `$val`, such that `attr` in `
` has the runtime value `value`.\n * This prevents XSS injection.\n */\nfunction htmlAttributeEncodeValue(value) {\n return value.replace(/[<>\"'&]/g, ch => {\n switch (ch) {\n case '<': return '<';\n case '>': return '>';\n case '\"': return '"';\n case '\\'': return ''';\n case '&': return '&';\n }\n return ch;\n });\n}\n/**\n * Converts HTML characters inside the string to use entities instead. Makes the string safe from\n * being used e.g. in HTMLElement.innerHTML.\n */\nfunction escape(html) {\n return html.replace(/[<>&]/g, function (match) {\n switch (match) {\n case '<': return '<';\n case '>': return '>';\n case '&': return '&';\n default: return match;\n }\n });\n}\n/**\n * Escapes regular expression characters in a given string\n */\nfunction escapeRegExpCharacters(value) {\n return value.replace(/[\\\\\\{\\}\\*\\+\\?\\|\\^\\$\\.\\[\\]\\(\\)]/g, '\\\\$&');\n}\n/**\n * Counts how often `substr` occurs inside `value`.\n */\nfunction count(value, substr) {\n let result = 0;\n let index = value.indexOf(substr);\n while (index !== -1) {\n result++;\n index = value.indexOf(substr, index + substr.length);\n }\n return result;\n}\nfunction truncate(value, maxLength, suffix = '…') {\n if (value.length <= maxLength) {\n return value;\n }\n return `${value.substr(0, maxLength)}${suffix}`;\n}\nfunction truncateMiddle(value, maxLength, suffix = '…') {\n if (value.length <= maxLength) {\n return value;\n }\n const prefixLength = Math.ceil(maxLength / 2) - suffix.length / 2;\n const suffixLength = Math.floor(maxLength / 2) - suffix.length / 2;\n return `${value.substr(0, prefixLength)}${suffix}${value.substr(value.length - suffixLength)}`;\n}\n/**\n * Removes all occurrences of needle from the beginning and end of haystack.\n * @param haystack string to trim\n * @param needle the thing to trim (default is a blank)\n */\nfunction trim(haystack, needle = ' ') {\n const trimmed = ltrim(haystack, needle);\n return rtrim(trimmed, needle);\n}\n/**\n * Removes all occurrences of needle from the beginning of haystack.\n * @param haystack string to trim\n * @param needle the thing to trim\n */\nfunction ltrim(haystack, needle) {\n if (!haystack || !needle) {\n return haystack;\n }\n const needleLen = needle.length;\n if (needleLen === 0 || haystack.length === 0) {\n return haystack;\n }\n let offset = 0;\n while (haystack.indexOf(needle, offset) === offset) {\n offset = offset + needleLen;\n }\n return haystack.substring(offset);\n}\n/**\n * Removes all occurrences of needle from the end of haystack.\n * @param haystack string to trim\n * @param needle the thing to trim\n */\nfunction rtrim(haystack, needle) {\n if (!haystack || !needle) {\n return haystack;\n }\n const needleLen = needle.length, haystackLen = haystack.length;\n if (needleLen === 0 || haystackLen === 0) {\n return haystack;\n }\n let offset = haystackLen, idx = -1;\n while (true) {\n idx = haystack.lastIndexOf(needle, offset - 1);\n if (idx === -1 || idx + needleLen !== offset) {\n break;\n }\n if (idx === 0) {\n return '';\n }\n offset = idx;\n }\n return haystack.substring(0, offset);\n}\nfunction convertSimple2RegExpPattern(pattern) {\n return pattern.replace(/[\\-\\\\\\{\\}\\+\\?\\|\\^\\$\\.\\,\\[\\]\\(\\)\\#\\s]/g, '\\\\$&').replace(/[\\*]/g, '.*');\n}\nfunction stripWildcards(pattern) {\n return pattern.replace(/\\*/g, '');\n}\nfunction createRegExp(searchString, isRegex, options = {}) {\n if (!searchString) {\n throw new Error('Cannot create regex from empty string');\n }\n if (!isRegex) {\n searchString = escapeRegExpCharacters(searchString);\n }\n if (options.wholeWord) {\n if (!/\\B/.test(searchString.charAt(0))) {\n searchString = '\\\\b' + searchString;\n }\n if (!/\\B/.test(searchString.charAt(searchString.length - 1))) {\n searchString = searchString + '\\\\b';\n }\n }\n let modifiers = '';\n if (options.global) {\n modifiers += 'g';\n }\n if (!options.matchCase) {\n modifiers += 'i';\n }\n if (options.multiline) {\n modifiers += 'm';\n }\n if (options.unicode) {\n modifiers += 'u';\n }\n return new RegExp(searchString, modifiers);\n}\nfunction regExpLeadsToEndlessLoop(regexp) {\n // Exit early if it's one of these special cases which are meant to match\n // against an empty string\n if (regexp.source === '^' || regexp.source === '^$' || regexp.source === '$' || regexp.source === '^\\\\s*$') {\n return false;\n }\n // We check against an empty string. If the regular expression doesn't advance\n // (e.g. ends in an endless loop) it will match an empty string.\n const match = regexp.exec('');\n return !!(match && regexp.lastIndex === 0);\n}\nfunction splitLines(str) {\n return str.split(/\\r\\n|\\r|\\n/);\n}\nfunction splitLinesIncludeSeparators(str) {\n const linesWithSeparators = [];\n const splitLinesAndSeparators = str.split(/(\\r\\n|\\r|\\n)/);\n for (let i = 0; i < Math.ceil(splitLinesAndSeparators.length / 2); i++) {\n linesWithSeparators.push(splitLinesAndSeparators[2 * i] + (splitLinesAndSeparators[2 * i + 1] ?? ''));\n }\n return linesWithSeparators;\n}\n/**\n * Returns first index of the string that is not whitespace.\n * If string is empty or contains only whitespaces, returns -1\n */\nfunction firstNonWhitespaceIndex(str) {\n for (let i = 0, len = str.length; i < len; i++) {\n const chCode = str.charCodeAt(i);\n if (chCode !== charCode_1.CharCode.Space && chCode !== charCode_1.CharCode.Tab) {\n return i;\n }\n }\n return -1;\n}\n/**\n * Returns the leading whitespace of the string.\n * If the string contains only whitespaces, returns entire string\n */\nfunction getLeadingWhitespace(str, start = 0, end = str.length) {\n for (let i = start; i < end; i++) {\n const chCode = str.charCodeAt(i);\n if (chCode !== charCode_1.CharCode.Space && chCode !== charCode_1.CharCode.Tab) {\n return str.substring(start, i);\n }\n }\n return str.substring(start, end);\n}\n/**\n * Returns last index of the string that is not whitespace.\n * If string is empty or contains only whitespaces, returns -1\n */\nfunction lastNonWhitespaceIndex(str, startIndex = str.length - 1) {\n for (let i = startIndex; i >= 0; i--) {\n const chCode = str.charCodeAt(i);\n if (chCode !== charCode_1.CharCode.Space && chCode !== charCode_1.CharCode.Tab) {\n return i;\n }\n }\n return -1;\n}\n/**\n * Function that works identically to String.prototype.replace, except, the\n * replace function is allowed to be async and return a Promise.\n */\nfunction replaceAsync(str, search, replacer) {\n const parts = [];\n let last = 0;\n for (const match of str.matchAll(search)) {\n parts.push(str.slice(last, match.index));\n if (match.index === undefined) {\n throw new Error('match.index should be defined');\n }\n last = match.index + match[0].length;\n parts.push(replacer(match[0], ...match.slice(1), match.index, str, match.groups));\n }\n parts.push(str.slice(last));\n return Promise.all(parts).then(p => p.join(''));\n}\nfunction compare(a, b) {\n if (a < b) {\n return -1;\n }\n else if (a > b) {\n return 1;\n }\n else {\n return 0;\n }\n}\nfunction compareSubstring(a, b, aStart = 0, aEnd = a.length, bStart = 0, bEnd = b.length) {\n for (; aStart < aEnd && bStart < bEnd; aStart++, bStart++) {\n const codeA = a.charCodeAt(aStart);\n const codeB = b.charCodeAt(bStart);\n if (codeA < codeB) {\n return -1;\n }\n else if (codeA > codeB) {\n return 1;\n }\n }\n const aLen = aEnd - aStart;\n const bLen = bEnd - bStart;\n if (aLen < bLen) {\n return -1;\n }\n else if (aLen > bLen) {\n return 1;\n }\n return 0;\n}\nfunction compareIgnoreCase(a, b) {\n return compareSubstringIgnoreCase(a, b, 0, a.length, 0, b.length);\n}\nfunction compareSubstringIgnoreCase(a, b, aStart = 0, aEnd = a.length, bStart = 0, bEnd = b.length) {\n for (; aStart < aEnd && bStart < bEnd; aStart++, bStart++) {\n let codeA = a.charCodeAt(aStart);\n let codeB = b.charCodeAt(bStart);\n if (codeA === codeB) {\n // equal\n continue;\n }\n if (codeA >= 128 || codeB >= 128) {\n // not ASCII letters -> fallback to lower-casing strings\n return compareSubstring(a.toLowerCase(), b.toLowerCase(), aStart, aEnd, bStart, bEnd);\n }\n // mapper lower-case ascii letter onto upper-case varinats\n // [97-122] (lower ascii) --> [65-90] (upper ascii)\n if (isLowerAsciiLetter(codeA)) {\n codeA -= 32;\n }\n if (isLowerAsciiLetter(codeB)) {\n codeB -= 32;\n }\n // compare both code points\n const diff = codeA - codeB;\n if (diff === 0) {\n continue;\n }\n return diff;\n }\n const aLen = aEnd - aStart;\n const bLen = bEnd - bStart;\n if (aLen < bLen) {\n return -1;\n }\n else if (aLen > bLen) {\n return 1;\n }\n return 0;\n}\nfunction isAsciiDigit(code) {\n return code >= charCode_1.CharCode.Digit0 && code <= charCode_1.CharCode.Digit9;\n}\nfunction isLowerAsciiLetter(code) {\n return code >= charCode_1.CharCode.a && code <= charCode_1.CharCode.z;\n}\nfunction isUpperAsciiLetter(code) {\n return code >= charCode_1.CharCode.A && code <= charCode_1.CharCode.Z;\n}\nfunction equalsIgnoreCase(a, b) {\n return a.length === b.length && compareSubstringIgnoreCase(a, b) === 0;\n}\nfunction startsWithIgnoreCase(str, candidate) {\n const candidateLength = candidate.length;\n if (candidate.length > str.length) {\n return false;\n }\n return compareSubstringIgnoreCase(str, candidate, 0, candidateLength) === 0;\n}\n/**\n * @returns the length of the common prefix of the two strings.\n */\nfunction commonPrefixLength(a, b) {\n const len = Math.min(a.length, b.length);\n let i;\n for (i = 0; i < len; i++) {\n if (a.charCodeAt(i) !== b.charCodeAt(i)) {\n return i;\n }\n }\n return len;\n}\n/**\n * @returns the length of the common suffix of the two strings.\n */\nfunction commonSuffixLength(a, b) {\n const len = Math.min(a.length, b.length);\n let i;\n const aLastIndex = a.length - 1;\n const bLastIndex = b.length - 1;\n for (i = 0; i < len; i++) {\n if (a.charCodeAt(aLastIndex - i) !== b.charCodeAt(bLastIndex - i)) {\n return i;\n }\n }\n return len;\n}\n/**\n * See http://en.wikipedia.org/wiki/Surrogate_pair\n */\nfunction isHighSurrogate(charCode) {\n return (0xD800 <= charCode && charCode <= 0xDBFF);\n}\n/**\n * See http://en.wikipedia.org/wiki/Surrogate_pair\n */\nfunction isLowSurrogate(charCode) {\n return (0xDC00 <= charCode && charCode <= 0xDFFF);\n}\n/**\n * See http://en.wikipedia.org/wiki/Surrogate_pair\n */\nfunction computeCodePoint(highSurrogate, lowSurrogate) {\n return ((highSurrogate - 0xD800) << 10) + (lowSurrogate - 0xDC00) + 0x10000;\n}\n/**\n * get the code point that begins at offset `offset`\n */\nfunction getNextCodePoint(str, len, offset) {\n const charCode = str.charCodeAt(offset);\n if (isHighSurrogate(charCode) && offset + 1 < len) {\n const nextCharCode = str.charCodeAt(offset + 1);\n if (isLowSurrogate(nextCharCode)) {\n return computeCodePoint(charCode, nextCharCode);\n }\n }\n return charCode;\n}\n/**\n * get the code point that ends right before offset `offset`\n */\nfunction getPrevCodePoint(str, offset) {\n const charCode = str.charCodeAt(offset - 1);\n if (isLowSurrogate(charCode) && offset > 1) {\n const prevCharCode = str.charCodeAt(offset - 2);\n if (isHighSurrogate(prevCharCode)) {\n return computeCodePoint(prevCharCode, charCode);\n }\n }\n return charCode;\n}\nclass CodePointIterator {\n get offset() {\n return this._offset;\n }\n constructor(str, offset = 0) {\n this._str = str;\n this._len = str.length;\n this._offset = offset;\n }\n setOffset(offset) {\n this._offset = offset;\n }\n prevCodePoint() {\n const codePoint = getPrevCodePoint(this._str, this._offset);\n this._offset -= (codePoint >= uint_1.Constants.UNICODE_SUPPLEMENTARY_PLANE_BEGIN ? 2 : 1);\n return codePoint;\n }\n nextCodePoint() {\n const codePoint = getNextCodePoint(this._str, this._len, this._offset);\n this._offset += (codePoint >= uint_1.Constants.UNICODE_SUPPLEMENTARY_PLANE_BEGIN ? 2 : 1);\n return codePoint;\n }\n eol() {\n return (this._offset >= this._len);\n }\n}\nexports.CodePointIterator = CodePointIterator;\nexports.noBreakWhitespace = '\\xa0';\n","\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.MicrotaskDelay = void 0;\n/**\n * Can be passed into the Delayed to defer using a microtask\n * */\nexports.MicrotaskDelay = Symbol('MicrotaskDelay');\n","\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Constants = void 0;\nexports.toUint8 = toUint8;\nexports.toUint32 = toUint32;\nvar Constants;\n(function (Constants) {\n /**\n * MAX SMI (SMall Integer) as defined in v8.\n * one bit is lost for boxing/unboxing flag.\n * one bit is lost for sign flag.\n * See https://thibaultlaurens.github.io/javascript/2013/04/29/how-the-v8-engine-works/#tagged-values\n */\n Constants[Constants[\"MAX_SAFE_SMALL_INTEGER\"] = 1073741824] = \"MAX_SAFE_SMALL_INTEGER\";\n /**\n * MIN SMI (SMall Integer) as defined in v8.\n * one bit is lost for boxing/unboxing flag.\n * one bit is lost for sign flag.\n * See https://thibaultlaurens.github.io/javascript/2013/04/29/how-the-v8-engine-works/#tagged-values\n */\n Constants[Constants[\"MIN_SAFE_SMALL_INTEGER\"] = -1073741824] = \"MIN_SAFE_SMALL_INTEGER\";\n /**\n * Max unsigned integer that fits on 8 bits.\n */\n Constants[Constants[\"MAX_UINT_8\"] = 255] = \"MAX_UINT_8\";\n /**\n * Max unsigned integer that fits on 16 bits.\n */\n Constants[Constants[\"MAX_UINT_16\"] = 65535] = \"MAX_UINT_16\";\n /**\n * Max unsigned integer that fits on 32 bits.\n */\n Constants[Constants[\"MAX_UINT_32\"] = 4294967295] = \"MAX_UINT_32\";\n Constants[Constants[\"UNICODE_SUPPLEMENTARY_PLANE_BEGIN\"] = 65536] = \"UNICODE_SUPPLEMENTARY_PLANE_BEGIN\";\n})(Constants || (exports.Constants = Constants = {}));\nfunction toUint8(v) {\n if (v < 0) {\n return 0;\n }\n if (v > Constants.MAX_UINT_8) {\n return Constants.MAX_UINT_8;\n }\n return v | 0;\n}\nfunction toUint32(v) {\n if (v < 0) {\n return 0;\n }\n if (v > Constants.MAX_UINT_32) {\n return Constants.MAX_UINT_32;\n }\n return v | 0;\n}\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","/**\n * Copyright (c) 2018 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport * as Strings from 'browser/LocalizableStrings';\nimport { CoreBrowserTerminal as TerminalCore } from 'browser/CoreBrowserTerminal';\nimport { IBufferRange, ITerminal } from 'browser/Types';\nimport { Disposable } from 'vs/base/common/lifecycle';\nimport { ITerminalOptions } from 'common/Types';\nimport { AddonManager } from 'common/public/AddonManager';\nimport { BufferNamespaceApi } from 'common/public/BufferNamespaceApi';\nimport { ParserApi } from 'common/public/ParserApi';\nimport { UnicodeApi } from 'common/public/UnicodeApi';\nimport { IBufferNamespace as IBufferNamespaceApi, IDecoration, IDecorationOptions, IDisposable, ILinkProvider, ILocalizableStrings, IMarker, IModes, IParser, ITerminalAddon, Terminal as ITerminalApi, ITerminalInitOnlyOptions, IUnicodeHandling } from '@xterm/xterm';\nimport type { Event } from 'vs/base/common/event';\n\n/**\n * The set of options that only have an effect when set in the Terminal constructor.\n */\nconst CONSTRUCTOR_ONLY_OPTIONS = ['cols', 'rows'];\n\nlet $value = 0;\n\nexport class Terminal extends Disposable implements ITerminalApi {\n private _core: ITerminal;\n private _addonManager: AddonManager;\n private _parser: IParser | undefined;\n private _buffer: BufferNamespaceApi | undefined;\n private _publicOptions: Required;\n\n constructor(options?: ITerminalOptions & ITerminalInitOnlyOptions) {\n super();\n\n this._core = this._register(new TerminalCore(options));\n this._addonManager = this._register(new AddonManager());\n\n this._publicOptions = { ... this._core.options };\n const getter = (propName: string): any => {\n return this._core.options[propName];\n };\n const setter = (propName: string, value: any): void => {\n this._checkReadonlyOptions(propName);\n this._core.options[propName] = value;\n };\n\n for (const propName in this._core.options) {\n const desc = {\n get: getter.bind(this, propName),\n set: setter.bind(this, propName)\n };\n Object.defineProperty(this._publicOptions, propName, desc);\n }\n }\n\n private _checkReadonlyOptions(propName: string): void {\n // Throw an error if any constructor only option is modified\n // from terminal.options\n // Modifications from anywhere else are allowed\n if (CONSTRUCTOR_ONLY_OPTIONS.includes(propName)) {\n throw new Error(`Option \"${propName}\" can only be set in the constructor`);\n }\n }\n\n private _checkProposedApi(): void {\n if (!this._core.optionsService.rawOptions.allowProposedApi) {\n throw new Error('You must set the allowProposedApi option to true to use proposed API');\n }\n }\n\n public get onBell(): Event { return this._core.onBell; }\n public get onBinary(): Event { return this._core.onBinary; }\n public get onCursorMove(): Event { return this._core.onCursorMove; }\n public get onData(): Event { return this._core.onData; }\n public get onKey(): Event<{ key: string, domEvent: KeyboardEvent }> { return this._core.onKey; }\n public get onLineFeed(): Event { return this._core.onLineFeed; }\n public get onRender(): Event<{ start: number, end: number }> { return this._core.onRender; }\n public get onResize(): Event<{ cols: number, rows: number }> { return this._core.onResize; }\n public get onScroll(): Event { return this._core.onScroll; }\n public get onSelectionChange(): Event { return this._core.onSelectionChange; }\n public get onTitleChange(): Event { return this._core.onTitleChange; }\n public get onWriteParsed(): Event { return this._core.onWriteParsed; }\n\n public get element(): HTMLElement | undefined { return this._core.element; }\n public get parser(): IParser {\n if (!this._parser) {\n this._parser = new ParserApi(this._core);\n }\n return this._parser;\n }\n public get unicode(): IUnicodeHandling {\n this._checkProposedApi();\n return new UnicodeApi(this._core);\n }\n public get textarea(): HTMLTextAreaElement | undefined { return this._core.textarea; }\n public get rows(): number { return this._core.rows; }\n public get cols(): number { return this._core.cols; }\n public get buffer(): IBufferNamespaceApi {\n if (!this._buffer) {\n this._buffer = this._register(new BufferNamespaceApi(this._core));\n }\n return this._buffer;\n }\n public get markers(): ReadonlyArray {\n this._checkProposedApi();\n return this._core.markers;\n }\n public get modes(): IModes {\n const m = this._core.coreService.decPrivateModes;\n let mouseTrackingMode: 'none' | 'x10' | 'vt200' | 'drag' | 'any' = 'none';\n switch (this._core.coreMouseService.activeProtocol) {\n case 'X10': mouseTrackingMode = 'x10'; break;\n case 'VT200': mouseTrackingMode = 'vt200'; break;\n case 'DRAG': mouseTrackingMode = 'drag'; break;\n case 'ANY': mouseTrackingMode = 'any'; break;\n }\n return {\n applicationCursorKeysMode: m.applicationCursorKeys,\n applicationKeypadMode: m.applicationKeypad,\n bracketedPasteMode: m.bracketedPasteMode,\n insertMode: this._core.coreService.modes.insertMode,\n mouseTrackingMode: mouseTrackingMode,\n originMode: m.origin,\n reverseWraparoundMode: m.reverseWraparound,\n sendFocusMode: m.sendFocus,\n synchronizedOutputMode: m.synchronizedOutput,\n wraparoundMode: m.wraparound\n };\n }\n public get options(): Required {\n return this._publicOptions;\n }\n public set options(options: ITerminalOptions) {\n for (const propName in options) {\n this._publicOptions[propName] = options[propName];\n }\n }\n public blur(): void {\n this._core.blur();\n }\n public focus(): void {\n this._core.focus();\n }\n public input(data: string, wasUserInput: boolean = true): void {\n this._core.input(data, wasUserInput);\n }\n public resize(columns: number, rows: number): void {\n this._verifyIntegers(columns, rows);\n this._core.resize(columns, rows);\n }\n public open(parent: HTMLElement): void {\n this._core.open(parent);\n }\n public attachCustomKeyEventHandler(customKeyEventHandler: (event: KeyboardEvent) => boolean): void {\n this._core.attachCustomKeyEventHandler(customKeyEventHandler);\n }\n public attachCustomWheelEventHandler(customWheelEventHandler: (event: WheelEvent) => boolean): void {\n this._core.attachCustomWheelEventHandler(customWheelEventHandler);\n }\n public registerLinkProvider(linkProvider: ILinkProvider): IDisposable {\n return this._core.registerLinkProvider(linkProvider);\n }\n public registerCharacterJoiner(handler: (text: string) => [number, number][]): number {\n this._checkProposedApi();\n return this._core.registerCharacterJoiner(handler);\n }\n public deregisterCharacterJoiner(joinerId: number): void {\n this._checkProposedApi();\n this._core.deregisterCharacterJoiner(joinerId);\n }\n public registerMarker(cursorYOffset: number = 0): IMarker {\n this._verifyIntegers(cursorYOffset);\n return this._core.registerMarker(cursorYOffset);\n }\n public registerDecoration(decorationOptions: IDecorationOptions): IDecoration | undefined {\n this._checkProposedApi();\n this._verifyPositiveIntegers(decorationOptions.x ?? 0, decorationOptions.width ?? 0, decorationOptions.height ?? 0);\n return this._core.registerDecoration(decorationOptions);\n }\n public hasSelection(): boolean {\n return this._core.hasSelection();\n }\n public select(column: number, row: number, length: number): void {\n this._verifyIntegers(column, row, length);\n this._core.select(column, row, length);\n }\n public getSelection(): string {\n return this._core.getSelection();\n }\n public getSelectionPosition(): IBufferRange | undefined {\n return this._core.getSelectionPosition();\n }\n public clearSelection(): void {\n this._core.clearSelection();\n }\n public selectAll(): void {\n this._core.selectAll();\n }\n public selectLines(start: number, end: number): void {\n this._verifyIntegers(start, end);\n this._core.selectLines(start, end);\n }\n public dispose(): void {\n super.dispose();\n }\n public scrollLines(amount: number): void {\n this._verifyIntegers(amount);\n this._core.scrollLines(amount);\n }\n public scrollPages(pageCount: number): void {\n this._verifyIntegers(pageCount);\n this._core.scrollPages(pageCount);\n }\n public scrollToTop(): void {\n this._core.scrollToTop();\n }\n public scrollToBottom(): void {\n this._core.scrollToBottom();\n }\n public scrollToLine(line: number): void {\n this._verifyIntegers(line);\n this._core.scrollToLine(line);\n }\n public clear(): void {\n this._core.clear();\n }\n public write(data: string | Uint8Array, callback?: () => void): void {\n this._core.write(data, callback);\n }\n public writeln(data: string | Uint8Array, callback?: () => void): void {\n this._core.write(data);\n this._core.write('\\r\\n', callback);\n }\n public paste(data: string): void {\n this._core.paste(data);\n }\n public refresh(start: number, end: number): void {\n this._verifyIntegers(start, end);\n this._core.refresh(start, end);\n }\n public reset(): void {\n this._core.reset();\n }\n public clearTextureAtlas(): void {\n this._core.clearTextureAtlas();\n }\n public loadAddon(addon: ITerminalAddon): void {\n this._addonManager.loadAddon(this, addon);\n }\n public static get strings(): ILocalizableStrings {\n // A wrapper is required here because esbuild prevents setting an `export let`\n return {\n get promptLabel(): string { return Strings.promptLabel.get(); },\n set promptLabel(value: string) { Strings.promptLabel.set(value); },\n get tooMuchOutput(): string { return Strings.tooMuchOutput.get(); },\n set tooMuchOutput(value: string) { Strings.tooMuchOutput.set(value); }\n };\n }\n\n private _verifyIntegers(...values: number[]): void {\n for ($value of values) {\n if ($value === Infinity || isNaN($value) || $value % 1 !== 0) {\n throw new Error('This API only accepts integers');\n }\n }\n }\n\n private _verifyPositiveIntegers(...values: number[]): void {\n for ($value of values) {\n if ($value && ($value === Infinity || isNaN($value) || $value % 1 !== 0 || $value < 0)) {\n throw new Error('This API only accepts positive integers');\n }\n }\n }\n}\n"],"names":["root","factory","exports","module","define","amd","a","i","globalThis","AccessibilityManager","Disposable","constructor","_terminal","instantiationService","super","_coreBrowserService","_renderService","_rowColumns","WeakMap","_liveRegionLineCount","_charsToConsume","_charsToAnnounce","doc","this","mainDocument","_accessibilityContainer","createElement","classList","add","_rowContainer","setAttribute","_rowElements","rows","_createAccessibilityTreeNode","appendChild","_topBoundaryFocusListener","e","_handleBoundaryFocus","_bottomBoundaryFocusListener","addEventListener","length","_liveRegion","_liveRegionDebouncer","_register","TimeBasedDebouncer","_renderRows","bind","element","Error","insertAdjacentElement","onResize","_handleResize","onRender","_refreshRows","start","end","onScroll","onA11yChar","char","_handleChar","onLineFeed","onA11yTab","spaceCount","_handleTab","onKey","_handleKey","key","onBlur","_clearLiveRegion","onDimensionsChange","_refreshRowsDimensions","addDisposableListener","_handleSelectionChange","onDprChange","toDisposable","remove","MAX_ROWS_TO_READ","shift","textContent","Strings","tooMuchOutput","get","keyChar","test","push","refresh","buffer","setSize","lines","toString","line","ydisp","columns","lineData","translateToString","undefined","posInSet","set","_alignRowWidth","_announceCharacters","position","boundaryElement","target","beforeBoundaryElement","getAttribute","relatedTarget","topBoundaryElement","bottomBoundaryElement","pop","removeChild","removeEventListener","newElement","unshift","scrollLines","focus","preventDefault","stopImmediatePropagation","selection","getSelection","isCollapsed","contains","anchorNode","clearSelection","focusNode","console","error","begin","node","offset","anchorOffset","focusOffset","compareDocumentPosition","Node","DOCUMENT_POSITION_PRECEDING","DOCUMENT_POSITION_CONTAINED_BY","DOCUMENT_POSITION_FOLLOWING","childNodes","lastRowElement","slice","toRowColumn","rowElement","Text","parentNode","row","parseInt","isNaN","warn","column","cols","beginRowColumn","endRowColumn","select","children","tabIndex","_refreshRowDimensions","dimensions","css","cell","height","Object","assign","style","width","canvas","fontSize","options","transform","getBoundingClientRect","lastColumn","targetWidth","IInstantiationService","ICoreBrowserService","IRenderService","prepareTextForTerminal","text","replace","bracketTextForPaste","bracketedPasteMode","paste","textarea","coreService","optionsService","decPrivateModes","rawOptions","ignoreBracketedPasteMode","triggerDataEvent","value","moveTextAreaUnderMouseCursor","ev","screenElement","pos","left","clientX","top","clientY","zIndex","selectionService","clipboardData","setData","selectionText","stopPropagation","getData","shouldSelectWord","rightClickSelect","_color","TwoKeyMap","_css","setCss","bg","fg","getCss","setColor","getColor","clear","CoreBrowserTerminal","CoreTerminal","linkifier","_linkifier","onFocus","_onFocus","event","_onBlur","_onA11yCharEmitter","_onA11yTabEmitter","onWillOpen","_onWillOpen","MutableDisposable","browser","Browser","_keyDownHandled","_keyDownSeen","_keyPressHandled","_unprocessedDeadKey","_accessibilityManager","_onCursorMove","Emitter","onCursorMove","_onKey","_onRender","_onSelectionChange","onSelectionChange","_onTitleChange","onTitleChange","_onBell","onBell","_setup","_decorationService","_instantiationService","createInstance","DecorationService","setService","IDecorationService","_linkProviderService","LinkProviderService","ILinkProviderService","registerLinkProvider","OscLinkProvider","_inputHandler","onRequestBell","fire","onRequestRefreshRows","onRequestSendFocus","_reportFocus","onRequestReset","reset","onRequestWindowsOptionsReport","type","_reportWindowsOptions","onColor","_handleColorEvent","Event","forward","_bufferService","_afterResize","_customKeyEventHandler","_themeService","req","acc","ident","index","colorRgb","color","toColorRGB","colors","ansi","C0","ESC","toRgbString","C1_ESCAPED","ST","modifyColors","channels","toColor","narrowedAcc","restoreColor","buffers","active","preventScroll","_handleScreenReaderModeOptionChange","_handleTextAreaFocus","sendFocus","_showCursor","blur","_handleTextAreaBlur","y","_syncTextArea","isCursorInViewport","_compositionHelper","isComposing","cursorY","ybase","bufferLine","cursorX","Math","min","x","cellHeight","getWidth","cellWidth","cursorTop","cursorLeft","lineHeight","_initGlobal","_bindKeys","hasSelection","copyHandler","_selectionService","pasteHandlerWrapper","handlePasteEvent","isFirefox","button","rightClickHandler","rightClickSelectsWord","isLinux","_keyUp","_keyDown","_keyPress","compositionstart","compositionupdate","compositionend","_inputEvent","updateCompositionElements","open","parent","isConnected","_logService","debug","ownerDocument","defaultView","window","_document","documentOverride","Document","dir","fragment","createDocumentFragment","_viewportElement","updateCursorStyle","_helperContainer","promptLabel","isChromeOS","onSpecificOptionChange","readOnly","disableStdin","CoreBrowserService","document","_charSizeService","CharSizeService","ICharSizeService","ThemeService","IThemeService","_characterJoinerService","CharacterJoinerService","ICharacterJoinerService","RenderService","onRenderedViewportChange","resize","_compositionView","CompositionHelper","_mouseService","MouseService","IMouseService","Linkifier","hasRenderer","setRenderer","_createRenderer","handleCursorMove","handleResize","handleBlur","handleFocus","_viewport","Viewport","onRequestScrollLines","SelectionService","ISelectionService","amount","suppressScrollEvent","onRequestRedraw","handleSelectionChanged","columnSelectMode","onLinuxMouseSelection","any","_onScroll","queueSync","BufferDecorationRenderer","handleMouseDown","coreMouseService","areMouseEventsActive","disable","enable","screenReaderMode","overviewRuler","_overviewRulerRenderer","OverviewRulerRenderer","measure","bindMouse","DomRenderer","self","el","sendEvent","getMouseReportCoords","but","action","overrideType","buttons","_customWheelEventHandler","deltaY","consumeWheelEvent","device","dpr","triggerMouseEvent","col","ctrl","ctrlKey","alt","altKey","shiftKey","requestedEvents","mouseup","wheel","mousedrag","mousemove","eventListeners","cancel","onProtocolChange","events","logLevel","explainEvents","passive","activeProtocol","shouldForceSelection","hasScrollback","sequence","applicationCursorKeys","refreshRows","shouldColumnSelect","isCursorInitialized","disp","scrollPages","pageCount","scrollToTop","scrollToBottom","disableSmoothScroll","scrollToLine","scrollAmount","data","attachCustomKeyEventHandler","customKeyEventHandler","attachCustomWheelEventHandler","customWheelEventHandler","linkProvider","registerCharacterJoiner","handler","joinerId","register","deregisterCharacterJoiner","deregister","markers","registerMarker","cursorYOffset","addMarker","registerDecoration","decorationOptions","setSelection","getSelectionPosition","selectionStart","selectionEnd","selectAll","selectLines","shouldIgnoreComposition","isMac","macOptionIsMeta","keydown","scrollOnUserInput","result","evaluateKeyboardEvent","scrollCount","_isThirdLevelShift","metaKey","charCodeAt","ETX","CR","domEvent","thirdLevelKey","isWindows","getModifierState","keyCode","wasModifierKeyOnlyEvent","charCode","which","String","fromCharCode","inputType","composed","hasValidSize","clearAllMarkers","getBlankLine","DEFAULT_ATTR_DATA","clearTextureAtlas","WindowsOptionsReportType","GET_WIN_SIZE_PIXELS","canvasWidth","toFixed","canvasHeight","GET_CELL_SIZE_PIXELS","force","cancelEvents","currentLink","_currentLink","_element","_linkCacheDisposables","_isMouseOut","_wasResized","_activeLine","_onShowLinkUnderline","onShowLinkUnderline","_onHideLinkUnderline","onHideLinkUnderline","dispose","_lastMouseEvent","_activeProviderReplies","_clearCurrentLink","_handleMouseMove","_handleMouseDown","_handleMouseUp","_positionFromMouseEvent","composedPath","_lastBufferCell","_handleHover","_askForLink","_linkAtPosition","link","useLineCache","forEach","reply","linkWithState","Map","linkProvided","linkProviders","entries","existingReply","_checkLinkProviderResult","provideLinks","links","linksWithState","map","size","_removeIntersectingLinks","replies","occupiedCells","Set","providerReply","startX","range","endX","has","splice","hasLinkBefore","j","linkAtPosition","find","_handleNewLink","_mouseDownLink","b","activate","startRow","endRow","_linkLeave","state","decorations","underline","pointerCursor","isHovered","_linkHover","defineProperties","v","toggle","_fireUnderlineEvent","hover","showEvent","scrollOffset","_createLinkUnderlineEvent","leave","lower","upper","current","mouseService","coords","getCoords","x1","y1","x2","y2","IBufferService","promptLabelInternal","tooMuchOutputInternal","_optionsService","_oscLinkService","callback","linkHandler","CellData","lineLength","getTrimmedLength","currentLinkId","currentStart","finishLink","hasContent","loadCell","hasExtendedAttrs","extended","urlId","getLinkData","uri","ignoreLink","allowNonHttpProtocols","parsed","URL","includes","protocol","defaultActivate","confirm","newWindow","opener","location","href","IOptionsService","IOscLinkService","_renderCallback","_refreshCallbacks","_animationFrame","cancelAnimationFrame","addRefreshCallback","requestAnimationFrame","_innerRefresh","rowStart","rowEnd","rowCount","_rowCount","_rowStart","_rowEnd","max","_runRefreshCallbacks","_debounceThresholdMS","_lastRefreshMs","_additionalRefreshRequested","_refreshTimeoutID","clearTimeout","refreshRequestTime","performance","now","elapsed","waitPeriodBeforeTrailingRefresh","setTimeout","DEFAULT_ANSI_COLORS","freeze","r","g","toCss","rgba","toRgba","c","coreBrowserService","themeService","_onRequestScrollLines","_isSyncing","_isHandlingScroll","_suppressOnScrollHandler","scrollable","Scrollable","forceIntegerValues","smoothScrollDuration","scheduleAtNextAnimationFrame","cb","setSmoothScrollDuration","_scrollableElement","SmoothScrollableElement","vertical","horizontal","useShadows","mouseWheelSmoothScroll","_getChangeOptions","onMultipleOptionChange","updateOptions","handleMouseWheel","setScrollDimensions","scrollHeight","runAndSubscribe","onChangeColors","getDomNode","backgroundColor","background","_styleElement","scrollbarSliderBackground","scrollbarSliderHoverBackground","scrollbarSliderActiveBackground","join","onBufferActivate","_latestYDisp","_sync","_handleScroll","getScrollPosition","setScrollPosition","reuseAnimation","scrollTop","mouseWheelScrollSensitivity","scrollSensitivity","fastScrollSensitivity","verticalScrollbarSize","_queuedAnimationFrame","newRow","round","diff","ICoreMouseService","_screenElement","_decorationElements","_altBufferIsActive","_dimensionsChanged","_container","_doRefreshDecorations","_queueRefresh","onDecorationRegistered","onDecorationRemoved","decoration","_removeDecoration","_renderDecoration","_refreshStyle","_refreshXPosition","_createElement","layer","marker","display","onRenderEmitter","onDispose","delete","anchor","right","_zones","_zonePool","_zonePoolIndex","_linePadding","full","center","zones","addDecoration","overviewRulerOptions","z","_lineIntersectsZone","_lineAdjacentToZone","_addLineToZone","startBufferLine","endBufferLine","setPadding","padding","zone","drawHeight","drawWidth","drawX","_width","_colorZoneStore","ColorZoneStore","_shouldUpdateDimensions","_shouldUpdateAnchor","_lastKnownBufferLength","_canvas","_refreshCanvasDimensions","parentElement","insertBefore","ctx","getContext","_ctx","normal","_refreshDrawHeightConstants","_refreshColorZonePadding","_containerHeight","clientHeight","_refreshDrawConstants","outerWidth","floor","innerWidth","ceil","pixelsPerLine","nonFullHeight","_refreshDecorations","clearRect","lineWidth","_renderRulerOutline","_renderColorZone","fillStyle","overviewRulerBorder","fillRect","showTopBorder","showBottomBorder","updateCanvasDimensions","updateAnchor","_isComposing","_textarea","_coreService","_isSendingComposition","_compositionPosition","_dataAlreadySent","_finalizeComposition","_handleAnyTextareaChanges","waitForPropagation","currentCompositionPosition","input","substring","oldValue","newValue","DEL","dontRecurse","fontFamily","compositionViewBounds","ICoreService","getCoordsRelativeToElement","rect","elementStyle","getComputedStyle","leftPadding","getPropertyValue","topPadding","colCount","hasValidCharSize","cssCellWidth","cssCellHeight","isSelection","targetX","targetY","bufferService","applicationCursor","startY","moveToRequestedRow","repeat","wrappedRowsForRow","resetStartingRow","direction","horizontalDirection","moveToRequestedCol","abs","rowDifference","currX","colsFromRowEnd","rowsToMove","wrappedRows","verticalDirection","isWrapped","wrappedRowsCount","currentRow","lineWraps","startCol","endCol","currentCol","bufferStr","translateBufferLineToString","mod","count","str","rpt","TERMINAL_CLASS_PREFIX","ROW_CONTAINER_CLASS","FG_CLASS_PREFIX","BG_CLASS_PREFIX","FOCUS_CLASS","SELECTION_CLASS","nextTerminalId","_linkifier2","_terminalClass","_selectionRenderModel","createSelectionRenderModel","_refreshRowElements","_selectionContainer","createRenderDimensions","_updateDimensions","onOptionChange","_handleOptionsChanged","_injectCss","_rowFactory","DomRendererRowFactory","_handleLinkHover","_handleLinkLeave","_widthCache","_themeStyleElement","_dimensionsStyleElement","WidthCache","setFont","fontWeight","fontWeightBold","_setDefaultSpacing","letterSpacing","overflow","styles","_terminalSelector","foreground","multiplyOpacity","blinkAnimationUnderlineId","blinkAnimationBarId","blinkAnimationBlockId","cursor","cursorAccent","cursorWidth","selectionBackgroundOpaque","selectionInactiveBackgroundOpaque","INVERTED_DEFAULT_COLOR","opaque","spacing","defaultSpacing","handleDevicePixelRatioChange","handleCharSizeChanged","renderRows","replaceChildren","update","viewportStartRow","viewportEndRow","viewportCappedStartRow","viewportCappedEndRow","documentFragment","isXFlipped","_createSelectionElement","middleRowsCount","colStart","colEnd","cursorAbsoluteY","cursorBlink","cursorStyle","cursorInactiveStyle","createRow","_setCellUnderline","enabled","maxY","bufferline","_workCell","_columnSelectMode","_selectionStart","_selectionEnd","isCursorRow","widthCache","linkStart","linkEnd","elements","joinedRanges","getJoinedCharacters","charElement","getNoBgTrimmedLength","cellAmount","oldBg","oldFg","oldExt","oldLinkHover","oldSpacing","oldIsInSelection","skipJoinedCheckUntilX","classes","hasHover","isJoined","isValidJoinRange","lastCharX","firstSelectionState","_isCellInSelection","JoinedCellData","isInSelection","isCursorCell","isLinkHover","isDecorated","forEachDecorationAtCell","d","chars","getChars","WHITESPACE_CELL_CHAR","isUnderline","isOverline","isBold","isItalic","selectionForeground","ext","isInvisible","isCursorHidden","isFocused","isDim","underlineStyle","isUnderlineColorDefault","isUnderlineColorRGB","textDecorationColor","AttributeData","getUnderlineColor","drawBoldTextInBrightColors","isStrikethrough","textDecoration","getFgColor","fgColorMode","getFgColorMode","getBgColor","bgColorMode","getBgColorMode","isInverse","temp","temp2","bgOverride","fgOverride","resolvedBg","isTop","backgroundColorRGB","foregroundColorRGB","_addStyle","padStart","_applyMinimumContrast","className","minimumContrastRatio","treatGlyphAsBackgroundColor","getCode","cache","_getContrastCache","adjustedColor","ratio","ensureContrastRatio","halfContrastCache","contrastCache","padChar","_flat","Float32Array","_font","_fontSize","_weight","_weightBold","_measureElements","whiteSpace","fontKerning","regular","bold","italic","fontStyle","boldItalic","_holey","fill","font","weight","weightBold","cp","_measure","variant","offsetWidth","isPowerlineGlyph","codepoint","isEmoji","glyphSizeX","deviceCellWidth","isNerdFontGlyph","isBoxOrBlockGlyph","currentOffset","SelectionRenderModel","terminal","viewportY","isCellSelected","isSelectAllActive","selectionStartLength","finalSelectionStart","areSelectionValuesReversed","finalSelectionEnd","startPlusLength","handleTrim","_onCharSizeChange","onCharSizeChange","_measureStrategy","TextMetricsMeasureStrategy","DomMeasureStrategy","BaseMeasureStategy","_result","_validateAndSet","_parentElement","_measureElement","Number","offsetHeight","OffscreenCanvas","measureText","metrics","fontBoundingBoxAscent","fontBoundingBoxDescent","firstCell","content","combinedData","isCombined","setFromCharData","getAsCharData","_characterJoiners","_nextCharacterJoinerId","joiner","id","ranges","lineStr","rangeStartColumn","currentStringIndex","rangeStartStringIndex","rangeAttrFG","getFg","rangeAttrBG","getBg","_getJoinedRanges","startIndex","endIndex","allJoinedRanges","joinerRanges","_mergeRanges","_stringRangesToCellRanges","currentRangeIndex","currentRangeStarted","currentRange","getString","newRange","inRange","_window","_isFocused","_cachedIsFocused","_screenDprMonitor","ScreenDprMonitor","_onDprChange","_onWindowChange","onWindowChange","w","setWindow","devicePixelRatio","hasFocus","queueMicrotask","_parentWindow","_windowResizeListener","_outerListener","_setDprAndFireIfDiffers","_currentDevicePixelRatio","_updateDpr","_setWindowResizeListener","clearListener","parentWindow","_resolutionMediaMatchList","removeListener","matchMedia","addListener","providerIndex","indexOf","_renderer","decorationService","_pausedResizeTask","DebouncedIdleTask","_observerDisposable","_isPaused","_needsFullRefresh","_isNextRenderRedrawOnly","_needsSelectionRefresh","_canvasWidth","_canvasHeight","_selectionState","_onDimensionsChange","_onRenderedViewportChange","_onRefreshRequest","onRefreshRequest","_renderDebouncer","RenderDebouncer","_syncOutputHandler","SynchronizedOutputHandler","_fullRefresh","_registerIntersectionObserver","observer","IntersectionObserver","_handleIntersectionChange","threshold","observe","disconnect","entry","isIntersecting","intersectionRatio","flush","isRedrawOnly","synchronizedOutput","bufferRows","buffered","_fireOnCanvasResize","renderer","_onTimeout","_start","_end","_isBuffering","_timeout","NON_BREAKING_SPACE_CHAR","ALL_NON_BREAKING_SPACE_REGEX","RegExp","_dragScrollAmount","_enabled","_mouseDownTimeStamp","_oldHasSelection","_oldSelectionStart","_oldSelectionEnd","_onLinuxMouseSelection","_onRedrawRequest","_mouseMoveListener","_mouseUpListener","onUserInput","_trimListener","onTrim","_handleTrim","_handleBufferActivate","_model","SelectionModel","_activeSelectionMode","_removeMouseDownListeners","rowsChanged","lineText","startRowEndCol","isLinuxMouseSelection","_refreshAnimationFrame","_refresh","_isClickInSelection","_getMouseBufferCoords","_areCoordsInSelection","isCellInSelection","_selectWordAtCursor","allowWhitespaceOnlySelection","getRangeLength","_selectWordAt","_getMouseEventScrollAmount","terminalHeight","macOptionClickForcesSelection","timeStamp","_handleIncrementalClick","detail","_handleSingleClick","_handleDoubleClick","_handleTripleClick","_addMouseDownListeners","_dragScrollIntervalTimer","setInterval","_dragScroll","clearInterval","hasWidth","_selectLineAt","previousSelectionEnd","_selectToWordAt","timeElapsed","altClickMovesCursor","coordinates","moveToCellSequence","_fireEventIfSelectionChanged","_fireOnSelectionChange","activeBuffer","_convertViewportColToCharacterIndex","charIndex","_getWordAt","followWrappedLinesAbove","followWrappedLinesBelow","charOffset","leftWideCharCount","rightWideCharCount","leftLongCharOffset","rightLongCharOffset","charAt","_isCharWordSeparator","trim","getCodePoint","previousBufferLine","previousLineWordPosition","nextBufferLine","nextLineWordPosition","wordPosition","wordSeparator","wrappedRange","getWrappedRangeForLine","first","last","createDecorator","DEFAULT_FOREGROUND","DEFAULT_BACKGROUND","DEFAULT_CURSOR","DEFAULT_CURSOR_ACCENT","DEFAULT_SELECTION","DEFAULT_OVERVIEW_RULER_BORDER","_colors","_contrastCache","ColorContrastCache","_halfContrastCache","_onChangeColors","selectionBackgroundTransparent","blend","selectionInactiveBackgroundTransparent","opacity","_updateRestoreColors","_setTheme","theme","parseColor","selectionBackground","selectionInactiveBackground","NULL_COLOR","isOpaque","black","red","green","yellow","blue","magenta","cyan","white","brightBlack","brightRed","brightGreen","brightYellow","brightBlue","brightMagenta","brightCyan","brightWhite","extendedAnsi","colorCount","slot","_restoreColor","_restoreColors","cssString","fallback","CircularList","_maxLength","onDeleteEmitter","onDelete","onInsertEmitter","onInsert","onTrimEmitter","_array","Array","_startIndex","_length","maxLength","newMaxLength","newArray","_getCyclicIndex","newLength","recycle","isFull","deleteCount","items","countToTrim","trimStart","shiftElements","expandListBy","clone","val","depth","clonedObject","isArray","$r","$g","$b","$a","rgb","toPaddedHex","s","contrastRatio","l1","l2","toChannels","fgR","fgG","fgB","bgR","bgG","bgB","rgbaColor","factor","$ctx","$litmusColor","willReadFrequently","globalCompositeOperation","createLinearGradient","match","rgbaMatch","parseFloat","getImageData","relativeLuminance2","rs","gs","bs","pow","relativeLuminance","reduceLuminance","bgRgba","fgRgba","cr","increaseLuminance","bgL","fgL","resultA","resultARatio","resultB","hasWriteSyncWarnHappened","_onScrollApi","_windowsWrappingHeuristics","_onBinary","onBinary","_onData","onData","_onLineFeed","_onResize","_onWriteParsed","onWriteParsed","InstantiationService","OptionsService","BufferService","LogService","ILogService","CoreService","CoreMouseService","unicodeService","UnicodeService","IUnicodeService","_charsetService","CharsetService","ICharsetService","OscLinkService","InputHandler","onRequestScrollToBottom","_writeBuffer","handleUserInput","_handleWindowsPtyOptionChange","markRangeDirty","scrollBottom","WriteBuffer","promiseResult","parse","write","writeSync","maxSubsequentCalls","LogLevelEnum","WARN","wasUserInput","MINIMUM_COLS","MINIMUM_ROWS","scroll","eraseAttr","registerEscHandler","registerDcsHandler","registerCsiHandler","registerOscHandler","windowsPty","buildNumber","backend","windowsMode","_enableWindowsWrappingHeuristics","disposables","updateWindowsModeWrappedState","final","GLEVEL","MAX_PARSEBUFFER_LENGTH","paramToWindowOption","n","opts","setWinLines","restoreWin","minimizeWin","setWinPosition","setWinSizePixels","raiseWin","lowerWin","refreshWin","setWinSizeChars","maximizeWin","fullscreenWin","getWinState","getWinPosition","getWinSizePixels","getScreenSizePixels","getCellSizePixels","getWinSizeChars","getScreenSizeChars","getIconTitle","getWinTitle","pushTitle","popTitle","$temp","getAttrData","_curAttrData","_coreMouseService","_unicodeService","_parser","EscapeSequenceParser","_parseBuffer","Uint32Array","_stringDecoder","StringToUtf32","_utf8Decoder","Utf8ToUtf32","_windowTitle","_iconName","_windowTitleStack","_iconNameStack","_eraseAttrDataInternal","_onRequestBell","_onRequestRefreshRows","_onRequestReset","_onRequestSendFocus","_onRequestSyncScrollBar","onRequestSyncScrollBar","_onRequestWindowsOptionsReport","_onA11yChar","_onA11yTab","_onColor","_parseStack","paused","cursorStartX","cursorStartY","decodedLength","_specialColors","_dirtyRowTracker","DirtyRowTracker","_activeBuffer","setCsiHandlerFallback","params","identifier","identToString","toArray","setEscHandlerFallback","setExecuteHandlerFallback","code","setOscHandlerFallback","setDcsHandlerFallback","payload","setPrintHandler","print","insertChars","intermediates","scrollLeft","cursorUp","scrollRight","cursorDown","cursorForward","cursorBackward","cursorNextLine","cursorPrecedingLine","cursorCharAbsolute","cursorPosition","cursorForwardTab","eraseInDisplay","prefix","eraseInLine","insertLines","deleteLines","deleteChars","scrollUp","scrollDown","eraseChars","cursorBackwardTab","charPosAbsolute","hPositionRelative","repeatPrecedingCharacter","sendDeviceAttributesPrimary","sendDeviceAttributesSecondary","linePosAbsolute","vPositionRelative","hVPosition","tabClear","setMode","setModePrivate","resetMode","resetModePrivate","charAttributes","deviceStatus","deviceStatusPrivate","softReset","setCursorStyle","setScrollRegion","saveCursor","windowOptions","restoreCursor","insertColumns","deleteColumns","selectProtected","requestMode","setExecuteHandler","BEL","bell","LF","lineFeed","VT","FF","carriageReturn","BS","backspace","HT","tab","SO","shiftOut","SI","shiftIn","C1","IND","NEL","nextLine","HTS","tabSet","OscHandler","setTitle","setIconName","setOrReportIndexedColor","setHyperlink","setOrReportFgColor","setOrReportBgColor","setOrReportCursorColor","restoreIndexedColor","restoreFgColor","restoreBgColor","restoreCursorColor","reverseIndex","keypadApplicationMode","keypadNumericMode","fullReset","setgLevel","selectDefaultCharset","flag","CHARSETS","selectCharset","screenAlignmentPattern","setErrorHandler","DcsHandler","requestStatusString","_preserveStack","_logSlowResolvingAsync","p","Promise","race","res","rej","catch","err","_getCurrentLinkId","wasPaused","DEBUG","prototype","call","TRACE","trace","split","clearRange","len","decode","subarray","viewportEnd","viewportStart","chWidth","charset","wraparoundMode","wraparound","insertMode","modes","curAttr","bufferRow","markDirty","setCellFromCodepoint","precedingJoinState","ch","currentInfo","charProperties","extractWidth","shouldJoin","extractShouldJoin","oldWidth","stringFromCodePoint","addLineToLink","oldRow","oldCol","_eraseAttrData","BufferLine","copyCellsFrom","addCodepointToCell","delta","insertCells","getNullCell","NULL_CELL_CODE","NULL_CELL_WIDTH","convertEol","reverseWraparound","_restrictCursor","originalX","nextStop","maxCol","origin","_setCursor","_moveCursor","diffToTop","diffToBottom","param","tabs","prevStop","_eraseInBufferLine","clearWrap","respectProtect","replaceCells","_resetBufferLine","clearMarkers","scrollOnEraseInDisplay","currentLine","scrollBackSize","scrollBottomRowsOffset","scrollBottomAbsolute","deleteCells","joinState","idata","itext","codePointAt","tlength","copyWithin","_is","term","termName","setgCharset","DEFAULT_CHARSET","applicationKeypad","activeEncoding","activateAltBuffer","activateNormalBuffer","dm","mouseProtocol","mouseEncoding","cs","b2v","m","_updateAttrColor","mode","c1","c2","c3","fromColorRGB","_extractColor","attr","accu","cSpace","advance","hasSubParams","subparams","getSubParams","underlineColor","_processUnderline","updateExtended","_processSGR0","l","savedX","savedY","savedCurAttrData","savedCharset","isBlinking","bottom","second","_savedCharset","slots","idx","spec","exec","isValidColorIndex","_createHyperlink","_finishHyperlink","parsedParams","idParamIndex","findIndex","startsWith","registerLink","_setOrReportSpecialColor","collectAndFlag","scrollRegionHeight","level","yOffset","markAllDirty","f","isProtected","_data","third","fourth","isSafari","majorVersion","userAgent","isNode","process","navigator","platform","isLegacyEdge","isIpad","isIphone","_getKey","_insertedValues","_flushInsertedTask","IdleTaskQueue","_isFlushingInserted","_deletedIndices","_flushDeletedTask","_isFlushingDeleted","insert","_flushCleanupDeleted","enqueue","_flushInserted","sortedAddedValues","sort","sortedAddedValuesIndex","arrayIndex","newArrayIndex","_flushCleanupInserted","_search","_flushDeleted","sortedDeletedIndices","sortedDeletedIndicesIndex","getKeyIterator","forEachByKey","values","mid","midKey","TaskQueue","_tasks","_i","task","_idleCallback","_cancelCallback","_requestCallback","_process","deadline","taskDuration","longestTask","lastDeadlineRemaining","timeRemaining","deadlineRemaining","PriorityTaskQueue","_createDeadline","duration","requestIdleCallback","cancelIdleCallback","_queue","lastChar","CHAR_DATA_CODE_INDEX","WHITESPACE_CELL_CODE","ExtendedAttrs","newObj","isBlink","isFgRGB","isBgRGB","isFgPalette","isBgPalette","isFgDefault","isBgDefault","isAttributeDefault","isEmpty","getUnderlineColorMode","isUnderlineColorPalette","getUnderlineStyle","getUnderlineVariantOffset","underlineVariantOffset","_urlId","_ext","MAX_BUFFER_SIZE","_hasScrollback","_nullCell","fromCharData","NULL_CELL_CHAR","_whitespaceCell","WHITESPACE_CELL_WIDTH","_isClearing","_memoryCleanupQueue","_memoryCleanupPosition","_cols","_rows","_getCorrectBufferLength","setupTabStops","getWhitespaceCell","relativeY","correctBufferLength","scrollback","fillViewportRows","fillAttr","newCols","newRows","nullCell","dirtyMemoryLines","addToY","amountToTrim","_isReflowEnabled","_reflow","_batchedMemoryCleanup","normalRun","counted","cleanupMemory","_reflowLarger","_reflowSmaller","reflowCursorLine","toRemove","reflowLargerGetLinesToRemove","newLayoutResult","reflowLargerCreateNewLayout","reflowLargerApplyNewLayout","layout","_reflowLargerAdjustViewport","countRemoved","viewportAdjustments","toInsert","countToInsert","wrappedLines","absoluteY","lastLineLength","destLineLengths","reflowSmallerGetNewLineLengths","linesToAdd","trimmedLines","newLines","newLine","destLineIndex","destCol","srcLineIndex","srcCol","cellsToCopy","wrappedLinesIndex","getWrappedLineTrimmedLength","setCell","insertEvents","originalLines","originalLinesLength","originalLineIndex","nextToInsertIndex","nextToInsert","countInsertedSoFar","nextI","insertCountEmitted","lineIndex","trimRight","tabStopWidth","Marker","_removeMarker","$startIndex","fillCellData","_combined","_extendedAttrs","CHAR_DATA_ATTR_INDEX","CHAR_DATA_CHAR_INDEX","CHAR_DATA_WIDTH_INDEX","codePoint","attrs","byteLength","uint32Cells","keys","extKeys","copyFrom","src","applyInReverse","srcData","srcCombinedKeys","outColumns","bufferCols","endsInNull","followingLineStartsWithWide","oldCols","bufferAbsoluteY","srcTrimmedTineLength","srcRemainingCells","destRemainingCells","countToRemove","nextToRemoveIndex","nextToRemoveStart","countRemovedSoFar","newLayout","newLayoutLines","newLineLengths","cellsNeeded","reduce","srcLine","cellsAvailable","oldTrimmedLength","endsWithWide","BufferSet","_onBufferActivate","_normal","Buffer","_alt","inactiveBuffer","obj","combined","DEFAULT_COLOR","DEFAULT_ATTR","DEFAULT_EXT","_id","isDisposed","_disposables","_nextId","_onDispose","disposable","C","NUL","SOH","STX","EOT","ENQ","ACK","DLE","DC1","DC2","DC3","DC4","NAK","SYN","ETB","CAN","EM","SUB","FS","GS","RS","US","SP","PAD","HOP","BPH","NBH","SSA","ESA","HTJ","VTS","PLD","PLU","RI","SS2","SS3","DCS","PU1","PU2","STS","CCH","MW","SPA","EPA","SOS","SGCI","SCI","CSI","OSC","PM","APC","applicationCursorMode","modifiers","keyMapping","KEYCODE_KEY_MAPPINGS","keyString","toUpperCase","toLowerCase","_interim","startPos","interim","Uint8Array","byte1","byte2","byte3","byte4","discardInterim","tmp","missing","fourStop","BMP_COMBINING","HIGH_COMBINING","table","version","wcwidth","num","ucs","bisearch","preceding","createPropertyValue","_action","_callbacks","_pendingData","_bufferOffset","_isSyncWriting","_syncCalls","_didUserInput","chunk","_innerWrite","lastTime","startTime","continuation","resolve","then","low","RGB_REX","base","HASH_REX","adv","bits","pad","s2","PAYLOAD_LIMIT","EMPTY_HANDLERS","_handlers","create","_active","_ident","_handlerFb","_stack","loopPosition","fallThrough","registerHandler","handlerList","handlerIndex","clearHandler","setHandlerFallback","unhook","hook","put","utf32ToString","success","handlerResult","EMPTY_PARAMS","Params","addParam","_handler","_params","_hitLimit","ret","TransitionTable","setDefault","next","addMany","codes","NON_ASCII_PRINTABLE","VT500_TRANSITION_TABLE","blueprint","apply","unused","PRINTABLES","EXECUTABLES","states","_transitions","handlers","handlerPos","transition","chunkPos","initialState","currentState","_collect","_printHandlerFb","_executeHandlerFb","_csiHandlerFb","_escHandlerFb","_errorHandlerFb","_printHandler","_executeHandlers","_csiHandlers","_escHandlers","_oscParser","OscParser","_dcsParser","DcsParser","_errorHandler","_identifier","finalRange","intermediate","finalCode","reverse","clearPrintHandler","clearEscHandler","clearExecuteHandler","clearCsiHandler","clearDcsHandler","clearOscHandler","clearErrorHandler","collect","abort","addSubParam","addDigit","handlersEsc","jj","_state","_put","MAX_VALUE","fromArray","k","maxSubParamsLength","Int32Array","_subParams","_subParamsLength","_subParamsIdx","Uint16Array","_rejectDigits","_rejectSubDigits","_digitIsSub","newParams","getSubParamsAll","store","cur","_addons","instance","loadAddon","loadedAddon","_wrappedAddonDispose","_buffer","init","baseY","getLine","BufferLineApiView","_line","getCell","startColumn","endColumn","BufferNamespaceApi","_core","_onBufferChange","onBufferChange","BufferApiView","_alternate","alternate","addCsiHandler","addDcsHandler","addEscHandler","addOscHandler","provider","versions","activeVersion","isUserScrolling","colsChanged","_cachedBlankLine","topRow","bottomRow","willBufferBeTrimmed","oldYdisp","glevel","_charsets","DEFAULT_PROTOCOLS","NONE","restrict","X10","VT200","DRAG","ANY","eventCode","isSGR","S","DEFAULT_ENCODINGS","DEFAULT","SGR","SGR_PIXELS","_protocols","_encodings","_activeProtocol","_activeEncoding","_lastEvent","_wheelPartialScroll","_onProtocolChange","name","addProtocol","addEncoding","encoding","targetWheelEventPixels","_applyScrollModifier","deltaMode","WheelEvent","DOM_DELTA_PIXEL","DOM_DELTA_PAGE","_equalEvents","report","triggerBinaryEvent","down","up","drag","move","e1","e2","pixels","DEFAULT_MODES","DEFAULT_DEC_PRIVATE_MODES","_onUserInput","_onRequestScrollToBottom","$xmin","$xmax","_decorations","SortedList","_onDecorationRegistered","_onDecorationRemoved","Decoration","markerDispose","listener","getDecorationsAtCell","xmin","xmax","DisposableStore","_cachedBg","_cachedFg","foregroundColor","ServiceCollection","_entries","service","_services","getService","ctor","args","serviceDependencies","getServiceDependencies","serviceArgs","dependency","firstServiceArgPos","logger","traceLogger","_target","descriptor","fn","JSON","stringify","optionsKeyToLogLevel","info","INFO","ERROR","off","OFF","_logLevel","_updateLogLevel","_evalLazyOptionalParams","optionalParams","_log","message","log","DEFAULT_OPTIONS","customGlyphs","fastScrollModifier","allowProposedApi","allowTransparency","rescaleOverlappingGlyphs","FONT_WEIGHT_OPTIONS","_onOptionChange","defaultOptions","_sanitizeAndValidateOption","_setupOptions","eventKey","getter","propName","setter","desc","defineProperty","isCursorStyle","_entriesWithId","_dataByLinkId","_removeMarkerFromLink","castData","_getEntryIdKey","linkId","every","linkData","DI_DEPENDENCIES","serviceRegistry","decorator","arguments","DI_TARGET","storeServiceDependency","extractCharKind","_providers","_onChange","onChange","defaultProvider","UnicodeV6","_activeProvider","getStringCellWidth","precedingInfo","isAndroid","isElectron","isWebkitWebView","isChrome","isWebKit","onDidChangeFullscreen","onDidChangeZoomLevel","addMatchMediaChangeListener","setZoomLevel","zoomLevel","targetWindow","WindowManager","INSTANCE","getZoomLevel","getZoomFactor","setZoomFactor","zoomFactor","setFullscreen","fullscreen","isFullscreen","isStandalone","standalone","isWCOEnabled","windowControlsOverlay","visible","getWCOBoundingRect","getTitlebarAreaRect","window_1","event_1","mapWindowIdToZoomLevel","_onDidChangeZoomLevel","mapWindowIdToZoomFactor","_onDidChangeFullscreen","mapWindowIdToFullScreen","getWindowId","targetWindowId","windowId","vscodeWindowId","query","mainWindow","standaloneMatchMedia","fullScreenMatchMedia","matches","__createBinding","o","k2","getOwnPropertyDescriptor","__esModule","writable","configurable","enumerable","__setModuleDefault","__importStar","hasOwnProperty","BrowserFeatures","KeyboardSupport","safeNavigator","clipboard","writeText","isNative","queryCommandSupported","readText","keyboard","Always","FullScreen","None","touch","maxTouchPoints","pointerEvents","PointerEvent","_a","SafeTriangle","DragAndDropObserver","ModifierKeyEmitter","DetectedFullscreenMode","Namespace","EventHelper","EventType","sharedMutationObserver","Dimension","WindowIntervalTimer","runAtThisOrScheduleAtNextAnimationFrame","WindowIdleValue","addStandardDisposableGenericMouseUpListener","addStandardDisposableGenericMouseDownListener","addStandardDisposableListener","onDidUnregisterWindow","onWillUnregisterWindow","onDidRegisterWindow","hasWindow","getWindowById","getWindowsCount","getWindows","getDocument","getWindow","registerWindow","clearNode","firstChild","clearNodeRecursively","domNode","addDisposableGenericMouseDownListener","addDisposableGenericMouseMoveListener","useCapture","isIOS","canIUse_1","POINTER_MOVE","MOUSE_MOVE","addDisposableGenericMouseUpListener","runWhenWindowIdle","timeout","async_1","_runWhenIdle","disposableWindowInterval","interval","iterations","iteration","timer","lifecycle_1","modify","addDisposableThrottledListener","eventMerger","minimumTimeMs","TimeoutThrottledDomListener","getClientArea","elWindow","elDocument","body","clientWidth","visualViewport","innerHeight","documentElement","getTopLeftOffset","getDomNodePagePosition","bb","scrollX","scrollY","getDomNodeZoomLevel","testElement","zoom","elementZoomLevel","getTotalWidth","getContentWidth","border","SizeUtils","getBorderLeftWidth","getBorderRightWidth","getPaddingLeft","getPaddingRight","getTotalScrollWidth","getContentHeight","getBorderTopWidth","getBorderBottomWidth","getPaddingTop","getPaddingBottom","getTotalHeight","margin","getMarginTop","getMarginBottom","getLargestChildWidth","childWidths","child","elementPosition","parentPosition","getRelativeLeft","isAncestor","setParentFlowTo","fromChildElement","toParentElement","dataset","parentFlowToDataKey","isAncestorUsingFlowTo","testChild","testAncestor","isHTMLElement","flowToParentElement","getParentFlowToElement","findParentWithClass","hasParentWithClass","clazz","stopAtClazzOrNode","isShadowRoot","isInShadowDOM","getShadowRoot","getActiveElement","isActiveElement","isAncestorOfActiveElement","ancestor","isActiveDocument","getActiveDocument","getActiveWindow","isGlobalStylesheet","globalStylesheets","createStyleSheet2","WrappedStyleElement","createStyleSheet","cloneGlobalStylesheets","globalStylesheet","clonedGlobalStylesheets","cloneGlobalStyleSheet","createMetaElement","container","head","createHeadElement","createLinkElement","createCSSRule","selector","cssText","getSharedStyleSheet","sheet","insertRule","clonedGlobalStylesheet","removeCSSRulesContainingSelector","ruleName","rules","getDynamicStyleSheetRules","toDelete","rule","isCSSStyleRule","selectorText","deleteRule","isHTMLAnchorElement","HTMLAnchorElement","isHTMLSpanElement","HTMLSpanElement","isHTMLTextAreaElement","HTMLTextAreaElement","isHTMLInputElement","HTMLInputElement","isHTMLButtonElement","HTMLButtonElement","isHTMLDivElement","HTMLDivElement","isSVGElement","SVGElement","isMouseEvent","MouseEvent","isKeyboardEvent","KeyboardEvent","isPointerEvent","isDragEvent","DragEvent","isEventLike","candidate","saveParentsScrollTop","nodeType","ELEMENT_NODE","restoreParentsScrollTop","trackFocus","FocusTracker","after","sibling","append","prepend","innerText","$","nodes","separator","cloneNode","createTextNode","setVisibility","show","hide","removeTabIndexAndUpdateFocus","hasAttribute","activeElement","parentFocusable","findParentWithAttribute","removeAttribute","finalHandler","domContentLoaded","readyState","computeScreenAwareSize","cssPx","screenPx","windowOpenNoOpener","url","windowOpenPopup","screenLeft","popupWidth","screenTop","popupHeight","windowOpenWithSuccess","noOpener","newTab","animate","step","stepDisposable","asCSSPropertyValue","asCssValueWithDefault","cssPropertyValue","dflt","variableMatch","varArguments","detectFullscreen","fullscreenElement","webkitFullscreenElement","webkitIsFullScreen","DOCUMENT","guess","screen","BROWSER","isMacintosh","outerHeight","multibyteAwareBtoa","btoa","codeUnits","binary","uint8array","toBinary","getCookieValue","cookie","h","tag","attributes","H_REGEX","groups","tagName","classNames","cssKey","cssValue","setProperty","camelCaseToHyphenCase","svgElem","createElementNS","copyAttributes","trackAttributes","from","to","filter","attributeFilter","mutations","mutation","attributeName","copyAttribute","keyboardEvent_1","mouseEvent_1","errors_1","keyCodes_1","hash_1","numbers_1","windows","ensureCodeWindow","mainWindowRegistration","registeredWindow","BEFORE_UNLOAD","fallbackToMain","candidateNode","candidateEvent","view","DomListener","_node","_type","_options","useCaptureOrOptions","_wrapAsStandardMouseEvent","StandardMouseEvent","POINTER_DOWN","MOUSE_DOWN","POINTER_UP","MOUSE_UP","wrapHandler","StandardKeyboardEvent","_wrapAsStandardKeyboardEvent","AbstractIdleValue","executor","IntervalTimer","defaultTarget","cancelAndSet","runner","AnimationFrameQueueItem","priority","_runner","_canceled","execute","onUnexpectedError","NEXT_QUEUE","CURRENT_QUEUE","animFrameRequested","inAnimationFrameRunner","item","nextQueue","currentQueue","animationFrameRunner","DEFAULT_EVENT_MERGER","lastEvent","currentEvent","lastHandlerTime","TimeoutTimer","invokeHandler","Date","getTime","elapsedTime","setIfNotSet","convertToPixels","getDimension","cssPropertyName","jsPropertyName","computedStyle","getMarginLeft","getMarginRight","is","lift","equals","offsetParent","offsetTop","offsetLeft","scrollWidth","Boolean","flowToParentId","getElementById","host","shadowRoot","_currentCssStyle","_styleSheet","setStyle","cssStyle","beforeAppend","disposableStore","media","globalStylesheetClones","cloneDisposable","cssRules","childList","mutationObservers","mutationObserversPerTarget","optionsHash","hash","mutationObserverPerOptions","users","onDidMutate","MutationObserver","resolvedMutationObserverPerOptions","_sharedStyleSheet","HTMLElement","CLICK","AUXCLICK","DBLCLICK","MOUSE_OVER","MOUSE_OUT","MOUSE_ENTER","MOUSE_LEAVE","MOUSE_WHEEL","POINTER_LEAVE","CONTEXT_MENU","WHEEL","KEY_DOWN","KEY_PRESS","KEY_UP","LOAD","UNLOAD","PAGE_SHOW","PAGE_HIDE","PASTE","ABORT","RESIZE","SCROLL","FULLSCREEN_CHANGE","WK_FULLSCREEN_CHANGE","SELECT","CHANGE","SUBMIT","RESET","FOCUS","FOCUS_IN","FOCUS_OUT","BLUR","INPUT","STORAGE","DRAG_START","DRAG_ENTER","DRAG_LEAVE","DRAG_OVER","DROP","DRAG_END","ANIMATION_START","ANIMATION_END","ANIMATION_ITERATION","stop","cancelBubble","hasFocusWithin","_onDidFocus","onDidFocus","_onDidBlur","onDidBlur","loosingFocus","_refreshStateHandler","refreshState","SELECTOR_REGEX","_$","namespace","description","HTML","SVG","_subscriptions","_keyStatus","registerListeners","defaultPrevented","KeyCode","Alt","lastKeyPressed","lastKeyReleased","resetKeyStatus","keyStatus","isModifierPressed","doResetKeyStatus","getInstance","callbacks","counter","dragStartTime","onDragStart","onDrag","onDragEnter","onDragOver","onDragLeave","onDragEnd","onDrop","originX","originY","triangles","t","isPointWithinTriangle","FastDomNode","createFastDomNode","_maxWidth","_height","_top","_left","_bottom","_right","_paddingTop","_paddingLeft","_paddingBottom","_paddingRight","_fontFamily","_fontWeight","_fontStyle","_fontFeatureSettings","_fontVariationSettings","_textDecoration","_lineHeight","_letterSpacing","_className","_display","_position","_visibility","_backgroundColor","_layerHint","_contain","_boxShadow","setMaxWidth","maxWidth","numberAsPixels","setWidth","setHeight","setTop","setLeft","setBottom","setRight","setPaddingTop","paddingTop","setPaddingLeft","paddingLeft","setPaddingBottom","paddingBottom","setPaddingRight","paddingRight","setFontFamily","setFontWeight","setFontSize","setFontStyle","setFontFeatureSettings","fontFeatureSettings","setFontVariationSettings","fontVariationSettings","setTextDecoration","setLineHeight","setLetterSpacing","setClassName","toggleClassName","shouldHaveIt","setDisplay","setPosition","visibility","setBackgroundColor","setLayerHinting","layerHint","setBoxShadow","boxShadow","setContain","contain","GlobalPointerMoveMonitor","dom","_hooks","_pointerMoveCallback","_onStopCallback","stopMonitoring","invokeStopCallback","browserEvent","isMonitoring","onStopCallback","startMonitoring","initialElement","pointerId","initialButtons","pointerMoveCallback","eventSource","setPointerCapture","releasePointerCapture","IframeUtils","parentOriginHash","async","parentOrigin","salt","crypto","subtle","strData","arrData","TextEncoder","encode","bytes","hexArray","BigInt","sha256AsBase32","digest","sameOriginWindowChainCache","getParentWindowIfSameOrigin","parentLocation","getSameOriginWindowChain","windowChainCache","WeakRef","iframeElement","frameElement","getPositionOfChildWindowRelativeToAncestorWindow","childWindow","ancestorWindow","windowChain","windowChainEl","windowInChain","deref","boundingRect","printKeyboardEvent","printStandardKeyboardEvent","KeyCodeUtils","keybindings_1","ctrlKeyMod","KeyMod","WinCtrl","CtrlCmd","altKeyMod","shiftKeyMod","Shift","metaKeyMod","source","_standardKeyboardEventBrand","altGraphKey","fromString","PauseBreak","Semicolon","IntlBackslash","Equal","NumpadAdd","NumpadSubtract","Minus","Meta","EVENT_KEY_CODE_MAP","Unknown","extractKeyCode","Ctrl","_asKeybinding","_computeKeybinding","_asKeyCodeChord","_computeKeyCodeChord","toKeyCodeChord","other","KeyCodeChord","StandardWheelEvent","DragMouseEvent","iframe_1","timestamp","leftButton","middleButton","rightButton","pageX","posx","posy","pageY","iframeOffsets","dataTransfer","deltaX","targetNode","srcElement","shouldFactorDPR","chromeVersionMatch","wheelDeltaY","VERTICAL_AXIS","axis","DOM_DELTA_LINE","wheelDeltaX","HORIZONTAL_AXIS","wheelDelta","__decorate","decorators","Reflect","decorate","Gesture","DomUtils","arrays","decorators_1","linkedList_1","Tap","Change","Start","End","Contextmenu","SCROLL_FRICTION","HOLD_DELAY","CLEAR_TAP_COUNT_TIME","dispatched","targets","LinkedList","ignoreTargets","activeTouches","handle","_lastSetTapCountTime","onTouchStart","onTouchEnd","onTouchMove","_store","addTarget","isTouchDevice","markAsSingleton","ignoreTarget","targetTouches","initialTarget","initialTimeStamp","initialPageX","initialPageY","rollingTimestamps","rollingPageX","rollingPageY","evt","newGestureEvent","dispatchEvent","activeTouchCount","changedTouches","holdTime","tail","finalX","finalY","deltaT","dispatchTo","inertia","createEvent","initEvent","tapCount","currentTime","setTapCount","_","t1","vX","dirX","vY","dirY","delta_pos_x","delta_pos_y","stopped","translationX","translationY","memoize","AbstractScrollbar","fastDomNode_1","globalPointerMoveMonitor_1","scrollbarArrow_1","scrollbarVisibilityController_1","widget_1","Widget","_lazyRender","lazyRender","_host","_scrollable","_scrollByPage","scrollByPage","_scrollbarState","scrollbarState","_visibilityController","ScrollbarVisibilityController","extraScrollbarClassName","setIsNeeded","isNeeded","_pointerMoveMonitor","_shouldRender","setDomNode","_domNodePointerDown","_createArrow","arrow","ScrollbarArrow","bgDomNode","_createSlider","slider","_sliderPointerDown","onclick","_onElementSize","visibleSize","setVisibleSize","render","_onElementScrollSize","elementScrollSize","setScrollSize","_onElementScrollPosition","elementScrollPosition","beginReveal","setShouldBeVisible","beginHide","_renderDomNode","getRectangleLargeSize","getRectangleSmallSize","_updateSlider","getSliderSize","getArrowSize","getSliderPosition","_onPointerDown","delegatePointerDown","domTop","getClientRects","sliderStart","sliderStop","pointerPos","_sliderPointerPosition","offsetX","offsetY","domNodePosition","_pointerDownRelativePosition","_setDesiredScrollPositionNow","getDesiredScrollPositionFromOffsetPaged","getDesiredScrollPositionFromOffset","Element","initialPointerPosition","initialPointerOrthogonalPosition","_sliderOrthogonalPointerPosition","initialScrollbarState","pointerMoveData","pointerOrthogonalPosition","pointerOrthogonalDelta","pointerDelta","getDesiredScrollPositionFromDelta","_desiredScrollPosition","desiredScrollPosition","writeScrollPosition","setScrollPositionNow","updateScrollbarSize","scrollbarSize","_updateScrollbarSize","setScrollbarSize","HorizontalScrollbar","abstractScrollbar_1","scrollbarState_1","scrollable_1","scrollDimensions","getScrollDimensions","scrollPosition","getCurrentScrollPosition","ScrollbarState","horizontalHasArrows","arrowSize","ScrollbarVisibility","Hidden","horizontalScrollbarSize","horizontalSliderSize","sliderSize","sliderPosition","largeSize","smallSize","onDidScroll","setOppositeScrollbarSize","DomScrollableElement","ScrollableElement","AbstractScrollableElement","MouseWheelClassifier","browser_1","horizontalScrollbar_1","verticalScrollbar_1","MouseWheelClassifierItem","score","_capacity","_memory","_front","_rear","isPhysicalMouseWheel","remainingInfluence","influence","acceptStandardWheelEvent","pageZoomFactor","accept","previousItem","_computeScore","_isAlmostInt","absDeltaX","absDeltaY","absPreviousDeltaX","absPreviousDeltaY","minDeltaX","minDeltaY","maxDeltaX","maxDeltaY","_onWillScroll","onWillScroll","flipAxes","consumeMouseWheelIfScrollbarIsNeeded","alwaysConsumeMouseWheel","scrollYToX","scrollPredominantAxis","listenOnDomNode","Auto","verticalHasArrows","verticalSliderSize","resolveOptions","_onDidScroll","scrollbarHost","onMouseWheel","mouseWheelEvent","_onMouseWheel","_onDragStart","_onDragEnd","_verticalScrollbar","VerticalScrollbar","_horizontalScrollbar","_domNode","_leftShadowDomNode","_topShadowDomNode","_topLeftShadowDomNode","_listenOnDomNode","_mouseWheelToDispose","_setListeningToMouseWheel","onmouseover","_onMouseOver","onmouseleave","_onMouseLeave","_hideTimeout","_isDragging","_mouseIsOver","_revealOnScroll","getOverviewRulerLayoutInfo","delegateVerticalScrollbarPointerDown","updateClassName","newClassName","newOptions","_render","setRevealOnScroll","delegateScrollFromMouseWheelEvent","shouldListen","classifier","didScroll","shiftConvert","futureScrollPosition","getFutureScrollPosition","deltaScrollTop","desiredScrollTop","deltaScrollLeft","desiredScrollLeft","validateScrollPosition","setScrollPositionSmooth","consumeMouseWheel","_reveal","renderNow","scrollState","enableTop","enableLeft","leftClassName","topClassName","topLeftClassName","_hide","_scheduleHide","scrollTopChanged","scrollLeftChanged","scanDomNode","ARROW_IMG_SIZE","_onActivate","onActivate","bgWidth","bgHeight","_arrowPointerDown","_pointerdownRepeatTimer","_pointerdownScheduleRepeatTimer","oppositeScrollbarSize","scrollSize","_scrollbarSize","_oppositeScrollbarSize","_arrowSize","_visibleSize","_scrollSize","_scrollPosition","_computedAvailableSize","_computedIsNeeded","_computedSliderSize","_computedSliderRatio","_computedSliderPosition","_refreshComputedValues","iVisibleSize","iScrollSize","iScrollPosition","_computeValues","computedAvailableSize","computedRepresentableSize","computedIsNeeded","computedSliderSize","computedSliderRatio","computedSliderPosition","desiredSliderPosition","correctedOffset","visibleClassName","invisibleClassName","_visibleClassName","_invisibleClassName","_isVisible","_isNeeded","_rawShouldBeVisible","_shouldBeVisible","_revealTimer","_updateShouldBeVisible","rawShouldBeVisible","_applyVisibilitySetting","Visible","shouldBeVisible","ensureVisibility","withFadeAway","touch_1","onmousedown","onkeydown","onkeyup","oninput","onblur","onfocus","onchange","ignoreGesture","fallbackWindowId","Permutation","CallbackIterable","ArrayQueue","booleanComparator","numberComparator","CompareResult","array","tail2","arr","one","itemEquals","removeFastWithoutKeepingOrder","binarySearch","comparator","binarySearch2","quickSelect","nth","compare","TypeError","pivotValue","random","higher","pivots","groupBy","currentGroup","groupAdjacentBy","shouldBeGrouped","forEachAdjacent","forEachWithNeighbors","sortedDiff","before","splices","removed","added","topStep","topAsync","batch","token","reject","isCancellationRequested","CancellationError","coalesce","coalesceInPlace","isFalsyOrEmpty","isNonEmptyArray","distinct","keyFn","seen","uniqueFilter","firstOrDefault","notFoundValue","lastOrDefault","commonPrefixLength","arg","indexer","mapper","arrayInsert","insertIndex","insertArr","concat","shuffle","_seed","rand","seed","sin","pushToStart","pushToEnd","pushMany","mapArrayOrNot","asArray","getRandomElement","insertInto","newItems","getActualStartIndex","compareBy","tieBreakComparators","comparators","item1","item2","isNeitherLessOrGreaterThan","neitherLessOrGreaterThan","reverseOrder","arraysFind_1","compareToKey","high","comp","pushSplice","latest","beforeIdx","afterIdx","beforeElement","afterElement","findFirstIdxMonotonousOrArrLen","startIdx","originalLength","newItemsLength","isLessThan","isLessThanOrEqual","isGreaterThan","greaterThan","lessThan","firstIdx","lastIdx","takeWhile","predicate","takeFromEndWhile","endIdx","peek","peekLast","dequeue","removeLast","takeCount","empty","_callback","iterate","mapFn","some","findFirst","findLast","findLastMaxBy","_indexMap","createSortPermutation","compareFn","sortIndices","index1","index2","inverse","inverseIndexMap","findLastIdx","fromIndex","findLastIdxMonotonous","endIdxEx","MonotonousArray","findLastMonotonous","findFirstMonotonous","findFirstIdxMonotonous","findFirstMax","findLastMax","findFirstMin","findMaxIdx","maxIdx","mapFindFirst","mapped","assertInvariants","_findLastMonotonousLastIdx","_prevFindLastPredicate","AsyncIterableSource","CancelableAsyncIterableObject","AsyncIterableObject","LazyStatefulPromise","StatefulPromise","Promises","DeferredPromise","IntervalCounter","TaskSequentializer","GlobalIdleValue","runWhenGlobalIdle","ThrottledWorker","RunOnceWorker","ProcessTimeRunOnceScheduler","RunOnceScheduler","LimitedQueue","Queue","Limiter","AutoOpenBarrier","Barrier","ThrottledDelayer","Delayer","SequencerByKey","Sequencer","Throttler","isThenable","createCancelablePromise","raceCancellation","promise","defaultValue","ref","onCancellationRequested","finally","raceCancellationError","raceCancellablePromises","cancellablePromises","resolvedPromiseIndex","promises","cancellablePromise","raceTimeout","onTimeout","promiseResolve","asPromise","promiseWithResolvers","disposableTimeout","deleteAndLeak","promiseFactories","results","thenHandler","shouldStop","loop","firstParallel","promiseList","todo","finish","retry","delay","retries","lastError","createCancelableAsyncIterable","cancellation_1","CancellationTokenSource","innerIterable","emitter","subscription","emitOne","platform_1","symbols_1","lazy_1","thenable","onfinally","activePromise","queuedPromise","queuedPromiseFactory","queue","promiseFactory","onComplete","promiseTask","promiseMap","newPromise","defaultDelay","deferred","completionPromise","doResolve","doReject","trigger","cancelTimeout","MicrotaskDelay","scheduled","isTriggered","microtaskDeferred","timeoutDeferred","delayer","throttler","_isOpen","_promise","_completePromise","isOpen","wait","millis","autoOpenTimeMs","maxDegreeOfParalellism","_size","_isDisposed","outstandingPromises","runningPromises","_onDrained","whenIdle","toPromise","onDrained","consume","iLimitedTask","consumed","sequentializer","tasks","isRunning","run","_token","BugIndicatingError","context","timeoutToken","timeoutHandler","isScheduled","schedule","doRun","intervalToken","intervalHandler","onInterval","units","work","unit","pendingWork","disposed","pending","maxBufferedWork","maxWorkChunkSize","doWork","throttleDelay","_targetWindow","setTimeout0","didTimeout","_didRun","_executor","_value","_error","_handle","isInitialized","taskId","_running","running","cancelRunning","onCancel","doneRunning","runQueued","_queued","queued","promiseReject","hasQueued","DeferredOutcome","AsyncIterableSourceState","nowFn","lastIncrementTime","increment","isRejected","outcome","Rejected","isResolved","Resolved","isSettled","completeCallback","errorCallback","complete","settled","firstError","all","withAsyncBody","bodyFn","_isResolved","requireValue","_compute","Lazy","getPromise","currentValue","rawValue","writer","emitMany","fromPromise","fromPromises","merge","iterables","iterable","EMPTY","onReturn","Initial","_results","_onReturn","_onStateChanged","Symbol","asyncIterator","DoneError","done","DoneOK","return","filterFn","_source","earlyError","earlyItems","_deferred","_asyncIterable","_errorFn","_emitFn","asyncIterable","CancellationToken","cancelOnDispose","shortcutEvent","isCancellationToken","thing","Cancelled","MutableToken","_isCancelled","_emitter","_parentListener","CharCode","SetWithKey","groupFn","diffSets","diffMaps","intersection","setA","setB","elem","toStringTag","toKey","_map","callbackfn","thisArg","iterator","fnKey","memoizeKey","debounce","reducer","initialValueProvider","timerKey","resultKey","throttle","lastRunKey","pendingKey","nextTime","ErrorNoTelemetry","ExpectedError","NotSupportedError","NotImplementedError","ReadonlyError","errorHandler","ErrorHandler","setUnexpectedErrorHandler","newUnexpectedErrorHandler","isSigPipeError","cast","syscall","isCancellationError","onUnexpectedExternalError","transformErrorForSerialization","$isError","stack","stacktrace","noTelemetry","isErrorNoTelemetry","transformErrorFromSerialization","canceled","canceledName","illegalArgument","illegalState","getErrorMessage","listeners","unexpectedErrorHandler","_removeListener","emit","getUnexpectedErrorHandler","isExpected","msg","fromError","setPrototypeOf","ValueWithChangeEvent","Relay","EventBufferer","DynamicListEventMultiplexer","EventMultiplexer","MicrotaskEmitter","DebounceEmitter","PauseableEmitter","AsyncEmitter","createEventDeliveryQueue","ListenerRefusalError","ListenerLeakError","EventProfiling","setGlobalLeakWarningThreshold","_globalLeakWarningThreshold","functional_1","stopwatch_1","once","thisArgs","didFire","snapshot","onWillAddFirstListener","onDidRemoveLastListener","leading","flushOnListenerRemove","leakWarningThreshold","output","doFire","numDebouncedCalls","_output","onWillRemoveListener","defer","each","signal","combinedDisposable","initial","accumulate","latch","firstCall","shouldEmit","isT","flushAfterTimeout","onDidAddFirstListener","chain","sythensize","ChainableSynthesis","evaluate","HaltChainable","steps","fromNodeEventEmitter","eventName","on","fromDOMEventEmitter","EmitterObserver","_observable","_counter","_hasChanged","addObserver","removeObserver","beginUpdate","handlePossibleChange","handleChange","_change","endUpdate","reportChanges","fromObservable","obs","fromObservableLight","observable","didChange","_idPool","listenerCount","invocationCount","elapsedOverall","durations","_stopWatch","StopWatch","LeakageMonitor","_warnCountdown","_stacks","check","topStack","topCount","getMostFrequentStack","Stacktrace","UniqueContainer","_leakageMon","onListenerError","_perfMon","_profName","_deliveryQueue","deliveryQueue","_disposed","_listeners","_event","tuple","contained","removeMonitor","EventDeliveryQueuePrivate","adjustDeliveryQueue","_deliver","_deliverQueue","dq","hasListeners","fireAsync","promiseJoin","_asyncDeliveryQueue","forEachListener","thenables","waitUntil","isFrozen","allSettled","status","reason","isPaused","_eventQueue","_mergeFn","pause","resume","_delay","_queuedEvents","onFirstListenerAdd","onLastListenerRemove","createSingleCallFunction","onAddItem","onRemoveItem","getEvent","multiplexer","itemListeners","DisposableMap","addItem","deleteAndDispose","wrapEvent","reduceData","reducedResult","bufferEvents","listening","inputEvent","inputEventListener","ConstValueWithChangeEvent","_onDidChange","onDidChange","fnDidRunCallback","_this","didCall","StringSHA1","Hasher","doHash","numberHash","stringHash","toHexString","strings","hashVal","initialHashVal","objectHash","booleanHash","SHA1Constant","leftRotate","totalBits","dest","bufferOrValue","bitsize","ArrayBuffer","leftPad","_bigBlock32","DataView","_h0","_h1","_h2","_h3","_h4","_buff","BLOCK_SIZE","_buffDV","_buffLen","_totalLen","_leftoverHighSurrogate","_finished","strLen","buff","buffLen","leftoverHighSurrogate","isHighSurrogate","nextCharCode","isLowSurrogate","computeCodePoint","UNICODE_REPLACEMENT","_push","_step","_wrapUp","ml","setUint32","bigBlock32","getUint32","Iterable","_empty","single","wrap","iterableOrElement","flatMap","initialValue","atMost","POSITIVE_INFINITY","asyncToArray","ScanCode","ScanCodeUtils","NATIVE_WINDOWS_KEY_CODE_TO_KEY_CODE","KeyChord","firstPart","secondPart","KeyCodeStrMap","_keyCodeToStr","_strToKeyCode","keyCodeToStr","strToKeyCode","uiMap","userSettingsUSMap","userSettingsGeneralMap","scanCodeIntToStr","scanCodeStrToInt","scanCodeLowerCaseStrToInt","lowerCaseToEnum","scanCode","toEnum","toUserSettingsUS","toUserSettingsGeneral","fromUserSettings","toElectronAccelerator","Numpad0","NumpadDivide","UpArrow","DownArrow","LeftArrow","RightArrow","ResolvedKeybinding","ResolvedChord","Keybinding","ScanCodeChord","decodeKeybinding","keybinding","OS","firstChord","secondChord","createSimpleKeybinding","chords","BinaryKeybindingsMask","ctrlCmd","winCtrl","OperatingSystem","Macintosh","getHashCode","isModifierKey","toKeybinding","isDuplicateModifierCase","ControlLeft","ControlRight","ShiftLeft","ShiftRight","AltLeft","AltRight","MetaLeft","MetaRight","keyLabel","keyAriaLabel","hasValue","ImmortalReference","AsyncReferenceCollection","ReferenceCollection","SafeDisposable","RefCountedDisposable","MandatoryMutableDisposable","DisposableTracker","setDisposableTracker","tracker","disposableTracker","trackDisposable","markAsDisposed","singleton","isDisposable","disposeIfDisposable","setParent","setParentOfDisposables","disposeOnReturn","arrays_1","collections_1","map_1","iterator_1","livingDisposables","getDisposableData","isSingleton","getRootParent","cacheValue","getTrackedDisposables","rootParentCache","computeLeakingDisposables","maxReported","preComputedLeaks","uncoveredLeakingObjs","leakingObjects","leakingObjsSet","getStackTracePath","leaking","linesToRemove","regexp","removePrefix","stackTraceStarts","SetMap","stackTracePath","stackTraceFormattedLines","prevStarts","continuations","cont","leaks","details","setParentOfDisposable","errors","AggregateError","DISABLE_DISPOSED_WARNING","_toDispose","clearAndLeak","_disposable","acquire","release","unset","isset","references","reference","object","createReferencedObject","destroyReferencedObject","referenceCollection","clearAndDisposeAll","skipDisposeOnOverwrite","Undefined","prev","_first","_last","_insert","atTheEnd","newNode","oldLast","oldFirst","didRemove","_remove","Touch","BidirectionalMap","CounterSet","getOrSet","mapToString","setToString","mapsStrictEqualIgnoreOrder","_m1","_m2","getKey","SlidingWindowAverage","MovingAverage","Counter","clamp","rot","modulo","ax","ay","bx","by","cx","cy","v0x","v0y","v1x","v1y","v2x","v2y","dot00","dot01","dot02","dot11","dot12","invDenom","u","_next","getNext","_n","_val","_values","_index","_sum","isEdge","setTimeout0IsFaster","translationsConfigFile","platformLocale","locale","Language","language","isCI","isMobile","webWorkerOrigin","isWebWorker","isWeb","isLinuxSnap","Platform","LANGUAGE_DEFAULT","PlatformToString","Web","Mac","Linux","Windows","isLittleEndian","_isLittleEndianComputed","_isLittleEndian","isBigSurOrNewer","osVersion","_locale","_translationsConfigFile","_userAgent","_isWindows","_isMacintosh","_isLinux","_isLinuxSnap","_isNative","_isWeb","_isElectron","_isIOS","_isCI","_isMobile","_language","_platformLocale","$globalThis","nodeProcess","vscode","isElectronProcess","electron","isElectronRenderer","env","rawNlsConfig","nlsConfig","userLocale","osLocale","resolvedLanguage","languagePack","_VSCODE_NLS_LANGUAGE","_platform","importScripts","isDefaultVariant","isDefault","postMessage","vscodeScheduleAsyncWork","lastId","myId","SmoothScrollingOperation","SmoothScrollingUpdate","ScrollState","_forceIntegerValues","_scrollStateBrand","rawScrollLeft","rawScrollTop","withScrollDimensions","useRawScrollPositions","withScrollPosition","createScrollEvent","previous","inSmoothScrolling","widthChanged","scrollWidthChanged","heightChanged","scrollHeightChanged","oldScrollWidth","oldScrollLeft","oldHeight","oldScrollHeight","oldScrollTop","_scrollableBrand","_smoothScrollDuration","_scheduleAtNextAnimationFrame","_smoothScrolling","newState","_setState","acceptScrollDimensions","validTarget","newSmoothScrolling","combine","animationFrameDisposable","_performSmoothScrolling","hasPendingScrollAnimation","tick","isDone","oldState","createEaseOutCubic","completion","_initAnimations","_initAnimation","viewportSize","stop1","stop2","cut","_tick","newScrollLeft","newScrollTop","hasPerformanceNow","highResolution","_now","_startTime","_stopTime","noBreakWhitespace","CodePointIterator","isFalsyOrWhitespace","format","_formatRegexp","group","format2","template","_format2Regexp","htmlAttributeEncodeValue","escape","html","escapeRegExpCharacters","substr","truncate","suffix","truncateMiddle","prefixLength","suffixLength","haystack","needle","rtrim","ltrim","convertSimple2RegExpPattern","pattern","stripWildcards","createRegExp","searchString","isRegex","wholeWord","global","matchCase","multiline","unicode","regExpLeadsToEndlessLoop","lastIndex","splitLines","splitLinesIncludeSeparators","linesWithSeparators","splitLinesAndSeparators","firstNonWhitespaceIndex","chCode","charCode_1","Space","Tab","getLeadingWhitespace","lastNonWhitespaceIndex","replaceAsync","search","replacer","parts","matchAll","compareSubstring","compareIgnoreCase","compareSubstringIgnoreCase","isAsciiDigit","Digit0","Digit9","isLowerAsciiLetter","isUpperAsciiLetter","A","Z","equalsIgnoreCase","startsWithIgnoreCase","candidateLength","commonSuffixLength","aLastIndex","bLastIndex","getNextCodePoint","uint_1","needleLen","haystackLen","lastIndexOf","aStart","aEnd","bStart","bEnd","codeA","codeB","aLen","bLen","highSurrogate","lowSurrogate","_offset","_str","_len","setOffset","prevCodePoint","prevCharCode","getPrevCodePoint","Constants","UNICODE_SUPPLEMENTARY_PLANE_BEGIN","nextCodePoint","eol","toUint8","MAX_UINT_8","toUint32","MAX_UINT_32","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","__webpack_modules__","CONSTRUCTOR_ONLY_OPTIONS","$value","Terminal","_addonManager","AddonManager","_publicOptions","_checkReadonlyOptions","_checkProposedApi","parser","ParserApi","UnicodeApi","mouseTrackingMode","applicationCursorKeysMode","applicationKeypadMode","originMode","reverseWraparoundMode","sendFocusMode","synchronizedOutputMode","_verifyIntegers","_verifyPositiveIntegers","writeln","addon","Infinity"],"sourceRoot":""} \ No newline at end of file diff --git a/node_modules/@xterm/xterm/lib/xterm.mjs b/node_modules/@xterm/xterm/lib/xterm.mjs new file mode 100644 index 0000000..d540256 --- /dev/null +++ b/node_modules/@xterm/xterm/lib/xterm.mjs @@ -0,0 +1,53 @@ +/** + * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved. + * @license MIT + * + * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License) + * @license MIT + * + * Originally forked from (with the author's permission): + * Fabrice Bellard's javascript vt100 for jslinux: + * http://bellard.org/jslinux/ + * Copyright (c) 2011 Fabrice Bellard + */ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +var zs=Object.defineProperty;var Rl=Object.getOwnPropertyDescriptor;var Ll=(s,t)=>{for(var e in t)zs(s,e,{get:t[e],enumerable:!0})};var M=(s,t,e,i)=>{for(var r=i>1?void 0:i?Rl(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(r=(i?o(t,e,r):o(r))||r);return i&&r&&zs(t,e,r),r},S=(s,t)=>(e,i)=>t(e,i,s);var Gs="Terminal input",mi={get:()=>Gs,set:s=>Gs=s},$s="Too much output to announce, navigate to rows manually to read",_i={get:()=>$s,set:s=>$s=s};function Al(s){return s.replace(/\r?\n/g,"\r")}function kl(s,t){return t?"\x1B[200~"+s+"\x1B[201~":s}function Vs(s,t){s.clipboardData&&s.clipboardData.setData("text/plain",t.selectionText),s.preventDefault()}function qs(s,t,e,i){if(s.stopPropagation(),s.clipboardData){let r=s.clipboardData.getData("text/plain");Cn(r,t,e,i)}}function Cn(s,t,e,i){s=Al(s),s=kl(s,e.decPrivateModes.bracketedPasteMode&&i.rawOptions.ignoreBracketedPasteMode!==!0),e.triggerDataEvent(s,!0),t.value=""}function Mn(s,t,e){let i=e.getBoundingClientRect(),r=s.clientX-i.left-10,n=s.clientY-i.top-10;t.style.width="20px",t.style.height="20px",t.style.left=`${r}px`,t.style.top=`${n}px`,t.style.zIndex="1000",t.focus()}function Pn(s,t,e,i,r){Mn(s,t,e),r&&i.rightClickSelect(s),t.value=i.selectionText,t.select()}function Ce(s){return s>65535?(s-=65536,String.fromCharCode((s>>10)+55296)+String.fromCharCode(s%1024+56320)):String.fromCharCode(s)}function It(s,t=0,e=s.length){let i="";for(let r=t;r65535?(n-=65536,i+=String.fromCharCode((n>>10)+55296)+String.fromCharCode(n%1024+56320)):i+=String.fromCharCode(n)}return i}var er=class{constructor(){this._interim=0}clear(){this._interim=0}decode(t,e){let i=t.length;if(!i)return 0;let r=0,n=0;if(this._interim){let o=t.charCodeAt(n++);56320<=o&&o<=57343?e[r++]=(this._interim-55296)*1024+o-56320+65536:(e[r++]=this._interim,e[r++]=o),this._interim=0}for(let o=n;o=i)return this._interim=l,r;let a=t.charCodeAt(o);56320<=a&&a<=57343?e[r++]=(l-55296)*1024+a-56320+65536:(e[r++]=l,e[r++]=a);continue}l!==65279&&(e[r++]=l)}return r}},tr=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(t,e){let i=t.length;if(!i)return 0;let r=0,n,o,l,a,u=0,h=0;if(this.interim[0]){let _=!1,p=this.interim[0];p&=(p&224)===192?31:(p&240)===224?15:7;let m=0,f;for(;(f=this.interim[++m]&63)&&m<4;)p<<=6,p|=f;let A=(this.interim[0]&224)===192?2:(this.interim[0]&240)===224?3:4,R=A-m;for(;h=i)return 0;if(f=t[h++],(f&192)!==128){h--,_=!0;break}else this.interim[m++]=f,p<<=6,p|=f&63}_||(A===2?p<128?h--:e[r++]=p:A===3?p<2048||p>=55296&&p<=57343||p===65279||(e[r++]=p):p<65536||p>1114111||(e[r++]=p)),this.interim.fill(0)}let c=i-4,d=h;for(;d=i)return this.interim[0]=n,r;if(o=t[d++],(o&192)!==128){d--;continue}if(u=(n&31)<<6|o&63,u<128){d--;continue}e[r++]=u}else if((n&240)===224){if(d>=i)return this.interim[0]=n,r;if(o=t[d++],(o&192)!==128){d--;continue}if(d>=i)return this.interim[0]=n,this.interim[1]=o,r;if(l=t[d++],(l&192)!==128){d--;continue}if(u=(n&15)<<12|(o&63)<<6|l&63,u<2048||u>=55296&&u<=57343||u===65279)continue;e[r++]=u}else if((n&248)===240){if(d>=i)return this.interim[0]=n,r;if(o=t[d++],(o&192)!==128){d--;continue}if(d>=i)return this.interim[0]=n,this.interim[1]=o,r;if(l=t[d++],(l&192)!==128){d--;continue}if(d>=i)return this.interim[0]=n,this.interim[1]=o,this.interim[2]=l,r;if(a=t[d++],(a&192)!==128){d--;continue}if(u=(n&7)<<18|(o&63)<<12|(l&63)<<6|a&63,u<65536||u>1114111)continue;e[r++]=u}}return r}};var ir="";var we=" ";var De=class s{constructor(){this.fg=0;this.bg=0;this.extended=new rt}static toColorRGB(t){return[t>>>16&255,t>>>8&255,t&255]}static fromColorRGB(t){return(t[0]&255)<<16|(t[1]&255)<<8|t[2]&255}clone(){let t=new s;return t.fg=this.fg,t.bg=this.bg,t.extended=this.extended.clone(),t}isInverse(){return this.fg&67108864}isBold(){return this.fg&134217728}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:this.fg&268435456}isBlink(){return this.fg&536870912}isInvisible(){return this.fg&1073741824}isItalic(){return this.bg&67108864}isDim(){return this.bg&134217728}isStrikethrough(){return this.fg&2147483648}isProtected(){return this.bg&536870912}isOverline(){return this.bg&1073741824}getFgColorMode(){return this.fg&50331648}getBgColorMode(){return this.bg&50331648}isFgRGB(){return(this.fg&50331648)===50331648}isBgRGB(){return(this.bg&50331648)===50331648}isFgPalette(){return(this.fg&50331648)===16777216||(this.fg&50331648)===33554432}isBgPalette(){return(this.bg&50331648)===16777216||(this.bg&50331648)===33554432}isFgDefault(){return(this.fg&50331648)===0}isBgDefault(){return(this.bg&50331648)===0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(this.fg&50331648){case 16777216:case 33554432:return this.fg&255;case 50331648:return this.fg&16777215;default:return-1}}getBgColor(){switch(this.bg&50331648){case 16777216:case 33554432:return this.bg&255;case 50331648:return this.bg&16777215;default:return-1}}hasExtendedAttrs(){return this.bg&268435456}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(this.bg&268435456&&~this.extended.underlineColor)switch(this.extended.underlineColor&50331648){case 16777216:case 33554432:return this.extended.underlineColor&255;case 50331648:return this.extended.underlineColor&16777215;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return this.bg&268435456&&~this.extended.underlineColor?this.extended.underlineColor&50331648:this.getFgColorMode()}isUnderlineColorRGB(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===50331648:this.isFgRGB()}isUnderlineColorPalette(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===16777216||(this.extended.underlineColor&50331648)===33554432:this.isFgPalette()}isUnderlineColorDefault(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===0:this.isFgDefault()}getUnderlineStyle(){return this.fg&268435456?this.bg&268435456?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},rt=class s{constructor(t=0,e=0){this._ext=0;this._urlId=0;this._ext=t,this._urlId=e}get ext(){return this._urlId?this._ext&-469762049|this.underlineStyle<<26:this._ext}set ext(t){this._ext=t}get underlineStyle(){return this._urlId?5:(this._ext&469762048)>>26}set underlineStyle(t){this._ext&=-469762049,this._ext|=t<<26&469762048}get underlineColor(){return this._ext&67108863}set underlineColor(t){this._ext&=-67108864,this._ext|=t&67108863}get urlId(){return this._urlId}set urlId(t){this._urlId=t}get underlineVariantOffset(){let t=(this._ext&3758096384)>>29;return t<0?t^4294967288:t}set underlineVariantOffset(t){this._ext&=536870911,this._ext|=t<<29&3758096384}clone(){return new s(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}};var q=class s extends De{constructor(){super(...arguments);this.content=0;this.fg=0;this.bg=0;this.extended=new rt;this.combinedData=""}static fromCharData(e){let i=new s;return i.setFromCharData(e),i}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?Ce(this.content&2097151):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):this.content&2097151}setFromCharData(e){this.fg=e[0],this.bg=0;let i=!1;if(e[1].length>2)i=!0;else if(e[1].length===2){let r=e[1].charCodeAt(0);if(55296<=r&&r<=56319){let n=e[1].charCodeAt(1);56320<=n&&n<=57343?this.content=(r-55296)*1024+n-56320+65536|e[2]<<22:i=!0}else i=!0}else this.content=e[1].charCodeAt(0)|e[2]<<22;i&&(this.combinedData=e[1],this.content=2097152|e[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}};var js="di$target",Hn="di$dependencies",Fn=new Map;function Xs(s){return s[Hn]||[]}function ie(s){if(Fn.has(s))return Fn.get(s);let t=function(e,i,r){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");Pl(t,e,r)};return t._id=s,Fn.set(s,t),t}function Pl(s,t,e){t[js]===t?t[Hn].push({id:s,index:e}):(t[Hn]=[{id:s,index:e}],t[js]=t)}var F=ie("BufferService"),rr=ie("CoreMouseService"),ge=ie("CoreService"),Zs=ie("CharsetService"),xt=ie("InstantiationService");var nr=ie("LogService"),H=ie("OptionsService"),sr=ie("OscLinkService"),Js=ie("UnicodeService"),Be=ie("DecorationService");var wt=class{constructor(t,e,i){this._bufferService=t;this._optionsService=e;this._oscLinkService=i}provideLinks(t,e){let i=this._bufferService.buffer.lines.get(t-1);if(!i){e(void 0);return}let r=[],n=this._optionsService.rawOptions.linkHandler,o=new q,l=i.getTrimmedLength(),a=-1,u=-1,h=!1;for(let c=0;cn?n.activate(m,f,_):Ol(m,f),hover:(m,f)=>n?.hover?.(m,f,_),leave:(m,f)=>n?.leave?.(m,f,_)})}h=!1,o.hasExtendedAttrs()&&o.extended.urlId?(u=c,a=o.extended.urlId):(u=-1,a=-1)}}e(r)}};wt=M([S(0,F),S(1,H),S(2,sr)],wt);function Ol(s,t){if(confirm(`Do you want to navigate to ${t}? + +WARNING: This link could potentially be dangerous`)){let i=window.open();if(i){try{i.opener=null}catch{}i.location.href=t}else console.warn("Opening link blocked as opener could not be cleared")}}var nt=ie("CharSizeService"),ae=ie("CoreBrowserService"),Dt=ie("MouseService"),ce=ie("RenderService"),Qs=ie("SelectionService"),or=ie("CharacterJoinerService"),Re=ie("ThemeService"),lr=ie("LinkProviderService");var Wn=class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(t){setTimeout(()=>{throw t.stack?ar.isErrorNoTelemetry(t)?new ar(t.message+` + +`+t.stack):new Error(t.message+` + +`+t.stack):t},0)}}addListener(t){return this.listeners.push(t),()=>{this._removeListener(t)}}emit(t){this.listeners.forEach(e=>{e(t)})}_removeListener(t){this.listeners.splice(this.listeners.indexOf(t),1)}setUnexpectedErrorHandler(t){this.unexpectedErrorHandler=t}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(t){this.unexpectedErrorHandler(t),this.emit(t)}onUnexpectedExternalError(t){this.unexpectedErrorHandler(t)}},Bl=new Wn;function Lt(s){Nl(s)||Bl.onUnexpectedError(s)}var Un="Canceled";function Nl(s){return s instanceof bi?!0:s instanceof Error&&s.name===Un&&s.message===Un}var bi=class extends Error{constructor(){super(Un),this.name=this.message}};function eo(s){return s?new Error(`Illegal argument: ${s}`):new Error("Illegal argument")}var ar=class s extends Error{constructor(t){super(t),this.name="CodeExpectedError"}static fromError(t){if(t instanceof s)return t;let e=new s;return e.message=t.message,e.stack=t.stack,e}static isErrorNoTelemetry(t){return t.name==="CodeExpectedError"}},Rt=class s extends Error{constructor(t){super(t||"An unexpected bug occurred."),Object.setPrototypeOf(this,s.prototype)}};function Fl(s,t,e=0,i=s.length){let r=e,n=i;for(;r{function s(a){return a<0}l.isLessThan=s;function t(a){return a<=0}l.isLessThanOrEqual=t;function e(a){return a>0}l.isGreaterThan=e;function i(a){return a===0}l.isNeitherLessOrGreaterThan=i,l.greaterThan=1,l.lessThan=-1,l.neitherLessOrGreaterThan=0})(ro||={});function no(s,t){return(e,i)=>t(s(e),s(i))}var so=(s,t)=>s-t;var At=class At{constructor(t){this.iterate=t}forEach(t){this.iterate(e=>(t(e),!0))}toArray(){let t=[];return this.iterate(e=>(t.push(e),!0)),t}filter(t){return new At(e=>this.iterate(i=>t(i)?e(i):!0))}map(t){return new At(e=>this.iterate(i=>e(t(i))))}some(t){let e=!1;return this.iterate(i=>(e=t(i),!e)),e}findFirst(t){let e;return this.iterate(i=>t(i)?(e=i,!1):!0),e}findLast(t){let e;return this.iterate(i=>(t(i)&&(e=i),!0)),e}findLastMaxBy(t){let e,i=!0;return this.iterate(r=>((i||ro.isGreaterThan(t(r,e)))&&(i=!1,e=r),!0)),e}};At.empty=new At(t=>{});var io=At;function co(s,t){let e=Object.create(null);for(let i of s){let r=t(i),n=e[r];n||(n=e[r]=[]),n.push(i)}return e}var lo,ao,oo=class{constructor(t,e){this.toKey=e;this._map=new Map;this[lo]="SetWithKey";for(let i of t)this.add(i)}get size(){return this._map.size}add(t){let e=this.toKey(t);return this._map.set(e,t),this}delete(t){return this._map.delete(this.toKey(t))}has(t){return this._map.has(this.toKey(t))}*entries(){for(let t of this._map.values())yield[t,t]}keys(){return this.values()}*values(){for(let t of this._map.values())yield t}clear(){this._map.clear()}forEach(t,e){this._map.forEach(i=>t.call(e,i,i,this))}[(ao=Symbol.iterator,lo=Symbol.toStringTag,ao)](){return this.values()}};var ur=class{constructor(){this.map=new Map}add(t,e){let i=this.map.get(t);i||(i=new Set,this.map.set(t,i)),i.add(e)}delete(t,e){let i=this.map.get(t);i&&(i.delete(e),i.size===0&&this.map.delete(t))}forEach(t,e){let i=this.map.get(t);i&&i.forEach(e)}get(t){let e=this.map.get(t);return e||new Set}};function Kn(s,t){let e=this,i=!1,r;return function(){if(i)return r;if(i=!0,t)try{r=s.apply(e,arguments)}finally{t()}else r=s.apply(e,arguments);return r}}var zn;(O=>{function s(I){return I&&typeof I=="object"&&typeof I[Symbol.iterator]=="function"}O.is=s;let t=Object.freeze([]);function e(){return t}O.empty=e;function*i(I){yield I}O.single=i;function r(I){return s(I)?I:i(I)}O.wrap=r;function n(I){return I||t}O.from=n;function*o(I){for(let k=I.length-1;k>=0;k--)yield I[k]}O.reverse=o;function l(I){return!I||I[Symbol.iterator]().next().done===!0}O.isEmpty=l;function a(I){return I[Symbol.iterator]().next().value}O.first=a;function u(I,k){let P=0;for(let oe of I)if(k(oe,P++))return!0;return!1}O.some=u;function h(I,k){for(let P of I)if(k(P))return P}O.find=h;function*c(I,k){for(let P of I)k(P)&&(yield P)}O.filter=c;function*d(I,k){let P=0;for(let oe of I)yield k(oe,P++)}O.map=d;function*_(I,k){let P=0;for(let oe of I)yield*k(oe,P++)}O.flatMap=_;function*p(...I){for(let k of I)yield*k}O.concat=p;function m(I,k,P){let oe=P;for(let Me of I)oe=k(oe,Me);return oe}O.reduce=m;function*f(I,k,P=I.length){for(k<0&&(k+=I.length),P<0?P+=I.length:P>I.length&&(P=I.length);ki.source!==null&&!this.getRootParent(i,t).isSingleton).flatMap(([i])=>i)}computeLeakingDisposables(t=10,e){let i;if(e)i=e;else{let a=new Map,u=[...this.livingDisposables.values()].filter(c=>c.source!==null&&!this.getRootParent(c,a).isSingleton);if(u.length===0)return;let h=new Set(u.map(c=>c.value));if(i=u.filter(c=>!(c.parent&&h.has(c.parent))),i.length===0)throw new Error("There are cyclic diposable chains!")}if(!i)return;function r(a){function u(c,d){for(;c.length>0&&d.some(_=>typeof _=="string"?_===c[0]:c[0].match(_));)c.shift()}let h=a.source.split(` +`).map(c=>c.trim().replace("at ","")).filter(c=>c!=="");return u(h,["Error",/^trackDisposable \(.*\)$/,/^DisposableTracker.trackDisposable \(.*\)$/]),h.reverse()}let n=new ur;for(let a of i){let u=r(a);for(let h=0;h<=u.length;h++)n.add(u.slice(0,h).join(` +`),a)}i.sort(no(a=>a.idx,so));let o="",l=0;for(let a of i.slice(0,t)){l++;let u=r(a),h=[];for(let c=0;cr(f)[c]),f=>f);delete m[u[c]];for(let[f,A]of Object.entries(m))h.unshift(` - stacktraces of ${A.length} other leaks continue with ${f}`);h.unshift(d)}o+=` + + +==================== Leaking disposable ${l}/${i.length}: ${a.value.constructor.name} ==================== +${h.join(` +`)} +============================================================ + +`}return i.length>t&&(o+=` + + +... and ${i.length-t} more leaking disposables + +`),{leaks:i,details:o}}};hr.idx=0;var uo=hr;function Ul(s){dt=s}if(Wl){let s="__is_disposable_tracked__";Ul(new class{trackDisposable(t){let e=new Error("Potentially leaked disposable").stack;setTimeout(()=>{t[s]||console.log(e)},3e3)}setParent(t,e){if(t&&t!==D.None)try{t[s]=!0}catch{}}markAsDisposed(t){if(t&&t!==D.None)try{t[s]=!0}catch{}}markAsSingleton(t){}})}function fr(s){return dt?.trackDisposable(s),s}function pr(s){dt?.markAsDisposed(s)}function vi(s,t){dt?.setParent(s,t)}function Kl(s,t){if(dt)for(let e of s)dt.setParent(e,t)}function Gn(s){return dt?.markAsSingleton(s),s}function Ne(s){if(zn.is(s)){let t=[];for(let e of s)if(e)try{e.dispose()}catch(i){t.push(i)}if(t.length===1)throw t[0];if(t.length>1)throw new AggregateError(t,"Encountered errors while disposing of store");return Array.isArray(s)?[]:s}else if(s)return s.dispose(),s}function ho(...s){let t=C(()=>Ne(s));return Kl(s,t),t}function C(s){let t=fr({dispose:Kn(()=>{pr(t),s()})});return t}var dr=class dr{constructor(){this._toDispose=new Set;this._isDisposed=!1;fr(this)}dispose(){this._isDisposed||(pr(this),this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{Ne(this._toDispose)}finally{this._toDispose.clear()}}add(t){if(!t)return t;if(t===this)throw new Error("Cannot register a disposable on itself!");return vi(t,this),this._isDisposed?dr.DISABLE_DISPOSED_WARNING||console.warn(new Error("Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!").stack):this._toDispose.add(t),t}delete(t){if(t){if(t===this)throw new Error("Cannot dispose a disposable on itself!");this._toDispose.delete(t),t.dispose()}}deleteAndLeak(t){t&&this._toDispose.has(t)&&(this._toDispose.delete(t),vi(t,null))}};dr.DISABLE_DISPOSED_WARNING=!1;var Ee=dr,D=class{constructor(){this._store=new Ee;fr(this),vi(this._store,this)}dispose(){pr(this),this._store.dispose()}_register(t){if(t===this)throw new Error("Cannot register a disposable on itself!");return this._store.add(t)}};D.None=Object.freeze({dispose(){}});var ye=class{constructor(){this._isDisposed=!1;fr(this)}get value(){return this._isDisposed?void 0:this._value}set value(t){this._isDisposed||t===this._value||(this._value?.dispose(),t&&vi(t,this),this._value=t)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,pr(this),this._value?.dispose(),this._value=void 0}clearAndLeak(){let t=this._value;return this._value=void 0,t&&vi(t,null),t}};var fe=typeof window=="object"?window:globalThis;var kt=class kt{constructor(t){this.element=t,this.next=kt.Undefined,this.prev=kt.Undefined}};kt.Undefined=new kt(void 0);var G=kt,Ct=class{constructor(){this._first=G.Undefined;this._last=G.Undefined;this._size=0}get size(){return this._size}isEmpty(){return this._first===G.Undefined}clear(){let t=this._first;for(;t!==G.Undefined;){let e=t.next;t.prev=G.Undefined,t.next=G.Undefined,t=e}this._first=G.Undefined,this._last=G.Undefined,this._size=0}unshift(t){return this._insert(t,!1)}push(t){return this._insert(t,!0)}_insert(t,e){let i=new G(t);if(this._first===G.Undefined)this._first=i,this._last=i;else if(e){let n=this._last;this._last=i,i.prev=n,n.next=i}else{let n=this._first;this._first=i,i.next=n,n.prev=i}this._size+=1;let r=!1;return()=>{r||(r=!0,this._remove(i))}}shift(){if(this._first!==G.Undefined){let t=this._first.element;return this._remove(this._first),t}}pop(){if(this._last!==G.Undefined){let t=this._last.element;return this._remove(this._last),t}}_remove(t){if(t.prev!==G.Undefined&&t.next!==G.Undefined){let e=t.prev;e.next=t.next,t.next.prev=e}else t.prev===G.Undefined&&t.next===G.Undefined?(this._first=G.Undefined,this._last=G.Undefined):t.next===G.Undefined?(this._last=this._last.prev,this._last.next=G.Undefined):t.prev===G.Undefined&&(this._first=this._first.next,this._first.prev=G.Undefined);this._size-=1}*[Symbol.iterator](){let t=this._first;for(;t!==G.Undefined;)yield t.element,t=t.next}};var zl=globalThis.performance&&typeof globalThis.performance.now=="function",mr=class s{static create(t){return new s(t)}constructor(t){this._now=zl&&t===!1?Date.now:globalThis.performance.now.bind(globalThis.performance),this._startTime=this._now(),this._stopTime=-1}stop(){this._stopTime=this._now()}reset(){this._startTime=this._now(),this._stopTime=-1}elapsed(){return this._stopTime!==-1?this._stopTime-this._startTime:this._now()-this._startTime}};var Gl=!1,fo=!1,$l=!1,$;(Qe=>{Qe.None=()=>D.None;function t(y){if($l){let{onDidAddListener:T}=y,g=gi.create(),w=0;y.onDidAddListener=()=>{++w===2&&(console.warn("snapshotted emitter LIKELY used public and SHOULD HAVE BEEN created with DisposableStore. snapshotted here"),g.print()),T?.()}}}function e(y,T){return d(y,()=>{},0,void 0,!0,void 0,T)}Qe.defer=e;function i(y){return(T,g=null,w)=>{let E=!1,x;return x=y(N=>{if(!E)return x?x.dispose():E=!0,T.call(g,N)},null,w),E&&x.dispose(),x}}Qe.once=i;function r(y,T,g){return h((w,E=null,x)=>y(N=>w.call(E,T(N)),null,x),g)}Qe.map=r;function n(y,T,g){return h((w,E=null,x)=>y(N=>{T(N),w.call(E,N)},null,x),g)}Qe.forEach=n;function o(y,T,g){return h((w,E=null,x)=>y(N=>T(N)&&w.call(E,N),null,x),g)}Qe.filter=o;function l(y){return y}Qe.signal=l;function a(...y){return(T,g=null,w)=>{let E=ho(...y.map(x=>x(N=>T.call(g,N))));return c(E,w)}}Qe.any=a;function u(y,T,g,w){let E=g;return r(y,x=>(E=T(E,x),E),w)}Qe.reduce=u;function h(y,T){let g,w={onWillAddFirstListener(){g=y(E.fire,E)},onDidRemoveLastListener(){g?.dispose()}};T||t(w);let E=new v(w);return T?.add(E),E.event}function c(y,T){return T instanceof Array?T.push(y):T&&T.add(y),y}function d(y,T,g=100,w=!1,E=!1,x,N){let Z,te,Oe,ze=0,le,et={leakWarningThreshold:x,onWillAddFirstListener(){Z=y(ht=>{ze++,te=T(te,ht),w&&!Oe&&(me.fire(te),te=void 0),le=()=>{let fi=te;te=void 0,Oe=void 0,(!w||ze>1)&&me.fire(fi),ze=0},typeof g=="number"?(clearTimeout(Oe),Oe=setTimeout(le,g)):Oe===void 0&&(Oe=0,queueMicrotask(le))})},onWillRemoveListener(){E&&ze>0&&le?.()},onDidRemoveLastListener(){le=void 0,Z.dispose()}};N||t(et);let me=new v(et);return N?.add(me),me.event}Qe.debounce=d;function _(y,T=0,g){return Qe.debounce(y,(w,E)=>w?(w.push(E),w):[E],T,void 0,!0,void 0,g)}Qe.accumulate=_;function p(y,T=(w,E)=>w===E,g){let w=!0,E;return o(y,x=>{let N=w||!T(x,E);return w=!1,E=x,N},g)}Qe.latch=p;function m(y,T,g){return[Qe.filter(y,T,g),Qe.filter(y,w=>!T(w),g)]}Qe.split=m;function f(y,T=!1,g=[],w){let E=g.slice(),x=y(te=>{E?E.push(te):Z.fire(te)});w&&w.add(x);let N=()=>{E?.forEach(te=>Z.fire(te)),E=null},Z=new v({onWillAddFirstListener(){x||(x=y(te=>Z.fire(te)),w&&w.add(x))},onDidAddFirstListener(){E&&(T?setTimeout(N):N())},onDidRemoveLastListener(){x&&x.dispose(),x=null}});return w&&w.add(Z),Z.event}Qe.buffer=f;function A(y,T){return(w,E,x)=>{let N=T(new O);return y(function(Z){let te=N.evaluate(Z);te!==R&&w.call(E,te)},void 0,x)}}Qe.chain=A;let R=Symbol("HaltChainable");class O{constructor(){this.steps=[]}map(T){return this.steps.push(T),this}forEach(T){return this.steps.push(g=>(T(g),g)),this}filter(T){return this.steps.push(g=>T(g)?g:R),this}reduce(T,g){let w=g;return this.steps.push(E=>(w=T(w,E),w)),this}latch(T=(g,w)=>g===w){let g=!0,w;return this.steps.push(E=>{let x=g||!T(E,w);return g=!1,w=E,x?E:R}),this}evaluate(T){for(let g of this.steps)if(T=g(T),T===R)break;return T}}function I(y,T,g=w=>w){let w=(...Z)=>N.fire(g(...Z)),E=()=>y.on(T,w),x=()=>y.removeListener(T,w),N=new v({onWillAddFirstListener:E,onDidRemoveLastListener:x});return N.event}Qe.fromNodeEventEmitter=I;function k(y,T,g=w=>w){let w=(...Z)=>N.fire(g(...Z)),E=()=>y.addEventListener(T,w),x=()=>y.removeEventListener(T,w),N=new v({onWillAddFirstListener:E,onDidRemoveLastListener:x});return N.event}Qe.fromDOMEventEmitter=k;function P(y){return new Promise(T=>i(y)(T))}Qe.toPromise=P;function oe(y){let T=new v;return y.then(g=>{T.fire(g)},()=>{T.fire(void 0)}).finally(()=>{T.dispose()}),T.event}Qe.fromPromise=oe;function Me(y,T){return y(g=>T.fire(g))}Qe.forward=Me;function Pe(y,T,g){return T(g),y(w=>T(w))}Qe.runAndSubscribe=Pe;class Ke{constructor(T,g){this._observable=T;this._counter=0;this._hasChanged=!1;let w={onWillAddFirstListener:()=>{T.addObserver(this)},onDidRemoveLastListener:()=>{T.removeObserver(this)}};g||t(w),this.emitter=new v(w),g&&g.add(this.emitter)}beginUpdate(T){this._counter++}handlePossibleChange(T){}handleChange(T,g){this._hasChanged=!0}endUpdate(T){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function di(y,T){return new Ke(y,T).emitter.event}Qe.fromObservable=di;function V(y){return(T,g,w)=>{let E=0,x=!1,N={beginUpdate(){E++},endUpdate(){E--,E===0&&(y.reportChanges(),x&&(x=!1,T.call(g)))},handlePossibleChange(){},handleChange(){x=!0}};y.addObserver(N),y.reportChanges();let Z={dispose(){y.removeObserver(N)}};return w instanceof Ee?w.add(Z):Array.isArray(w)&&w.push(Z),Z}}Qe.fromObservableLight=V})($||={});var Mt=class Mt{constructor(t){this.listenerCount=0;this.invocationCount=0;this.elapsedOverall=0;this.durations=[];this.name=`${t}_${Mt._idPool++}`,Mt.all.add(this)}start(t){this._stopWatch=new mr,this.listenerCount=t}stop(){if(this._stopWatch){let t=this._stopWatch.elapsed();this.durations.push(t),this.elapsedOverall+=t,this.invocationCount+=1,this._stopWatch=void 0}}};Mt.all=new Set,Mt._idPool=0;var $n=Mt,po=-1;var br=class br{constructor(t,e,i=(br._idPool++).toString(16).padStart(3,"0")){this._errorHandler=t;this.threshold=e;this.name=i;this._warnCountdown=0}dispose(){this._stacks?.clear()}check(t,e){let i=this.threshold;if(i<=0||e{let n=this._stacks.get(t.value)||0;this._stacks.set(t.value,n-1)}}getMostFrequentStack(){if(!this._stacks)return;let t,e=0;for(let[i,r]of this._stacks)(!t||e{if(s instanceof Pt)t(s);else for(let e=0;e{s.length!==0&&(console.warn("[LEAKING LISTENERS] GC'ed these listeners that were NOT yet disposed:"),console.warn(s.join(` +`)),s.length=0)},3e3),_r=new FinalizationRegistry(t=>{typeof t=="string"&&s.push(t)})}var v=class{constructor(t){this._size=0;this._options=t,this._leakageMon=po>0||this._options?.leakWarningThreshold?new Vn(t?.onListenerError??Lt,this._options?.leakWarningThreshold??po):void 0,this._perfMon=this._options?._profName?new $n(this._options._profName):void 0,this._deliveryQueue=this._options?.deliveryQueue}dispose(){if(!this._disposed){if(this._disposed=!0,this._deliveryQueue?.current===this&&this._deliveryQueue.reset(),this._listeners){if(fo){let t=this._listeners;queueMicrotask(()=>{Yl(t,e=>e.stack?.print())})}this._listeners=void 0,this._size=0}this._options?.onDidRemoveLastListener?.(),this._leakageMon?.dispose()}}get event(){return this._event??=(t,e,i)=>{if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let a=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(a);let u=this._leakageMon.getMostFrequentStack()??["UNKNOWN stack",-1],h=new Yn(`${a}. HINT: Stack shows most frequent listener (${u[1]}-times)`,u[0]);return(this._options?.onListenerError||Lt)(h),D.None}if(this._disposed)return D.None;e&&(t=t.bind(e));let r=new Pt(t),n,o;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(r.stack=gi.create(),n=this._leakageMon.check(r.stack,this._size+1)),fo&&(r.stack=o??gi.create()),this._listeners?this._listeners instanceof Pt?(this._deliveryQueue??=new jn,this._listeners=[this._listeners,r]):this._listeners.push(r):(this._options?.onWillAddFirstListener?.(this),this._listeners=r,this._options?.onDidAddFirstListener?.(this)),this._size++;let l=C(()=>{_r?.unregister(l),n?.(),this._removeListener(r)});if(i instanceof Ee?i.add(l):Array.isArray(i)&&i.push(l),_r){let a=new Error().stack.split(` +`).slice(2,3).join(` +`).trim(),u=/(file:|vscode-file:\/\/vscode-app)?(\/[^:]*:\d+:\d+)/.exec(a);_r.register(l,u?.[2]??a,l)}return l},this._event}_removeListener(t){if(this._options?.onWillRemoveListener?.(this),!this._listeners)return;if(this._size===1){this._listeners=void 0,this._options?.onDidRemoveLastListener?.(this),this._size=0;return}let e=this._listeners,i=e.indexOf(t);if(i===-1)throw console.log("disposed?",this._disposed),console.log("size?",this._size),console.log("arr?",JSON.stringify(this._listeners)),new Error("Attempted to dispose unknown listener");this._size--,e[i]=void 0;let r=this._deliveryQueue.current===this;if(this._size*ql<=e.length){let n=0;for(let o=0;o0}};var jn=class{constructor(){this.i=-1;this.end=0}enqueue(t,e,i){this.i=0,this.end=i,this.current=t,this.value=e}reset(){this.i=this.end,this.current=void 0,this.value=void 0}};var gr=class gr{constructor(){this.mapWindowIdToZoomLevel=new Map;this._onDidChangeZoomLevel=new v;this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event;this.mapWindowIdToZoomFactor=new Map;this._onDidChangeFullscreen=new v;this.onDidChangeFullscreen=this._onDidChangeFullscreen.event;this.mapWindowIdToFullScreen=new Map}getZoomLevel(t){return this.mapWindowIdToZoomLevel.get(this.getWindowId(t))??0}setZoomLevel(t,e){if(this.getZoomLevel(e)===t)return;let i=this.getWindowId(e);this.mapWindowIdToZoomLevel.set(i,t),this._onDidChangeZoomLevel.fire(i)}getZoomFactor(t){return this.mapWindowIdToZoomFactor.get(this.getWindowId(t))??1}setZoomFactor(t,e){this.mapWindowIdToZoomFactor.set(this.getWindowId(e),t)}setFullscreen(t,e){if(this.isFullscreen(e)===t)return;let i=this.getWindowId(e);this.mapWindowIdToFullScreen.set(i,t),this._onDidChangeFullscreen.fire(i)}isFullscreen(t){return!!this.mapWindowIdToFullScreen.get(this.getWindowId(t))}getWindowId(t){return t.vscodeWindowId}};gr.INSTANCE=new gr;var Si=gr;function Xl(s,t,e){typeof t=="string"&&(t=s.matchMedia(t)),t.addEventListener("change",e)}var Eu=Si.INSTANCE.onDidChangeZoomLevel;function mo(s){return Si.INSTANCE.getZoomFactor(s)}var Tu=Si.INSTANCE.onDidChangeFullscreen,Ot=typeof navigator=="object"?navigator.userAgent:"",Ei=Ot.indexOf("Firefox")>=0,Bt=Ot.indexOf("AppleWebKit")>=0,Ti=Ot.indexOf("Chrome")>=0,Sr=!Ti&&Ot.indexOf("Safari")>=0;var Iu=Ot.indexOf("Electron/")>=0,yu=Ot.indexOf("Android")>=0,vr=!1;if(typeof fe.matchMedia=="function"){let s=fe.matchMedia("(display-mode: standalone) or (display-mode: window-controls-overlay)"),t=fe.matchMedia("(display-mode: fullscreen)");vr=s.matches,Xl(fe,s,({matches:e})=>{vr&&t.matches||(vr=e)})}function _o(){return vr}var Nt="en",yr=!1,xr=!1,Ii=!1,Zl=!1,vo=!1,go=!1,Jl=!1,Ql=!1,ea=!1,ta=!1,Tr,Ir=Nt,bo=Nt,ia,$e,Ve=globalThis,xe;typeof Ve.vscode<"u"&&typeof Ve.vscode.process<"u"?xe=Ve.vscode.process:typeof process<"u"&&typeof process?.versions?.node=="string"&&(xe=process);var So=typeof xe?.versions?.electron=="string",ra=So&&xe?.type==="renderer";if(typeof xe=="object"){yr=xe.platform==="win32",xr=xe.platform==="darwin",Ii=xe.platform==="linux",Zl=Ii&&!!xe.env.SNAP&&!!xe.env.SNAP_REVISION,Jl=So,ea=!!xe.env.CI||!!xe.env.BUILD_ARTIFACTSTAGINGDIRECTORY,Tr=Nt,Ir=Nt;let s=xe.env.VSCODE_NLS_CONFIG;if(s)try{let t=JSON.parse(s);Tr=t.userLocale,bo=t.osLocale,Ir=t.resolvedLanguage||Nt,ia=t.languagePack?.translationsConfigFile}catch{}vo=!0}else typeof navigator=="object"&&!ra?($e=navigator.userAgent,yr=$e.indexOf("Windows")>=0,xr=$e.indexOf("Macintosh")>=0,Ql=($e.indexOf("Macintosh")>=0||$e.indexOf("iPad")>=0||$e.indexOf("iPhone")>=0)&&!!navigator.maxTouchPoints&&navigator.maxTouchPoints>0,Ii=$e.indexOf("Linux")>=0,ta=$e?.indexOf("Mobi")>=0,go=!0,Ir=globalThis._VSCODE_NLS_LANGUAGE||Nt,Tr=navigator.language.toLowerCase(),bo=Tr):console.error("Unable to resolve platform.");var Xn=0;xr?Xn=1:yr?Xn=3:Ii&&(Xn=2);var wr=yr,Te=xr,Zn=Ii;var Dr=vo;var na=go&&typeof Ve.importScripts=="function",xu=na?Ve.origin:void 0;var Fe=$e,st=Ir,sa;(i=>{function s(){return st}i.value=s;function t(){return st.length===2?st==="en":st.length>=3?st[0]==="e"&&st[1]==="n"&&st[2]==="-":!1}i.isDefaultVariant=t;function e(){return st==="en"}i.isDefault=e})(sa||={});var oa=typeof Ve.postMessage=="function"&&!Ve.importScripts,Eo=(()=>{if(oa){let s=[];Ve.addEventListener("message",e=>{if(e.data&&e.data.vscodeScheduleAsyncWork)for(let i=0,r=s.length;i{let i=++t;s.push({id:i,callback:e}),Ve.postMessage({vscodeScheduleAsyncWork:i},"*")}}return s=>setTimeout(s)})();var la=!!(Fe&&Fe.indexOf("Chrome")>=0),wu=!!(Fe&&Fe.indexOf("Firefox")>=0),Du=!!(!la&&Fe&&Fe.indexOf("Safari")>=0),Ru=!!(Fe&&Fe.indexOf("Edg/")>=0),Lu=!!(Fe&&Fe.indexOf("Android")>=0);var ot=typeof navigator=="object"?navigator:{},aa={clipboard:{writeText:Dr||document.queryCommandSupported&&document.queryCommandSupported("copy")||!!(ot&&ot.clipboard&&ot.clipboard.writeText),readText:Dr||!!(ot&&ot.clipboard&&ot.clipboard.readText)},keyboard:Dr||_o()?0:ot.keyboard||Sr?1:2,touch:"ontouchstart"in fe||ot.maxTouchPoints>0,pointerEvents:fe.PointerEvent&&("ontouchstart"in fe||navigator.maxTouchPoints>0)};var yi=class{constructor(){this._keyCodeToStr=[],this._strToKeyCode=Object.create(null)}define(t,e){this._keyCodeToStr[t]=e,this._strToKeyCode[e.toLowerCase()]=t}keyCodeToStr(t){return this._keyCodeToStr[t]}strToKeyCode(t){return this._strToKeyCode[t.toLowerCase()]||0}},Jn=new yi,To=new yi,Io=new yi,yo=new Array(230);var Qn;(o=>{function s(l){return Jn.keyCodeToStr(l)}o.toString=s;function t(l){return Jn.strToKeyCode(l)}o.fromString=t;function e(l){return To.keyCodeToStr(l)}o.toUserSettingsUS=e;function i(l){return Io.keyCodeToStr(l)}o.toUserSettingsGeneral=i;function r(l){return To.strToKeyCode(l)||Io.strToKeyCode(l)}o.fromUserSettings=r;function n(l){if(l>=98&&l<=113)return null;switch(l){case 16:return"Up";case 18:return"Down";case 15:return"Left";case 17:return"Right"}return Jn.keyCodeToStr(l)}o.toElectronAccelerator=n})(Qn||={});var Rr=class s{constructor(t,e,i,r,n){this.ctrlKey=t;this.shiftKey=e;this.altKey=i;this.metaKey=r;this.keyCode=n}equals(t){return t instanceof s&&this.ctrlKey===t.ctrlKey&&this.shiftKey===t.shiftKey&&this.altKey===t.altKey&&this.metaKey===t.metaKey&&this.keyCode===t.keyCode}getHashCode(){let t=this.ctrlKey?"1":"0",e=this.shiftKey?"1":"0",i=this.altKey?"1":"0",r=this.metaKey?"1":"0";return`K${t}${e}${i}${r}${this.keyCode}`}isModifierKey(){return this.keyCode===0||this.keyCode===5||this.keyCode===57||this.keyCode===6||this.keyCode===4}toKeybinding(){return new es([this])}isDuplicateModifierCase(){return this.ctrlKey&&this.keyCode===5||this.shiftKey&&this.keyCode===4||this.altKey&&this.keyCode===6||this.metaKey&&this.keyCode===57}};var es=class{constructor(t){if(t.length===0)throw eo("chords");this.chords=t}getHashCode(){let t="";for(let e=0,i=this.chords.length;e{function s(r){return r===i.None||r===i.Cancelled||r instanceof ts?!0:!r||typeof r!="object"?!1:typeof r.isCancellationRequested=="boolean"&&typeof r.onCancellationRequested=="function"}i.isCancellationToken=s,i.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:$.None}),i.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:Do})})(ma||={});var ts=class{constructor(){this._isCancelled=!1;this._emitter=null}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?Do:(this._emitter||(this._emitter=new v),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=null)}};var _a=Symbol("MicrotaskDelay");var Ye=class{constructor(t,e){this._isDisposed=!1;this._token=-1,typeof t=="function"&&typeof e=="number"&&this.setIfNotSet(t,e)}dispose(){this.cancel(),this._isDisposed=!0}cancel(){this._token!==-1&&(clearTimeout(this._token),this._token=-1)}cancelAndSet(t,e){if(this._isDisposed)throw new Rt("Calling 'cancelAndSet' on a disposed TimeoutTimer");this.cancel(),this._token=setTimeout(()=>{this._token=-1,t()},e)}setIfNotSet(t,e){if(this._isDisposed)throw new Rt("Calling 'setIfNotSet' on a disposed TimeoutTimer");this._token===-1&&(this._token=setTimeout(()=>{this._token=-1,t()},e))}},kr=class{constructor(){this.disposable=void 0;this.isDisposed=!1}cancel(){this.disposable?.dispose(),this.disposable=void 0}cancelAndSet(t,e,i=globalThis){if(this.isDisposed)throw new Rt("Calling 'cancelAndSet' on a disposed IntervalTimer");this.cancel();let r=i.setInterval(()=>{t()},e);this.disposable=C(()=>{i.clearInterval(r),this.disposable=void 0})}dispose(){this.cancel(),this.isDisposed=!0}};var ba,Ar;(function(){typeof globalThis.requestIdleCallback!="function"||typeof globalThis.cancelIdleCallback!="function"?Ar=(s,t)=>{Eo(()=>{if(e)return;let i=Date.now()+15;t(Object.freeze({didTimeout:!0,timeRemaining(){return Math.max(0,i-Date.now())}}))});let e=!1;return{dispose(){e||(e=!0)}}}:Ar=(s,t,e)=>{let i=s.requestIdleCallback(t,typeof e=="number"?{timeout:e}:void 0),r=!1;return{dispose(){r||(r=!0,s.cancelIdleCallback(i))}}},ba=s=>Ar(globalThis,s)})();var va;(e=>{async function s(i){let r,n=await Promise.all(i.map(o=>o.then(l=>l,l=>{r||(r=l)})));if(typeof r<"u")throw r;return n}e.settled=s;function t(i){return new Promise(async(r,n)=>{try{await i(r,n)}catch(o){n(o)}})}e.withAsyncBody=t})(va||={});var _e=class _e{static fromArray(t){return new _e(e=>{e.emitMany(t)})}static fromPromise(t){return new _e(async e=>{e.emitMany(await t)})}static fromPromises(t){return new _e(async e=>{await Promise.all(t.map(async i=>e.emitOne(await i)))})}static merge(t){return new _e(async e=>{await Promise.all(t.map(async i=>{for await(let r of i)e.emitOne(r)}))})}constructor(t,e){this._state=0,this._results=[],this._error=null,this._onReturn=e,this._onStateChanged=new v,queueMicrotask(async()=>{let i={emitOne:r=>this.emitOne(r),emitMany:r=>this.emitMany(r),reject:r=>this.reject(r)};try{await Promise.resolve(t(i)),this.resolve()}catch(r){this.reject(r)}finally{i.emitOne=void 0,i.emitMany=void 0,i.reject=void 0}})}[Symbol.asyncIterator](){let t=0;return{next:async()=>{do{if(this._state===2)throw this._error;if(t(this._onReturn?.(),{done:!0,value:void 0})}}static map(t,e){return new _e(async i=>{for await(let r of t)i.emitOne(e(r))})}map(t){return _e.map(this,t)}static filter(t,e){return new _e(async i=>{for await(let r of t)e(r)&&i.emitOne(r)})}filter(t){return _e.filter(this,t)}static coalesce(t){return _e.filter(t,e=>!!e)}coalesce(){return _e.coalesce(this)}static async toPromise(t){let e=[];for await(let i of t)e.push(i);return e}toPromise(){return _e.toPromise(this)}emitOne(t){this._state===0&&(this._results.push(t),this._onStateChanged.fire())}emitMany(t){this._state===0&&(this._results=this._results.concat(t),this._onStateChanged.fire())}resolve(){this._state===0&&(this._state=1,this._onStateChanged.fire())}reject(t){this._state===0&&(this._state=2,this._error=t,this._onStateChanged.fire())}};_e.EMPTY=_e.fromArray([]);var Ro=_e;function Lo(s){return 55296<=s&&s<=56319}function is(s){return 56320<=s&&s<=57343}function Ao(s,t){return(s-55296<<10)+(t-56320)+65536}function Mo(s){return ns(s,0)}function ns(s,t){switch(typeof s){case"object":return s===null?je(349,t):Array.isArray(s)?Ea(s,t):Ta(s,t);case"string":return Po(s,t);case"boolean":return Sa(s,t);case"number":return je(s,t);case"undefined":return je(937,t);default:return je(617,t)}}function je(s,t){return(t<<5)-t+s|0}function Sa(s,t){return je(s?433:863,t)}function Po(s,t){t=je(149417,t);for(let e=0,i=s.length;ens(i,e),t)}function Ta(s,t){return t=je(181387,t),Object.keys(s).sort().reduce((e,i)=>(e=Po(i,e),ns(s[i],e)),t)}function rs(s,t,e=32){let i=e-t,r=~((1<>>i)>>>0}function ko(s,t=0,e=s.byteLength,i=0){for(let r=0;re.toString(16).padStart(2,"0")).join(""):Ia((s>>>0).toString(16),t/4)}var Cr=class Cr{constructor(){this._h0=1732584193;this._h1=4023233417;this._h2=2562383102;this._h3=271733878;this._h4=3285377520;this._buff=new Uint8Array(67),this._buffDV=new DataView(this._buff.buffer),this._buffLen=0,this._totalLen=0,this._leftoverHighSurrogate=0,this._finished=!1}update(t){let e=t.length;if(e===0)return;let i=this._buff,r=this._buffLen,n=this._leftoverHighSurrogate,o,l;for(n!==0?(o=n,l=-1,n=0):(o=t.charCodeAt(0),l=0);;){let a=o;if(Lo(o))if(l+1>>6,t[e++]=128|(i&63)>>>0):i<65536?(t[e++]=224|(i&61440)>>>12,t[e++]=128|(i&4032)>>>6,t[e++]=128|(i&63)>>>0):(t[e++]=240|(i&1835008)>>>18,t[e++]=128|(i&258048)>>>12,t[e++]=128|(i&4032)>>>6,t[e++]=128|(i&63)>>>0),e>=64&&(this._step(),e-=64,this._totalLen+=64,t[0]=t[64],t[1]=t[65],t[2]=t[66]),e}digest(){return this._finished||(this._finished=!0,this._leftoverHighSurrogate&&(this._leftoverHighSurrogate=0,this._buffLen=this._push(this._buff,this._buffLen,65533)),this._totalLen+=this._buffLen,this._wrapUp()),wi(this._h0)+wi(this._h1)+wi(this._h2)+wi(this._h3)+wi(this._h4)}_wrapUp(){this._buff[this._buffLen++]=128,ko(this._buff,this._buffLen),this._buffLen>56&&(this._step(),ko(this._buff));let t=8*this._totalLen;this._buffDV.setUint32(56,Math.floor(t/4294967296),!1),this._buffDV.setUint32(60,t%4294967296,!1),this._step()}_step(){let t=Cr._bigBlock32,e=this._buffDV;for(let c=0;c<64;c+=4)t.setUint32(c,e.getUint32(c,!1),!1);for(let c=64;c<320;c+=4)t.setUint32(c,rs(t.getUint32(c-12,!1)^t.getUint32(c-32,!1)^t.getUint32(c-56,!1)^t.getUint32(c-64,!1),1),!1);let i=this._h0,r=this._h1,n=this._h2,o=this._h3,l=this._h4,a,u,h;for(let c=0;c<80;c++)c<20?(a=r&n|~r&o,u=1518500249):c<40?(a=r^n^o,u=1859775393):c<60?(a=r&n|r&o|n&o,u=2400959708):(a=r^n^o,u=3395469782),h=rs(i,5)+a+l+u+t.getUint32(c*4,!1)&4294967295,l=o,o=n,n=rs(r,30),r=i,i=h;this._h0=this._h0+i&4294967295,this._h1=this._h1+r&4294967295,this._h2=this._h2+n&4294967295,this._h3=this._h3+o&4294967295,this._h4=this._h4+l&4294967295}};Cr._bigBlock32=new DataView(new ArrayBuffer(320));var Co=Cr;var{registerWindow:Bh,getWindow:be,getDocument:Nh,getWindows:Fh,getWindowsCount:Hh,getWindowId:Oo,getWindowById:Wh,hasWindow:Uh,onDidRegisterWindow:No,onWillUnregisterWindow:Kh,onDidUnregisterWindow:zh}=function(){let s=new Map;fe;let t={window:fe,disposables:new Ee};s.set(fe.vscodeWindowId,t);let e=new v,i=new v,r=new v;function n(o,l){return(typeof o=="number"?s.get(o):void 0)??(l?t:void 0)}return{onDidRegisterWindow:e.event,onWillUnregisterWindow:r.event,onDidUnregisterWindow:i.event,registerWindow(o){if(s.has(o.vscodeWindowId))return D.None;let l=new Ee,a={window:o,disposables:l.add(new Ee)};return s.set(o.vscodeWindowId,a),l.add(C(()=>{s.delete(o.vscodeWindowId),i.fire(o)})),l.add(L(o,Y.BEFORE_UNLOAD,()=>{r.fire(o)})),e.fire(a),l},getWindows(){return s.values()},getWindowsCount(){return s.size},getWindowId(o){return o.vscodeWindowId},hasWindow(o){return s.has(o)},getWindowById:n,getWindow(o){let l=o;if(l?.ownerDocument?.defaultView)return l.ownerDocument.defaultView.window;let a=o;return a?.view?a.view.window:fe},getDocument(o){return be(o).document}}}();var ss=class{constructor(t,e,i,r){this._node=t,this._type=e,this._handler=i,this._options=r||!1,this._node.addEventListener(this._type,this._handler,this._options)}dispose(){this._handler&&(this._node.removeEventListener(this._type,this._handler,this._options),this._node=null,this._handler=null)}};function L(s,t,e,i){return new ss(s,t,e,i)}function ya(s,t){return function(e){return t(new qe(s,e))}}function xa(s){return function(t){return s(new ft(t))}}var os=function(t,e,i,r){let n=i;return e==="click"||e==="mousedown"||e==="contextmenu"?n=ya(be(t),i):(e==="keydown"||e==="keypress"||e==="keyup")&&(n=xa(i)),L(t,e,n,r)};var wa,mt;var Mr=class extends kr{constructor(t){super(),this.defaultTarget=t&&be(t)}cancelAndSet(t,e,i){return super.cancelAndSet(t,e,i??this.defaultTarget)}},Di=class{constructor(t,e=0){this._runner=t,this.priority=e,this._canceled=!1}dispose(){this._canceled=!0}execute(){if(!this._canceled)try{this._runner()}catch(t){Lt(t)}}static sort(t,e){return e.priority-t.priority}};(function(){let s=new Map,t=new Map,e=new Map,i=new Map,r=n=>{e.set(n,!1);let o=s.get(n)??[];for(t.set(n,o),s.set(n,[]),i.set(n,!0);o.length>0;)o.sort(Di.sort),o.shift().execute();i.set(n,!1)};mt=(n,o,l=0)=>{let a=Oo(n),u=new Di(o,l),h=s.get(a);return h||(h=[],s.set(a,h)),h.push(u),e.get(a)||(e.set(a,!0),n.requestAnimationFrame(()=>r(a))),u},wa=(n,o,l)=>{let a=Oo(n);if(i.get(a)){let u=new Di(o,l),h=t.get(a);return h||(h=[],t.set(a,h)),h.push(u),u}else return mt(n,o,l)}})();var pt=class pt{constructor(t,e){this.width=t;this.height=e}with(t=this.width,e=this.height){return t!==this.width||e!==this.height?new pt(t,e):this}static is(t){return typeof t=="object"&&typeof t.height=="number"&&typeof t.width=="number"}static lift(t){return t instanceof pt?t:new pt(t.width,t.height)}static equals(t,e){return t===e?!0:!t||!e?!1:t.width===e.width&&t.height===e.height}};pt.None=new pt(0,0);var Bo=pt;function Fo(s){let t=s.getBoundingClientRect(),e=be(s);return{left:t.left+e.scrollX,top:t.top+e.scrollY,width:t.width,height:t.height}}var Gh=new class{constructor(){this.mutationObservers=new Map}observe(s,t,e){let i=this.mutationObservers.get(s);i||(i=new Map,this.mutationObservers.set(s,i));let r=Mo(e),n=i.get(r);if(n)n.users+=1;else{let o=new v,l=new MutationObserver(u=>o.fire(u));l.observe(s,e);let a=n={users:1,observer:l,onDidMutate:o.event};t.add(C(()=>{a.users-=1,a.users===0&&(o.dispose(),l.disconnect(),i?.delete(r),i?.size===0&&this.mutationObservers.delete(s))})),i.set(r,n)}return n.onDidMutate}};var Y={CLICK:"click",AUXCLICK:"auxclick",DBLCLICK:"dblclick",MOUSE_UP:"mouseup",MOUSE_DOWN:"mousedown",MOUSE_OVER:"mouseover",MOUSE_MOVE:"mousemove",MOUSE_OUT:"mouseout",MOUSE_ENTER:"mouseenter",MOUSE_LEAVE:"mouseleave",MOUSE_WHEEL:"wheel",POINTER_UP:"pointerup",POINTER_DOWN:"pointerdown",POINTER_MOVE:"pointermove",POINTER_LEAVE:"pointerleave",CONTEXT_MENU:"contextmenu",WHEEL:"wheel",KEY_DOWN:"keydown",KEY_PRESS:"keypress",KEY_UP:"keyup",LOAD:"load",BEFORE_UNLOAD:"beforeunload",UNLOAD:"unload",PAGE_SHOW:"pageshow",PAGE_HIDE:"pagehide",PASTE:"paste",ABORT:"abort",ERROR:"error",RESIZE:"resize",SCROLL:"scroll",FULLSCREEN_CHANGE:"fullscreenchange",WK_FULLSCREEN_CHANGE:"webkitfullscreenchange",SELECT:"select",CHANGE:"change",SUBMIT:"submit",RESET:"reset",FOCUS:"focus",FOCUS_IN:"focusin",FOCUS_OUT:"focusout",BLUR:"blur",INPUT:"input",STORAGE:"storage",DRAG_START:"dragstart",DRAG:"drag",DRAG_ENTER:"dragenter",DRAG_LEAVE:"dragleave",DRAG_OVER:"dragover",DROP:"drop",DRAG_END:"dragend",ANIMATION_START:Bt?"webkitAnimationStart":"animationstart",ANIMATION_END:Bt?"webkitAnimationEnd":"animationend",ANIMATION_ITERATION:Bt?"webkitAnimationIteration":"animationiteration"};var Da=/([\w\-]+)?(#([\w\-]+))?((\.([\w\-]+))*)/;function Ho(s,t,e,...i){let r=Da.exec(t);if(!r)throw new Error("Bad use of emmet");let n=r[1]||"div",o;return s!=="http://www.w3.org/1999/xhtml"?o=document.createElementNS(s,n):o=document.createElement(n),r[3]&&(o.id=r[3]),r[4]&&(o.className=r[4].replace(/\./g," ").trim()),e&&Object.entries(e).forEach(([l,a])=>{typeof a>"u"||(/^on\w+$/.test(l)?o[l]=a:l==="selected"?a&&o.setAttribute(l,"true"):o.setAttribute(l,a))}),o.append(...i),o}function Ra(s,t,...e){return Ho("http://www.w3.org/1999/xhtml",s,t,...e)}Ra.SVG=function(s,t,...e){return Ho("http://www.w3.org/2000/svg",s,t,...e)};var ls=class{constructor(t){this.domNode=t;this._maxWidth="";this._width="";this._height="";this._top="";this._left="";this._bottom="";this._right="";this._paddingTop="";this._paddingLeft="";this._paddingBottom="";this._paddingRight="";this._fontFamily="";this._fontWeight="";this._fontSize="";this._fontStyle="";this._fontFeatureSettings="";this._fontVariationSettings="";this._textDecoration="";this._lineHeight="";this._letterSpacing="";this._className="";this._display="";this._position="";this._visibility="";this._color="";this._backgroundColor="";this._layerHint=!1;this._contain="none";this._boxShadow=""}setMaxWidth(t){let e=Ie(t);this._maxWidth!==e&&(this._maxWidth=e,this.domNode.style.maxWidth=this._maxWidth)}setWidth(t){let e=Ie(t);this._width!==e&&(this._width=e,this.domNode.style.width=this._width)}setHeight(t){let e=Ie(t);this._height!==e&&(this._height=e,this.domNode.style.height=this._height)}setTop(t){let e=Ie(t);this._top!==e&&(this._top=e,this.domNode.style.top=this._top)}setLeft(t){let e=Ie(t);this._left!==e&&(this._left=e,this.domNode.style.left=this._left)}setBottom(t){let e=Ie(t);this._bottom!==e&&(this._bottom=e,this.domNode.style.bottom=this._bottom)}setRight(t){let e=Ie(t);this._right!==e&&(this._right=e,this.domNode.style.right=this._right)}setPaddingTop(t){let e=Ie(t);this._paddingTop!==e&&(this._paddingTop=e,this.domNode.style.paddingTop=this._paddingTop)}setPaddingLeft(t){let e=Ie(t);this._paddingLeft!==e&&(this._paddingLeft=e,this.domNode.style.paddingLeft=this._paddingLeft)}setPaddingBottom(t){let e=Ie(t);this._paddingBottom!==e&&(this._paddingBottom=e,this.domNode.style.paddingBottom=this._paddingBottom)}setPaddingRight(t){let e=Ie(t);this._paddingRight!==e&&(this._paddingRight=e,this.domNode.style.paddingRight=this._paddingRight)}setFontFamily(t){this._fontFamily!==t&&(this._fontFamily=t,this.domNode.style.fontFamily=this._fontFamily)}setFontWeight(t){this._fontWeight!==t&&(this._fontWeight=t,this.domNode.style.fontWeight=this._fontWeight)}setFontSize(t){let e=Ie(t);this._fontSize!==e&&(this._fontSize=e,this.domNode.style.fontSize=this._fontSize)}setFontStyle(t){this._fontStyle!==t&&(this._fontStyle=t,this.domNode.style.fontStyle=this._fontStyle)}setFontFeatureSettings(t){this._fontFeatureSettings!==t&&(this._fontFeatureSettings=t,this.domNode.style.fontFeatureSettings=this._fontFeatureSettings)}setFontVariationSettings(t){this._fontVariationSettings!==t&&(this._fontVariationSettings=t,this.domNode.style.fontVariationSettings=this._fontVariationSettings)}setTextDecoration(t){this._textDecoration!==t&&(this._textDecoration=t,this.domNode.style.textDecoration=this._textDecoration)}setLineHeight(t){let e=Ie(t);this._lineHeight!==e&&(this._lineHeight=e,this.domNode.style.lineHeight=this._lineHeight)}setLetterSpacing(t){let e=Ie(t);this._letterSpacing!==e&&(this._letterSpacing=e,this.domNode.style.letterSpacing=this._letterSpacing)}setClassName(t){this._className!==t&&(this._className=t,this.domNode.className=this._className)}toggleClassName(t,e){this.domNode.classList.toggle(t,e),this._className=this.domNode.className}setDisplay(t){this._display!==t&&(this._display=t,this.domNode.style.display=this._display)}setPosition(t){this._position!==t&&(this._position=t,this.domNode.style.position=this._position)}setVisibility(t){this._visibility!==t&&(this._visibility=t,this.domNode.style.visibility=this._visibility)}setColor(t){this._color!==t&&(this._color=t,this.domNode.style.color=this._color)}setBackgroundColor(t){this._backgroundColor!==t&&(this._backgroundColor=t,this.domNode.style.backgroundColor=this._backgroundColor)}setLayerHinting(t){this._layerHint!==t&&(this._layerHint=t,this.domNode.style.transform=this._layerHint?"translate3d(0px, 0px, 0px)":"")}setBoxShadow(t){this._boxShadow!==t&&(this._boxShadow=t,this.domNode.style.boxShadow=t)}setContain(t){this._contain!==t&&(this._contain=t,this.domNode.style.contain=this._contain)}setAttribute(t,e){this.domNode.setAttribute(t,e)}removeAttribute(t){this.domNode.removeAttribute(t)}appendChild(t){this.domNode.appendChild(t.domNode)}removeChild(t){this.domNode.removeChild(t.domNode)}};function Ie(s){return typeof s=="number"?`${s}px`:s}function _t(s){return new ls(s)}var Wt=class{constructor(){this._hooks=new Ee;this._pointerMoveCallback=null;this._onStopCallback=null}dispose(){this.stopMonitoring(!1),this._hooks.dispose()}stopMonitoring(t,e){if(!this.isMonitoring())return;this._hooks.clear(),this._pointerMoveCallback=null;let i=this._onStopCallback;this._onStopCallback=null,t&&i&&i(e)}isMonitoring(){return!!this._pointerMoveCallback}startMonitoring(t,e,i,r,n){this.isMonitoring()&&this.stopMonitoring(!1),this._pointerMoveCallback=r,this._onStopCallback=n;let o=t;try{t.setPointerCapture(e),this._hooks.add(C(()=>{try{t.releasePointerCapture(e)}catch{}}))}catch{o=be(t)}this._hooks.add(L(o,Y.POINTER_MOVE,l=>{if(l.buttons!==i){this.stopMonitoring(!0);return}l.preventDefault(),this._pointerMoveCallback(l)})),this._hooks.add(L(o,Y.POINTER_UP,l=>this.stopMonitoring(!0)))}};function Wo(s,t,e){let i=null,r=null;if(typeof e.value=="function"?(i="value",r=e.value,r.length!==0&&console.warn("Memoize should only be used in functions with zero parameters")):typeof e.get=="function"&&(i="get",r=e.get),!r)throw new Error("not supported");let n=`$memoize$${t}`;e[i]=function(...o){return this.hasOwnProperty(n)||Object.defineProperty(this,n,{configurable:!1,enumerable:!1,writable:!1,value:r.apply(this,o)}),this[n]}}var He;(n=>(n.Tap="-xterm-gesturetap",n.Change="-xterm-gesturechange",n.Start="-xterm-gesturestart",n.End="-xterm-gesturesend",n.Contextmenu="-xterm-gesturecontextmenu"))(He||={});var Q=class Q extends D{constructor(){super();this.dispatched=!1;this.targets=new Ct;this.ignoreTargets=new Ct;this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register($.runAndSubscribe(No,({window:e,disposables:i})=>{i.add(L(e.document,"touchstart",r=>this.onTouchStart(r),{passive:!1})),i.add(L(e.document,"touchend",r=>this.onTouchEnd(e,r))),i.add(L(e.document,"touchmove",r=>this.onTouchMove(r),{passive:!1}))},{window:fe,disposables:this._store}))}static addTarget(e){if(!Q.isTouchDevice())return D.None;Q.INSTANCE||(Q.INSTANCE=Gn(new Q));let i=Q.INSTANCE.targets.push(e);return C(i)}static ignoreTarget(e){if(!Q.isTouchDevice())return D.None;Q.INSTANCE||(Q.INSTANCE=Gn(new Q));let i=Q.INSTANCE.ignoreTargets.push(e);return C(i)}static isTouchDevice(){return"ontouchstart"in fe||navigator.maxTouchPoints>0}dispose(){this.handle&&(this.handle.dispose(),this.handle=null),super.dispose()}onTouchStart(e){let i=Date.now();this.handle&&(this.handle.dispose(),this.handle=null);for(let r=0,n=e.targetTouches.length;r=Q.HOLD_DELAY&&Math.abs(u.initialPageX-Se(u.rollingPageX))<30&&Math.abs(u.initialPageY-Se(u.rollingPageY))<30){let c=this.newGestureEvent(He.Contextmenu,u.initialTarget);c.pageX=Se(u.rollingPageX),c.pageY=Se(u.rollingPageY),this.dispatchEvent(c)}else if(n===1){let c=Se(u.rollingPageX),d=Se(u.rollingPageY),_=Se(u.rollingTimestamps)-u.rollingTimestamps[0],p=c-u.rollingPageX[0],m=d-u.rollingPageY[0],f=[...this.targets].filter(A=>u.initialTarget instanceof Node&&A.contains(u.initialTarget));this.inertia(e,f,r,Math.abs(p)/_,p>0?1:-1,c,Math.abs(m)/_,m>0?1:-1,d)}this.dispatchEvent(this.newGestureEvent(He.End,u.initialTarget)),delete this.activeTouches[a.identifier]}this.dispatched&&(i.preventDefault(),i.stopPropagation(),this.dispatched=!1)}newGestureEvent(e,i){let r=document.createEvent("CustomEvent");return r.initEvent(e,!1,!0),r.initialTarget=i,r.tapCount=0,r}dispatchEvent(e){if(e.type===He.Tap){let i=new Date().getTime(),r=0;i-this._lastSetTapCountTime>Q.CLEAR_TAP_COUNT_TIME?r=1:r=2,this._lastSetTapCountTime=i,e.tapCount=r}else(e.type===He.Change||e.type===He.Contextmenu)&&(this._lastSetTapCountTime=0);if(e.initialTarget instanceof Node){for(let r of this.ignoreTargets)if(r.contains(e.initialTarget))return;let i=[];for(let r of this.targets)if(r.contains(e.initialTarget)){let n=0,o=e.initialTarget;for(;o&&o!==r;)n++,o=o.parentElement;i.push([n,r])}i.sort((r,n)=>r[0]-n[0]);for(let[r,n]of i)n.dispatchEvent(e),this.dispatched=!0}}inertia(e,i,r,n,o,l,a,u,h){this.handle=mt(e,()=>{let c=Date.now(),d=c-r,_=0,p=0,m=!0;n+=Q.SCROLL_FRICTION*d,a+=Q.SCROLL_FRICTION*d,n>0&&(m=!1,_=o*n*d),a>0&&(m=!1,p=u*a*d);let f=this.newGestureEvent(He.Change);f.translationX=_,f.translationY=p,i.forEach(A=>A.dispatchEvent(f)),m||this.inertia(e,i,c,n,o,l+_,a,u,h+p)})}onTouchMove(e){let i=Date.now();for(let r=0,n=e.changedTouches.length;r3&&(l.rollingPageX.shift(),l.rollingPageY.shift(),l.rollingTimestamps.shift()),l.rollingPageX.push(o.pageX),l.rollingPageY.push(o.pageY),l.rollingTimestamps.push(i)}this.dispatched&&(e.preventDefault(),e.stopPropagation(),this.dispatched=!1)}};Q.SCROLL_FRICTION=-.005,Q.HOLD_DELAY=700,Q.CLEAR_TAP_COUNT_TIME=400,M([Wo],Q,"isTouchDevice",1);var Pr=Q;var lt=class extends D{onclick(t,e){this._register(L(t,Y.CLICK,i=>e(new qe(be(t),i))))}onmousedown(t,e){this._register(L(t,Y.MOUSE_DOWN,i=>e(new qe(be(t),i))))}onmouseover(t,e){this._register(L(t,Y.MOUSE_OVER,i=>e(new qe(be(t),i))))}onmouseleave(t,e){this._register(L(t,Y.MOUSE_LEAVE,i=>e(new qe(be(t),i))))}onkeydown(t,e){this._register(L(t,Y.KEY_DOWN,i=>e(new ft(i))))}onkeyup(t,e){this._register(L(t,Y.KEY_UP,i=>e(new ft(i))))}oninput(t,e){this._register(L(t,Y.INPUT,e))}onblur(t,e){this._register(L(t,Y.BLUR,e))}onfocus(t,e){this._register(L(t,Y.FOCUS,e))}onchange(t,e){this._register(L(t,Y.CHANGE,e))}ignoreGesture(t){return Pr.ignoreTarget(t)}};var Uo=11,Or=class extends lt{constructor(t){super(),this._onActivate=t.onActivate,this.bgDomNode=document.createElement("div"),this.bgDomNode.className="arrow-background",this.bgDomNode.style.position="absolute",this.bgDomNode.style.width=t.bgWidth+"px",this.bgDomNode.style.height=t.bgHeight+"px",typeof t.top<"u"&&(this.bgDomNode.style.top="0px"),typeof t.left<"u"&&(this.bgDomNode.style.left="0px"),typeof t.bottom<"u"&&(this.bgDomNode.style.bottom="0px"),typeof t.right<"u"&&(this.bgDomNode.style.right="0px"),this.domNode=document.createElement("div"),this.domNode.className=t.className,this.domNode.style.position="absolute",this.domNode.style.width=Uo+"px",this.domNode.style.height=Uo+"px",typeof t.top<"u"&&(this.domNode.style.top=t.top+"px"),typeof t.left<"u"&&(this.domNode.style.left=t.left+"px"),typeof t.bottom<"u"&&(this.domNode.style.bottom=t.bottom+"px"),typeof t.right<"u"&&(this.domNode.style.right=t.right+"px"),this._pointerMoveMonitor=this._register(new Wt),this._register(os(this.bgDomNode,Y.POINTER_DOWN,e=>this._arrowPointerDown(e))),this._register(os(this.domNode,Y.POINTER_DOWN,e=>this._arrowPointerDown(e))),this._pointerdownRepeatTimer=this._register(new Mr),this._pointerdownScheduleRepeatTimer=this._register(new Ye)}_arrowPointerDown(t){if(!t.target||!(t.target instanceof Element))return;let e=()=>{this._pointerdownRepeatTimer.cancelAndSet(()=>this._onActivate(),1e3/24,be(t))};this._onActivate(),this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancelAndSet(e,200),this._pointerMoveMonitor.startMonitoring(t.target,t.pointerId,t.buttons,i=>{},()=>{this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancel()}),t.preventDefault()}};var cs=class s{constructor(t,e,i,r,n,o,l){this._forceIntegerValues=t;this._scrollStateBrand=void 0;this._forceIntegerValues&&(e=e|0,i=i|0,r=r|0,n=n|0,o=o|0,l=l|0),this.rawScrollLeft=r,this.rawScrollTop=l,e<0&&(e=0),r+e>i&&(r=i-e),r<0&&(r=0),n<0&&(n=0),l+n>o&&(l=o-n),l<0&&(l=0),this.width=e,this.scrollWidth=i,this.scrollLeft=r,this.height=n,this.scrollHeight=o,this.scrollTop=l}equals(t){return this.rawScrollLeft===t.rawScrollLeft&&this.rawScrollTop===t.rawScrollTop&&this.width===t.width&&this.scrollWidth===t.scrollWidth&&this.scrollLeft===t.scrollLeft&&this.height===t.height&&this.scrollHeight===t.scrollHeight&&this.scrollTop===t.scrollTop}withScrollDimensions(t,e){return new s(this._forceIntegerValues,typeof t.width<"u"?t.width:this.width,typeof t.scrollWidth<"u"?t.scrollWidth:this.scrollWidth,e?this.rawScrollLeft:this.scrollLeft,typeof t.height<"u"?t.height:this.height,typeof t.scrollHeight<"u"?t.scrollHeight:this.scrollHeight,e?this.rawScrollTop:this.scrollTop)}withScrollPosition(t){return new s(this._forceIntegerValues,this.width,this.scrollWidth,typeof t.scrollLeft<"u"?t.scrollLeft:this.rawScrollLeft,this.height,this.scrollHeight,typeof t.scrollTop<"u"?t.scrollTop:this.rawScrollTop)}createScrollEvent(t,e){let i=this.width!==t.width,r=this.scrollWidth!==t.scrollWidth,n=this.scrollLeft!==t.scrollLeft,o=this.height!==t.height,l=this.scrollHeight!==t.scrollHeight,a=this.scrollTop!==t.scrollTop;return{inSmoothScrolling:e,oldWidth:t.width,oldScrollWidth:t.scrollWidth,oldScrollLeft:t.scrollLeft,width:this.width,scrollWidth:this.scrollWidth,scrollLeft:this.scrollLeft,oldHeight:t.height,oldScrollHeight:t.scrollHeight,oldScrollTop:t.scrollTop,height:this.height,scrollHeight:this.scrollHeight,scrollTop:this.scrollTop,widthChanged:i,scrollWidthChanged:r,scrollLeftChanged:n,heightChanged:o,scrollHeightChanged:l,scrollTopChanged:a}}},Ri=class extends D{constructor(e){super();this._scrollableBrand=void 0;this._onScroll=this._register(new v);this.onScroll=this._onScroll.event;this._smoothScrollDuration=e.smoothScrollDuration,this._scheduleAtNextAnimationFrame=e.scheduleAtNextAnimationFrame,this._state=new cs(e.forceIntegerValues,0,0,0,0,0,0),this._smoothScrolling=null}dispose(){this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),super.dispose()}setSmoothScrollDuration(e){this._smoothScrollDuration=e}validateScrollPosition(e){return this._state.withScrollPosition(e)}getScrollDimensions(){return this._state}setScrollDimensions(e,i){let r=this._state.withScrollDimensions(e,i);this._setState(r,!!this._smoothScrolling),this._smoothScrolling?.acceptScrollDimensions(this._state)}getFutureScrollPosition(){return this._smoothScrolling?this._smoothScrolling.to:this._state}getCurrentScrollPosition(){return this._state}setScrollPositionNow(e){let i=this._state.withScrollPosition(e);this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),this._setState(i,!1)}setScrollPositionSmooth(e,i){if(this._smoothScrollDuration===0)return this.setScrollPositionNow(e);if(this._smoothScrolling){e={scrollLeft:typeof e.scrollLeft>"u"?this._smoothScrolling.to.scrollLeft:e.scrollLeft,scrollTop:typeof e.scrollTop>"u"?this._smoothScrolling.to.scrollTop:e.scrollTop};let r=this._state.withScrollPosition(e);if(this._smoothScrolling.to.scrollLeft===r.scrollLeft&&this._smoothScrolling.to.scrollTop===r.scrollTop)return;let n;i?n=new Nr(this._smoothScrolling.from,r,this._smoothScrolling.startTime,this._smoothScrolling.duration):n=this._smoothScrolling.combine(this._state,r,this._smoothScrollDuration),this._smoothScrolling.dispose(),this._smoothScrolling=n}else{let r=this._state.withScrollPosition(e);this._smoothScrolling=Nr.start(this._state,r,this._smoothScrollDuration)}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}hasPendingScrollAnimation(){return!!this._smoothScrolling}_performSmoothScrolling(){if(!this._smoothScrolling)return;let e=this._smoothScrolling.tick(),i=this._state.withScrollPosition(e);if(this._setState(i,!0),!!this._smoothScrolling){if(e.isDone){this._smoothScrolling.dispose(),this._smoothScrolling=null;return}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}}_setState(e,i){let r=this._state;r.equals(e)||(this._state=e,this._onScroll.fire(this._state.createScrollEvent(r,i)))}},Br=class{constructor(t,e,i){this.scrollLeft=t,this.scrollTop=e,this.isDone=i}};function as(s,t){let e=t-s;return function(i){return s+e*ka(i)}}function La(s,t,e){return function(i){return i2.5*i){let n,o;return t{this._domNode?.setClassName(this._visibleClassName)},0))}_hide(t){this._revealTimer.cancel(),this._isVisible&&(this._isVisible=!1,this._domNode?.setClassName(this._invisibleClassName+(t?" fade":"")))}};var Ca=140,Ut=class extends lt{constructor(t){super(),this._lazyRender=t.lazyRender,this._host=t.host,this._scrollable=t.scrollable,this._scrollByPage=t.scrollByPage,this._scrollbarState=t.scrollbarState,this._visibilityController=this._register(new Fr(t.visibility,"visible scrollbar "+t.extraScrollbarClassName,"invisible scrollbar "+t.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new Wt),this._shouldRender=!0,this.domNode=_t(document.createElement("div")),this.domNode.setAttribute("role","presentation"),this.domNode.setAttribute("aria-hidden","true"),this._visibilityController.setDomNode(this.domNode),this.domNode.setPosition("absolute"),this._register(L(this.domNode.domNode,Y.POINTER_DOWN,e=>this._domNodePointerDown(e)))}_createArrow(t){let e=this._register(new Or(t));this.domNode.domNode.appendChild(e.bgDomNode),this.domNode.domNode.appendChild(e.domNode)}_createSlider(t,e,i,r){this.slider=_t(document.createElement("div")),this.slider.setClassName("slider"),this.slider.setPosition("absolute"),this.slider.setTop(t),this.slider.setLeft(e),typeof i=="number"&&this.slider.setWidth(i),typeof r=="number"&&this.slider.setHeight(r),this.slider.setLayerHinting(!0),this.slider.setContain("strict"),this.domNode.domNode.appendChild(this.slider.domNode),this._register(L(this.slider.domNode,Y.POINTER_DOWN,n=>{n.button===0&&(n.preventDefault(),this._sliderPointerDown(n))})),this.onclick(this.slider.domNode,n=>{n.leftButton&&n.stopPropagation()})}_onElementSize(t){return this._scrollbarState.setVisibleSize(t)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollSize(t){return this._scrollbarState.setScrollSize(t)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollPosition(t){return this._scrollbarState.setScrollPosition(t)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}beginReveal(){this._visibilityController.setShouldBeVisible(!0)}beginHide(){this._visibilityController.setShouldBeVisible(!1)}render(){this._shouldRender&&(this._shouldRender=!1,this._renderDomNode(this._scrollbarState.getRectangleLargeSize(),this._scrollbarState.getRectangleSmallSize()),this._updateSlider(this._scrollbarState.getSliderSize(),this._scrollbarState.getArrowSize()+this._scrollbarState.getSliderPosition()))}_domNodePointerDown(t){t.target===this.domNode.domNode&&this._onPointerDown(t)}delegatePointerDown(t){let e=this.domNode.domNode.getClientRects()[0].top,i=e+this._scrollbarState.getSliderPosition(),r=e+this._scrollbarState.getSliderPosition()+this._scrollbarState.getSliderSize(),n=this._sliderPointerPosition(t);i<=n&&n<=r?t.button===0&&(t.preventDefault(),this._sliderPointerDown(t)):this._onPointerDown(t)}_onPointerDown(t){let e,i;if(t.target===this.domNode.domNode&&typeof t.offsetX=="number"&&typeof t.offsetY=="number")e=t.offsetX,i=t.offsetY;else{let n=Fo(this.domNode.domNode);e=t.pageX-n.left,i=t.pageY-n.top}let r=this._pointerDownRelativePosition(e,i);this._setDesiredScrollPositionNow(this._scrollByPage?this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(r):this._scrollbarState.getDesiredScrollPositionFromOffset(r)),t.button===0&&(t.preventDefault(),this._sliderPointerDown(t))}_sliderPointerDown(t){if(!t.target||!(t.target instanceof Element))return;let e=this._sliderPointerPosition(t),i=this._sliderOrthogonalPointerPosition(t),r=this._scrollbarState.clone();this.slider.toggleClassName("active",!0),this._pointerMoveMonitor.startMonitoring(t.target,t.pointerId,t.buttons,n=>{let o=this._sliderOrthogonalPointerPosition(n),l=Math.abs(o-i);if(wr&&l>Ca){this._setDesiredScrollPositionNow(r.getScrollPosition());return}let u=this._sliderPointerPosition(n)-e;this._setDesiredScrollPositionNow(r.getDesiredScrollPositionFromDelta(u))},()=>{this.slider.toggleClassName("active",!1),this._host.onDragEnd()}),this._host.onDragStart()}_setDesiredScrollPositionNow(t){let e={};this.writeScrollPosition(e,t),this._scrollable.setScrollPositionNow(e)}updateScrollbarSize(t){this._updateScrollbarSize(t),this._scrollbarState.setScrollbarSize(t),this._shouldRender=!0,this._lazyRender||this.render()}isNeeded(){return this._scrollbarState.isNeeded()}};var Kt=class s{constructor(t,e,i,r,n,o){this._scrollbarSize=Math.round(e),this._oppositeScrollbarSize=Math.round(i),this._arrowSize=Math.round(t),this._visibleSize=r,this._scrollSize=n,this._scrollPosition=o,this._computedAvailableSize=0,this._computedIsNeeded=!1,this._computedSliderSize=0,this._computedSliderRatio=0,this._computedSliderPosition=0,this._refreshComputedValues()}clone(){return new s(this._arrowSize,this._scrollbarSize,this._oppositeScrollbarSize,this._visibleSize,this._scrollSize,this._scrollPosition)}setVisibleSize(t){let e=Math.round(t);return this._visibleSize!==e?(this._visibleSize=e,this._refreshComputedValues(),!0):!1}setScrollSize(t){let e=Math.round(t);return this._scrollSize!==e?(this._scrollSize=e,this._refreshComputedValues(),!0):!1}setScrollPosition(t){let e=Math.round(t);return this._scrollPosition!==e?(this._scrollPosition=e,this._refreshComputedValues(),!0):!1}setScrollbarSize(t){this._scrollbarSize=Math.round(t)}setOppositeScrollbarSize(t){this._oppositeScrollbarSize=Math.round(t)}static _computeValues(t,e,i,r,n){let o=Math.max(0,i-t),l=Math.max(0,o-2*e),a=r>0&&r>i;if(!a)return{computedAvailableSize:Math.round(o),computedIsNeeded:a,computedSliderSize:Math.round(l),computedSliderRatio:0,computedSliderPosition:0};let u=Math.round(Math.max(20,Math.floor(i*l/r))),h=(l-u)/(r-i),c=n*h;return{computedAvailableSize:Math.round(o),computedIsNeeded:a,computedSliderSize:Math.round(u),computedSliderRatio:h,computedSliderPosition:Math.round(c)}}_refreshComputedValues(){let t=s._computeValues(this._oppositeScrollbarSize,this._arrowSize,this._visibleSize,this._scrollSize,this._scrollPosition);this._computedAvailableSize=t.computedAvailableSize,this._computedIsNeeded=t.computedIsNeeded,this._computedSliderSize=t.computedSliderSize,this._computedSliderRatio=t.computedSliderRatio,this._computedSliderPosition=t.computedSliderPosition}getArrowSize(){return this._arrowSize}getScrollPosition(){return this._scrollPosition}getRectangleLargeSize(){return this._computedAvailableSize}getRectangleSmallSize(){return this._scrollbarSize}isNeeded(){return this._computedIsNeeded}getSliderSize(){return this._computedSliderSize}getSliderPosition(){return this._computedSliderPosition}getDesiredScrollPositionFromOffset(t){if(!this._computedIsNeeded)return 0;let e=t-this._arrowSize-this._computedSliderSize/2;return Math.round(e/this._computedSliderRatio)}getDesiredScrollPositionFromOffsetPaged(t){if(!this._computedIsNeeded)return 0;let e=t-this._arrowSize,i=this._scrollPosition;return e0&&Math.abs(t.deltaY)>0)return 1;let i=.5;if((!this._isAlmostInt(t.deltaX)||!this._isAlmostInt(t.deltaY))&&(i+=.25),e){let r=Math.abs(t.deltaX),n=Math.abs(t.deltaY),o=Math.abs(e.deltaX),l=Math.abs(e.deltaY),a=Math.max(Math.min(r,o),1),u=Math.max(Math.min(n,l),1),h=Math.max(r,o),c=Math.max(n,l);h%a===0&&c%u===0&&(i-=.5)}return Math.min(Math.max(i,0),1)}_isAlmostInt(t){return Math.abs(Math.round(t)-t)<.01}};zr.INSTANCE=new zr;var hs=zr,ds=class extends lt{constructor(e,i,r){super();this._onScroll=this._register(new v);this.onScroll=this._onScroll.event;this._onWillScroll=this._register(new v);this.onWillScroll=this._onWillScroll.event;this._options=Pa(i),this._scrollable=r,this._register(this._scrollable.onScroll(o=>{this._onWillScroll.fire(o),this._onDidScroll(o),this._onScroll.fire(o)}));let n={onMouseWheel:o=>this._onMouseWheel(o),onDragStart:()=>this._onDragStart(),onDragEnd:()=>this._onDragEnd()};this._verticalScrollbar=this._register(new Ur(this._scrollable,this._options,n)),this._horizontalScrollbar=this._register(new Wr(this._scrollable,this._options,n)),this._domNode=document.createElement("div"),this._domNode.className="xterm-scrollable-element "+this._options.className,this._domNode.setAttribute("role","presentation"),this._domNode.style.position="relative",this._domNode.appendChild(e),this._domNode.appendChild(this._horizontalScrollbar.domNode.domNode),this._domNode.appendChild(this._verticalScrollbar.domNode.domNode),this._options.useShadows?(this._leftShadowDomNode=_t(document.createElement("div")),this._leftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=_t(document.createElement("div")),this._topShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=_t(document.createElement("div")),this._topLeftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topLeftShadowDomNode.domNode)):(this._leftShadowDomNode=null,this._topShadowDomNode=null,this._topLeftShadowDomNode=null),this._listenOnDomNode=this._options.listenOnDomNode||this._domNode,this._mouseWheelToDispose=[],this._setListeningToMouseWheel(this._options.handleMouseWheel),this.onmouseover(this._listenOnDomNode,o=>this._onMouseOver(o)),this.onmouseleave(this._listenOnDomNode,o=>this._onMouseLeave(o)),this._hideTimeout=this._register(new Ye),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}get options(){return this._options}dispose(){this._mouseWheelToDispose=Ne(this._mouseWheelToDispose),super.dispose()}getDomNode(){return this._domNode}getOverviewRulerLayoutInfo(){return{parent:this._domNode,insertBefore:this._verticalScrollbar.domNode.domNode}}delegateVerticalScrollbarPointerDown(e){this._verticalScrollbar.delegatePointerDown(e)}getScrollDimensions(){return this._scrollable.getScrollDimensions()}setScrollDimensions(e){this._scrollable.setScrollDimensions(e,!1)}updateClassName(e){this._options.className=e,Te&&(this._options.className+=" mac"),this._domNode.className="xterm-scrollable-element "+this._options.className}updateOptions(e){typeof e.handleMouseWheel<"u"&&(this._options.handleMouseWheel=e.handleMouseWheel,this._setListeningToMouseWheel(this._options.handleMouseWheel)),typeof e.mouseWheelScrollSensitivity<"u"&&(this._options.mouseWheelScrollSensitivity=e.mouseWheelScrollSensitivity),typeof e.fastScrollSensitivity<"u"&&(this._options.fastScrollSensitivity=e.fastScrollSensitivity),typeof e.scrollPredominantAxis<"u"&&(this._options.scrollPredominantAxis=e.scrollPredominantAxis),typeof e.horizontal<"u"&&(this._options.horizontal=e.horizontal),typeof e.vertical<"u"&&(this._options.vertical=e.vertical),typeof e.horizontalScrollbarSize<"u"&&(this._options.horizontalScrollbarSize=e.horizontalScrollbarSize),typeof e.verticalScrollbarSize<"u"&&(this._options.verticalScrollbarSize=e.verticalScrollbarSize),typeof e.scrollByPage<"u"&&(this._options.scrollByPage=e.scrollByPage),this._horizontalScrollbar.updateOptions(this._options),this._verticalScrollbar.updateOptions(this._options),this._options.lazyRender||this._render()}setRevealOnScroll(e){this._revealOnScroll=e}delegateScrollFromMouseWheelEvent(e){this._onMouseWheel(new xi(e))}_setListeningToMouseWheel(e){if(this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=Ne(this._mouseWheelToDispose),e)){let r=n=>{this._onMouseWheel(new xi(n))};this._mouseWheelToDispose.push(L(this._listenOnDomNode,Y.MOUSE_WHEEL,r,{passive:!1}))}}_onMouseWheel(e){if(e.browserEvent?.defaultPrevented)return;let i=hs.INSTANCE;zo&&i.acceptStandardWheelEvent(e);let r=!1;if(e.deltaY||e.deltaX){let o=e.deltaY*this._options.mouseWheelScrollSensitivity,l=e.deltaX*this._options.mouseWheelScrollSensitivity;this._options.scrollPredominantAxis&&(this._options.scrollYToX&&l+o===0?l=o=0:Math.abs(o)>=Math.abs(l)?l=0:o=0),this._options.flipAxes&&([o,l]=[l,o]);let a=!Te&&e.browserEvent&&e.browserEvent.shiftKey;(this._options.scrollYToX||a)&&!l&&(l=o,o=0),e.browserEvent&&e.browserEvent.altKey&&(l=l*this._options.fastScrollSensitivity,o=o*this._options.fastScrollSensitivity);let u=this._scrollable.getFutureScrollPosition(),h={};if(o){let c=Ko*o,d=u.scrollTop-(c<0?Math.floor(c):Math.ceil(c));this._verticalScrollbar.writeScrollPosition(h,d)}if(l){let c=Ko*l,d=u.scrollLeft-(c<0?Math.floor(c):Math.ceil(c));this._horizontalScrollbar.writeScrollPosition(h,d)}h=this._scrollable.validateScrollPosition(h),(u.scrollLeft!==h.scrollLeft||u.scrollTop!==h.scrollTop)&&(zo&&this._options.mouseWheelSmoothScroll&&i.isPhysicalMouseWheel()?this._scrollable.setScrollPositionSmooth(h):this._scrollable.setScrollPositionNow(h),r=!0)}let n=r;!n&&this._options.alwaysConsumeMouseWheel&&(n=!0),!n&&this._options.consumeMouseWheelIfScrollbarIsNeeded&&(this._verticalScrollbar.isNeeded()||this._horizontalScrollbar.isNeeded())&&(n=!0),n&&(e.preventDefault(),e.stopPropagation())}_onDidScroll(e){this._shouldRender=this._horizontalScrollbar.onDidScroll(e)||this._shouldRender,this._shouldRender=this._verticalScrollbar.onDidScroll(e)||this._shouldRender,this._options.useShadows&&(this._shouldRender=!0),this._revealOnScroll&&this._reveal(),this._options.lazyRender||this._render()}renderNow(){if(!this._options.lazyRender)throw new Error("Please use `lazyRender` together with `renderNow`!");this._render()}_render(){if(this._shouldRender&&(this._shouldRender=!1,this._horizontalScrollbar.render(),this._verticalScrollbar.render(),this._options.useShadows)){let e=this._scrollable.getCurrentScrollPosition(),i=e.scrollTop>0,r=e.scrollLeft>0,n=r?" left":"",o=i?" top":"",l=r||i?" top-left-corner":"";this._leftShadowDomNode.setClassName(`shadow${n}`),this._topShadowDomNode.setClassName(`shadow${o}`),this._topLeftShadowDomNode.setClassName(`shadow${l}${o}${n}`)}}_onDragStart(){this._isDragging=!0,this._reveal()}_onDragEnd(){this._isDragging=!1,this._hide()}_onMouseLeave(e){this._mouseIsOver=!1,this._hide()}_onMouseOver(e){this._mouseIsOver=!0,this._reveal()}_reveal(){this._verticalScrollbar.beginReveal(),this._horizontalScrollbar.beginReveal(),this._scheduleHide()}_hide(){!this._mouseIsOver&&!this._isDragging&&(this._verticalScrollbar.beginHide(),this._horizontalScrollbar.beginHide())}_scheduleHide(){!this._mouseIsOver&&!this._isDragging&&this._hideTimeout.cancelAndSet(()=>this._hide(),Ma)}};var Kr=class extends ds{constructor(t,e,i){super(t,e,i)}setScrollPosition(t){t.reuseAnimation?this._scrollable.setScrollPositionSmooth(t,t.reuseAnimation):this._scrollable.setScrollPositionNow(t)}getScrollPosition(){return this._scrollable.getCurrentScrollPosition()}};function Pa(s){let t={lazyRender:typeof s.lazyRender<"u"?s.lazyRender:!1,className:typeof s.className<"u"?s.className:"",useShadows:typeof s.useShadows<"u"?s.useShadows:!0,handleMouseWheel:typeof s.handleMouseWheel<"u"?s.handleMouseWheel:!0,flipAxes:typeof s.flipAxes<"u"?s.flipAxes:!1,consumeMouseWheelIfScrollbarIsNeeded:typeof s.consumeMouseWheelIfScrollbarIsNeeded<"u"?s.consumeMouseWheelIfScrollbarIsNeeded:!1,alwaysConsumeMouseWheel:typeof s.alwaysConsumeMouseWheel<"u"?s.alwaysConsumeMouseWheel:!1,scrollYToX:typeof s.scrollYToX<"u"?s.scrollYToX:!1,mouseWheelScrollSensitivity:typeof s.mouseWheelScrollSensitivity<"u"?s.mouseWheelScrollSensitivity:1,fastScrollSensitivity:typeof s.fastScrollSensitivity<"u"?s.fastScrollSensitivity:5,scrollPredominantAxis:typeof s.scrollPredominantAxis<"u"?s.scrollPredominantAxis:!0,mouseWheelSmoothScroll:typeof s.mouseWheelSmoothScroll<"u"?s.mouseWheelSmoothScroll:!0,arrowSize:typeof s.arrowSize<"u"?s.arrowSize:11,listenOnDomNode:typeof s.listenOnDomNode<"u"?s.listenOnDomNode:null,horizontal:typeof s.horizontal<"u"?s.horizontal:1,horizontalScrollbarSize:typeof s.horizontalScrollbarSize<"u"?s.horizontalScrollbarSize:10,horizontalSliderSize:typeof s.horizontalSliderSize<"u"?s.horizontalSliderSize:0,horizontalHasArrows:typeof s.horizontalHasArrows<"u"?s.horizontalHasArrows:!1,vertical:typeof s.vertical<"u"?s.vertical:1,verticalScrollbarSize:typeof s.verticalScrollbarSize<"u"?s.verticalScrollbarSize:10,verticalHasArrows:typeof s.verticalHasArrows<"u"?s.verticalHasArrows:!1,verticalSliderSize:typeof s.verticalSliderSize<"u"?s.verticalSliderSize:0,scrollByPage:typeof s.scrollByPage<"u"?s.scrollByPage:!1};return t.horizontalSliderSize=typeof s.horizontalSliderSize<"u"?s.horizontalSliderSize:t.horizontalScrollbarSize,t.verticalSliderSize=typeof s.verticalSliderSize<"u"?s.verticalSliderSize:t.verticalScrollbarSize,Te&&(t.className+=" mac"),t}var zt=class extends D{constructor(e,i,r,n,o,l,a,u){super();this._bufferService=r;this._optionsService=a;this._renderService=u;this._onRequestScrollLines=this._register(new v);this.onRequestScrollLines=this._onRequestScrollLines.event;this._isSyncing=!1;this._isHandlingScroll=!1;this._suppressOnScrollHandler=!1;let h=this._register(new Ri({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:c=>mt(n.window,c)}));this._register(this._optionsService.onSpecificOptionChange("smoothScrollDuration",()=>{h.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)})),this._scrollableElement=this._register(new Kr(i,{vertical:1,horizontal:2,useShadows:!1,mouseWheelSmoothScroll:!0,...this._getChangeOptions()},h)),this._register(this._optionsService.onMultipleOptionChange(["scrollSensitivity","fastScrollSensitivity","overviewRuler"],()=>this._scrollableElement.updateOptions(this._getChangeOptions()))),this._register(o.onProtocolChange(c=>{this._scrollableElement.updateOptions({handleMouseWheel:!(c&16)})})),this._scrollableElement.setScrollDimensions({height:0,scrollHeight:0}),this._register($.runAndSubscribe(l.onChangeColors,()=>{this._scrollableElement.getDomNode().style.backgroundColor=l.colors.background.css})),e.appendChild(this._scrollableElement.getDomNode()),this._register(C(()=>this._scrollableElement.getDomNode().remove())),this._styleElement=n.mainDocument.createElement("style"),i.appendChild(this._styleElement),this._register(C(()=>this._styleElement.remove())),this._register($.runAndSubscribe(l.onChangeColors,()=>{this._styleElement.textContent=[".xterm .xterm-scrollable-element > .scrollbar > .slider {",` background: ${l.colors.scrollbarSliderBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider:hover {",` background: ${l.colors.scrollbarSliderHoverBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider.active {",` background: ${l.colors.scrollbarSliderActiveBackground.css};`,"}"].join(` +`)})),this._register(this._bufferService.onResize(()=>this.queueSync())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._latestYDisp=void 0,this.queueSync()})),this._register(this._bufferService.onScroll(()=>this._sync())),this._register(this._scrollableElement.onScroll(c=>this._handleScroll(c)))}scrollLines(e){let i=this._scrollableElement.getScrollPosition();this._scrollableElement.setScrollPosition({reuseAnimation:!0,scrollTop:i.scrollTop+e*this._renderService.dimensions.css.cell.height})}scrollToLine(e,i){i&&(this._latestYDisp=e),this._scrollableElement.setScrollPosition({reuseAnimation:!i,scrollTop:e*this._renderService.dimensions.css.cell.height})}_getChangeOptions(){return{mouseWheelScrollSensitivity:this._optionsService.rawOptions.scrollSensitivity,fastScrollSensitivity:this._optionsService.rawOptions.fastScrollSensitivity,verticalScrollbarSize:this._optionsService.rawOptions.overviewRuler?.width||14}}queueSync(e){e!==void 0&&(this._latestYDisp=e),this._queuedAnimationFrame===void 0&&(this._queuedAnimationFrame=this._renderService.addRefreshCallback(()=>{this._queuedAnimationFrame=void 0,this._sync(this._latestYDisp)}))}_sync(e=this._bufferService.buffer.ydisp){!this._renderService||this._isSyncing||(this._isSyncing=!0,this._suppressOnScrollHandler=!0,this._scrollableElement.setScrollDimensions({height:this._renderService.dimensions.css.canvas.height,scrollHeight:this._renderService.dimensions.css.cell.height*this._bufferService.buffer.lines.length}),this._suppressOnScrollHandler=!1,e!==this._latestYDisp&&this._scrollableElement.setScrollPosition({scrollTop:e*this._renderService.dimensions.css.cell.height}),this._isSyncing=!1)}_handleScroll(e){if(!this._renderService||this._isHandlingScroll||this._suppressOnScrollHandler)return;this._isHandlingScroll=!0;let i=Math.round(e.scrollTop/this._renderService.dimensions.css.cell.height),r=i-this._bufferService.buffer.ydisp;r!==0&&(this._latestYDisp=i,this._onRequestScrollLines.fire(r)),this._isHandlingScroll=!1}};zt=M([S(2,F),S(3,ae),S(4,rr),S(5,Re),S(6,H),S(7,ce)],zt);var Gt=class extends D{constructor(e,i,r,n,o){super();this._screenElement=e;this._bufferService=i;this._coreBrowserService=r;this._decorationService=n;this._renderService=o;this._decorationElements=new Map;this._altBufferIsActive=!1;this._dimensionsChanged=!1;this._container=document.createElement("div"),this._container.classList.add("xterm-decoration-container"),this._screenElement.appendChild(this._container),this._register(this._renderService.onRenderedViewportChange(()=>this._doRefreshDecorations())),this._register(this._renderService.onDimensionsChange(()=>{this._dimensionsChanged=!0,this._queueRefresh()})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt})),this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh())),this._register(this._decorationService.onDecorationRemoved(l=>this._removeDecoration(l))),this._register(C(()=>{this._container.remove(),this._decorationElements.clear()}))}_queueRefresh(){this._animationFrame===void 0&&(this._animationFrame=this._renderService.addRefreshCallback(()=>{this._doRefreshDecorations(),this._animationFrame=void 0}))}_doRefreshDecorations(){for(let e of this._decorationService.decorations)this._renderDecoration(e);this._dimensionsChanged=!1}_renderDecoration(e){this._refreshStyle(e),this._dimensionsChanged&&this._refreshXPosition(e)}_createElement(e){let i=this._coreBrowserService.mainDocument.createElement("div");i.classList.add("xterm-decoration"),i.classList.toggle("xterm-decoration-top-layer",e?.options?.layer==="top"),i.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,i.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,i.style.top=`${(e.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height}px`,i.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;let r=e.options.x??0;return r&&r>this._bufferService.cols&&(i.style.display="none"),this._refreshXPosition(e,i),i}_refreshStyle(e){let i=e.marker.line-this._bufferService.buffers.active.ydisp;if(i<0||i>=this._bufferService.rows)e.element&&(e.element.style.display="none",e.onRenderEmitter.fire(e.element));else{let r=this._decorationElements.get(e);r||(r=this._createElement(e),e.element=r,this._decorationElements.set(e,r),this._container.appendChild(r),e.onDispose(()=>{this._decorationElements.delete(e),r.remove()})),r.style.display=this._altBufferIsActive?"none":"block",this._altBufferIsActive||(r.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,r.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,r.style.top=`${i*this._renderService.dimensions.css.cell.height}px`,r.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`),e.onRenderEmitter.fire(r)}}_refreshXPosition(e,i=e.element){if(!i)return;let r=e.options.x??0;(e.options.anchor||"left")==="right"?i.style.right=r?`${r*this._renderService.dimensions.css.cell.width}px`:"":i.style.left=r?`${r*this._renderService.dimensions.css.cell.width}px`:""}_removeDecoration(e){this._decorationElements.get(e)?.remove(),this._decorationElements.delete(e),e.dispose()}};Gt=M([S(1,F),S(2,ae),S(3,Be),S(4,ce)],Gt);var Gr=class{constructor(){this._zones=[];this._zonePool=[];this._zonePoolIndex=0;this._linePadding={full:0,left:0,center:0,right:0}}get zones(){return this._zonePool.length=Math.min(this._zonePool.length,this._zones.length),this._zones}clear(){this._zones.length=0,this._zonePoolIndex=0}addDecoration(t){if(t.options.overviewRulerOptions){for(let e of this._zones)if(e.color===t.options.overviewRulerOptions.color&&e.position===t.options.overviewRulerOptions.position){if(this._lineIntersectsZone(e,t.marker.line))return;if(this._lineAdjacentToZone(e,t.marker.line,t.options.overviewRulerOptions.position)){this._addLineToZone(e,t.marker.line);return}}if(this._zonePoolIndex=t.startBufferLine&&e<=t.endBufferLine}_lineAdjacentToZone(t,e,i){return e>=t.startBufferLine-this._linePadding[i||"full"]&&e<=t.endBufferLine+this._linePadding[i||"full"]}_addLineToZone(t,e){t.startBufferLine=Math.min(t.startBufferLine,e),t.endBufferLine=Math.max(t.endBufferLine,e)}};var We={full:0,left:0,center:0,right:0},at={full:0,left:0,center:0,right:0},Li={full:0,left:0,center:0,right:0},bt=class extends D{constructor(e,i,r,n,o,l,a,u){super();this._viewportElement=e;this._screenElement=i;this._bufferService=r;this._decorationService=n;this._renderService=o;this._optionsService=l;this._themeService=a;this._coreBrowserService=u;this._colorZoneStore=new Gr;this._shouldUpdateDimensions=!0;this._shouldUpdateAnchor=!0;this._lastKnownBufferLength=0;this._canvas=this._coreBrowserService.mainDocument.createElement("canvas"),this._canvas.classList.add("xterm-decoration-overview-ruler"),this._refreshCanvasDimensions(),this._viewportElement.parentElement?.insertBefore(this._canvas,this._viewportElement),this._register(C(()=>this._canvas?.remove()));let h=this._canvas.getContext("2d");if(h)this._ctx=h;else throw new Error("Ctx cannot be null");this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh(void 0,!0))),this._register(this._decorationService.onDecorationRemoved(()=>this._queueRefresh(void 0,!0))),this._register(this._renderService.onRenderedViewportChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._canvas.style.display=this._bufferService.buffer===this._bufferService.buffers.alt?"none":"block"})),this._register(this._bufferService.onScroll(()=>{this._lastKnownBufferLength!==this._bufferService.buffers.normal.lines.length&&(this._refreshDrawHeightConstants(),this._refreshColorZonePadding())})),this._register(this._renderService.onRender(()=>{(!this._containerHeight||this._containerHeight!==this._screenElement.clientHeight)&&(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh(!0))),this._register(this._optionsService.onSpecificOptionChange("overviewRuler",()=>this._queueRefresh(!0))),this._register(this._themeService.onChangeColors(()=>this._queueRefresh())),this._queueRefresh(!0)}get _width(){return this._optionsService.options.overviewRuler?.width||0}_refreshDrawConstants(){let e=Math.floor((this._canvas.width-1)/3),i=Math.ceil((this._canvas.width-1)/3);at.full=this._canvas.width,at.left=e,at.center=i,at.right=e,this._refreshDrawHeightConstants(),Li.full=1,Li.left=1,Li.center=1+at.left,Li.right=1+at.left+at.center}_refreshDrawHeightConstants(){We.full=Math.round(2*this._coreBrowserService.dpr);let e=this._canvas.height/this._bufferService.buffer.lines.length,i=Math.round(Math.max(Math.min(e,12),6)*this._coreBrowserService.dpr);We.left=i,We.center=i,We.right=i}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*We.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*We.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*We.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*We.right)}),this._lastKnownBufferLength=this._bufferService.buffers.normal.lines.length}_refreshCanvasDimensions(){this._canvas.style.width=`${this._width}px`,this._canvas.width=Math.round(this._width*this._coreBrowserService.dpr),this._canvas.style.height=`${this._screenElement.clientHeight}px`,this._canvas.height=Math.round(this._screenElement.clientHeight*this._coreBrowserService.dpr),this._refreshDrawConstants(),this._refreshColorZonePadding()}_refreshDecorations(){this._shouldUpdateDimensions&&this._refreshCanvasDimensions(),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._colorZoneStore.clear();for(let i of this._decorationService.decorations)this._colorZoneStore.addDecoration(i);this._ctx.lineWidth=1,this._renderRulerOutline();let e=this._colorZoneStore.zones;for(let i of e)i.position!=="full"&&this._renderColorZone(i);for(let i of e)i.position==="full"&&this._renderColorZone(i);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderRulerOutline(){this._ctx.fillStyle=this._themeService.colors.overviewRulerBorder.css,this._ctx.fillRect(0,0,1,this._canvas.height),this._optionsService.rawOptions.overviewRuler.showTopBorder&&this._ctx.fillRect(1,0,this._canvas.width-1,1),this._optionsService.rawOptions.overviewRuler.showBottomBorder&&this._ctx.fillRect(1,this._canvas.height-1,this._canvas.width-1,this._canvas.height)}_renderColorZone(e){this._ctx.fillStyle=e.color,this._ctx.fillRect(Li[e.position||"full"],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-We[e.position||"full"]/2),at[e.position||"full"],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+We[e.position||"full"]))}_queueRefresh(e,i){this._shouldUpdateDimensions=e||this._shouldUpdateDimensions,this._shouldUpdateAnchor=i||this._shouldUpdateAnchor,this._animationFrame===void 0&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._refreshDecorations(),this._animationFrame=void 0}))}};bt=M([S(2,F),S(3,Be),S(4,ce),S(5,H),S(6,Re),S(7,ae)],bt);var b;(E=>(E.NUL="\0",E.SOH="",E.STX="",E.ETX="",E.EOT="",E.ENQ="",E.ACK="",E.BEL="\x07",E.BS="\b",E.HT=" ",E.LF=` +`,E.VT="\v",E.FF="\f",E.CR="\r",E.SO="",E.SI="",E.DLE="",E.DC1="",E.DC2="",E.DC3="",E.DC4="",E.NAK="",E.SYN="",E.ETB="",E.CAN="",E.EM="",E.SUB="",E.ESC="\x1B",E.FS="",E.GS="",E.RS="",E.US="",E.SP=" ",E.DEL="\x7F"))(b||={});var Ai;(g=>(g.PAD="\x80",g.HOP="\x81",g.BPH="\x82",g.NBH="\x83",g.IND="\x84",g.NEL="\x85",g.SSA="\x86",g.ESA="\x87",g.HTS="\x88",g.HTJ="\x89",g.VTS="\x8A",g.PLD="\x8B",g.PLU="\x8C",g.RI="\x8D",g.SS2="\x8E",g.SS3="\x8F",g.DCS="\x90",g.PU1="\x91",g.PU2="\x92",g.STS="\x93",g.CCH="\x94",g.MW="\x95",g.SPA="\x96",g.EPA="\x97",g.SOS="\x98",g.SGCI="\x99",g.SCI="\x9A",g.CSI="\x9B",g.ST="\x9C",g.OSC="\x9D",g.PM="\x9E",g.APC="\x9F"))(Ai||={});var fs;(t=>t.ST=`${b.ESC}\\`)(fs||={});var $t=class{constructor(t,e,i,r,n,o){this._textarea=t;this._compositionView=e;this._bufferService=i;this._optionsService=r;this._coreService=n;this._renderService=o;this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=""}get isComposing(){return this._isComposing}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent="",this._dataAlreadySent="",this._compositionView.classList.add("active")}compositionupdate(t){this._compositionView.textContent=t.data,this.updateCompositionElements(),setTimeout(()=>{this._compositionPosition.end=this._textarea.value.length},0)}compositionend(){this._finalizeComposition(!0)}keydown(t){if(this._isComposing||this._isSendingComposition){if(t.keyCode===20||t.keyCode===229||t.keyCode===16||t.keyCode===17||t.keyCode===18)return!1;this._finalizeComposition(!1)}return t.keyCode===229?(this._handleAnyTextareaChanges(),!1):!0}_finalizeComposition(t){if(this._compositionView.classList.remove("active"),this._isComposing=!1,t){let e={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(()=>{if(this._isSendingComposition){this._isSendingComposition=!1;let i;e.start+=this._dataAlreadySent.length,this._isComposing?i=this._textarea.value.substring(e.start,this._compositionPosition.start):i=this._textarea.value.substring(e.start),i.length>0&&this._coreService.triggerDataEvent(i,!0)}},0)}else{this._isSendingComposition=!1;let e=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(e,!0)}}_handleAnyTextareaChanges(){let t=this._textarea.value;setTimeout(()=>{if(!this._isComposing){let e=this._textarea.value,i=e.replace(t,"");this._dataAlreadySent=i,e.length>t.length?this._coreService.triggerDataEvent(i,!0):e.lengththis.updateCompositionElements(!0),0)}}};$t=M([S(2,F),S(3,H),S(4,ge),S(5,ce)],$t);var ue=0,he=0,de=0,J=0,ps={css:"#00000000",rgba:0},j;(i=>{function s(r,n,o,l){return l!==void 0?`#${vt(r)}${vt(n)}${vt(o)}${vt(l)}`:`#${vt(r)}${vt(n)}${vt(o)}`}i.toCss=s;function t(r,n,o,l=255){return(r<<24|n<<16|o<<8|l)>>>0}i.toRgba=t;function e(r,n,o,l){return{css:i.toCss(r,n,o,l),rgba:i.toRgba(r,n,o,l)}}i.toColor=e})(j||={});var U;(l=>{function s(a,u){if(J=(u.rgba&255)/255,J===1)return{css:u.css,rgba:u.rgba};let h=u.rgba>>24&255,c=u.rgba>>16&255,d=u.rgba>>8&255,_=a.rgba>>24&255,p=a.rgba>>16&255,m=a.rgba>>8&255;ue=_+Math.round((h-_)*J),he=p+Math.round((c-p)*J),de=m+Math.round((d-m)*J);let f=j.toCss(ue,he,de),A=j.toRgba(ue,he,de);return{css:f,rgba:A}}l.blend=s;function t(a){return(a.rgba&255)===255}l.isOpaque=t;function e(a,u,h){let c=$r.ensureContrastRatio(a.rgba,u.rgba,h);if(c)return j.toColor(c>>24&255,c>>16&255,c>>8&255)}l.ensureContrastRatio=e;function i(a){let u=(a.rgba|255)>>>0;return[ue,he,de]=$r.toChannels(u),{css:j.toCss(ue,he,de),rgba:u}}l.opaque=i;function r(a,u){return J=Math.round(u*255),[ue,he,de]=$r.toChannels(a.rgba),{css:j.toCss(ue,he,de,J),rgba:j.toRgba(ue,he,de,J)}}l.opacity=r;function n(a,u){return J=a.rgba&255,r(a,J*u/255)}l.multiplyOpacity=n;function o(a){return[a.rgba>>24&255,a.rgba>>16&255,a.rgba>>8&255]}l.toColorRGB=o})(U||={});var z;(i=>{let s,t;try{let r=document.createElement("canvas");r.width=1,r.height=1;let n=r.getContext("2d",{willReadFrequently:!0});n&&(s=n,s.globalCompositeOperation="copy",t=s.createLinearGradient(0,0,1,1))}catch{}function e(r){if(r.match(/#[\da-f]{3,8}/i))switch(r.length){case 4:return ue=parseInt(r.slice(1,2).repeat(2),16),he=parseInt(r.slice(2,3).repeat(2),16),de=parseInt(r.slice(3,4).repeat(2),16),j.toColor(ue,he,de);case 5:return ue=parseInt(r.slice(1,2).repeat(2),16),he=parseInt(r.slice(2,3).repeat(2),16),de=parseInt(r.slice(3,4).repeat(2),16),J=parseInt(r.slice(4,5).repeat(2),16),j.toColor(ue,he,de,J);case 7:return{css:r,rgba:(parseInt(r.slice(1),16)<<8|255)>>>0};case 9:return{css:r,rgba:parseInt(r.slice(1),16)>>>0}}let n=r.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(n)return ue=parseInt(n[1]),he=parseInt(n[2]),de=parseInt(n[3]),J=Math.round((n[5]===void 0?1:parseFloat(n[5]))*255),j.toColor(ue,he,de,J);if(!s||!t)throw new Error("css.toColor: Unsupported css format");if(s.fillStyle=t,s.fillStyle=r,typeof s.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(s.fillRect(0,0,1,1),[ue,he,de,J]=s.getImageData(0,0,1,1).data,J!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:j.toRgba(ue,he,de,J),css:r}}i.toColor=e})(z||={});var ve;(e=>{function s(i){return t(i>>16&255,i>>8&255,i&255)}e.relativeLuminance=s;function t(i,r,n){let o=i/255,l=r/255,a=n/255,u=o<=.03928?o/12.92:Math.pow((o+.055)/1.055,2.4),h=l<=.03928?l/12.92:Math.pow((l+.055)/1.055,2.4),c=a<=.03928?a/12.92:Math.pow((a+.055)/1.055,2.4);return u*.2126+h*.7152+c*.0722}e.relativeLuminance2=t})(ve||={});var $r;(n=>{function s(o,l){if(J=(l&255)/255,J===1)return l;let a=l>>24&255,u=l>>16&255,h=l>>8&255,c=o>>24&255,d=o>>16&255,_=o>>8&255;return ue=c+Math.round((a-c)*J),he=d+Math.round((u-d)*J),de=_+Math.round((h-_)*J),j.toRgba(ue,he,de)}n.blend=s;function t(o,l,a){let u=ve.relativeLuminance(o>>8),h=ve.relativeLuminance(l>>8);if(Xe(u,h)>8));if(m>8));return m>A?p:f}return p}let d=i(o,l,a),_=Xe(u,ve.relativeLuminance(d>>8));if(_>8));return _>m?d:p}return d}}n.ensureContrastRatio=t;function e(o,l,a){let u=o>>24&255,h=o>>16&255,c=o>>8&255,d=l>>24&255,_=l>>16&255,p=l>>8&255,m=Xe(ve.relativeLuminance2(d,_,p),ve.relativeLuminance2(u,h,c));for(;m0||_>0||p>0);)d-=Math.max(0,Math.ceil(d*.1)),_-=Math.max(0,Math.ceil(_*.1)),p-=Math.max(0,Math.ceil(p*.1)),m=Xe(ve.relativeLuminance2(d,_,p),ve.relativeLuminance2(u,h,c));return(d<<24|_<<16|p<<8|255)>>>0}n.reduceLuminance=e;function i(o,l,a){let u=o>>24&255,h=o>>16&255,c=o>>8&255,d=l>>24&255,_=l>>16&255,p=l>>8&255,m=Xe(ve.relativeLuminance2(d,_,p),ve.relativeLuminance2(u,h,c));for(;m>>0}n.increaseLuminance=i;function r(o){return[o>>24&255,o>>16&255,o>>8&255,o&255]}n.toChannels=r})($r||={});function vt(s){let t=s.toString(16);return t.length<2?"0"+t:t}function Xe(s,t){return s1){let c=this._getJoinedRanges(r,l,o,e,n);for(let d=0;d1){let h=this._getJoinedRanges(r,l,o,e,n);for(let c=0;c=di,E=y,x=this._workCell;if(_.length>0&&y===_[0][0]&&w){let W=_.shift(),An=this._isCellInSelection(W[0],e);for(O=W[0]+1;O=W[1],w?(g=!0,x=new Vr(this._workCell,t.translateToString(!0,W[0],W[1]),W[1]-W[0]),E=W[1]-1,T=x.getWidth()):di=W[1]}let N=this._isCellInSelection(y,e),Z=i&&y===o,te=Qe&&y>=h&&y<=c,Oe=!1;this._decorationService.forEachDecorationAtCell(y,e,void 0,W=>{Oe=!0});let ze=x.getChars()||we;if(ze===" "&&(x.isUnderline()||x.isOverline())&&(ze="\xA0"),Ke=T*a-u.get(ze,x.isBold(),x.isItalic()),!f)f=this._document.createElement("span");else if(A&&(N&&Pe||!N&&!Pe&&x.bg===I)&&(N&&Pe&&p.selectionForeground||x.fg===k)&&x.extended.ext===P&&te===oe&&Ke===Me&&!Z&&!g&&!Oe&&w){x.isInvisible()?R+=we:R+=ze,A++;continue}else A&&(f.textContent=R),f=this._document.createElement("span"),A=0,R="";if(I=x.bg,k=x.fg,P=x.extended.ext,oe=te,Me=Ke,Pe=N,g&&o>=y&&o<=E&&(o=y),!this._coreService.isCursorHidden&&Z&&this._coreService.isCursorInitialized){if(V.push("xterm-cursor"),this._coreBrowserService.isFocused)l&&V.push("xterm-cursor-blink"),V.push(r==="bar"?"xterm-cursor-bar":r==="underline"?"xterm-cursor-underline":"xterm-cursor-block");else if(n)switch(n){case"outline":V.push("xterm-cursor-outline");break;case"block":V.push("xterm-cursor-block");break;case"bar":V.push("xterm-cursor-bar");break;case"underline":V.push("xterm-cursor-underline");break;default:break}}if(x.isBold()&&V.push("xterm-bold"),x.isItalic()&&V.push("xterm-italic"),x.isDim()&&V.push("xterm-dim"),x.isInvisible()?R=we:R=x.getChars()||we,x.isUnderline()&&(V.push(`xterm-underline-${x.extended.underlineStyle}`),R===" "&&(R="\xA0"),!x.isUnderlineColorDefault()))if(x.isUnderlineColorRGB())f.style.textDecorationColor=`rgb(${De.toColorRGB(x.getUnderlineColor()).join(",")})`;else{let W=x.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&x.isBold()&&W<8&&(W+=8),f.style.textDecorationColor=p.ansi[W].css}x.isOverline()&&(V.push("xterm-overline"),R===" "&&(R="\xA0")),x.isStrikethrough()&&V.push("xterm-strikethrough"),te&&(f.style.textDecoration="underline");let le=x.getFgColor(),et=x.getFgColorMode(),me=x.getBgColor(),ht=x.getBgColorMode(),fi=!!x.isInverse();if(fi){let W=le;le=me,me=W;let An=et;et=ht,ht=An}let tt,Qi,pi=!1;this._decorationService.forEachDecorationAtCell(y,e,void 0,W=>{W.options.layer!=="top"&&pi||(W.backgroundColorRGB&&(ht=50331648,me=W.backgroundColorRGB.rgba>>8&16777215,tt=W.backgroundColorRGB),W.foregroundColorRGB&&(et=50331648,le=W.foregroundColorRGB.rgba>>8&16777215,Qi=W.foregroundColorRGB),pi=W.options.layer==="top")}),!pi&&N&&(tt=this._coreBrowserService.isFocused?p.selectionBackgroundOpaque:p.selectionInactiveBackgroundOpaque,me=tt.rgba>>8&16777215,ht=50331648,pi=!0,p.selectionForeground&&(et=50331648,le=p.selectionForeground.rgba>>8&16777215,Qi=p.selectionForeground)),pi&&V.push("xterm-decoration-top");let it;switch(ht){case 16777216:case 33554432:it=p.ansi[me],V.push(`xterm-bg-${me}`);break;case 50331648:it=j.toColor(me>>16,me>>8&255,me&255),this._addStyle(f,`background-color:#${qo((me>>>0).toString(16),"0",6)}`);break;case 0:default:fi?(it=p.foreground,V.push(`xterm-bg-${257}`)):it=p.background}switch(tt||x.isDim()&&(tt=U.multiplyOpacity(it,.5)),et){case 16777216:case 33554432:x.isBold()&&le<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(le+=8),this._applyMinimumContrast(f,it,p.ansi[le],x,tt,void 0)||V.push(`xterm-fg-${le}`);break;case 50331648:let W=j.toColor(le>>16&255,le>>8&255,le&255);this._applyMinimumContrast(f,it,W,x,tt,Qi)||this._addStyle(f,`color:#${qo(le.toString(16),"0",6)}`);break;case 0:default:this._applyMinimumContrast(f,it,p.foreground,x,tt,Qi)||fi&&V.push(`xterm-fg-${257}`)}V.length&&(f.className=V.join(" "),V.length=0),!Z&&!g&&!Oe&&w?A++:f.textContent=R,Ke!==this.defaultSpacing&&(f.style.letterSpacing=`${Ke}px`),d.push(f),y=E}return f&&A&&(f.textContent=R),d}_applyMinimumContrast(t,e,i,r,n,o){if(this._optionsService.rawOptions.minimumContrastRatio===1||$o(r.getCode()))return!1;let l=this._getContrastCache(r),a;if(!n&&!o&&(a=l.getColor(e.rgba,i.rgba)),a===void 0){let u=this._optionsService.rawOptions.minimumContrastRatio/(r.isDim()?2:1);a=U.ensureContrastRatio(n||e,o||i,u),l.setColor((n||e).rgba,(o||i).rgba,a??null)}return a?(this._addStyle(t,`color:${a.css}`),!0):!1}_getContrastCache(t){return t.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(t,e){t.setAttribute("style",`${t.getAttribute("style")||""}${e};`)}_isCellInSelection(t,e){let i=this._selectionStart,r=this._selectionEnd;return!i||!r?!1:this._columnSelectMode?i[0]<=r[0]?t>=i[0]&&e>=i[1]&&t=i[1]&&t>=r[0]&&e<=r[1]:e>i[1]&&e=i[0]&&t=i[0]}};Vt=M([S(1,or),S(2,H),S(3,ae),S(4,ge),S(5,Be),S(6,Re)],Vt);function qo(s,t,e){for(;s.length0&&(this._flat[r]=l),l}let n=t;e&&(n+="B"),i&&(n+="I");let o=this._holey.get(n);if(o===void 0){let l=0;e&&(l|=1),i&&(l|=2),o=this._measure(t,l),o>0&&this._holey.set(n,o)}return o}_measure(t,e){let i=this._measureElements[e];return i.textContent=t.repeat(32),i.offsetWidth/32}};var ms=class{constructor(){this.clear()}clear(){this.hasSelection=!1,this.columnSelectMode=!1,this.viewportStartRow=0,this.viewportEndRow=0,this.viewportCappedStartRow=0,this.viewportCappedEndRow=0,this.startCol=0,this.endCol=0,this.selectionStart=void 0,this.selectionEnd=void 0}update(t,e,i,r=!1){if(this.selectionStart=e,this.selectionEnd=i,!e||!i||e[0]===i[0]&&e[1]===i[1]){this.clear();return}let n=t.buffers.active.ydisp,o=e[1]-n,l=i[1]-n,a=Math.max(o,0),u=Math.min(l,t.rows-1);if(a>=t.rows||u<0){this.clear();return}this.hasSelection=!0,this.columnSelectMode=r,this.viewportStartRow=o,this.viewportEndRow=l,this.viewportCappedStartRow=a,this.viewportCappedEndRow=u,this.startCol=e[0],this.endCol=i[0]}isCellSelected(t,e,i){return this.hasSelection?(i-=t.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?e>=this.startCol&&i>=this.viewportCappedStartRow&&e=this.viewportCappedStartRow&&e>=this.endCol&&i<=this.viewportCappedEndRow:i>this.viewportStartRow&&i=this.startCol&&e=this.startCol):!1}};function Yo(){return new ms}var _s="xterm-dom-renderer-owner-",Le="xterm-rows",jr="xterm-fg-",jo="xterm-bg-",ki="xterm-focus",Xr="xterm-selection",Na=1,Yt=class extends D{constructor(e,i,r,n,o,l,a,u,h,c,d,_,p,m){super();this._terminal=e;this._document=i;this._element=r;this._screenElement=n;this._viewportElement=o;this._helperContainer=l;this._linkifier2=a;this._charSizeService=h;this._optionsService=c;this._bufferService=d;this._coreService=_;this._coreBrowserService=p;this._themeService=m;this._terminalClass=Na++;this._rowElements=[];this._selectionRenderModel=Yo();this.onRequestRedraw=this._register(new v).event;this._rowContainer=this._document.createElement("div"),this._rowContainer.classList.add(Le),this._rowContainer.style.lineHeight="normal",this._rowContainer.setAttribute("aria-hidden","true"),this._refreshRowElements(this._bufferService.cols,this._bufferService.rows),this._selectionContainer=this._document.createElement("div"),this._selectionContainer.classList.add(Xr),this._selectionContainer.setAttribute("aria-hidden","true"),this.dimensions=Vo(),this._updateDimensions(),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._themeService.onChangeColors(f=>this._injectCss(f))),this._injectCss(this._themeService.colors),this._rowFactory=u.createInstance(Vt,document),this._element.classList.add(_s+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline(f=>this._handleLinkHover(f))),this._register(this._linkifier2.onHideLinkUnderline(f=>this._handleLinkLeave(f))),this._register(C(()=>{this._element.classList.remove(_s+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new Yr(this._document,this._helperContainer),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}_updateDimensions(){let e=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*e,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*e),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.left=0,this.dimensions.device.char.top=0,this.dimensions.device.canvas.width=this.dimensions.device.cell.width*this._bufferService.cols,this.dimensions.device.canvas.height=this.dimensions.device.cell.height*this._bufferService.rows,this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/e),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/e),this.dimensions.css.cell.width=this.dimensions.css.canvas.width/this._bufferService.cols,this.dimensions.css.cell.height=this.dimensions.css.canvas.height/this._bufferService.rows;for(let r of this._rowElements)r.style.width=`${this.dimensions.css.canvas.width}px`,r.style.height=`${this.dimensions.css.cell.height}px`,r.style.lineHeight=`${this.dimensions.css.cell.height}px`,r.style.overflow="hidden";this._dimensionsStyleElement||(this._dimensionsStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._dimensionsStyleElement));let i=`${this._terminalSelector} .${Le} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=i,this._selectionContainer.style.height=this._viewportElement.style.height,this._screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._screenElement.style.height=`${this.dimensions.css.canvas.height}px`}_injectCss(e){this._themeStyleElement||(this._themeStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._themeStyleElement));let i=`${this._terminalSelector} .${Le} { pointer-events: none; color: ${e.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;i+=`${this._terminalSelector} .${Le} .xterm-dim { color: ${U.multiplyOpacity(e.foreground,.5).css};}`,i+=`${this._terminalSelector} span:not(.xterm-bold) { font-weight: ${this._optionsService.rawOptions.fontWeight};}${this._terminalSelector} span.xterm-bold { font-weight: ${this._optionsService.rawOptions.fontWeightBold};}${this._terminalSelector} span.xterm-italic { font-style: italic;}`;let r=`blink_underline_${this._terminalClass}`,n=`blink_bar_${this._terminalClass}`,o=`blink_block_${this._terminalClass}`;i+=`@keyframes ${r} { 50% { border-bottom-style: hidden; }}`,i+=`@keyframes ${n} { 50% { box-shadow: none; }}`,i+=`@keyframes ${o} { 0% { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css}; } 50% { background-color: inherit; color: ${e.cursor.css}; }}`,i+=`${this._terminalSelector} .${Le}.${ki} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${r} 1s step-end infinite;}${this._terminalSelector} .${Le}.${ki} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${n} 1s step-end infinite;}${this._terminalSelector} .${Le}.${ki} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${o} 1s step-end infinite;}${this._terminalSelector} .${Le} .xterm-cursor.xterm-cursor-block { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css};}${this._terminalSelector} .${Le} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e.cursor.css} !important; color: ${e.cursorAccent.css} !important;}${this._terminalSelector} .${Le} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${Le} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}${this._terminalSelector} .${Le} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,i+=`${this._terminalSelector} .${Xr} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${Xr} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${Xr} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(let[l,a]of e.ansi.entries())i+=`${this._terminalSelector} .${jr}${l} { color: ${a.css}; }${this._terminalSelector} .${jr}${l}.xterm-dim { color: ${U.multiplyOpacity(a,.5).css}; }${this._terminalSelector} .${jo}${l} { background-color: ${a.css}; }`;i+=`${this._terminalSelector} .${jr}${257} { color: ${U.opaque(e.background).css}; }${this._terminalSelector} .${jr}${257}.xterm-dim { color: ${U.multiplyOpacity(U.opaque(e.background),.5).css}; }${this._terminalSelector} .${jo}${257} { background-color: ${e.foreground.css}; }`,this._themeStyleElement.textContent=i}_setDefaultSpacing(){let e=this.dimensions.css.cell.width-this._widthCache.get("W",!1,!1);this._rowContainer.style.letterSpacing=`${e}px`,this._rowFactory.defaultSpacing=e}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(e,i){for(let r=this._rowElements.length;r<=i;r++){let n=this._document.createElement("div");this._rowContainer.appendChild(n),this._rowElements.push(n)}for(;this._rowElements.length>i;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(e,i){this._refreshRowElements(e,i),this._updateDimensions(),this.handleSelectionChanged(this._selectionRenderModel.selectionStart,this._selectionRenderModel.selectionEnd,this._selectionRenderModel.columnSelectMode)}handleCharSizeChanged(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}handleBlur(){this._rowContainer.classList.remove(ki),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(ki),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(e,i,r){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(e,i,r),this.renderRows(0,this._bufferService.rows-1),!e||!i||(this._selectionRenderModel.update(this._terminal,e,i,r),!this._selectionRenderModel.hasSelection))return;let n=this._selectionRenderModel.viewportStartRow,o=this._selectionRenderModel.viewportEndRow,l=this._selectionRenderModel.viewportCappedStartRow,a=this._selectionRenderModel.viewportCappedEndRow,u=this._document.createDocumentFragment();if(r){let h=e[0]>i[0];u.appendChild(this._createSelectionElement(l,h?i[0]:e[0],h?e[0]:i[0],a-l+1))}else{let h=n===l?e[0]:0,c=l===o?i[0]:this._bufferService.cols;u.appendChild(this._createSelectionElement(l,h,c));let d=a-l-1;if(u.appendChild(this._createSelectionElement(l+1,0,this._bufferService.cols,d)),l!==a){let _=o===a?i[0]:this._bufferService.cols;u.appendChild(this._createSelectionElement(a,0,_))}}this._selectionContainer.appendChild(u)}_createSelectionElement(e,i,r,n=1){let o=this._document.createElement("div"),l=i*this.dimensions.css.cell.width,a=this.dimensions.css.cell.width*(r-i);return l+a>this.dimensions.css.canvas.width&&(a=this.dimensions.css.canvas.width-l),o.style.height=`${n*this.dimensions.css.cell.height}px`,o.style.top=`${e*this.dimensions.css.cell.height}px`,o.style.left=`${l}px`,o.style.width=`${a}px`,o}handleCursorMove(){}_handleOptionsChanged(){this._updateDimensions(),this._injectCss(this._themeService.colors),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}clear(){for(let e of this._rowElements)e.replaceChildren()}renderRows(e,i){let r=this._bufferService.buffer,n=r.ybase+r.y,o=Math.min(r.x,this._bufferService.cols-1),l=this._coreService.decPrivateModes.cursorBlink??this._optionsService.rawOptions.cursorBlink,a=this._coreService.decPrivateModes.cursorStyle??this._optionsService.rawOptions.cursorStyle,u=this._optionsService.rawOptions.cursorInactiveStyle;for(let h=e;h<=i;h++){let c=h+r.ydisp,d=this._rowElements[h],_=r.lines.get(c);if(!d||!_)break;d.replaceChildren(...this._rowFactory.createRow(_,c,c===n,a,u,o,l,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${_s}${this._terminalClass}`}_handleLinkHover(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!0)}_handleLinkLeave(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!1)}_setCellUnderline(e,i,r,n,o,l){r<0&&(e=0),n<0&&(i=0);let a=this._bufferService.rows-1;r=Math.max(Math.min(r,a),0),n=Math.max(Math.min(n,a),0),o=Math.min(o,this._bufferService.cols);let u=this._bufferService.buffer,h=u.ybase+u.y,c=Math.min(u.x,o-1),d=this._optionsService.rawOptions.cursorBlink,_=this._optionsService.rawOptions.cursorStyle,p=this._optionsService.rawOptions.cursorInactiveStyle;for(let m=r;m<=n;++m){let f=m+u.ydisp,A=this._rowElements[m],R=u.lines.get(f);if(!A||!R)break;A.replaceChildren(...this._rowFactory.createRow(R,f,f===h,_,p,c,d,this.dimensions.css.cell.width,this._widthCache,l?m===r?e:0:-1,l?(m===n?i:o)-1:-1))}}};Yt=M([S(7,xt),S(8,nt),S(9,H),S(10,F),S(11,ge),S(12,ae),S(13,Re)],Yt);var jt=class extends D{constructor(e,i,r){super();this._optionsService=r;this.width=0;this.height=0;this._onCharSizeChange=this._register(new v);this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this._register(new vs(this._optionsService))}catch{this._measureStrategy=this._register(new bs(e,i,this._optionsService))}this._register(this._optionsService.onMultipleOptionChange(["fontFamily","fontSize"],()=>this.measure()))}get hasValidSize(){return this.width>0&&this.height>0}measure(){let e=this._measureStrategy.measure();(e.width!==this.width||e.height!==this.height)&&(this.width=e.width,this.height=e.height,this._onCharSizeChange.fire())}};jt=M([S(2,H)],jt);var Zr=class extends D{constructor(){super(...arguments);this._result={width:0,height:0}}_validateAndSet(e,i){e!==void 0&&e>0&&i!==void 0&&i>0&&(this._result.width=e,this._result.height=i)}},bs=class extends Zr{constructor(e,i,r){super();this._document=e;this._parentElement=i;this._optionsService=r;this._measureElement=this._document.createElement("span"),this._measureElement.classList.add("xterm-char-measure-element"),this._measureElement.textContent="W".repeat(32),this._measureElement.setAttribute("aria-hidden","true"),this._measureElement.style.whiteSpace="pre",this._measureElement.style.fontKerning="none",this._parentElement.appendChild(this._measureElement)}measure(){return this._measureElement.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._measureElement.style.fontSize=`${this._optionsService.rawOptions.fontSize}px`,this._validateAndSet(Number(this._measureElement.offsetWidth)/32,Number(this._measureElement.offsetHeight)),this._result}},vs=class extends Zr{constructor(e){super();this._optionsService=e;this._canvas=new OffscreenCanvas(100,100),this._ctx=this._canvas.getContext("2d");let i=this._ctx.measureText("W");if(!("width"in i&&"fontBoundingBoxAscent"in i&&"fontBoundingBoxDescent"in i))throw new Error("Required font metrics not supported")}measure(){this._ctx.font=`${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`;let e=this._ctx.measureText("W");return this._validateAndSet(e.width,e.fontBoundingBoxAscent+e.fontBoundingBoxDescent),this._result}};var Jr=class extends D{constructor(e,i,r){super();this._textarea=e;this._window=i;this.mainDocument=r;this._isFocused=!1;this._cachedIsFocused=void 0;this._screenDprMonitor=this._register(new gs(this._window));this._onDprChange=this._register(new v);this.onDprChange=this._onDprChange.event;this._onWindowChange=this._register(new v);this.onWindowChange=this._onWindowChange.event;this._register(this.onWindowChange(n=>this._screenDprMonitor.setWindow(n))),this._register($.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register(L(this._textarea,"focus",()=>this._isFocused=!0)),this._register(L(this._textarea,"blur",()=>this._isFocused=!1))}get window(){return this._window}set window(e){this._window!==e&&(this._window=e,this._onWindowChange.fire(this._window))}get dpr(){return this.window.devicePixelRatio}get isFocused(){return this._cachedIsFocused===void 0&&(this._cachedIsFocused=this._isFocused&&this._textarea.ownerDocument.hasFocus(),queueMicrotask(()=>this._cachedIsFocused=void 0)),this._cachedIsFocused}},gs=class extends D{constructor(e){super();this._parentWindow=e;this._windowResizeListener=this._register(new ye);this._onDprChange=this._register(new v);this.onDprChange=this._onDprChange.event;this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this._register(C(()=>this.clearListener()))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=L(this._parentWindow,"resize",()=>this._setDprAndFireIfDiffers())}_setDprAndFireIfDiffers(){this._parentWindow.devicePixelRatio!==this._currentDevicePixelRatio&&this._onDprChange.fire(this._parentWindow.devicePixelRatio),this._updateDpr()}_updateDpr(){this._outerListener&&(this._resolutionMediaMatchList?.removeListener(this._outerListener),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._resolutionMediaMatchList=this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`),this._resolutionMediaMatchList.addListener(this._outerListener))}clearListener(){!this._resolutionMediaMatchList||!this._outerListener||(this._resolutionMediaMatchList.removeListener(this._outerListener),this._resolutionMediaMatchList=void 0,this._outerListener=void 0)}};var Qr=class extends D{constructor(){super();this.linkProviders=[];this._register(C(()=>this.linkProviders.length=0))}registerLinkProvider(e){return this.linkProviders.push(e),{dispose:()=>{let i=this.linkProviders.indexOf(e);i!==-1&&this.linkProviders.splice(i,1)}}}};function Ci(s,t,e){let i=e.getBoundingClientRect(),r=s.getComputedStyle(e),n=parseInt(r.getPropertyValue("padding-left")),o=parseInt(r.getPropertyValue("padding-top"));return[t.clientX-i.left-n,t.clientY-i.top-o]}function Xo(s,t,e,i,r,n,o,l,a){if(!n)return;let u=Ci(s,t,e);if(u)return u[0]=Math.ceil((u[0]+(a?o/2:0))/o),u[1]=Math.ceil(u[1]/l),u[0]=Math.min(Math.max(u[0],1),i+(a?1:0)),u[1]=Math.min(Math.max(u[1],1),r),u}var Xt=class{constructor(t,e){this._renderService=t;this._charSizeService=e}getCoords(t,e,i,r,n){return Xo(window,t,e,i,r,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,n)}getMouseReportCoords(t,e){let i=Ci(window,t,e);if(this._charSizeService.hasValidSize)return i[0]=Math.min(Math.max(i[0],0),this._renderService.dimensions.css.canvas.width-1),i[1]=Math.min(Math.max(i[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(i[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(i[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(i[0]),y:Math.floor(i[1])}}};Xt=M([S(0,ce),S(1,nt)],Xt);var en=class{constructor(t,e){this._renderCallback=t;this._coreBrowserService=e;this._refreshCallbacks=[]}dispose(){this._animationFrame&&(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0)}addRefreshCallback(t){return this._refreshCallbacks.push(t),this._animationFrame||(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh())),this._animationFrame}refresh(t,e,i){this._rowCount=i,t=t!==void 0?t:0,e=e!==void 0?e:this._rowCount-1,this._rowStart=this._rowStart!==void 0?Math.min(this._rowStart,t):t,this._rowEnd=this._rowEnd!==void 0?Math.max(this._rowEnd,e):e,!this._animationFrame&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()))}_innerRefresh(){if(this._animationFrame=void 0,this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0){this._runRefreshCallbacks();return}let t=Math.max(this._rowStart,0),e=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(t,e),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(let t of this._refreshCallbacks)t(0);this._refreshCallbacks=[]}};var tn={};Ll(tn,{getSafariVersion:()=>Ha,isChromeOS:()=>Ts,isFirefox:()=>Ss,isIpad:()=>Wa,isIphone:()=>Ua,isLegacyEdge:()=>Fa,isLinux:()=>Bi,isMac:()=>Zt,isNode:()=>Mi,isSafari:()=>Zo,isWindows:()=>Es});var Mi=typeof process<"u"&&"title"in process,Pi=Mi?"node":navigator.userAgent,Oi=Mi?"node":navigator.platform,Ss=Pi.includes("Firefox"),Fa=Pi.includes("Edge"),Zo=/^((?!chrome|android).)*safari/i.test(Pi);function Ha(){if(!Zo)return 0;let s=Pi.match(/Version\/(\d+)/);return s===null||s.length<2?0:parseInt(s[1])}var Zt=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(Oi),Wa=Oi==="iPad",Ua=Oi==="iPhone",Es=["Windows","Win16","Win32","WinCE"].includes(Oi),Bi=Oi.indexOf("Linux")>=0,Ts=/\bCrOS\b/.test(Pi);var rn=class{constructor(){this._tasks=[];this._i=0}enqueue(t){this._tasks.push(t),this._start()}flush(){for(;this._in){r-e<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(r-e))}ms`),this._start();return}r=n}this.clear()}},Is=class extends rn{_requestCallback(t){return setTimeout(()=>t(this._createDeadline(16)))}_cancelCallback(t){clearTimeout(t)}_createDeadline(t){let e=performance.now()+t;return{timeRemaining:()=>Math.max(0,e-performance.now())}}},ys=class extends rn{_requestCallback(t){return requestIdleCallback(t)}_cancelCallback(t){cancelIdleCallback(t)}},Jt=!Mi&&"requestIdleCallback"in window?ys:Is,nn=class{constructor(){this._queue=new Jt}set(t){this._queue.clear(),this._queue.enqueue(t)}flush(){this._queue.flush()}};var Qt=class extends D{constructor(e,i,r,n,o,l,a,u,h){super();this._rowCount=e;this._optionsService=r;this._charSizeService=n;this._coreService=o;this._coreBrowserService=u;this._renderer=this._register(new ye);this._pausedResizeTask=new nn;this._observerDisposable=this._register(new ye);this._isPaused=!1;this._needsFullRefresh=!1;this._isNextRenderRedrawOnly=!0;this._needsSelectionRefresh=!1;this._canvasWidth=0;this._canvasHeight=0;this._selectionState={start:void 0,end:void 0,columnSelectMode:!1};this._onDimensionsChange=this._register(new v);this.onDimensionsChange=this._onDimensionsChange.event;this._onRenderedViewportChange=this._register(new v);this.onRenderedViewportChange=this._onRenderedViewportChange.event;this._onRender=this._register(new v);this.onRender=this._onRender.event;this._onRefreshRequest=this._register(new v);this.onRefreshRequest=this._onRefreshRequest.event;this._renderDebouncer=new en((c,d)=>this._renderRows(c,d),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new xs(this._coreBrowserService,this._coreService,()=>this._fullRefresh()),this._register(C(()=>this._syncOutputHandler.dispose())),this._register(this._coreBrowserService.onDprChange(()=>this.handleDevicePixelRatioChange())),this._register(a.onResize(()=>this._fullRefresh())),this._register(a.buffers.onBufferActivate(()=>this._renderer.value?.clear())),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._charSizeService.onCharSizeChange(()=>this.handleCharSizeChanged())),this._register(l.onDecorationRegistered(()=>this._fullRefresh())),this._register(l.onDecorationRemoved(()=>this._fullRefresh())),this._register(this._optionsService.onMultipleOptionChange(["customGlyphs","drawBoldTextInBrightColors","letterSpacing","lineHeight","fontFamily","fontSize","fontWeight","fontWeightBold","minimumContrastRatio","rescaleOverlappingGlyphs"],()=>{this.clear(),this.handleResize(a.cols,a.rows),this._fullRefresh()})),this._register(this._optionsService.onMultipleOptionChange(["cursorBlink","cursorStyle"],()=>this.refreshRows(a.buffer.y,a.buffer.y,!0))),this._register(h.onChangeColors(()=>this._fullRefresh())),this._registerIntersectionObserver(this._coreBrowserService.window,i),this._register(this._coreBrowserService.onWindowChange(c=>this._registerIntersectionObserver(c,i)))}get dimensions(){return this._renderer.value.dimensions}_registerIntersectionObserver(e,i){if("IntersectionObserver"in e){let r=new e.IntersectionObserver(n=>this._handleIntersectionChange(n[n.length-1]),{threshold:0});r.observe(i),this._observerDisposable.value=C(()=>r.disconnect())}}_handleIntersectionChange(e){this._isPaused=e.isIntersecting===void 0?e.intersectionRatio===0:!e.isIntersecting,!this._isPaused&&!this._charSizeService.hasValidSize&&this._charSizeService.measure(),!this._isPaused&&this._needsFullRefresh&&(this._pausedResizeTask.flush(),this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)}refreshRows(e,i,r=!1){if(this._isPaused){this._needsFullRefresh=!0;return}if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,i);return}let n=this._syncOutputHandler.flush();n&&(e=Math.min(e,n.start),i=Math.max(i,n.end)),r||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(e,i,this._rowCount)}_renderRows(e,i){if(this._renderer.value){if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,i);return}e=Math.min(e,this._rowCount-1),i=Math.min(i,this._rowCount-1),this._renderer.value.renderRows(e,i),this._needsSelectionRefresh&&(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),this._needsSelectionRefresh=!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:e,end:i}),this._onRender.fire({start:e,end:i}),this._isNextRenderRedrawOnly=!0}}resize(e,i){this._rowCount=i,this._fireOnCanvasResize()}_handleOptionsChanged(){this._renderer.value&&(this.refreshRows(0,this._rowCount-1),this._fireOnCanvasResize())}_fireOnCanvasResize(){this._renderer.value&&(this._renderer.value.dimensions.css.canvas.width===this._canvasWidth&&this._renderer.value.dimensions.css.canvas.height===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.value.dimensions))}hasRenderer(){return!!this._renderer.value}setRenderer(e){this._renderer.value=e,this._renderer.value&&(this._renderer.value.onRequestRedraw(i=>this.refreshRows(i.start,i.end,!0)),this._needsSelectionRefresh=!0,this._fullRefresh())}addRefreshCallback(e){return this._renderDebouncer.addRefreshCallback(e)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){this._renderer.value&&(this._renderer.value.clearTextureAtlas?.(),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(e,i){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set(()=>this._renderer.value?.handleResize(e,i)):this._renderer.value.handleResize(e,i),this._fullRefresh())}handleCharSizeChanged(){this._renderer.value?.handleCharSizeChanged()}handleBlur(){this._renderer.value?.handleBlur()}handleFocus(){this._renderer.value?.handleFocus()}handleSelectionChanged(e,i,r){this._selectionState.start=e,this._selectionState.end=i,this._selectionState.columnSelectMode=r,this._renderer.value?.handleSelectionChanged(e,i,r)}handleCursorMove(){this._renderer.value?.handleCursorMove()}clear(){this._renderer.value?.clear()}};Qt=M([S(2,H),S(3,nt),S(4,ge),S(5,Be),S(6,F),S(7,ae),S(8,Re)],Qt);var xs=class{constructor(t,e,i){this._coreBrowserService=t;this._coreService=e;this._onTimeout=i;this._start=0;this._end=0;this._isBuffering=!1}bufferRows(t,e){this._isBuffering?(this._start=Math.min(this._start,t),this._end=Math.max(this._end,e)):(this._start=t,this._end=e,this._isBuffering=!0),this._timeout===void 0&&(this._timeout=this._coreBrowserService.window.setTimeout(()=>{this._timeout=void 0,this._coreService.decPrivateModes.synchronizedOutput=!1,this._onTimeout()},1e3))}flush(){if(this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0),!this._isBuffering)return;let t={start:this._start,end:this._end};return this._isBuffering=!1,t}dispose(){this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0)}};function Jo(s,t,e,i){let r=e.buffer.x,n=e.buffer.y;if(!e.buffer.hasScrollback)return Ga(r,n,s,t,e,i)+sn(n,t,e,i)+$a(r,n,s,t,e,i);let o;if(n===t)return o=r>s?"D":"C",Fi(Math.abs(r-s),Ni(o,i));o=n>t?"D":"C";let l=Math.abs(n-t),a=za(n>t?s:r,e)+(l-1)*e.cols+1+Ka(n>t?r:s,e);return Fi(a,Ni(o,i))}function Ka(s,t){return s-1}function za(s,t){return t.cols-s}function Ga(s,t,e,i,r,n){return sn(t,i,r,n).length===0?"":Fi(el(s,t,s,t-gt(t,r),!1,r).length,Ni("D",n))}function sn(s,t,e,i){let r=s-gt(s,e),n=t-gt(t,e),o=Math.abs(r-n)-Va(s,t,e);return Fi(o,Ni(Qo(s,t),i))}function $a(s,t,e,i,r,n){let o;sn(t,i,r,n).length>0?o=i-gt(i,r):o=t;let l=i,a=qa(s,t,e,i,r,n);return Fi(el(s,o,e,l,a==="C",r).length,Ni(a,n))}function Va(s,t,e){let i=0,r=s-gt(s,e),n=t-gt(t,e);for(let o=0;o=0&&s0?o=i-gt(i,r):o=t,s=e&&ot?"A":"B"}function el(s,t,e,i,r,n){let o=s,l=t,a="";for(;(o!==e||l!==i)&&l>=0&&ln.cols-1?(a+=n.buffer.translateBufferLineToString(l,!1,s,o),o=0,s=0,l++):!r&&o<0&&(a+=n.buffer.translateBufferLineToString(l,!1,0,s+1),o=n.cols-1,s=o,l--);return a+n.buffer.translateBufferLineToString(l,!1,s,o)}function Ni(s,t){let e=t?"O":"[";return b.ESC+e+s}function Fi(s,t){s=Math.floor(s);let e="";for(let i=0;ithis._bufferService.cols?t%this._bufferService.cols===0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(t/this._bufferService.cols)-1]:[t%this._bufferService.cols,this.selectionStart[1]+Math.floor(t/this._bufferService.cols)]:[t,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){let t=this.selectionStart[0]+this.selectionStartLength;return t>this._bufferService.cols?[t%this._bufferService.cols,this.selectionStart[1]+Math.floor(t/this._bufferService.cols)]:[Math.max(t,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){let t=this.selectionStart,e=this.selectionEnd;return!t||!e?!1:t[1]>e[1]||t[1]===e[1]&&t[0]>e[0]}handleTrim(t){return this.selectionStart&&(this.selectionStart[1]-=t),this.selectionEnd&&(this.selectionEnd[1]-=t),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}};function ws(s,t){if(s.start.y>s.end.y)throw new Error(`Buffer range end (${s.end.x}, ${s.end.y}) cannot be before start (${s.start.x}, ${s.start.y})`);return t*(s.end.y-s.start.y)+(s.end.x-s.start.x+1)}var Ds=50,Ya=15,ja=50,Xa=500,Za="\xA0",Ja=new RegExp(Za,"g");var ei=class extends D{constructor(e,i,r,n,o,l,a,u,h){super();this._element=e;this._screenElement=i;this._linkifier=r;this._bufferService=n;this._coreService=o;this._mouseService=l;this._optionsService=a;this._renderService=u;this._coreBrowserService=h;this._dragScrollAmount=0;this._enabled=!0;this._workCell=new q;this._mouseDownTimeStamp=0;this._oldHasSelection=!1;this._oldSelectionStart=void 0;this._oldSelectionEnd=void 0;this._onLinuxMouseSelection=this._register(new v);this.onLinuxMouseSelection=this._onLinuxMouseSelection.event;this._onRedrawRequest=this._register(new v);this.onRequestRedraw=this._onRedrawRequest.event;this._onSelectionChange=this._register(new v);this.onSelectionChange=this._onSelectionChange.event;this._onRequestScrollLines=this._register(new v);this.onRequestScrollLines=this._onRequestScrollLines.event;this._mouseMoveListener=c=>this._handleMouseMove(c),this._mouseUpListener=c=>this._handleMouseUp(c),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(c=>this._handleTrim(c)),this._register(this._bufferService.buffers.onBufferActivate(c=>this._handleBufferActivate(c))),this.enable(),this._model=new on(this._bufferService),this._activeSelectionMode=0,this._register(C(()=>{this._removeMouseDownListeners()})),this._register(this._bufferService.onResize(c=>{c.rowsChanged&&this.clearSelection()}))}reset(){this.clearSelection()}disable(){this.clearSelection(),this._enabled=!1}enable(){this._enabled=!0}get selectionStart(){return this._model.finalSelectionStart}get selectionEnd(){return this._model.finalSelectionEnd}get hasSelection(){let e=this._model.finalSelectionStart,i=this._model.finalSelectionEnd;return!e||!i?!1:e[0]!==i[0]||e[1]!==i[1]}get selectionText(){let e=this._model.finalSelectionStart,i=this._model.finalSelectionEnd;if(!e||!i)return"";let r=this._bufferService.buffer,n=[];if(this._activeSelectionMode===3){if(e[0]===i[0])return"";let l=e[0]l.replace(Ja," ")).join(Es?`\r +`:` +`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh())),Bi&&e&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(e){let i=this._getMouseBufferCoords(e),r=this._model.finalSelectionStart,n=this._model.finalSelectionEnd;return!r||!n||!i?!1:this._areCoordsInSelection(i,r,n)}isCellInSelection(e,i){let r=this._model.finalSelectionStart,n=this._model.finalSelectionEnd;return!r||!n?!1:this._areCoordsInSelection([e,i],r,n)}_areCoordsInSelection(e,i,r){return e[1]>i[1]&&e[1]=i[0]&&e[0]=i[0]}_selectWordAtCursor(e,i){let r=this._linkifier.currentLink?.link?.range;if(r)return this._model.selectionStart=[r.start.x-1,r.start.y-1],this._model.selectionStartLength=ws(r,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let n=this._getMouseBufferCoords(e);return n?(this._selectWordAt(n,i),this._model.selectionEnd=void 0,!0):!1}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,i){this._model.clearSelection(),e=Math.max(e,0),i=Math.min(i,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,i],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){let i=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(i)return i[0]--,i[1]--,i[1]+=this._bufferService.buffer.ydisp,i}_getMouseEventScrollAmount(e){let i=Ci(this._coreBrowserService.window,e,this._screenElement)[1],r=this._renderService.dimensions.css.canvas.height;return i>=0&&i<=r?0:(i>r&&(i-=r),i=Math.min(Math.max(i,-Ds),Ds),i/=Ds,i/Math.abs(i)+Math.round(i*(Ya-1)))}shouldForceSelection(e){return Zt?e.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:e.shiftKey}handleMouseDown(e){if(this._mouseDownTimeStamp=e.timeStamp,!(e.button===2&&this.hasSelection)&&e.button===0){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._handleIncrementalClick(e):e.detail===1?this._handleSingleClick(e):e.detail===2?this._handleDoubleClick(e):e.detail===3&&this._handleTripleClick(e),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener("mouseup",this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval(()=>this._dragScroll(),ja)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener("mouseup",this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))}_handleSingleClick(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(e)?3:0,this._model.selectionStart=this._getMouseBufferCoords(e),!this._model.selectionStart)return;this._model.selectionEnd=void 0;let i=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);i&&i.length!==this._model.selectionStart[0]&&i.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(e){this._selectWordAtCursor(e,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(e){let i=this._getMouseBufferCoords(e);i&&(this._activeSelectionMode=2,this._selectLineAt(i[1]))}shouldColumnSelect(e){return e.altKey&&!(Zt&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;let i=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!this._model.selectionEnd){this.refresh(!0);return}this._activeSelectionMode===2?this._model.selectionEnd[1]0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));let r=this._bufferService.buffer;if(this._model.selectionEnd[1]0?(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(e.ydisp+this._bufferService.rows,e.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=e.ydisp),this.refresh()}}_handleMouseUp(e){let i=e.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&ithis._handleTrim(i))}_convertViewportColToCharacterIndex(e,i){let r=i;for(let n=0;i>=n;n++){let o=e.loadCell(n,this._workCell).getChars().length;this._workCell.getWidth()===0?r--:o>1&&i!==n&&(r+=o-1)}return r}setSelection(e,i,r){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,i],this._model.selectionStartLength=r,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(e){this._isClickInSelection(e)||(this._selectWordAtCursor(e,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(e,i,r=!0,n=!0){if(e[0]>=this._bufferService.cols)return;let o=this._bufferService.buffer,l=o.lines.get(e[1]);if(!l)return;let a=o.translateBufferLineToString(e[1],!1),u=this._convertViewportColToCharacterIndex(l,e[0]),h=u,c=e[0]-u,d=0,_=0,p=0,m=0;if(a.charAt(u)===" "){for(;u>0&&a.charAt(u-1)===" ";)u--;for(;h1&&(m+=I-1,h+=I-1);R>0&&u>0&&!this._isCharWordSeparator(l.loadCell(R-1,this._workCell));){l.loadCell(R-1,this._workCell);let k=this._workCell.getChars().length;this._workCell.getWidth()===0?(d++,R--):k>1&&(p+=k-1,u-=k-1),u--,R--}for(;O1&&(m+=k-1,h+=k-1),h++,O++}}h++;let f=u+c-d+p,A=Math.min(this._bufferService.cols,h-u+d+_-p-m);if(!(!i&&a.slice(u,h).trim()==="")){if(r&&f===0&&l.getCodePoint(0)!==32){let R=o.lines.get(e[1]-1);if(R&&l.isWrapped&&R.getCodePoint(this._bufferService.cols-1)!==32){let O=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(O){let I=this._bufferService.cols-O.start;f-=I,A+=I}}}if(n&&f+A===this._bufferService.cols&&l.getCodePoint(this._bufferService.cols-1)!==32){let R=o.lines.get(e[1]+1);if(R?.isWrapped&&R.getCodePoint(0)!==32){let O=this._getWordAt([0,e[1]+1],!1,!1,!0);O&&(A+=O.length)}}return{start:f,length:A}}}_selectWordAt(e,i){let r=this._getWordAt(e,i);if(r){for(;r.start<0;)r.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[r.start,e[1]],this._model.selectionStartLength=r.length}}_selectToWordAt(e){let i=this._getWordAt(e,!0);if(i){let r=e[1];for(;i.start<0;)i.start+=this._bufferService.cols,r--;if(!this._model.areSelectionValuesReversed())for(;i.start+i.length>this._bufferService.cols;)i.length-=this._bufferService.cols,r++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?i.start:i.start+i.length,r]}}_isCharWordSeparator(e){return e.getWidth()===0?!1:this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars())>=0}_selectLineAt(e){let i=this._bufferService.buffer.getWrappedRangeForLine(e),r={start:{x:0,y:i.first},end:{x:this._bufferService.cols-1,y:i.last}};this._model.selectionStart=[0,i.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=ws(r,this._bufferService.cols)}};ei=M([S(3,F),S(4,ge),S(5,Dt),S(6,H),S(7,ce),S(8,ae)],ei);var Hi=class{constructor(){this._data={}}set(t,e,i){this._data[t]||(this._data[t]={}),this._data[t][e]=i}get(t,e){return this._data[t]?this._data[t][e]:void 0}clear(){this._data={}}};var Wi=class{constructor(){this._color=new Hi;this._css=new Hi}setCss(t,e,i){this._css.set(t,e,i)}getCss(t,e){return this._css.get(t,e)}setColor(t,e,i){this._color.set(t,e,i)}getColor(t,e){return this._color.get(t,e)}clear(){this._color.clear(),this._css.clear()}};var re=Object.freeze((()=>{let s=[z.toColor("#2e3436"),z.toColor("#cc0000"),z.toColor("#4e9a06"),z.toColor("#c4a000"),z.toColor("#3465a4"),z.toColor("#75507b"),z.toColor("#06989a"),z.toColor("#d3d7cf"),z.toColor("#555753"),z.toColor("#ef2929"),z.toColor("#8ae234"),z.toColor("#fce94f"),z.toColor("#729fcf"),z.toColor("#ad7fa8"),z.toColor("#34e2e2"),z.toColor("#eeeeec")],t=[0,95,135,175,215,255];for(let e=0;e<216;e++){let i=t[e/36%6|0],r=t[e/6%6|0],n=t[e%6];s.push({css:j.toCss(i,r,n),rgba:j.toRgba(i,r,n)})}for(let e=0;e<24;e++){let i=8+e*10;s.push({css:j.toCss(i,i,i),rgba:j.toRgba(i,i,i)})}return s})());var St=z.toColor("#ffffff"),Ki=z.toColor("#000000"),tl=z.toColor("#ffffff"),il=Ki,Ui={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117},Qa=St,ti=class extends D{constructor(e){super();this._optionsService=e;this._contrastCache=new Wi;this._halfContrastCache=new Wi;this._onChangeColors=this._register(new v);this.onChangeColors=this._onChangeColors.event;this._colors={foreground:St,background:Ki,cursor:tl,cursorAccent:il,selectionForeground:void 0,selectionBackgroundTransparent:Ui,selectionBackgroundOpaque:U.blend(Ki,Ui),selectionInactiveBackgroundTransparent:Ui,selectionInactiveBackgroundOpaque:U.blend(Ki,Ui),scrollbarSliderBackground:U.opacity(St,.2),scrollbarSliderHoverBackground:U.opacity(St,.4),scrollbarSliderActiveBackground:U.opacity(St,.5),overviewRulerBorder:St,ansi:re.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this._register(this._optionsService.onSpecificOptionChange("minimumContrastRatio",()=>this._contrastCache.clear())),this._register(this._optionsService.onSpecificOptionChange("theme",()=>this._setTheme(this._optionsService.rawOptions.theme)))}get colors(){return this._colors}_setTheme(e={}){let i=this._colors;if(i.foreground=K(e.foreground,St),i.background=K(e.background,Ki),i.cursor=U.blend(i.background,K(e.cursor,tl)),i.cursorAccent=U.blend(i.background,K(e.cursorAccent,il)),i.selectionBackgroundTransparent=K(e.selectionBackground,Ui),i.selectionBackgroundOpaque=U.blend(i.background,i.selectionBackgroundTransparent),i.selectionInactiveBackgroundTransparent=K(e.selectionInactiveBackground,i.selectionBackgroundTransparent),i.selectionInactiveBackgroundOpaque=U.blend(i.background,i.selectionInactiveBackgroundTransparent),i.selectionForeground=e.selectionForeground?K(e.selectionForeground,ps):void 0,i.selectionForeground===ps&&(i.selectionForeground=void 0),U.isOpaque(i.selectionBackgroundTransparent)&&(i.selectionBackgroundTransparent=U.opacity(i.selectionBackgroundTransparent,.3)),U.isOpaque(i.selectionInactiveBackgroundTransparent)&&(i.selectionInactiveBackgroundTransparent=U.opacity(i.selectionInactiveBackgroundTransparent,.3)),i.scrollbarSliderBackground=K(e.scrollbarSliderBackground,U.opacity(i.foreground,.2)),i.scrollbarSliderHoverBackground=K(e.scrollbarSliderHoverBackground,U.opacity(i.foreground,.4)),i.scrollbarSliderActiveBackground=K(e.scrollbarSliderActiveBackground,U.opacity(i.foreground,.5)),i.overviewRulerBorder=K(e.overviewRulerBorder,Qa),i.ansi=re.slice(),i.ansi[0]=K(e.black,re[0]),i.ansi[1]=K(e.red,re[1]),i.ansi[2]=K(e.green,re[2]),i.ansi[3]=K(e.yellow,re[3]),i.ansi[4]=K(e.blue,re[4]),i.ansi[5]=K(e.magenta,re[5]),i.ansi[6]=K(e.cyan,re[6]),i.ansi[7]=K(e.white,re[7]),i.ansi[8]=K(e.brightBlack,re[8]),i.ansi[9]=K(e.brightRed,re[9]),i.ansi[10]=K(e.brightGreen,re[10]),i.ansi[11]=K(e.brightYellow,re[11]),i.ansi[12]=K(e.brightBlue,re[12]),i.ansi[13]=K(e.brightMagenta,re[13]),i.ansi[14]=K(e.brightCyan,re[14]),i.ansi[15]=K(e.brightWhite,re[15]),e.extendedAnsi){let r=Math.min(i.ansi.length-16,e.extendedAnsi.length);for(let n=0;no.index-l.index),r=[];for(let o of i){let l=this._services.get(o.id);if(!l)throw new Error(`[createInstance] ${t.name} depends on UNKNOWN service ${o.id._id}.`);r.push(l)}let n=i.length>0?i[0].index:e.length;if(e.length!==n)throw new Error(`[createInstance] First service dependency of ${t.name} at position ${n+1} conflicts with ${e.length} static arguments`);return new t(...e,...r)}};var ec={trace:0,debug:1,info:2,warn:3,error:4,off:5},tc="xterm.js: ",ii=class extends D{constructor(e){super();this._optionsService=e;this._logLevel=5;this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange("logLevel",()=>this._updateLogLevel())),ic=this}get logLevel(){return this._logLevel}_updateLogLevel(){this._logLevel=ec[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e){for(let i=0;ithis._length)for(let i=this._length;i=e;n--)this._array[this._getCyclicIndex(n+r.length)]=this._array[this._getCyclicIndex(n)];for(let n=0;nthis._maxLength){let n=this._length+r.length-this._maxLength;this._startIndex+=n,this._length=this._maxLength,this.onTrimEmitter.fire(n)}else this._length+=r.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,i,r){if(!(i<=0)){if(e<0||e>=this._length)throw new Error("start argument out of range");if(e+r<0)throw new Error("Cannot shift elements in list beyond index 0");if(r>0){for(let o=i-1;o>=0;o--)this.set(e+o+r,this.get(e+o));let n=e+i+r-this._length;if(n>0)for(this._length+=n;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let n=0;n>22,e&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):i]}set(t,e){this._data[t*B+1]=e[0],e[1].length>1?(this._combined[t]=e[1],this._data[t*B+0]=t|2097152|e[2]<<22):this._data[t*B+0]=e[1].charCodeAt(0)|e[2]<<22}getWidth(t){return this._data[t*B+0]>>22}hasWidth(t){return this._data[t*B+0]&12582912}getFg(t){return this._data[t*B+1]}getBg(t){return this._data[t*B+2]}hasContent(t){return this._data[t*B+0]&4194303}getCodePoint(t){let e=this._data[t*B+0];return e&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):e&2097151}isCombined(t){return this._data[t*B+0]&2097152}getString(t){let e=this._data[t*B+0];return e&2097152?this._combined[t]:e&2097151?Ce(e&2097151):""}isProtected(t){return this._data[t*B+2]&536870912}loadCell(t,e){return an=t*B,e.content=this._data[an+0],e.fg=this._data[an+1],e.bg=this._data[an+2],e.content&2097152&&(e.combinedData=this._combined[t]),e.bg&268435456&&(e.extended=this._extendedAttrs[t]),e}setCell(t,e){e.content&2097152&&(this._combined[t]=e.combinedData),e.bg&268435456&&(this._extendedAttrs[t]=e.extended),this._data[t*B+0]=e.content,this._data[t*B+1]=e.fg,this._data[t*B+2]=e.bg}setCellFromCodepoint(t,e,i,r){r.bg&268435456&&(this._extendedAttrs[t]=r.extended),this._data[t*B+0]=e|i<<22,this._data[t*B+1]=r.fg,this._data[t*B+2]=r.bg}addCodepointToCell(t,e,i){let r=this._data[t*B+0];r&2097152?this._combined[t]+=Ce(e):r&2097151?(this._combined[t]=Ce(r&2097151)+Ce(e),r&=-2097152,r|=2097152):r=e|1<<22,i&&(r&=-12582913,r|=i<<22),this._data[t*B+0]=r}insertCells(t,e,i){if(t%=this.length,t&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t-1,0,1,i),e=0;--n)this.setCell(t+e+n,this.loadCell(t+n,r));for(let n=0;nthis.length){if(this._data.buffer.byteLength>=i*4)this._data=new Uint32Array(this._data.buffer,0,i);else{let r=new Uint32Array(i);r.set(this._data),this._data=r}for(let r=this.length;r=t&&delete this._combined[l]}let n=Object.keys(this._extendedAttrs);for(let o=0;o=t&&delete this._extendedAttrs[l]}}return this.length=t,i*4*Ls=0;--t)if(this._data[t*B+0]&4194303)return t+(this._data[t*B+0]>>22);return 0}getNoBgTrimmedLength(){for(let t=this.length-1;t>=0;--t)if(this._data[t*B+0]&4194303||this._data[t*B+2]&50331648)return t+(this._data[t*B+0]>>22);return 0}copyCellsFrom(t,e,i,r,n){let o=t._data;if(n)for(let a=r-1;a>=0;a--){for(let u=0;u=e&&(this._combined[u-e+i]=t._combined[u])}}translateToString(t,e,i,r){e=e??0,i=i??this.length,t&&(i=Math.min(i,this.getTrimmedLength())),r&&(r.length=0);let n="";for(;e>22||1}return r&&r.push(e),n}};function sl(s,t,e,i,r,n){let o=[];for(let l=0;l=l&&i0&&(f>c||h[f].getTrimmedLength()===0);f--)m++;m>0&&(o.push(l+h.length-m),o.push(m)),l+=h.length-1}return o}function ol(s,t){let e=[],i=0,r=t[i],n=0;for(let o=0;ori(s,u,t)).reduce((a,u)=>a+u),n=0,o=0,l=0;for(;la&&(n-=a,o++);let u=s[o].getWidth(n-1)===2;u&&n--;let h=u?e-1:e;i.push(h),l+=h}return i}function ri(s,t,e){if(t===s.length-1)return s[t].getTrimmedLength();let i=!s[t].hasContent(e-1)&&s[t].getWidth(e-1)===1,r=s[t+1].getWidth(0)===2;return i&&r?e-1:e}var un=class un{constructor(t){this.line=t;this.isDisposed=!1;this._disposables=[];this._id=un._nextId++;this._onDispose=this.register(new v);this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),Ne(this._disposables),this._disposables.length=0)}register(t){return this._disposables.push(t),t}};un._nextId=1;var cn=un;var ne={},Je=ne.B;ne[0]={"`":"\u25C6",a:"\u2592",b:"\u2409",c:"\u240C",d:"\u240D",e:"\u240A",f:"\xB0",g:"\xB1",h:"\u2424",i:"\u240B",j:"\u2518",k:"\u2510",l:"\u250C",m:"\u2514",n:"\u253C",o:"\u23BA",p:"\u23BB",q:"\u2500",r:"\u23BC",s:"\u23BD",t:"\u251C",u:"\u2524",v:"\u2534",w:"\u252C",x:"\u2502",y:"\u2264",z:"\u2265","{":"\u03C0","|":"\u2260","}":"\xA3","~":"\xB7"};ne.A={"#":"\xA3"};ne.B=void 0;ne[4]={"#":"\xA3","@":"\xBE","[":"ij","\\":"\xBD","]":"|","{":"\xA8","|":"f","}":"\xBC","~":"\xB4"};ne.C=ne[5]={"[":"\xC4","\\":"\xD6","]":"\xC5","^":"\xDC","`":"\xE9","{":"\xE4","|":"\xF6","}":"\xE5","~":"\xFC"};ne.R={"#":"\xA3","@":"\xE0","[":"\xB0","\\":"\xE7","]":"\xA7","{":"\xE9","|":"\xF9","}":"\xE8","~":"\xA8"};ne.Q={"@":"\xE0","[":"\xE2","\\":"\xE7","]":"\xEA","^":"\xEE","`":"\xF4","{":"\xE9","|":"\xF9","}":"\xE8","~":"\xFB"};ne.K={"@":"\xA7","[":"\xC4","\\":"\xD6","]":"\xDC","{":"\xE4","|":"\xF6","}":"\xFC","~":"\xDF"};ne.Y={"#":"\xA3","@":"\xA7","[":"\xB0","\\":"\xE7","]":"\xE9","`":"\xF9","{":"\xE0","|":"\xF2","}":"\xE8","~":"\xEC"};ne.E=ne[6]={"@":"\xC4","[":"\xC6","\\":"\xD8","]":"\xC5","^":"\xDC","`":"\xE4","{":"\xE6","|":"\xF8","}":"\xE5","~":"\xFC"};ne.Z={"#":"\xA3","@":"\xA7","[":"\xA1","\\":"\xD1","]":"\xBF","{":"\xB0","|":"\xF1","}":"\xE7"};ne.H=ne[7]={"@":"\xC9","[":"\xC4","\\":"\xD6","]":"\xC5","^":"\xDC","`":"\xE9","{":"\xE4","|":"\xF6","}":"\xE5","~":"\xFC"};ne["="]={"#":"\xF9","@":"\xE0","[":"\xE9","\\":"\xE7","]":"\xEA","^":"\xEE",_:"\xE8","`":"\xF4","{":"\xE4","|":"\xF6","}":"\xFC","~":"\xFB"};var cl=4294967295,$i=class{constructor(t,e,i){this._hasScrollback=t;this._optionsService=e;this._bufferService=i;this.ydisp=0;this.ybase=0;this.y=0;this.x=0;this.tabs={};this.savedY=0;this.savedX=0;this.savedCurAttrData=X.clone();this.savedCharset=Je;this.markers=[];this._nullCell=q.fromCharData([0,ir,1,0]);this._whitespaceCell=q.fromCharData([0,we,1,32]);this._isClearing=!1;this._memoryCleanupQueue=new Jt;this._memoryCleanupPosition=0;this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new zi(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(t){return t?(this._nullCell.fg=t.fg,this._nullCell.bg=t.bg,this._nullCell.extended=t.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new rt),this._nullCell}getWhitespaceCell(t){return t?(this._whitespaceCell.fg=t.fg,this._whitespaceCell.bg=t.bg,this._whitespaceCell.extended=t.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new rt),this._whitespaceCell}getBlankLine(t,e){return new Ze(this._bufferService.cols,this.getNullCell(t),e)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let e=this.ybase+this.y-this.ydisp;return e>=0&&ecl?cl:e}fillViewportRows(t){if(this.lines.length===0){t===void 0&&(t=X);let e=this._rows;for(;e--;)this.lines.push(this.getBlankLine(t))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new zi(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(t,e){let i=this.getNullCell(X),r=0,n=this._getCorrectBufferLength(e);if(n>this.lines.maxLength&&(this.lines.maxLength=n),this.lines.length>0){if(this._cols0&&this.lines.length<=this.ybase+this.y+o+1?(this.ybase--,o++,this.ydisp>0&&this.ydisp--):this.lines.push(new Ze(t,i)));else for(let l=this._rows;l>e;l--)this.lines.length>e+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(n0&&(this.lines.trimStart(l),this.ybase=Math.max(this.ybase-l,0),this.ydisp=Math.max(this.ydisp-l,0),this.savedY=Math.max(this.savedY-l,0)),this.lines.maxLength=n}this.x=Math.min(this.x,t-1),this.y=Math.min(this.y,e-1),o&&(this.y+=o),this.savedX=Math.min(this.savedX,t-1),this.scrollTop=0}if(this.scrollBottom=e-1,this._isReflowEnabled&&(this._reflow(t,e),this._cols>t))for(let o=0;o.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let t=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,t=!1);let e=0;for(;this._memoryCleanupPosition100)return!0;return t}get _isReflowEnabled(){let t=this._optionsService.rawOptions.windowsPty;return t&&t.buildNumber?this._hasScrollback&&t.backend==="conpty"&&t.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(t,e){this._cols!==t&&(t>this._cols?this._reflowLarger(t,e):this._reflowSmaller(t,e))}_reflowLarger(t,e){let i=this._optionsService.rawOptions.reflowCursorLine,r=sl(this.lines,this._cols,t,this.ybase+this.y,this.getNullCell(X),i);if(r.length>0){let n=ol(this.lines,r);ll(this.lines,n.layout),this._reflowLargerAdjustViewport(t,e,n.countRemoved)}}_reflowLargerAdjustViewport(t,e,i){let r=this.getNullCell(X),n=i;for(;n-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length=0;l--){let a=this.lines.get(l);if(!a||!a.isWrapped&&a.getTrimmedLength()<=t)continue;let u=[a];for(;a.isWrapped&&l>0;)a=this.lines.get(--l),u.unshift(a);if(!i){let I=this.ybase+this.y;if(I>=l&&I0&&(n.push({start:l+u.length+o,newLines:p}),o+=p.length),u.push(...p);let m=c.length-1,f=c[m];f===0&&(m--,f=c[m]);let A=u.length-d-1,R=h;for(;A>=0;){let I=Math.min(R,f);if(u[m]===void 0)break;if(u[m].copyCellsFrom(u[A],R-I,f-I,I,!0),f-=I,f===0&&(m--,f=c[m]),R-=I,R===0){A--;let k=Math.max(A,0);R=ri(u,k,this._cols)}}for(let I=0;I0;)this.ybase===0?this.y0){let l=[],a=[];for(let f=0;f=0;f--)if(d&&d.start>h+_){for(let A=d.newLines.length-1;A>=0;A--)this.lines.set(f--,d.newLines[A]);f++,l.push({index:h+1,amount:d.newLines.length}),_+=d.newLines.length,d=n[++c]}else this.lines.set(f,a[h--]);let p=0;for(let f=l.length-1;f>=0;f--)l[f].index+=p,this.lines.onInsertEmitter.fire(l[f]),p+=l[f].amount;let m=Math.max(0,u+o-this.lines.maxLength);m>0&&this.lines.onTrimEmitter.fire(m)}}translateBufferLineToString(t,e,i=0,r){let n=this.lines.get(t);return n?n.translateToString(e,i,r):""}getWrappedRangeForLine(t){let e=t,i=t;for(;e>0&&this.lines.get(e).isWrapped;)e--;for(;i+10;);return t>=this._cols?this._cols-1:t<0?0:t}nextStop(t){for(t==null&&(t=this.x);!this.tabs[++t]&&t=this._cols?this._cols-1:t<0?0:t}clearMarkers(t){this._isClearing=!0;for(let e=0;e{e.line-=i,e.line<0&&e.dispose()})),e.register(this.lines.onInsert(i=>{e.line>=i.index&&(e.line+=i.amount)})),e.register(this.lines.onDelete(i=>{e.line>=i.index&&e.linei.index&&(e.line-=i.amount)})),e.register(e.onDispose(()=>this._removeMarker(e))),e}_removeMarker(t){this._isClearing||this.markers.splice(this.markers.indexOf(t),1)}};var hn=class extends D{constructor(e,i){super();this._optionsService=e;this._bufferService=i;this._onBufferActivate=this._register(new v);this.onBufferActivate=this._onBufferActivate.event;this.reset(),this._register(this._optionsService.onSpecificOptionChange("scrollback",()=>this.resize(this._bufferService.cols,this._bufferService.rows))),this._register(this._optionsService.onSpecificOptionChange("tabStopWidth",()=>this.setupTabStops()))}reset(){this._normal=new $i(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new $i(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(e){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(e,i){this._normal.resize(e,i),this._alt.resize(e,i),this.setupTabStops(e)}setupTabStops(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)}};var ks=2,Cs=1,ni=class extends D{constructor(e){super();this.isUserScrolling=!1;this._onResize=this._register(new v);this.onResize=this._onResize.event;this._onScroll=this._register(new v);this.onScroll=this._onScroll.event;this.cols=Math.max(e.rawOptions.cols||0,ks),this.rows=Math.max(e.rawOptions.rows||0,Cs),this.buffers=this._register(new hn(e,this)),this._register(this.buffers.onBufferActivate(i=>{this._onScroll.fire(i.activeBuffer.ydisp)}))}get buffer(){return this.buffers.active}resize(e,i){let r=this.cols!==e,n=this.rows!==i;this.cols=e,this.rows=i,this.buffers.resize(e,i),this._onResize.fire({cols:e,rows:i,colsChanged:r,rowsChanged:n})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,i=!1){let r=this.buffer,n;n=this._cachedBlankLine,(!n||n.length!==this.cols||n.getFg(0)!==e.fg||n.getBg(0)!==e.bg)&&(n=r.getBlankLine(e,i),this._cachedBlankLine=n),n.isWrapped=i;let o=r.ybase+r.scrollTop,l=r.ybase+r.scrollBottom;if(r.scrollTop===0){let a=r.lines.isFull;l===r.lines.length-1?a?r.lines.recycle().copyFrom(n):r.lines.push(n.clone()):r.lines.splice(l+1,0,n.clone()),a?this.isUserScrolling&&(r.ydisp=Math.max(r.ydisp-1,0)):(r.ybase++,this.isUserScrolling||r.ydisp++)}else{let a=l-o+1;r.lines.shiftElements(o+1,a-1,-1),r.lines.set(l,n.clone())}this.isUserScrolling||(r.ydisp=r.ybase),this._onScroll.fire(r.ydisp)}scrollLines(e,i){let r=this.buffer;if(e<0){if(r.ydisp===0)return;this.isUserScrolling=!0}else e+r.ydisp>=r.ybase&&(this.isUserScrolling=!1);let n=r.ydisp;r.ydisp=Math.max(Math.min(r.ydisp+e,r.ybase),0),n!==r.ydisp&&(i||this._onScroll.fire(r.ydisp))}};ni=M([S(0,H)],ni);var si={cols:80,rows:24,cursorBlink:!1,cursorStyle:"block",cursorWidth:1,cursorInactiveStyle:"outline",customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:"alt",fastScrollSensitivity:5,fontFamily:"monospace",fontSize:15,fontWeight:"normal",fontWeightBold:"bold",ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:"info",logger:null,scrollback:1e3,scrollOnEraseInDisplay:!1,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},reflowCursorLine:!1,rescaleOverlappingGlyphs:!1,rightClickSelectsWord:Zt,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRuler:{}},nc=["normal","bold","100","200","300","400","500","600","700","800","900"],dn=class extends D{constructor(e){super();this._onOptionChange=this._register(new v);this.onOptionChange=this._onOptionChange.event;let i={...si};for(let r in e)if(r in i)try{let n=e[r];i[r]=this._sanitizeAndValidateOption(r,n)}catch(n){console.error(n)}this.rawOptions=i,this.options={...i},this._setupOptions(),this._register(C(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(e,i){return this.onOptionChange(r=>{r===e&&i(this.rawOptions[e])})}onMultipleOptionChange(e,i){return this.onOptionChange(r=>{e.indexOf(r)!==-1&&i()})}_setupOptions(){let e=r=>{if(!(r in si))throw new Error(`No option with key "${r}"`);return this.rawOptions[r]},i=(r,n)=>{if(!(r in si))throw new Error(`No option with key "${r}"`);n=this._sanitizeAndValidateOption(r,n),this.rawOptions[r]!==n&&(this.rawOptions[r]=n,this._onOptionChange.fire(r))};for(let r in this.rawOptions){let n={get:e.bind(this,r),set:i.bind(this,r)};Object.defineProperty(this.options,r,n)}}_sanitizeAndValidateOption(e,i){switch(e){case"cursorStyle":if(i||(i=si[e]),!sc(i))throw new Error(`"${i}" is not a valid value for ${e}`);break;case"wordSeparator":i||(i=si[e]);break;case"fontWeight":case"fontWeightBold":if(typeof i=="number"&&1<=i&&i<=1e3)break;i=nc.includes(i)?i:si[e];break;case"cursorWidth":i=Math.floor(i);case"lineHeight":case"tabStopWidth":if(i<1)throw new Error(`${e} cannot be less than 1, value: ${i}`);break;case"minimumContrastRatio":i=Math.max(1,Math.min(21,Math.round(i*10)/10));break;case"scrollback":if(i=Math.min(i,4294967295),i<0)throw new Error(`${e} cannot be less than 0, value: ${i}`);break;case"fastScrollSensitivity":case"scrollSensitivity":if(i<=0)throw new Error(`${e} cannot be less than or equal to 0, value: ${i}`);break;case"rows":case"cols":if(!i&&i!==0)throw new Error(`${e} must be numeric, value: ${i}`);break;case"windowsPty":i=i??{};break}return i}};function sc(s){return s==="block"||s==="underline"||s==="bar"}function oi(s,t=5){if(typeof s!="object")return s;let e=Array.isArray(s)?[]:{};for(let i in s)e[i]=t<=1?s[i]:s[i]&&oi(s[i],t-1);return e}var ul=Object.freeze({insertMode:!1}),hl=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),li=class extends D{constructor(e,i,r){super();this._bufferService=e;this._logService=i;this._optionsService=r;this.isCursorInitialized=!1;this.isCursorHidden=!1;this._onData=this._register(new v);this.onData=this._onData.event;this._onUserInput=this._register(new v);this.onUserInput=this._onUserInput.event;this._onBinary=this._register(new v);this.onBinary=this._onBinary.event;this._onRequestScrollToBottom=this._register(new v);this.onRequestScrollToBottom=this._onRequestScrollToBottom.event;this.modes=oi(ul),this.decPrivateModes=oi(hl)}reset(){this.modes=oi(ul),this.decPrivateModes=oi(hl)}triggerDataEvent(e,i=!1){if(this._optionsService.rawOptions.disableStdin)return;let r=this._bufferService.buffer;i&&this._optionsService.rawOptions.scrollOnUserInput&&r.ybase!==r.ydisp&&this._onRequestScrollToBottom.fire(),i&&this._onUserInput.fire(),this._logService.debug(`sending data "${e}"`),this._logService.trace("sending data (codes)",()=>e.split("").map(n=>n.charCodeAt(0))),this._onData.fire(e)}triggerBinaryEvent(e){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${e}"`),this._logService.trace("sending binary (codes)",()=>e.split("").map(i=>i.charCodeAt(0))),this._onBinary.fire(e))}};li=M([S(0,F),S(1,nr),S(2,H)],li);var dl={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:s=>s.button===4||s.action!==1?!1:(s.ctrl=!1,s.alt=!1,s.shift=!1,!0)},VT200:{events:19,restrict:s=>s.action!==32},DRAG:{events:23,restrict:s=>!(s.action===32&&s.button===3)},ANY:{events:31,restrict:s=>!0}};function Ms(s,t){let e=(s.ctrl?16:0)|(s.shift?4:0)|(s.alt?8:0);return s.button===4?(e|=64,e|=s.action):(e|=s.button&3,s.button&4&&(e|=64),s.button&8&&(e|=128),s.action===32?e|=32:s.action===0&&!t&&(e|=3)),e}var Ps=String.fromCharCode,fl={DEFAULT:s=>{let t=[Ms(s,!1)+32,s.col+32,s.row+32];return t[0]>255||t[1]>255||t[2]>255?"":`\x1B[M${Ps(t[0])}${Ps(t[1])}${Ps(t[2])}`},SGR:s=>{let t=s.action===0&&s.button!==4?"m":"M";return`\x1B[<${Ms(s,!0)};${s.col};${s.row}${t}`},SGR_PIXELS:s=>{let t=s.action===0&&s.button!==4?"m":"M";return`\x1B[<${Ms(s,!0)};${s.x};${s.y}${t}`}},ai=class extends D{constructor(e,i,r){super();this._bufferService=e;this._coreService=i;this._optionsService=r;this._protocols={};this._encodings={};this._activeProtocol="";this._activeEncoding="";this._lastEvent=null;this._wheelPartialScroll=0;this._onProtocolChange=this._register(new v);this.onProtocolChange=this._onProtocolChange.event;for(let n of Object.keys(dl))this.addProtocol(n,dl[n]);for(let n of Object.keys(fl))this.addEncoding(n,fl[n]);this.reset()}addProtocol(e,i){this._protocols[e]=i}addEncoding(e,i){this._encodings[e]=i}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(e){if(!this._protocols[e])throw new Error(`unknown protocol "${e}"`);this._activeProtocol=e,this._onProtocolChange.fire(this._protocols[e].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(e){if(!this._encodings[e])throw new Error(`unknown encoding "${e}"`);this._activeEncoding=e}reset(){this.activeProtocol="NONE",this.activeEncoding="DEFAULT",this._lastEvent=null,this._wheelPartialScroll=0}consumeWheelEvent(e,i,r){if(e.deltaY===0||e.shiftKey||i===void 0||r===void 0)return 0;let n=i/r,o=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(o/=n+0,Math.abs(e.deltaY)<50&&(o*=.3),this._wheelPartialScroll+=o,o=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(o*=this._bufferService.rows),o}_applyScrollModifier(e,i){return i.altKey||i.ctrlKey||i.shiftKey?e*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:e*this._optionsService.rawOptions.scrollSensitivity}triggerMouseEvent(e){if(e.col<0||e.col>=this._bufferService.cols||e.row<0||e.row>=this._bufferService.rows||e.button===4&&e.action===32||e.button===3&&e.action!==32||e.button!==4&&(e.action===2||e.action===3)||(e.col++,e.row++,e.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,e,this._activeEncoding==="SGR_PIXELS"))||!this._protocols[this._activeProtocol].restrict(e))return!1;let i=this._encodings[this._activeEncoding](e);return i&&(this._activeEncoding==="DEFAULT"?this._coreService.triggerBinaryEvent(i):this._coreService.triggerDataEvent(i,!0)),this._lastEvent=e,!0}explainEvents(e){return{down:!!(e&1),up:!!(e&2),drag:!!(e&4),move:!!(e&8),wheel:!!(e&16)}}_equalEvents(e,i,r){if(r){if(e.x!==i.x||e.y!==i.y)return!1}else if(e.col!==i.col||e.row!==i.row)return!1;return!(e.button!==i.button||e.action!==i.action||e.ctrl!==i.ctrl||e.alt!==i.alt||e.shift!==i.shift)}};ai=M([S(0,F),S(1,ge),S(2,H)],ai);var Os=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],ac=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]],se;function cc(s,t){let e=0,i=t.length-1,r;if(st[i][1])return!1;for(;i>=e;)if(r=e+i>>1,s>t[r][1])e=r+1;else if(s=131072&&t<=196605||t>=196608&&t<=262141?2:1}charProperties(t,e){let i=this.wcwidth(t),r=i===0&&e!==0;if(r){let n=Ae.extractWidth(e);n===0?r=!1:n>i&&(i=n)}return Ae.createPropertyValue(0,i,r)}};var Ae=class s{constructor(){this._providers=Object.create(null);this._active="";this._onChange=new v;this.onChange=this._onChange.event;let t=new fn;this.register(t),this._active=t.version,this._activeProvider=t}static extractShouldJoin(t){return(t&1)!==0}static extractWidth(t){return t>>1&3}static extractCharKind(t){return t>>3}static createPropertyValue(t,e,i=!1){return(t&16777215)<<3|(e&3)<<1|(i?1:0)}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(t){if(!this._providers[t])throw new Error(`unknown Unicode version "${t}"`);this._active=t,this._activeProvider=this._providers[t],this._onChange.fire(t)}register(t){this._providers[t.version]=t}wcwidth(t){return this._activeProvider.wcwidth(t)}getStringCellWidth(t){let e=0,i=0,r=t.length;for(let n=0;n=r)return e+this.wcwidth(o);let u=t.charCodeAt(n);56320<=u&&u<=57343?o=(o-55296)*1024+u-56320+65536:e+=this.wcwidth(u)}let l=this.charProperties(o,i),a=s.extractWidth(l);s.extractShouldJoin(l)&&(a-=s.extractWidth(i)),e+=a,i=l}return e}charProperties(t,e){return this._activeProvider.charProperties(t,e)}};var pn=class{constructor(){this.glevel=0;this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(t){this.glevel=t,this.charset=this._charsets[t]}setgCharset(t,e){this._charsets[t]=e,this.glevel===t&&(this.charset=e)}};function Bs(s){let e=s.buffer.lines.get(s.buffer.ybase+s.buffer.y-1)?.get(s.cols-1),i=s.buffer.lines.get(s.buffer.ybase+s.buffer.y);i&&e&&(i.isWrapped=e[3]!==0&&e[3]!==32)}var Vi=2147483647,uc=256,ci=class s{constructor(t=32,e=32){this.maxLength=t;this.maxSubParamsLength=e;if(e>uc)throw new Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(t),this.length=0,this._subParams=new Int32Array(e),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(t),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}static fromArray(t){let e=new s;if(!t.length)return e;for(let i=Array.isArray(t[0])?1:0;i>8,r=this._subParamsIdx[e]&255;r-i>0&&t.push(Array.prototype.slice.call(this._subParams,i,r))}return t}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(t){if(this._digitIsSub=!1,this.length>=this.maxLength){this._rejectDigits=!0;return}if(t<-1)throw new Error("values lesser than -1 are not allowed");this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=t>Vi?Vi:t}addSubParam(t){if(this._digitIsSub=!0,!!this.length){if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength){this._rejectSubDigits=!0;return}if(t<-1)throw new Error("values lesser than -1 are not allowed");this._subParams[this._subParamsLength++]=t>Vi?Vi:t,this._subParamsIdx[this.length-1]++}}hasSubParams(t){return(this._subParamsIdx[t]&255)-(this._subParamsIdx[t]>>8)>0}getSubParams(t){let e=this._subParamsIdx[t]>>8,i=this._subParamsIdx[t]&255;return i-e>0?this._subParams.subarray(e,i):null}getSubParamsAll(){let t={};for(let e=0;e>8,r=this._subParamsIdx[e]&255;r-i>0&&(t[e]=this._subParams.slice(i,r))}return t}addDigit(t){let e;if(this._rejectDigits||!(e=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let i=this._digitIsSub?this._subParams:this.params,r=i[e-1];i[e-1]=~r?Math.min(r*10+t,Vi):t}};var qi=[],mn=class{constructor(){this._state=0;this._active=qi;this._id=-1;this._handlers=Object.create(null);this._handlerFb=()=>{};this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(t,e){this._handlers[t]===void 0&&(this._handlers[t]=[]);let i=this._handlers[t];return i.push(e),{dispose:()=>{let r=i.indexOf(e);r!==-1&&i.splice(r,1)}}}clearHandler(t){this._handlers[t]&&delete this._handlers[t]}setHandlerFallback(t){this._handlerFb=t}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=qi}reset(){if(this._state===2)for(let t=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;t>=0;--t)this._active[t].end(!1);this._stack.paused=!1,this._active=qi,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||qi,!this._active.length)this._handlerFb(this._id,"START");else for(let t=this._active.length-1;t>=0;t--)this._active[t].start()}_put(t,e,i){if(!this._active.length)this._handlerFb(this._id,"PUT",It(t,e,i));else for(let r=this._active.length-1;r>=0;r--)this._active[r].put(t,e,i)}start(){this.reset(),this._state=1}put(t,e,i){if(this._state!==3){if(this._state===1)for(;e0&&this._put(t,e,i)}}end(t,e=!0){if(this._state!==0){if(this._state!==3)if(this._state===1&&this._start(),!this._active.length)this._handlerFb(this._id,"END",t);else{let i=!1,r=this._active.length-1,n=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,i=e,n=this._stack.fallThrough,this._stack.paused=!1),!n&&i===!1){for(;r>=0&&(i=this._active[r].end(t),i!==!0);r--)if(i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,i;r--}for(;r>=0;r--)if(i=this._active[r].end(!1),i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,i}this._active=qi,this._id=-1,this._state=0}}},pe=class{constructor(t){this._handler=t;this._data="";this._hitLimit=!1}start(){this._data="",this._hitLimit=!1}put(t,e,i){this._hitLimit||(this._data+=It(t,e,i),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}end(t){let e=!1;if(this._hitLimit)e=!1;else if(t&&(e=this._handler(this._data),e instanceof Promise))return e.then(i=>(this._data="",this._hitLimit=!1,i));return this._data="",this._hitLimit=!1,e}};var Yi=[],_n=class{constructor(){this._handlers=Object.create(null);this._active=Yi;this._ident=0;this._handlerFb=()=>{};this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=Yi}registerHandler(t,e){this._handlers[t]===void 0&&(this._handlers[t]=[]);let i=this._handlers[t];return i.push(e),{dispose:()=>{let r=i.indexOf(e);r!==-1&&i.splice(r,1)}}}clearHandler(t){this._handlers[t]&&delete this._handlers[t]}setHandlerFallback(t){this._handlerFb=t}reset(){if(this._active.length)for(let t=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;t>=0;--t)this._active[t].unhook(!1);this._stack.paused=!1,this._active=Yi,this._ident=0}hook(t,e){if(this.reset(),this._ident=t,this._active=this._handlers[t]||Yi,!this._active.length)this._handlerFb(this._ident,"HOOK",e);else for(let i=this._active.length-1;i>=0;i--)this._active[i].hook(e)}put(t,e,i){if(!this._active.length)this._handlerFb(this._ident,"PUT",It(t,e,i));else for(let r=this._active.length-1;r>=0;r--)this._active[r].put(t,e,i)}unhook(t,e=!0){if(!this._active.length)this._handlerFb(this._ident,"UNHOOK",t);else{let i=!1,r=this._active.length-1,n=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,i=e,n=this._stack.fallThrough,this._stack.paused=!1),!n&&i===!1){for(;r>=0&&(i=this._active[r].unhook(t),i!==!0);r--)if(i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,i;r--}for(;r>=0;r--)if(i=this._active[r].unhook(!1),i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,i}this._active=Yi,this._ident=0}},ji=new ci;ji.addParam(0);var Xi=class{constructor(t){this._handler=t;this._data="";this._params=ji;this._hitLimit=!1}hook(t){this._params=t.length>1||t.params[0]?t.clone():ji,this._data="",this._hitLimit=!1}put(t,e,i){this._hitLimit||(this._data+=It(t,e,i),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}unhook(t){let e=!1;if(this._hitLimit)e=!1;else if(t&&(e=this._handler(this._data,this._params),e instanceof Promise))return e.then(i=>(this._params=ji,this._data="",this._hitLimit=!1,i));return this._params=ji,this._data="",this._hitLimit=!1,e}};var Fs=class{constructor(t){this.table=new Uint8Array(t)}setDefault(t,e){this.table.fill(t<<4|e)}add(t,e,i,r){this.table[e<<8|t]=i<<4|r}addMany(t,e,i,r){for(let n=0;nu),i=(a,u)=>e.slice(a,u),r=i(32,127),n=i(0,24);n.push(25),n.push.apply(n,i(28,32));let o=i(0,14),l;s.setDefault(1,0),s.addMany(r,0,2,0);for(l in o)s.addMany([24,26,153,154],l,3,0),s.addMany(i(128,144),l,3,0),s.addMany(i(144,152),l,3,0),s.add(156,l,0,0),s.add(27,l,11,1),s.add(157,l,4,8),s.addMany([152,158,159],l,0,7),s.add(155,l,11,3),s.add(144,l,11,9);return s.addMany(n,0,3,0),s.addMany(n,1,3,1),s.add(127,1,0,1),s.addMany(n,8,0,8),s.addMany(n,3,3,3),s.add(127,3,0,3),s.addMany(n,4,3,4),s.add(127,4,0,4),s.addMany(n,6,3,6),s.addMany(n,5,3,5),s.add(127,5,0,5),s.addMany(n,2,3,2),s.add(127,2,0,2),s.add(93,1,4,8),s.addMany(r,8,5,8),s.add(127,8,5,8),s.addMany([156,27,24,26,7],8,6,0),s.addMany(i(28,32),8,0,8),s.addMany([88,94,95],1,0,7),s.addMany(r,7,0,7),s.addMany(n,7,0,7),s.add(156,7,0,0),s.add(127,7,0,7),s.add(91,1,11,3),s.addMany(i(64,127),3,7,0),s.addMany(i(48,60),3,8,4),s.addMany([60,61,62,63],3,9,4),s.addMany(i(48,60),4,8,4),s.addMany(i(64,127),4,7,0),s.addMany([60,61,62,63],4,0,6),s.addMany(i(32,64),6,0,6),s.add(127,6,0,6),s.addMany(i(64,127),6,0,0),s.addMany(i(32,48),3,9,5),s.addMany(i(32,48),5,9,5),s.addMany(i(48,64),5,0,6),s.addMany(i(64,127),5,7,0),s.addMany(i(32,48),4,9,5),s.addMany(i(32,48),1,9,2),s.addMany(i(32,48),2,9,2),s.addMany(i(48,127),2,10,0),s.addMany(i(48,80),1,10,0),s.addMany(i(81,88),1,10,0),s.addMany([89,90,92],1,10,0),s.addMany(i(96,127),1,10,0),s.add(80,1,11,9),s.addMany(n,9,0,9),s.add(127,9,0,9),s.addMany(i(28,32),9,0,9),s.addMany(i(32,48),9,9,12),s.addMany(i(48,60),9,8,10),s.addMany([60,61,62,63],9,9,10),s.addMany(n,11,0,11),s.addMany(i(32,128),11,0,11),s.addMany(i(28,32),11,0,11),s.addMany(n,10,0,10),s.add(127,10,0,10),s.addMany(i(28,32),10,0,10),s.addMany(i(48,60),10,8,10),s.addMany([60,61,62,63],10,0,11),s.addMany(i(32,48),10,9,12),s.addMany(n,12,0,12),s.add(127,12,0,12),s.addMany(i(28,32),12,0,12),s.addMany(i(32,48),12,9,12),s.addMany(i(48,64),12,0,11),s.addMany(i(64,127),12,12,13),s.addMany(i(64,127),10,12,13),s.addMany(i(64,127),9,12,13),s.addMany(n,13,13,13),s.addMany(r,13,13,13),s.add(127,13,0,13),s.addMany([27,156,24,26],13,14,0),s.add(ke,0,2,0),s.add(ke,8,5,8),s.add(ke,6,0,6),s.add(ke,11,0,11),s.add(ke,13,13,13),s}(),bn=class extends D{constructor(e=hc){super();this._transitions=e;this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0};this.initialState=0,this.currentState=this.initialState,this._params=new ci,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(i,r,n)=>{},this._executeHandlerFb=i=>{},this._csiHandlerFb=(i,r)=>{},this._escHandlerFb=i=>{},this._errorHandlerFb=i=>i,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this._register(C(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new mn),this._dcsParser=this._register(new _n),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:"\\"},()=>!0)}_identifier(e,i=[64,126]){let r=0;if(e.prefix){if(e.prefix.length>1)throw new Error("only one byte as prefix supported");if(r=e.prefix.charCodeAt(0),r&&60>r||r>63)throw new Error("prefix must be in range 0x3c .. 0x3f")}if(e.intermediates){if(e.intermediates.length>2)throw new Error("only two bytes as intermediates are supported");for(let o=0;ol||l>47)throw new Error("intermediate must be in range 0x20 .. 0x2f");r<<=8,r|=l}}if(e.final.length!==1)throw new Error("final must be a single byte");let n=e.final.charCodeAt(0);if(i[0]>n||n>i[1])throw new Error(`final must be in range ${i[0]} .. ${i[1]}`);return r<<=8,r|=n,r}identToString(e){let i=[];for(;e;)i.push(String.fromCharCode(e&255)),e>>=8;return i.reverse().join("")}setPrintHandler(e){this._printHandler=e}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(e,i){let r=this._identifier(e,[48,126]);this._escHandlers[r]===void 0&&(this._escHandlers[r]=[]);let n=this._escHandlers[r];return n.push(i),{dispose:()=>{let o=n.indexOf(i);o!==-1&&n.splice(o,1)}}}clearEscHandler(e){this._escHandlers[this._identifier(e,[48,126])]&&delete this._escHandlers[this._identifier(e,[48,126])]}setEscHandlerFallback(e){this._escHandlerFb=e}setExecuteHandler(e,i){this._executeHandlers[e.charCodeAt(0)]=i}clearExecuteHandler(e){this._executeHandlers[e.charCodeAt(0)]&&delete this._executeHandlers[e.charCodeAt(0)]}setExecuteHandlerFallback(e){this._executeHandlerFb=e}registerCsiHandler(e,i){let r=this._identifier(e);this._csiHandlers[r]===void 0&&(this._csiHandlers[r]=[]);let n=this._csiHandlers[r];return n.push(i),{dispose:()=>{let o=n.indexOf(i);o!==-1&&n.splice(o,1)}}}clearCsiHandler(e){this._csiHandlers[this._identifier(e)]&&delete this._csiHandlers[this._identifier(e)]}setCsiHandlerFallback(e){this._csiHandlerFb=e}registerDcsHandler(e,i){return this._dcsParser.registerHandler(this._identifier(e),i)}clearDcsHandler(e){this._dcsParser.clearHandler(this._identifier(e))}setDcsHandlerFallback(e){this._dcsParser.setHandlerFallback(e)}registerOscHandler(e,i){return this._oscParser.registerHandler(e,i)}clearOscHandler(e){this._oscParser.clearHandler(e)}setOscHandlerFallback(e){this._oscParser.setHandlerFallback(e)}setErrorHandler(e){this._errorHandler=e}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(e,i,r,n,o){this._parseStack.state=e,this._parseStack.handlers=i,this._parseStack.handlerPos=r,this._parseStack.transition=n,this._parseStack.chunkPos=o}parse(e,i,r){let n=0,o=0,l=0,a;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,l=this._parseStack.chunkPos+1;else{if(r===void 0||this._parseStack.state===1)throw this._parseStack.state=1,new Error("improper continuation due to previous async handler, giving up parsing");let u=this._parseStack.handlers,h=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(r===!1&&h>-1){for(;h>=0&&(a=u[h](this._params),a!==!0);h--)if(a instanceof Promise)return this._parseStack.handlerPos=h,a}this._parseStack.handlers=[];break;case 4:if(r===!1&&h>-1){for(;h>=0&&(a=u[h](),a!==!0);h--)if(a instanceof Promise)return this._parseStack.handlerPos=h,a}this._parseStack.handlers=[];break;case 6:if(n=e[this._parseStack.chunkPos],a=this._dcsParser.unhook(n!==24&&n!==26,r),a)return a;n===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(n=e[this._parseStack.chunkPos],a=this._oscParser.end(n!==24&&n!==26,r),a)return a;n===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break}this._parseStack.state=0,l=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=this._parseStack.transition&15}for(let u=l;u>4){case 2:for(let m=u+1;;++m){if(m>=i||(n=e[m])<32||n>126&&n=i||(n=e[m])<32||n>126&&n=i||(n=e[m])<32||n>126&&n=i||(n=e[m])<32||n>126&&n=0&&(a=c[d](this._params),a!==!0);d--)if(a instanceof Promise)return this._preserveStack(3,c,d,o,u),a;d<0&&this._csiHandlerFb(this._collect<<8|n,this._params),this.precedingJoinState=0;break;case 8:do switch(n){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(n-48)}while(++u47&&n<60);u--;break;case 9:this._collect<<=8,this._collect|=n;break;case 10:let _=this._escHandlers[this._collect<<8|n],p=_?_.length-1:-1;for(;p>=0&&(a=_[p](),a!==!0);p--)if(a instanceof Promise)return this._preserveStack(4,_,p,o,u),a;p<0&&this._escHandlerFb(this._collect<<8|n),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|n,this._params);break;case 13:for(let m=u+1;;++m)if(m>=i||(n=e[m])===24||n===26||n===27||n>127&&n=i||(n=e[m])<32||n>127&&n>4:n>>8}return i}}function Hs(s,t){let e=s.toString(16),i=e.length<2?"0"+e:e;switch(t){case 4:return e[0];case 8:return i;case 12:return(i+i).slice(0,3);default:return i+i}}function ml(s,t=16){let[e,i,r]=s;return`rgb:${Hs(e,t)}/${Hs(i,t)}/${Hs(r,t)}`}var mc={"(":0,")":1,"*":2,"+":3,"-":1,".":2},ut=131072,_l=10;function bl(s,t){if(s>24)return t.setWinLines||!1;switch(s){case 1:return!!t.restoreWin;case 2:return!!t.minimizeWin;case 3:return!!t.setWinPosition;case 4:return!!t.setWinSizePixels;case 5:return!!t.raiseWin;case 6:return!!t.lowerWin;case 7:return!!t.refreshWin;case 8:return!!t.setWinSizeChars;case 9:return!!t.maximizeWin;case 10:return!!t.fullscreenWin;case 11:return!!t.getWinState;case 13:return!!t.getWinPosition;case 14:return!!t.getWinSizePixels;case 15:return!!t.getScreenSizePixels;case 16:return!!t.getCellSizePixels;case 18:return!!t.getWinSizeChars;case 19:return!!t.getScreenSizeChars;case 20:return!!t.getIconTitle;case 21:return!!t.getWinTitle;case 22:return!!t.pushTitle;case 23:return!!t.popTitle;case 24:return!!t.setWinLines}return!1}var vl=5e3,gl=0,vn=class extends D{constructor(e,i,r,n,o,l,a,u,h=new bn){super();this._bufferService=e;this._charsetService=i;this._coreService=r;this._logService=n;this._optionsService=o;this._oscLinkService=l;this._coreMouseService=a;this._unicodeService=u;this._parser=h;this._parseBuffer=new Uint32Array(4096);this._stringDecoder=new er;this._utf8Decoder=new tr;this._windowTitle="";this._iconName="";this._windowTitleStack=[];this._iconNameStack=[];this._curAttrData=X.clone();this._eraseAttrDataInternal=X.clone();this._onRequestBell=this._register(new v);this.onRequestBell=this._onRequestBell.event;this._onRequestRefreshRows=this._register(new v);this.onRequestRefreshRows=this._onRequestRefreshRows.event;this._onRequestReset=this._register(new v);this.onRequestReset=this._onRequestReset.event;this._onRequestSendFocus=this._register(new v);this.onRequestSendFocus=this._onRequestSendFocus.event;this._onRequestSyncScrollBar=this._register(new v);this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event;this._onRequestWindowsOptionsReport=this._register(new v);this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event;this._onA11yChar=this._register(new v);this.onA11yChar=this._onA11yChar.event;this._onA11yTab=this._register(new v);this.onA11yTab=this._onA11yTab.event;this._onCursorMove=this._register(new v);this.onCursorMove=this._onCursorMove.event;this._onLineFeed=this._register(new v);this.onLineFeed=this._onLineFeed.event;this._onScroll=this._register(new v);this.onScroll=this._onScroll.event;this._onTitleChange=this._register(new v);this.onTitleChange=this._onTitleChange.event;this._onColor=this._register(new v);this.onColor=this._onColor.event;this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0};this._specialColors=[256,257,258];this._register(this._parser),this._dirtyRowTracker=new Zi(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(c=>this._activeBuffer=c.activeBuffer)),this._parser.setCsiHandlerFallback((c,d)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(c),params:d.toArray()})}),this._parser.setEscHandlerFallback(c=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(c)})}),this._parser.setExecuteHandlerFallback(c=>{this._logService.debug("Unknown EXECUTE code: ",{code:c})}),this._parser.setOscHandlerFallback((c,d,_)=>{this._logService.debug("Unknown OSC code: ",{identifier:c,action:d,data:_})}),this._parser.setDcsHandlerFallback((c,d,_)=>{d==="HOOK"&&(_=_.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(c),action:d,payload:_})}),this._parser.setPrintHandler((c,d,_)=>this.print(c,d,_)),this._parser.registerCsiHandler({final:"@"},c=>this.insertChars(c)),this._parser.registerCsiHandler({intermediates:" ",final:"@"},c=>this.scrollLeft(c)),this._parser.registerCsiHandler({final:"A"},c=>this.cursorUp(c)),this._parser.registerCsiHandler({intermediates:" ",final:"A"},c=>this.scrollRight(c)),this._parser.registerCsiHandler({final:"B"},c=>this.cursorDown(c)),this._parser.registerCsiHandler({final:"C"},c=>this.cursorForward(c)),this._parser.registerCsiHandler({final:"D"},c=>this.cursorBackward(c)),this._parser.registerCsiHandler({final:"E"},c=>this.cursorNextLine(c)),this._parser.registerCsiHandler({final:"F"},c=>this.cursorPrecedingLine(c)),this._parser.registerCsiHandler({final:"G"},c=>this.cursorCharAbsolute(c)),this._parser.registerCsiHandler({final:"H"},c=>this.cursorPosition(c)),this._parser.registerCsiHandler({final:"I"},c=>this.cursorForwardTab(c)),this._parser.registerCsiHandler({final:"J"},c=>this.eraseInDisplay(c,!1)),this._parser.registerCsiHandler({prefix:"?",final:"J"},c=>this.eraseInDisplay(c,!0)),this._parser.registerCsiHandler({final:"K"},c=>this.eraseInLine(c,!1)),this._parser.registerCsiHandler({prefix:"?",final:"K"},c=>this.eraseInLine(c,!0)),this._parser.registerCsiHandler({final:"L"},c=>this.insertLines(c)),this._parser.registerCsiHandler({final:"M"},c=>this.deleteLines(c)),this._parser.registerCsiHandler({final:"P"},c=>this.deleteChars(c)),this._parser.registerCsiHandler({final:"S"},c=>this.scrollUp(c)),this._parser.registerCsiHandler({final:"T"},c=>this.scrollDown(c)),this._parser.registerCsiHandler({final:"X"},c=>this.eraseChars(c)),this._parser.registerCsiHandler({final:"Z"},c=>this.cursorBackwardTab(c)),this._parser.registerCsiHandler({final:"`"},c=>this.charPosAbsolute(c)),this._parser.registerCsiHandler({final:"a"},c=>this.hPositionRelative(c)),this._parser.registerCsiHandler({final:"b"},c=>this.repeatPrecedingCharacter(c)),this._parser.registerCsiHandler({final:"c"},c=>this.sendDeviceAttributesPrimary(c)),this._parser.registerCsiHandler({prefix:">",final:"c"},c=>this.sendDeviceAttributesSecondary(c)),this._parser.registerCsiHandler({final:"d"},c=>this.linePosAbsolute(c)),this._parser.registerCsiHandler({final:"e"},c=>this.vPositionRelative(c)),this._parser.registerCsiHandler({final:"f"},c=>this.hVPosition(c)),this._parser.registerCsiHandler({final:"g"},c=>this.tabClear(c)),this._parser.registerCsiHandler({final:"h"},c=>this.setMode(c)),this._parser.registerCsiHandler({prefix:"?",final:"h"},c=>this.setModePrivate(c)),this._parser.registerCsiHandler({final:"l"},c=>this.resetMode(c)),this._parser.registerCsiHandler({prefix:"?",final:"l"},c=>this.resetModePrivate(c)),this._parser.registerCsiHandler({final:"m"},c=>this.charAttributes(c)),this._parser.registerCsiHandler({final:"n"},c=>this.deviceStatus(c)),this._parser.registerCsiHandler({prefix:"?",final:"n"},c=>this.deviceStatusPrivate(c)),this._parser.registerCsiHandler({intermediates:"!",final:"p"},c=>this.softReset(c)),this._parser.registerCsiHandler({intermediates:" ",final:"q"},c=>this.setCursorStyle(c)),this._parser.registerCsiHandler({final:"r"},c=>this.setScrollRegion(c)),this._parser.registerCsiHandler({final:"s"},c=>this.saveCursor(c)),this._parser.registerCsiHandler({final:"t"},c=>this.windowOptions(c)),this._parser.registerCsiHandler({final:"u"},c=>this.restoreCursor(c)),this._parser.registerCsiHandler({intermediates:"'",final:"}"},c=>this.insertColumns(c)),this._parser.registerCsiHandler({intermediates:"'",final:"~"},c=>this.deleteColumns(c)),this._parser.registerCsiHandler({intermediates:'"',final:"q"},c=>this.selectProtected(c)),this._parser.registerCsiHandler({intermediates:"$",final:"p"},c=>this.requestMode(c,!0)),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},c=>this.requestMode(c,!1)),this._parser.setExecuteHandler(b.BEL,()=>this.bell()),this._parser.setExecuteHandler(b.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(b.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(b.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(b.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(b.BS,()=>this.backspace()),this._parser.setExecuteHandler(b.HT,()=>this.tab()),this._parser.setExecuteHandler(b.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(b.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(Ai.IND,()=>this.index()),this._parser.setExecuteHandler(Ai.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(Ai.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new pe(c=>(this.setTitle(c),this.setIconName(c),!0))),this._parser.registerOscHandler(1,new pe(c=>this.setIconName(c))),this._parser.registerOscHandler(2,new pe(c=>this.setTitle(c))),this._parser.registerOscHandler(4,new pe(c=>this.setOrReportIndexedColor(c))),this._parser.registerOscHandler(8,new pe(c=>this.setHyperlink(c))),this._parser.registerOscHandler(10,new pe(c=>this.setOrReportFgColor(c))),this._parser.registerOscHandler(11,new pe(c=>this.setOrReportBgColor(c))),this._parser.registerOscHandler(12,new pe(c=>this.setOrReportCursorColor(c))),this._parser.registerOscHandler(104,new pe(c=>this.restoreIndexedColor(c))),this._parser.registerOscHandler(110,new pe(c=>this.restoreFgColor(c))),this._parser.registerOscHandler(111,new pe(c=>this.restoreBgColor(c))),this._parser.registerOscHandler(112,new pe(c=>this.restoreCursorColor(c))),this._parser.registerEscHandler({final:"7"},()=>this.saveCursor()),this._parser.registerEscHandler({final:"8"},()=>this.restoreCursor()),this._parser.registerEscHandler({final:"D"},()=>this.index()),this._parser.registerEscHandler({final:"E"},()=>this.nextLine()),this._parser.registerEscHandler({final:"H"},()=>this.tabSet()),this._parser.registerEscHandler({final:"M"},()=>this.reverseIndex()),this._parser.registerEscHandler({final:"="},()=>this.keypadApplicationMode()),this._parser.registerEscHandler({final:">"},()=>this.keypadNumericMode()),this._parser.registerEscHandler({final:"c"},()=>this.fullReset()),this._parser.registerEscHandler({final:"n"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"o"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"|"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"}"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"~"},()=>this.setgLevel(1)),this._parser.registerEscHandler({intermediates:"%",final:"@"},()=>this.selectDefaultCharset()),this._parser.registerEscHandler({intermediates:"%",final:"G"},()=>this.selectDefaultCharset());for(let c in ne)this._parser.registerEscHandler({intermediates:"(",final:c},()=>this.selectCharset("("+c)),this._parser.registerEscHandler({intermediates:")",final:c},()=>this.selectCharset(")"+c)),this._parser.registerEscHandler({intermediates:"*",final:c},()=>this.selectCharset("*"+c)),this._parser.registerEscHandler({intermediates:"+",final:c},()=>this.selectCharset("+"+c)),this._parser.registerEscHandler({intermediates:"-",final:c},()=>this.selectCharset("-"+c)),this._parser.registerEscHandler({intermediates:".",final:c},()=>this.selectCharset("."+c)),this._parser.registerEscHandler({intermediates:"/",final:c},()=>this.selectCharset("/"+c));this._parser.registerEscHandler({intermediates:"#",final:"8"},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(c=>(this._logService.error("Parsing error: ",c),c)),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new Xi((c,d)=>this.requestStatusString(c,d)))}getAttrData(){return this._curAttrData}_preserveStack(e,i,r,n){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=i,this._parseStack.decodedLength=r,this._parseStack.position=n}_logSlowResolvingAsync(e){this._logService.logLevel<=3&&Promise.race([e,new Promise((i,r)=>setTimeout(()=>r("#SLOW_TIMEOUT"),vl))]).catch(i=>{if(i!=="#SLOW_TIMEOUT")throw i;console.warn(`async parser handler taking longer than ${vl} ms`)})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,i){let r,n=this._activeBuffer.x,o=this._activeBuffer.y,l=0,a=this._parseStack.paused;if(a){if(r=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,i))return this._logSlowResolvingAsync(r),r;n=this._parseStack.cursorStartX,o=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>ut&&(l=this._parseStack.position+ut)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e=="string"?` "${e}"`:` "${Array.prototype.map.call(e,c=>String.fromCharCode(c)).join("")}"`}`),this._logService.logLevel===0&&this._logService.trace("parsing data (codes)",typeof e=="string"?e.split("").map(c=>c.charCodeAt(0)):e),this._parseBuffer.lengthut)for(let c=l;c0&&_.getWidth(this._activeBuffer.x-1)===2&&_.setCellFromCodepoint(this._activeBuffer.x-1,0,1,d);let p=this._parser.precedingJoinState;for(let m=i;mu){if(h){let O=_,I=this._activeBuffer.x-R;for(this._activeBuffer.x=R,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),_=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),R>0&&_ instanceof Ze&&_.copyCellsFrom(O,I,0,R,!1);I=0;)_.setCellFromCodepoint(this._activeBuffer.x++,0,0,d);continue}if(c&&(_.insertCells(this._activeBuffer.x,o-R,this._activeBuffer.getNullCell(d)),_.getWidth(u-1)===2&&_.setCellFromCodepoint(u-1,0,1,d)),_.setCellFromCodepoint(this._activeBuffer.x++,n,o,d),o>0)for(;--o;)_.setCellFromCodepoint(this._activeBuffer.x++,0,0,d)}this._parser.precedingJoinState=p,this._activeBuffer.x0&&_.getWidth(this._activeBuffer.x)===0&&!_.hasContent(this._activeBuffer.x)&&_.setCellFromCodepoint(this._activeBuffer.x,0,1,d),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,i){return e.final==="t"&&!e.prefix&&!e.intermediates?this._parser.registerCsiHandler(e,r=>bl(r.params[0],this._optionsService.rawOptions.windowOptions)?i(r):!0):this._parser.registerCsiHandler(e,i)}registerDcsHandler(e,i){return this._parser.registerDcsHandler(e,new Xi(i))}registerEscHandler(e,i){return this._parser.registerEscHandler(e,i)}registerOscHandler(e,i){return this._parser.registerOscHandler(e,new pe(i))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y)?.isWrapped){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);e.hasWidth(this._activeBuffer.x)&&!e.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let e=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(e,i){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e,this._activeBuffer.y=this._activeBuffer.scrollTop+i):(this._activeBuffer.x=e,this._activeBuffer.y=i),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e,i){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e,this._activeBuffer.y+i)}cursorUp(e){let i=this._activeBuffer.y-this._activeBuffer.scrollTop;return i>=0?this._moveCursor(0,-Math.min(i,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1)),!0}cursorDown(e){let i=this._activeBuffer.scrollBottom-this._activeBuffer.y;return i>=0?this._moveCursor(0,Math.min(i,e.params[0]||1)):this._moveCursor(0,e.params[0]||1),!0}cursorForward(e){return this._moveCursor(e.params[0]||1,0),!0}cursorBackward(e){return this._moveCursor(-(e.params[0]||1),0),!0}cursorNextLine(e){return this.cursorDown(e),this._activeBuffer.x=0,!0}cursorPrecedingLine(e){return this.cursorUp(e),this._activeBuffer.x=0,!0}cursorCharAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e){return this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1),!0}charPosAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e){return this._moveCursor(e.params[0]||1,0),!0}linePosAbsolute(e){return this._setCursor(this._activeBuffer.x,(e.params[0]||1)-1),!0}vPositionRelative(e){return this._moveCursor(0,e.params[0]||1),!0}hVPosition(e){return this.cursorPosition(e),!0}tabClear(e){let i=e.params[0];return i===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:i===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let i=e.params[0]||1;for(;i--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let i=e.params[0]||1;for(;i--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e){let i=e.params[0];return i===1&&(this._curAttrData.bg|=536870912),(i===2||i===0)&&(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(e,i,r,n=!1,o=!1){let l=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);l.replaceCells(i,r,this._activeBuffer.getNullCell(this._eraseAttrData()),o),n&&(l.isWrapped=!1)}_resetBufferLine(e,i=!1){let r=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);r&&(r.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),i),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),r.isWrapped=!1)}eraseInDisplay(e,i=!1){this._restrictCursor(this._bufferService.cols);let r;switch(e.params[0]){case 0:for(r=this._activeBuffer.y,this._dirtyRowTracker.markDirty(r),this._eraseInBufferLine(r++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,i);r=this._bufferService.cols&&(this._activeBuffer.lines.get(r+1).isWrapped=!1);r--;)this._resetBufferLine(r,i);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(r=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,r-1);r--&&!this._activeBuffer.lines.get(this._activeBuffer.ybase+r)?.getTrimmedLength(););for(;r>=0;r--)this._bufferService.scroll(this._eraseAttrData())}else{for(r=this._bufferService.rows,this._dirtyRowTracker.markDirty(r-1);r--;)this._resetBufferLine(r,i);this._dirtyRowTracker.markDirty(0)}break;case 3:let n=this._activeBuffer.lines.length-this._bufferService.rows;n>0&&(this._activeBuffer.lines.trimStart(n),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-n,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-n,0),this._onScroll.fire(0));break}return!0}eraseInLine(e,i=!1){switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,i);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,i);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,i);break}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e){this._restrictCursor();let i=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.y65535?2:1}let c=h;for(let d=1;d0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(b.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(b.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(b.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(b.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(e.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(b.ESC+"[>83;40003;0c")),!0}_is(e){return(this._optionsService.rawOptions.termName+"").indexOf(e)===0}setMode(e){for(let i=0;i(P[P.NOT_RECOGNIZED=0]="NOT_RECOGNIZED",P[P.SET=1]="SET",P[P.RESET=2]="RESET",P[P.PERMANENTLY_SET=3]="PERMANENTLY_SET",P[P.PERMANENTLY_RESET=4]="PERMANENTLY_RESET"))(r||={});let n=this._coreService.decPrivateModes,{activeProtocol:o,activeEncoding:l}=this._coreMouseService,a=this._coreService,{buffers:u,cols:h}=this._bufferService,{active:c,alt:d}=u,_=this._optionsService.rawOptions,p=(A,R)=>(a.triggerDataEvent(`${b.ESC}[${i?"":"?"}${A};${R}$y`),!0),m=A=>A?1:2,f=e.params[0];return i?f===2?p(f,4):f===4?p(f,m(a.modes.insertMode)):f===12?p(f,3):f===20?p(f,m(_.convertEol)):p(f,0):f===1?p(f,m(n.applicationCursorKeys)):f===3?p(f,_.windowOptions.setWinLines?h===80?2:h===132?1:0:0):f===6?p(f,m(n.origin)):f===7?p(f,m(n.wraparound)):f===8?p(f,3):f===9?p(f,m(o==="X10")):f===12?p(f,m(_.cursorBlink)):f===25?p(f,m(!a.isCursorHidden)):f===45?p(f,m(n.reverseWraparound)):f===66?p(f,m(n.applicationKeypad)):f===67?p(f,4):f===1e3?p(f,m(o==="VT200")):f===1002?p(f,m(o==="DRAG")):f===1003?p(f,m(o==="ANY")):f===1004?p(f,m(n.sendFocus)):f===1005?p(f,4):f===1006?p(f,m(l==="SGR")):f===1015?p(f,4):f===1016?p(f,m(l==="SGR_PIXELS")):f===1048?p(f,1):f===47||f===1047||f===1049?p(f,m(c===d)):f===2004?p(f,m(n.bracketedPasteMode)):f===2026?p(f,m(n.synchronizedOutput)):p(f,0)}_updateAttrColor(e,i,r,n,o){return i===2?(e|=50331648,e&=-16777216,e|=De.fromColorRGB([r,n,o])):i===5&&(e&=-50331904,e|=33554432|r&255),e}_extractColor(e,i,r){let n=[0,0,-1,0,0,0],o=0,l=0;do{if(n[l+o]=e.params[i+l],e.hasSubParams(i+l)){let a=e.getSubParams(i+l),u=0;do n[1]===5&&(o=1),n[l+u+1+o]=a[u];while(++u=2||n[1]===2&&l+o>=5)break;n[1]&&(o=1)}while(++l+i5)&&(e=1),i.extended.underlineStyle=e,i.fg|=268435456,e===0&&(i.fg&=-268435457),i.updateExtended()}_processSGR0(e){e.fg=X.fg,e.bg=X.bg,e.extended=e.extended.clone(),e.extended.underlineStyle=0,e.extended.underlineColor&=-67108864,e.updateExtended()}charAttributes(e){if(e.length===1&&e.params[0]===0)return this._processSGR0(this._curAttrData),!0;let i=e.length,r,n=this._curAttrData;for(let o=0;o=30&&r<=37?(n.fg&=-50331904,n.fg|=16777216|r-30):r>=40&&r<=47?(n.bg&=-50331904,n.bg|=16777216|r-40):r>=90&&r<=97?(n.fg&=-50331904,n.fg|=16777216|r-90|8):r>=100&&r<=107?(n.bg&=-50331904,n.bg|=16777216|r-100|8):r===0?this._processSGR0(n):r===1?n.fg|=134217728:r===3?n.bg|=67108864:r===4?(n.fg|=268435456,this._processUnderline(e.hasSubParams(o)?e.getSubParams(o)[0]:1,n)):r===5?n.fg|=536870912:r===7?n.fg|=67108864:r===8?n.fg|=1073741824:r===9?n.fg|=2147483648:r===2?n.bg|=134217728:r===21?this._processUnderline(2,n):r===22?(n.fg&=-134217729,n.bg&=-134217729):r===23?n.bg&=-67108865:r===24?(n.fg&=-268435457,this._processUnderline(0,n)):r===25?n.fg&=-536870913:r===27?n.fg&=-67108865:r===28?n.fg&=-1073741825:r===29?n.fg&=2147483647:r===39?(n.fg&=-67108864,n.fg|=X.fg&16777215):r===49?(n.bg&=-67108864,n.bg|=X.bg&16777215):r===38||r===48||r===58?o+=this._extractColor(e,o,n):r===53?n.bg|=1073741824:r===55?n.bg&=-1073741825:r===59?(n.extended=n.extended.clone(),n.extended.underlineColor=-1,n.updateExtended()):r===100?(n.fg&=-67108864,n.fg|=X.fg&16777215,n.bg&=-67108864,n.bg|=X.bg&16777215):this._logService.debug("Unknown SGR attribute: %d.",r);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${b.ESC}[0n`);break;case 6:let i=this._activeBuffer.y+1,r=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${b.ESC}[${i};${r}R`);break}return!0}deviceStatusPrivate(e){switch(e.params[0]){case 6:let i=this._activeBuffer.y+1,r=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${b.ESC}[?${i};${r}R`);break;case 15:break;case 25:break;case 26:break;case 53:break}return!0}softReset(e){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=X.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(e){let i=e.length===0?1:e.params[0];if(i===0)this._coreService.decPrivateModes.cursorStyle=void 0,this._coreService.decPrivateModes.cursorBlink=void 0;else{switch(i){case 1:case 2:this._coreService.decPrivateModes.cursorStyle="block";break;case 3:case 4:this._coreService.decPrivateModes.cursorStyle="underline";break;case 5:case 6:this._coreService.decPrivateModes.cursorStyle="bar";break}let r=i%2===1;this._coreService.decPrivateModes.cursorBlink=r}return!0}setScrollRegion(e){let i=e.params[0]||1,r;return(e.length<2||(r=e.params[1])>this._bufferService.rows||r===0)&&(r=this._bufferService.rows),r>i&&(this._activeBuffer.scrollTop=i-1,this._activeBuffer.scrollBottom=r-1,this._setCursor(0,0)),!0}windowOptions(e){if(!bl(e.params[0],this._optionsService.rawOptions.windowOptions))return!0;let i=e.length>1?e.params[1]:0;switch(e.params[0]){case 14:i!==2&&this._onRequestWindowsOptionsReport.fire(0);break;case 16:this._onRequestWindowsOptionsReport.fire(1);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${b.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(i===0||i===2)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>_l&&this._windowTitleStack.shift()),(i===0||i===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>_l&&this._iconNameStack.shift());break;case 23:(i===0||i===2)&&this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),(i===0||i===1)&&this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop());break}return!0}saveCursor(e){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(e){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(e){return this._windowTitle=e,this._onTitleChange.fire(e),!0}setIconName(e){return this._iconName=e,!0}setOrReportIndexedColor(e){let i=[],r=e.split(";");for(;r.length>1;){let n=r.shift(),o=r.shift();if(/^\d+$/.exec(n)){let l=parseInt(n);if(Sl(l))if(o==="?")i.push({type:0,index:l});else{let a=Ws(o);a&&i.push({type:1,index:l,color:a})}}}return i.length&&this._onColor.fire(i),!0}setHyperlink(e){let i=e.indexOf(";");if(i===-1)return!0;let r=e.slice(0,i).trim(),n=e.slice(i+1);return n?this._createHyperlink(r,n):r.trim()?!1:this._finishHyperlink()}_createHyperlink(e,i){this._getCurrentLinkId()&&this._finishHyperlink();let r=e.split(":"),n,o=r.findIndex(l=>l.startsWith("id="));return o!==-1&&(n=r[o].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:n,uri:i}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e,i){let r=e.split(";");for(let n=0;n=this._specialColors.length);++n,++i)if(r[n]==="?")this._onColor.fire([{type:0,index:this._specialColors[i]}]);else{let o=Ws(r[n]);o&&this._onColor.fire([{type:1,index:this._specialColors[i],color:o}])}return!0}setOrReportFgColor(e){return this._setOrReportSpecialColor(e,0)}setOrReportBgColor(e){return this._setOrReportSpecialColor(e,1)}setOrReportCursorColor(e){return this._setOrReportSpecialColor(e,2)}restoreIndexedColor(e){if(!e)return this._onColor.fire([{type:2}]),!0;let i=[],r=e.split(";");for(let n=0;n=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){let e=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,e,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=X.clone(),this._eraseAttrDataInternal=X.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=this._curAttrData.bg&67108863,this._eraseAttrDataInternal}setgLevel(e){return this._charsetService.setgLevel(e),!0}screenAlignmentPattern(){let e=new q;e.content=1<<22|69,e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let i=0;i(this._coreService.triggerDataEvent(`${b.ESC}${a}${b.ESC}\\`),!0),n=this._bufferService.buffer,o=this._optionsService.rawOptions,l={block:2,underline:4,bar:6};return r(e==='"q'?`P1$r${this._curAttrData.isProtected()?1:0}"q`:e==='"p'?'P1$r61;1"p':e==="r"?`P1$r${n.scrollTop+1};${n.scrollBottom+1}r`:e==="m"?"P1$r0m":e===" q"?`P1$r${l[o.cursorStyle]-(o.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(e,i){this._dirtyRowTracker.markRangeDirty(e,i)}},Zi=class{constructor(t){this._bufferService=t;this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(t){tthis.end&&(this.end=t)}markRangeDirty(t,e){t>e&&(gl=t,t=e,e=gl),tthis.end&&(this.end=e)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};Zi=M([S(0,F)],Zi);function Sl(s){return 0<=s&&s<256}var _c=5e7,El=12,bc=50,gn=class extends D{constructor(e){super();this._action=e;this._writeBuffer=[];this._callbacks=[];this._pendingData=0;this._bufferOffset=0;this._isSyncWriting=!1;this._syncCalls=0;this._didUserInput=!1;this._onWriteParsed=this._register(new v);this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(e,i){if(i!==void 0&&this._syncCalls>i){this._syncCalls=0;return}if(this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;this._isSyncWriting=!0;let r;for(;r=this._writeBuffer.shift();){this._action(r);let n=this._callbacks.shift();n&&n()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(e,i){if(this._pendingData>_c)throw new Error("write data discarded, use flow control to avoid losing data");if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput){this._didUserInput=!1,this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(i),this._innerWrite();return}setTimeout(()=>this._innerWrite())}this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(i)}_innerWrite(e=0,i=!0){let r=e||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){let n=this._writeBuffer[this._bufferOffset],o=this._action(n,i);if(o){let a=u=>performance.now()-r>=El?setTimeout(()=>this._innerWrite(0,u)):this._innerWrite(r,u);o.catch(u=>(queueMicrotask(()=>{throw u}),Promise.resolve(!1))).then(a);return}let l=this._callbacks[this._bufferOffset];if(l&&l(),this._bufferOffset++,this._pendingData-=n.length,performance.now()-r>=El)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>bc&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout(()=>this._innerWrite())):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}};var ui=class{constructor(t){this._bufferService=t;this._nextId=1;this._entriesWithId=new Map;this._dataByLinkId=new Map}registerLink(t){let e=this._bufferService.buffer;if(t.id===void 0){let a=e.addMarker(e.ybase+e.y),u={data:t,id:this._nextId++,lines:[a]};return a.onDispose(()=>this._removeMarkerFromLink(u,a)),this._dataByLinkId.set(u.id,u),u.id}let i=t,r=this._getEntryIdKey(i),n=this._entriesWithId.get(r);if(n)return this.addLineToLink(n.id,e.ybase+e.y),n.id;let o=e.addMarker(e.ybase+e.y),l={id:this._nextId++,key:this._getEntryIdKey(i),data:i,lines:[o]};return o.onDispose(()=>this._removeMarkerFromLink(l,o)),this._entriesWithId.set(l.key,l),this._dataByLinkId.set(l.id,l),l.id}addLineToLink(t,e){let i=this._dataByLinkId.get(t);if(i&&i.lines.every(r=>r.line!==e)){let r=this._bufferService.buffer.addMarker(e);i.lines.push(r),r.onDispose(()=>this._removeMarkerFromLink(i,r))}}getLinkData(t){return this._dataByLinkId.get(t)?.data}_getEntryIdKey(t){return`${t.id};;${t.uri}`}_removeMarkerFromLink(t,e){let i=t.lines.indexOf(e);i!==-1&&(t.lines.splice(i,1),t.lines.length===0&&(t.data.id!==void 0&&this._entriesWithId.delete(t.key),this._dataByLinkId.delete(t.id)))}};ui=M([S(0,F)],ui);var Tl=!1,Sn=class extends D{constructor(e){super();this._windowsWrappingHeuristics=this._register(new ye);this._onBinary=this._register(new v);this.onBinary=this._onBinary.event;this._onData=this._register(new v);this.onData=this._onData.event;this._onLineFeed=this._register(new v);this.onLineFeed=this._onLineFeed.event;this._onResize=this._register(new v);this.onResize=this._onResize.event;this._onWriteParsed=this._register(new v);this.onWriteParsed=this._onWriteParsed.event;this._onScroll=this._register(new v);this._instantiationService=new ln,this.optionsService=this._register(new dn(e)),this._instantiationService.setService(H,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(ni)),this._instantiationService.setService(F,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(ii)),this._instantiationService.setService(nr,this._logService),this.coreService=this._register(this._instantiationService.createInstance(li)),this._instantiationService.setService(ge,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(ai)),this._instantiationService.setService(rr,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(Ae)),this._instantiationService.setService(Js,this.unicodeService),this._charsetService=this._instantiationService.createInstance(pn),this._instantiationService.setService(Zs,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(ui),this._instantiationService.setService(sr,this._oscLinkService),this._inputHandler=this._register(new vn(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register($.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register($.forward(this._bufferService.onResize,this._onResize)),this._register($.forward(this.coreService.onData,this._onData)),this._register($.forward(this.coreService.onBinary,this._onBinary)),this._register(this.coreService.onRequestScrollToBottom(()=>this.scrollToBottom(!0))),this._register(this.coreService.onUserInput(()=>this._writeBuffer.handleUserInput())),this._register(this.optionsService.onMultipleOptionChange(["windowsMode","windowsPty"],()=>this._handleWindowsPtyOptionChange())),this._register(this._bufferService.onScroll(()=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this._writeBuffer=this._register(new gn((i,r)=>this._inputHandler.parse(i,r))),this._register($.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new v),this._onScroll.event(e=>{this._onScrollApi?.fire(e.position)})),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(e){for(let i in e)this.optionsService.options[i]=e[i]}write(e,i){this._writeBuffer.write(e,i)}writeSync(e,i){this._logService.logLevel<=3&&!Tl&&(this._logService.warn("writeSync is unreliable and will be removed soon."),Tl=!0),this._writeBuffer.writeSync(e,i)}input(e,i=!0){this.coreService.triggerDataEvent(e,i)}resize(e,i){isNaN(e)||isNaN(i)||(e=Math.max(e,ks),i=Math.max(i,Cs),this._bufferService.resize(e,i))}scroll(e,i=!1){this._bufferService.scroll(e,i)}scrollLines(e,i){this._bufferService.scrollLines(e,i)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let i=e-this._bufferService.buffer.ydisp;i!==0&&this.scrollLines(i)}registerEscHandler(e,i){return this._inputHandler.registerEscHandler(e,i)}registerDcsHandler(e,i){return this._inputHandler.registerDcsHandler(e,i)}registerCsiHandler(e,i){return this._inputHandler.registerCsiHandler(e,i)}registerOscHandler(e,i){return this._inputHandler.registerOscHandler(e,i)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let e=!1,i=this.optionsService.rawOptions.windowsPty;i&&i.buildNumber!==void 0&&i.buildNumber!==void 0?e=i.backend==="conpty"&&i.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(e=!0),e?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let e=[];e.push(this.onLineFeed(Bs.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:"H"},()=>(Bs(this._bufferService),!1))),this._windowsWrappingHeuristics.value=C(()=>{for(let i of e)i.dispose()})}}};var gc={48:["0",")"],49:["1","!"],50:["2","@"],51:["3","#"],52:["4","$"],53:["5","%"],54:["6","^"],55:["7","&"],56:["8","*"],57:["9","("],186:[";",":"],187:["=","+"],188:[",","<"],189:["-","_"],190:[".",">"],191:["/","?"],192:["`","~"],219:["[","{"],220:["\\","|"],221:["]","}"],222:["'",'"']};function Il(s,t,e,i){let r={type:0,cancel:!1,key:void 0},n=(s.shiftKey?1:0)|(s.altKey?2:0)|(s.ctrlKey?4:0)|(s.metaKey?8:0);switch(s.keyCode){case 0:s.key==="UIKeyInputUpArrow"?t?r.key=b.ESC+"OA":r.key=b.ESC+"[A":s.key==="UIKeyInputLeftArrow"?t?r.key=b.ESC+"OD":r.key=b.ESC+"[D":s.key==="UIKeyInputRightArrow"?t?r.key=b.ESC+"OC":r.key=b.ESC+"[C":s.key==="UIKeyInputDownArrow"&&(t?r.key=b.ESC+"OB":r.key=b.ESC+"[B");break;case 8:r.key=s.ctrlKey?"\b":b.DEL,s.altKey&&(r.key=b.ESC+r.key);break;case 9:if(s.shiftKey){r.key=b.ESC+"[Z";break}r.key=b.HT,r.cancel=!0;break;case 13:r.key=s.altKey?b.ESC+b.CR:b.CR,r.cancel=!0;break;case 27:r.key=b.ESC,s.altKey&&(r.key=b.ESC+b.ESC),r.cancel=!0;break;case 37:if(s.metaKey)break;n?r.key=b.ESC+"[1;"+(n+1)+"D":t?r.key=b.ESC+"OD":r.key=b.ESC+"[D";break;case 39:if(s.metaKey)break;n?r.key=b.ESC+"[1;"+(n+1)+"C":t?r.key=b.ESC+"OC":r.key=b.ESC+"[C";break;case 38:if(s.metaKey)break;n?r.key=b.ESC+"[1;"+(n+1)+"A":t?r.key=b.ESC+"OA":r.key=b.ESC+"[A";break;case 40:if(s.metaKey)break;n?r.key=b.ESC+"[1;"+(n+1)+"B":t?r.key=b.ESC+"OB":r.key=b.ESC+"[B";break;case 45:!s.shiftKey&&!s.ctrlKey&&(r.key=b.ESC+"[2~");break;case 46:n?r.key=b.ESC+"[3;"+(n+1)+"~":r.key=b.ESC+"[3~";break;case 36:n?r.key=b.ESC+"[1;"+(n+1)+"H":t?r.key=b.ESC+"OH":r.key=b.ESC+"[H";break;case 35:n?r.key=b.ESC+"[1;"+(n+1)+"F":t?r.key=b.ESC+"OF":r.key=b.ESC+"[F";break;case 33:s.shiftKey?r.type=2:s.ctrlKey?r.key=b.ESC+"[5;"+(n+1)+"~":r.key=b.ESC+"[5~";break;case 34:s.shiftKey?r.type=3:s.ctrlKey?r.key=b.ESC+"[6;"+(n+1)+"~":r.key=b.ESC+"[6~";break;case 112:n?r.key=b.ESC+"[1;"+(n+1)+"P":r.key=b.ESC+"OP";break;case 113:n?r.key=b.ESC+"[1;"+(n+1)+"Q":r.key=b.ESC+"OQ";break;case 114:n?r.key=b.ESC+"[1;"+(n+1)+"R":r.key=b.ESC+"OR";break;case 115:n?r.key=b.ESC+"[1;"+(n+1)+"S":r.key=b.ESC+"OS";break;case 116:n?r.key=b.ESC+"[15;"+(n+1)+"~":r.key=b.ESC+"[15~";break;case 117:n?r.key=b.ESC+"[17;"+(n+1)+"~":r.key=b.ESC+"[17~";break;case 118:n?r.key=b.ESC+"[18;"+(n+1)+"~":r.key=b.ESC+"[18~";break;case 119:n?r.key=b.ESC+"[19;"+(n+1)+"~":r.key=b.ESC+"[19~";break;case 120:n?r.key=b.ESC+"[20;"+(n+1)+"~":r.key=b.ESC+"[20~";break;case 121:n?r.key=b.ESC+"[21;"+(n+1)+"~":r.key=b.ESC+"[21~";break;case 122:n?r.key=b.ESC+"[23;"+(n+1)+"~":r.key=b.ESC+"[23~";break;case 123:n?r.key=b.ESC+"[24;"+(n+1)+"~":r.key=b.ESC+"[24~";break;default:if(s.ctrlKey&&!s.shiftKey&&!s.altKey&&!s.metaKey)s.keyCode>=65&&s.keyCode<=90?r.key=String.fromCharCode(s.keyCode-64):s.keyCode===32?r.key=b.NUL:s.keyCode>=51&&s.keyCode<=55?r.key=String.fromCharCode(s.keyCode-51+27):s.keyCode===56?r.key=b.DEL:s.keyCode===219?r.key=b.ESC:s.keyCode===220?r.key=b.FS:s.keyCode===221&&(r.key=b.GS);else if((!e||i)&&s.altKey&&!s.metaKey){let l=gc[s.keyCode]?.[s.shiftKey?1:0];if(l)r.key=b.ESC+l;else if(s.keyCode>=65&&s.keyCode<=90){let a=s.ctrlKey?s.keyCode-64:s.keyCode+32,u=String.fromCharCode(a);s.shiftKey&&(u=u.toUpperCase()),r.key=b.ESC+u}else if(s.keyCode===32)r.key=b.ESC+(s.ctrlKey?b.NUL:" ");else if(s.key==="Dead"&&s.code.startsWith("Key")){let a=s.code.slice(3,4);s.shiftKey||(a=a.toLowerCase()),r.key=b.ESC+a,r.cancel=!0}}else e&&!s.altKey&&!s.ctrlKey&&!s.shiftKey&&s.metaKey?s.keyCode===65&&(r.type=1):s.key&&!s.ctrlKey&&!s.altKey&&!s.metaKey&&s.keyCode>=48&&s.key.length===1?r.key=s.key:s.key&&s.ctrlKey&&(s.key==="_"&&(r.key=b.US),s.key==="@"&&(r.key=b.NUL));break}return r}var ee=0,En=class{constructor(t){this._getKey=t;this._array=[];this._insertedValues=[];this._flushInsertedTask=new Jt;this._isFlushingInserted=!1;this._deletedIndices=[];this._flushDeletedTask=new Jt;this._isFlushingDeleted=!1}clear(){this._array.length=0,this._insertedValues.length=0,this._flushInsertedTask.clear(),this._isFlushingInserted=!1,this._deletedIndices.length=0,this._flushDeletedTask.clear(),this._isFlushingDeleted=!1}insert(t){this._flushCleanupDeleted(),this._insertedValues.length===0&&this._flushInsertedTask.enqueue(()=>this._flushInserted()),this._insertedValues.push(t)}_flushInserted(){let t=this._insertedValues.sort((n,o)=>this._getKey(n)-this._getKey(o)),e=0,i=0,r=new Array(this._array.length+this._insertedValues.length);for(let n=0;n=this._array.length||this._getKey(t[e])<=this._getKey(this._array[i])?(r[n]=t[e],e++):r[n]=this._array[i++];this._array=r,this._insertedValues.length=0}_flushCleanupInserted(){!this._isFlushingInserted&&this._insertedValues.length>0&&this._flushInsertedTask.flush()}delete(t){if(this._flushCleanupInserted(),this._array.length===0)return!1;let e=this._getKey(t);if(e===void 0||(ee=this._search(e),ee===-1)||this._getKey(this._array[ee])!==e)return!1;do if(this._array[ee]===t)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(ee),!0;while(++een-o),e=0,i=new Array(this._array.length-t.length),r=0;for(let n=0;n0&&this._flushDeletedTask.flush()}*getKeyIterator(t){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(ee=this._search(t),!(ee<0||ee>=this._array.length)&&this._getKey(this._array[ee])===t))do yield this._array[ee];while(++ee=this._array.length)&&this._getKey(this._array[ee])===t))do e(this._array[ee]);while(++ee=e;){let r=e+i>>1,n=this._getKey(this._array[r]);if(n>t)i=r-1;else if(n0&&this._getKey(this._array[r-1])===t;)r--;return r}}return e}};var Us=0,yl=0,Tn=class extends D{constructor(){super();this._decorations=new En(e=>e?.marker.line);this._onDecorationRegistered=this._register(new v);this.onDecorationRegistered=this._onDecorationRegistered.event;this._onDecorationRemoved=this._register(new v);this.onDecorationRemoved=this._onDecorationRemoved.event;this._register(C(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let i=new Ks(e);if(i){let r=i.marker.onDispose(()=>i.dispose()),n=i.onDispose(()=>{n.dispose(),i&&(this._decorations.delete(i)&&this._onDecorationRemoved.fire(i),r.dispose())});this._decorations.insert(i),this._onDecorationRegistered.fire(i)}return i}reset(){for(let e of this._decorations.values())e.dispose();this._decorations.clear()}*getDecorationsAtCell(e,i,r){let n=0,o=0;for(let l of this._decorations.getKeyIterator(i))n=l.options.x??0,o=n+(l.options.width??1),e>=n&&e{Us=o.options.x??0,yl=Us+(o.options.width??1),e>=Us&&e=this._debounceThresholdMS)this._lastRefreshMs=r,this._innerRefresh();else if(!this._additionalRefreshRequested){let n=r-this._lastRefreshMs,o=this._debounceThresholdMS-n;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=performance.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},o)}}_innerRefresh(){if(this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return;let t=Math.max(this._rowStart,0),e=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(t,e)}};var xl=20;var wl=!1,Tt=class extends D{constructor(e,i,r,n){super();this._terminal=e;this._coreBrowserService=r;this._renderService=n;this._rowColumns=new WeakMap;this._liveRegionLineCount=0;this._charsToConsume=[];this._charsToAnnounce="";let o=this._coreBrowserService.mainDocument;this._accessibilityContainer=o.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=o.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let l=0;lthis._handleBoundaryFocus(l,0),this._bottomBoundaryFocusListener=l=>this._handleBoundaryFocus(l,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=o.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this._register(new In(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");wl?(this._accessibilityContainer.classList.add("debug"),this._rowContainer.classList.add("debug"),this._debugRootContainer=o.createElement("div"),this._debugRootContainer.classList.add("xterm"),this._debugRootContainer.appendChild(o.createTextNode("------start a11y------")),this._debugRootContainer.appendChild(this._accessibilityContainer),this._debugRootContainer.appendChild(o.createTextNode("------end a11y------")),this._terminal.element.insertAdjacentElement("afterend",this._debugRootContainer)):this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this._register(this._terminal.onResize(l=>this._handleResize(l.rows))),this._register(this._terminal.onRender(l=>this._refreshRows(l.start,l.end))),this._register(this._terminal.onScroll(()=>this._refreshRows())),this._register(this._terminal.onA11yChar(l=>this._handleChar(l))),this._register(this._terminal.onLineFeed(()=>this._handleChar(` +`))),this._register(this._terminal.onA11yTab(l=>this._handleTab(l))),this._register(this._terminal.onKey(l=>this._handleKey(l.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register(L(o,"selectionchange",()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(C(()=>{wl?this._debugRootContainer.remove():this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let i=0;i0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===` +`&&(this._liveRegionLineCount++,this._liveRegionLineCount===xl+1&&(this._liveRegion.textContent+=_i.get())))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),/\p{Control}/u.test(e)||this._charsToConsume.push(e)}_refreshRows(e,i){this._liveRegionDebouncer.refresh(e,i,this._terminal.rows)}_renderRows(e,i){let r=this._terminal.buffer,n=r.lines.length.toString();for(let o=e;o<=i;o++){let l=r.lines.get(r.ydisp+o),a=[],u=l?.translateToString(!0,void 0,void 0,a)||"",h=(r.ydisp+o+1).toString(),c=this._rowElements[o];c&&(u.length===0?(c.textContent="\xA0",this._rowColumns.set(c,[0,1])):(c.textContent=u,this._rowColumns.set(c,a)),c.setAttribute("aria-posinset",h),c.setAttribute("aria-setsize",n),this._alignRowWidth(c))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(e,i){let r=e.target,n=this._rowElements[i===0?1:this._rowElements.length-2],o=r.getAttribute("aria-posinset"),l=i===0?"1":`${this._terminal.buffer.lines.length}`;if(o===l||e.relatedTarget!==n)return;let a,u;if(i===0?(a=r,u=this._rowElements.pop(),this._rowContainer.removeChild(u)):(a=this._rowElements.shift(),u=r,this._rowContainer.removeChild(a)),a.removeEventListener("focus",this._topBoundaryFocusListener),u.removeEventListener("focus",this._bottomBoundaryFocusListener),i===0){let h=this._createAccessibilityTreeNode();this._rowElements.unshift(h),this._rowContainer.insertAdjacentElement("afterbegin",h)}else{let h=this._createAccessibilityTreeNode();this._rowElements.push(h),this._rowContainer.appendChild(h)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(i===0?-1:1),this._rowElements[i===0?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}_handleSelectionChange(){if(this._rowElements.length===0)return;let e=this._coreBrowserService.mainDocument.getSelection();if(!e)return;if(e.isCollapsed){this._rowContainer.contains(e.anchorNode)&&this._terminal.clearSelection();return}if(!e.anchorNode||!e.focusNode){console.error("anchorNode and/or focusNode are null");return}let i={node:e.anchorNode,offset:e.anchorOffset},r={node:e.focusNode,offset:e.focusOffset};if((i.node.compareDocumentPosition(r.node)&Node.DOCUMENT_POSITION_PRECEDING||i.node===r.node&&i.offset>r.offset)&&([i,r]=[r,i]),i.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(i={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(i.node))return;let n=this._rowElements.slice(-1)[0];if(r.node.compareDocumentPosition(n)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(r={node:n,offset:n.textContent?.length??0}),!this._rowContainer.contains(r.node))return;let o=({node:u,offset:h})=>{let c=u instanceof Text?u.parentNode:u,d=parseInt(c?.getAttribute("aria-posinset"),10)-1;if(isNaN(d))return console.warn("row is invalid. Race condition?"),null;let _=this._rowColumns.get(c);if(!_)return console.warn("columns is null. Race condition?"),null;let p=h<_.length?_[h]:_.slice(-1)[0]+1;return p>=this._terminal.cols&&(++d,p=0),{row:d,column:p}},l=o(i),a=o(r);if(!(!l||!a)){if(l.row>a.row||l.row===a.row&&l.column>=a.column)throw new Error("invalid range");this._terminal.select(l.column,l.row,(a.row-l.row)*this._terminal.cols-l.column+a.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let i=this._rowContainer.children.length;ie;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){let e=this._coreBrowserService.mainDocument.createElement("div");return e.setAttribute("role","listitem"),e.tabIndex=-1,this._refreshRowDimensions(e),e}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){Object.assign(this._accessibilityContainer.style,{width:`${this._renderService.dimensions.css.canvas.width}px`,fontSize:`${this._terminal.options.fontSize}px`}),this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let e=0;e{Ne(this._linkCacheDisposables),this._linkCacheDisposables.length=0,this._lastMouseEvent=void 0,this._activeProviderReplies?.clear()})),this._register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0})),this._register(L(this._element,"mouseleave",()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(L(this._element,"mousemove",this._handleMouseMove.bind(this))),this._register(L(this._element,"mousedown",this._handleMouseDown.bind(this))),this._register(L(this._element,"mouseup",this._handleMouseUp.bind(this)))}get currentLink(){return this._currentLink}_handleMouseMove(e){this._lastMouseEvent=e;let i=this._positionFromMouseEvent(e,this._element,this._mouseService);if(!i)return;this._isMouseOut=!1;let r=e.composedPath();for(let n=0;n{n?.forEach(o=>{o.link.dispose&&o.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=e.y);let r=!1;for(let[n,o]of this._linkProviderService.linkProviders.entries())i?this._activeProviderReplies?.get(n)&&(r=this._checkLinkProviderResult(n,e,r)):o.provideLinks(e.y,l=>{if(this._isMouseOut)return;let a=l?.map(u=>({link:u}));this._activeProviderReplies?.set(n,a),r=this._checkLinkProviderResult(n,e,r),this._activeProviderReplies?.size===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)})}_removeIntersectingLinks(e,i){let r=new Set;for(let n=0;ne?this._bufferService.cols:a.link.range.end.x;for(let c=u;c<=h;c++){if(r.has(c)){o.splice(l--,1);break}r.add(c)}}}}_checkLinkProviderResult(e,i,r){if(!this._activeProviderReplies)return r;let n=this._activeProviderReplies.get(e),o=!1;for(let l=0;lthis._linkAtPosition(a.link,i));l&&(r=!0,this._handleNewLink(l))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!r)for(let l=0;lthis._linkAtPosition(u.link,i));if(a){r=!0,this._handleNewLink(a);break}}return r}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){if(!this._currentLink)return;let i=this._positionFromMouseEvent(e,this._element,this._mouseService);i&&this._mouseDownLink&&Ec(this._mouseDownLink.link,this._currentLink.link)&&this._linkAtPosition(this._currentLink.link,i)&&this._currentLink.link.activate(e,this._currentLink.link.text)}_clearCurrentLink(e,i){!this._currentLink||!this._lastMouseEvent||(!e||!i||this._currentLink.link.range.start.y>=e&&this._currentLink.link.range.end.y<=i)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,Ne(this._linkCacheDisposables),this._linkCacheDisposables.length=0)}_handleNewLink(e){if(!this._lastMouseEvent)return;let i=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);i&&this._linkAtPosition(e.link,i)&&(this._currentLink=e,this._currentLink.state={decorations:{underline:e.link.decorations===void 0?!0:e.link.decorations.underline,pointerCursor:e.link.decorations===void 0?!0:e.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,e.link,this._lastMouseEvent),e.link.decorations={},Object.defineProperties(e.link.decorations,{pointerCursor:{get:()=>this._currentLink?.state?.decorations.pointerCursor,set:r=>{this._currentLink?.state&&this._currentLink.state.decorations.pointerCursor!==r&&(this._currentLink.state.decorations.pointerCursor=r,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",r))}},underline:{get:()=>this._currentLink?.state?.decorations.underline,set:r=>{this._currentLink?.state&&this._currentLink?.state?.decorations.underline!==r&&(this._currentLink.state.decorations.underline=r,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,r))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(r=>{if(!this._currentLink)return;let n=r.start===0?0:r.start+1+this._bufferService.buffer.ydisp,o=this._bufferService.buffer.ydisp+1+r.end;if(this._currentLink.link.range.start.y>=n&&this._currentLink.link.range.end.y<=o&&(this._clearCurrentLink(n,o),this._lastMouseEvent)){let l=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);l&&this._askForLink(l,!1)}})))}_linkHover(e,i,r){this._currentLink?.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(i,!0),this._currentLink.state.decorations.pointerCursor&&e.classList.add("xterm-cursor-pointer")),i.hover&&i.hover(r,i.text)}_fireUnderlineEvent(e,i){let r=e.range,n=this._bufferService.buffer.ydisp,o=this._createLinkUnderlineEvent(r.start.x-1,r.start.y-n-1,r.end.x,r.end.y-n-1,void 0);(i?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(o)}_linkLeave(e,i,r){this._currentLink?.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(i,!1),this._currentLink.state.decorations.pointerCursor&&e.classList.remove("xterm-cursor-pointer")),i.leave&&i.leave(r,i.text)}_linkAtPosition(e,i){let r=e.range.start.y*this._bufferService.cols+e.range.start.x,n=e.range.end.y*this._bufferService.cols+e.range.end.x,o=i.y*this._bufferService.cols+i.x;return r<=o&&o<=n}_positionFromMouseEvent(e,i,r){let n=r.getCoords(e,i,this._bufferService.cols,this._bufferService.rows);if(n)return{x:n[0],y:n[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,i,r,n,o){return{x1:e,y1:i,x2:r,y2:n,cols:this._bufferService.cols,fg:o}}};hi=M([S(1,Dt),S(2,ce),S(3,F),S(4,lr)],hi);function Ec(s,t){return s.text===t.text&&s.range.start.x===t.range.start.x&&s.range.start.y===t.range.start.y&&s.range.end.x===t.range.end.x&&s.range.end.y===t.range.end.y}var yn=class extends Sn{constructor(e={}){super(e);this._linkifier=this._register(new ye);this.browser=tn;this._keyDownHandled=!1;this._keyDownSeen=!1;this._keyPressHandled=!1;this._unprocessedDeadKey=!1;this._accessibilityManager=this._register(new ye);this._onCursorMove=this._register(new v);this.onCursorMove=this._onCursorMove.event;this._onKey=this._register(new v);this.onKey=this._onKey.event;this._onRender=this._register(new v);this.onRender=this._onRender.event;this._onSelectionChange=this._register(new v);this.onSelectionChange=this._onSelectionChange.event;this._onTitleChange=this._register(new v);this.onTitleChange=this._onTitleChange.event;this._onBell=this._register(new v);this.onBell=this._onBell.event;this._onFocus=this._register(new v);this._onBlur=this._register(new v);this._onA11yCharEmitter=this._register(new v);this._onA11yTabEmitter=this._register(new v);this._onWillOpen=this._register(new v);this._setup(),this._decorationService=this._instantiationService.createInstance(Tn),this._instantiationService.setService(Be,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(Qr),this._instantiationService.setService(lr,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(wt)),this._register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this._register(this._inputHandler.onRequestRefreshRows(i=>this.refresh(i?.start??0,i?.end??this.rows-1))),this._register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this._register(this._inputHandler.onRequestReset(()=>this.reset())),this._register(this._inputHandler.onRequestWindowsOptionsReport(i=>this._reportWindowsOptions(i))),this._register(this._inputHandler.onColor(i=>this._handleColorEvent(i))),this._register($.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register($.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register($.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register($.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(i=>this._afterResize(i.cols,i.rows))),this._register(C(()=>{this._customKeyEventHandler=void 0,this.element?.parentNode?.removeChild(this.element)}))}get linkifier(){return this._linkifier.value}get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}_handleColorEvent(e){if(this._themeService)for(let i of e){let r,n="";switch(i.index){case 256:r="foreground",n="10";break;case 257:r="background",n="11";break;case 258:r="cursor",n="12";break;default:r="ansi",n="4;"+i.index}switch(i.type){case 0:let o=U.toColorRGB(r==="ansi"?this._themeService.colors.ansi[i.index]:this._themeService.colors[r]);this.coreService.triggerDataEvent(`${b.ESC}]${n};${ml(o)}${fs.ST}`);break;case 1:if(r==="ansi")this._themeService.modifyColors(l=>l.ansi[i.index]=j.toColor(...i.color));else{let l=r;this._themeService.modifyColors(a=>a[l]=j.toColor(...i.color))}break;case 2:this._themeService.restoreColor(i.index);break}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(e){e?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(Tt,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(b.ESC+"[I"),this.element.classList.add("focus"),this._showCursor(),this._onFocus.fire()}blur(){return this.textarea?.blur()}_handleTextAreaBlur(){this.textarea.value="",this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(b.ESC+"[O"),this.element.classList.remove("focus"),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;let e=this.buffer.ybase+this.buffer.y,i=this.buffer.lines.get(e);if(!i)return;let r=Math.min(this.buffer.x,this.cols-1),n=this._renderService.dimensions.css.cell.height,o=i.getWidth(r),l=this._renderService.dimensions.css.cell.width*o,a=this.buffer.y*this._renderService.dimensions.css.cell.height,u=r*this._renderService.dimensions.css.cell.width;this.textarea.style.left=u+"px",this.textarea.style.top=a+"px",this.textarea.style.width=l+"px",this.textarea.style.height=n+"px",this.textarea.style.lineHeight=n+"px",this.textarea.style.zIndex="-5"}_initGlobal(){this._bindKeys(),this._register(L(this.element,"copy",i=>{this.hasSelection()&&Vs(i,this._selectionService)}));let e=i=>qs(i,this.textarea,this.coreService,this.optionsService);this._register(L(this.textarea,"paste",e)),this._register(L(this.element,"paste",e)),Ss?this._register(L(this.element,"mousedown",i=>{i.button===2&&Pn(i,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(L(this.element,"contextmenu",i=>{Pn(i,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),Bi&&this._register(L(this.element,"auxclick",i=>{i.button===1&&Mn(i,this.textarea,this.screenElement)}))}_bindKeys(){this._register(L(this.textarea,"keyup",e=>this._keyUp(e),!0)),this._register(L(this.textarea,"keydown",e=>this._keyDown(e),!0)),this._register(L(this.textarea,"keypress",e=>this._keyPress(e),!0)),this._register(L(this.textarea,"compositionstart",()=>this._compositionHelper.compositionstart())),this._register(L(this.textarea,"compositionupdate",e=>this._compositionHelper.compositionupdate(e))),this._register(L(this.textarea,"compositionend",()=>this._compositionHelper.compositionend())),this._register(L(this.textarea,"input",e=>this._inputEvent(e),!0)),this._register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(e){if(!e)throw new Error("Terminal requires a parent element.");if(e.isConnected||this._logService.debug("Terminal.open was called on an element that was not attached to the DOM"),this.element?.ownerDocument.defaultView&&this._coreBrowserService){this.element.ownerDocument.defaultView!==this._coreBrowserService.window&&(this._coreBrowserService.window=this.element.ownerDocument.defaultView);return}this._document=e.ownerDocument,this.options.documentOverride&&this.options.documentOverride instanceof Document&&(this._document=this.optionsService.rawOptions.documentOverride),this.element=this._document.createElement("div"),this.element.dir="ltr",this.element.classList.add("terminal"),this.element.classList.add("xterm"),e.appendChild(this.element);let i=this._document.createDocumentFragment();this._viewportElement=this._document.createElement("div"),this._viewportElement.classList.add("xterm-viewport"),i.appendChild(this._viewportElement),this.screenElement=this._document.createElement("div"),this.screenElement.classList.add("xterm-screen"),this._register(L(this.screenElement,"mousemove",o=>this.updateCursorStyle(o))),this._helperContainer=this._document.createElement("div"),this._helperContainer.classList.add("xterm-helpers"),this.screenElement.appendChild(this._helperContainer),i.appendChild(this.screenElement);let r=this.textarea=this._document.createElement("textarea");this.textarea.classList.add("xterm-helper-textarea"),this.textarea.setAttribute("aria-label",mi.get()),Ts||this.textarea.setAttribute("aria-multiline","false"),this.textarea.setAttribute("autocorrect","off"),this.textarea.setAttribute("autocapitalize","off"),this.textarea.setAttribute("spellcheck","false"),this.textarea.tabIndex=0,this._register(this.optionsService.onSpecificOptionChange("disableStdin",()=>r.readOnly=this.optionsService.rawOptions.disableStdin)),this.textarea.readOnly=this.optionsService.rawOptions.disableStdin,this._coreBrowserService=this._register(this._instantiationService.createInstance(Jr,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<"u"?window.document:null)),this._instantiationService.setService(ae,this._coreBrowserService),this._register(L(this.textarea,"focus",o=>this._handleTextAreaFocus(o))),this._register(L(this.textarea,"blur",()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(jt,this._document,this._helperContainer),this._instantiationService.setService(nt,this._charSizeService),this._themeService=this._instantiationService.createInstance(ti),this._instantiationService.setService(Re,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(ct),this._instantiationService.setService(or,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(Qt,this.rows,this.screenElement)),this._instantiationService.setService(ce,this._renderService),this._register(this._renderService.onRenderedViewportChange(o=>this._onRender.fire(o))),this.onResize(o=>this._renderService.resize(o.cols,o.rows)),this._compositionView=this._document.createElement("div"),this._compositionView.classList.add("composition-view"),this._compositionHelper=this._instantiationService.createInstance($t,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(Xt),this._instantiationService.setService(Dt,this._mouseService);let n=this._linkifier.value=this._register(this._instantiationService.createInstance(hi,this.screenElement));this.element.appendChild(i);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this._register(this.onCursorMove(()=>{this._renderService.handleCursorMove(),this._syncTextArea()})),this._register(this.onResize(()=>this._renderService.handleResize(this.cols,this.rows))),this._register(this.onBlur(()=>this._renderService.handleBlur())),this._register(this.onFocus(()=>this._renderService.handleFocus())),this._viewport=this._register(this._instantiationService.createInstance(zt,this.element,this.screenElement)),this._register(this._viewport.onRequestScrollLines(o=>{super.scrollLines(o,!1),this.refresh(0,this.rows-1)})),this._selectionService=this._register(this._instantiationService.createInstance(ei,this.element,this.screenElement,n)),this._instantiationService.setService(Qs,this._selectionService),this._register(this._selectionService.onRequestScrollLines(o=>this.scrollLines(o.amount,o.suppressScrollEvent))),this._register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this._register(this._selectionService.onRequestRedraw(o=>this._renderService.handleSelectionChanged(o.start,o.end,o.columnSelectMode))),this._register(this._selectionService.onLinuxMouseSelection(o=>{this.textarea.value=o,this.textarea.focus(),this.textarea.select()})),this._register($.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{this._selectionService.refresh(),this._viewport?.queueSync()})),this._register(this._instantiationService.createInstance(Gt,this.screenElement)),this._register(L(this.element,"mousedown",o=>this._selectionService.handleMouseDown(o))),this.coreMouseService.areMouseEventsActive?(this._selectionService.disable(),this.element.classList.add("enable-mouse-events")):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager.value=this._instantiationService.createInstance(Tt,this)),this._register(this.optionsService.onSpecificOptionChange("screenReaderMode",o=>this._handleScreenReaderModeOptionChange(o))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(bt,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRuler",o=>{!this._overviewRulerRenderer&&o&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(bt,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(Yt,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,i=this.element;function r(l){let a=e._mouseService.getMouseReportCoords(l,e.screenElement);if(!a)return!1;let u,h;switch(l.overrideType||l.type){case"mousemove":h=32,l.buttons===void 0?(u=3,l.button!==void 0&&(u=l.button<3?l.button:3)):u=l.buttons&1?0:l.buttons&4?1:l.buttons&2?2:3;break;case"mouseup":h=0,u=l.button<3?l.button:3;break;case"mousedown":h=1,u=l.button<3?l.button:3;break;case"wheel":if(e._customWheelEventHandler&&e._customWheelEventHandler(l)===!1)return!1;let c=l.deltaY;if(c===0||e.coreMouseService.consumeWheelEvent(l,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return!1;h=c<0?0:1,u=4;break;default:return!1}return h===void 0||u===void 0||u>4?!1:e.coreMouseService.triggerMouseEvent({col:a.col,row:a.row,x:a.x,y:a.y,button:u,action:h,ctrl:l.ctrlKey,alt:l.altKey,shift:l.shiftKey})}let n={mouseup:null,wheel:null,mousedrag:null,mousemove:null},o={mouseup:l=>(r(l),l.buttons||(this._document.removeEventListener("mouseup",n.mouseup),n.mousedrag&&this._document.removeEventListener("mousemove",n.mousedrag)),this.cancel(l)),wheel:l=>(r(l),this.cancel(l,!0)),mousedrag:l=>{l.buttons&&r(l)},mousemove:l=>{l.buttons||r(l)}};this._register(this.coreMouseService.onProtocolChange(l=>{l?(this.optionsService.rawOptions.logLevel==="debug"&&this._logService.debug("Binding to mouse events:",this.coreMouseService.explainEvents(l)),this.element.classList.add("enable-mouse-events"),this._selectionService.disable()):(this._logService.debug("Unbinding from mouse events."),this.element.classList.remove("enable-mouse-events"),this._selectionService.enable()),l&8?n.mousemove||(i.addEventListener("mousemove",o.mousemove),n.mousemove=o.mousemove):(i.removeEventListener("mousemove",n.mousemove),n.mousemove=null),l&16?n.wheel||(i.addEventListener("wheel",o.wheel,{passive:!1}),n.wheel=o.wheel):(i.removeEventListener("wheel",n.wheel),n.wheel=null),l&2?n.mouseup||(n.mouseup=o.mouseup):(this._document.removeEventListener("mouseup",n.mouseup),n.mouseup=null),l&4?n.mousedrag||(n.mousedrag=o.mousedrag):(this._document.removeEventListener("mousemove",n.mousedrag),n.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register(L(i,"mousedown",l=>{if(l.preventDefault(),this.focus(),!(!this.coreMouseService.areMouseEventsActive||this._selectionService.shouldForceSelection(l)))return r(l),n.mouseup&&this._document.addEventListener("mouseup",n.mouseup),n.mousedrag&&this._document.addEventListener("mousemove",n.mousedrag),this.cancel(l)})),this._register(L(i,"wheel",l=>{if(!n.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(l)===!1)return!1;if(!this.buffer.hasScrollback){if(l.deltaY===0)return!1;if(e.coreMouseService.consumeWheelEvent(l,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return this.cancel(l,!0);let h=b.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?"O":"[")+(l.deltaY<0?"A":"B");return this.coreService.triggerDataEvent(h,!0),this.cancel(l,!0)}}},{passive:!1}))}refresh(e,i){this._renderService?.refreshRows(e,i)}updateCursorStyle(e){this._selectionService?.shouldColumnSelect(e)?this.element.classList.add("column-select"):this.element.classList.remove("column-select")}_showCursor(){this.coreService.isCursorInitialized||(this.coreService.isCursorInitialized=!0,this.refresh(this.buffer.y,this.buffer.y))}scrollLines(e,i){this._viewport?this._viewport.scrollLines(e):super.scrollLines(e,i),this.refresh(0,this.rows-1)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){e&&this._viewport?this._viewport.scrollToLine(this.buffer.ybase,!0):this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let i=e-this._bufferService.buffer.ydisp;i!==0&&this.scrollLines(i)}paste(e){Cn(e,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(e){this._customKeyEventHandler=e}attachCustomWheelEventHandler(e){this._customWheelEventHandler=e}registerLinkProvider(e){return this._linkProviderService.registerLinkProvider(e)}registerCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");let i=this._characterJoinerService.register(e);return this.refresh(0,this.rows-1),i}deregisterCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");this._characterJoinerService.deregister(e)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(e){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+e)}registerDecoration(e){return this._decorationService.registerDecoration(e)}hasSelection(){return this._selectionService?this._selectionService.hasSelection:!1}select(e,i,r){this._selectionService.setSelection(e,i,r)}getSelection(){return this._selectionService?this._selectionService.selectionText:""}getSelectionPosition(){if(!(!this._selectionService||!this._selectionService.hasSelection))return{start:{x:this._selectionService.selectionStart[0],y:this._selectionService.selectionStart[1]},end:{x:this._selectionService.selectionEnd[0],y:this._selectionService.selectionEnd[1]}}}clearSelection(){this._selectionService?.clearSelection()}selectAll(){this._selectionService?.selectAll()}selectLines(e,i){this._selectionService?.selectLines(e,i)}_keyDown(e){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;let i=this.browser.isMac&&this.options.macOptionIsMeta&&e.altKey;if(!i&&!this._compositionHelper.keydown(e))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(!0),!1;!i&&(e.key==="Dead"||e.key==="AltGraph")&&(this._unprocessedDeadKey=!0);let r=Il(e,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),r.type===3||r.type===2){let n=this.rows-1;return this.scrollLines(r.type===2?-n:n),this.cancel(e,!0)}if(r.type===1&&this.selectAll(),this._isThirdLevelShift(this.browser,e)||(r.cancel&&this.cancel(e,!0),!r.key)||e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.key.length===1&&e.key.charCodeAt(0)>=65&&e.key.charCodeAt(0)<=90)return!0;if(this._unprocessedDeadKey)return this._unprocessedDeadKey=!1,!0;if((r.key===b.ETX||r.key===b.CR)&&(this.textarea.value=""),this._onKey.fire({key:r.key,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(r.key,!0),!this.optionsService.rawOptions.screenReaderMode||e.altKey||e.ctrlKey)return this.cancel(e,!0);this._keyDownHandled=!0}_isThirdLevelShift(e,i){let r=e.isMac&&!this.options.macOptionIsMeta&&i.altKey&&!i.ctrlKey&&!i.metaKey||e.isWindows&&i.altKey&&i.ctrlKey&&!i.metaKey||e.isWindows&&i.getModifierState("AltGraph");return i.type==="keypress"?r:r&&(!i.keyCode||i.keyCode>47)}_keyUp(e){this._keyDownSeen=!1,!(this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)&&(Tc(e)||this.focus(),this.updateCursorStyle(e),this._keyPressHandled=!1)}_keyPress(e){let i;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;if(this.cancel(e),e.charCode)i=e.charCode;else if(e.which===null||e.which===void 0)i=e.keyCode;else if(e.which!==0&&e.charCode!==0)i=e.which;else return!1;return!i||(e.altKey||e.ctrlKey||e.metaKey)&&!this._isThirdLevelShift(this.browser,e)?!1:(i=String.fromCharCode(i),this._onKey.fire({key:i,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(i,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,!0)}_inputEvent(e){if(e.data&&e.inputType==="insertText"&&(!e.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;let i=e.data;return this.coreService.triggerDataEvent(i,!0),this.cancel(e),!0}return!1}resize(e,i){if(e===this.cols&&i===this.rows){this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure();return}super.resize(e,i)}_afterResize(e,i){this._charSizeService?.measure()}clear(){if(!(this.buffer.ybase===0&&this.buffer.y===0)){this.buffer.clearAllMarkers(),this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let e=1;e=0;t--)this._addons[t].instance.dispose()}loadAddon(t,e){let i={instance:e,dispose:e.dispose,isDisposed:!1};this._addons.push(i),e.dispose=()=>this._wrappedAddonDispose(i),e.activate(t)}_wrappedAddonDispose(t){if(t.isDisposed)return;let e=-1;for(let i=0;i=this._line.length))return e?(this._line.loadCell(t,e),e):this._line.loadCell(t,new q)}translateToString(t,e,i){return this._line.translateToString(t,e,i)}};var Ji=class{constructor(t,e){this._buffer=t;this.type=e}init(t){return this._buffer=t,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(t){let e=this._buffer.lines.get(t);if(e)return new wn(e)}getNullCell(){return new q}};var Dn=class extends D{constructor(e){super();this._core=e;this._onBufferChange=this._register(new v);this.onBufferChange=this._onBufferChange.event;this._normal=new Ji(this._core.buffers.normal,"normal"),this._alternate=new Ji(this._core.buffers.alt,"alternate"),this._core.buffers.onBufferActivate(()=>this._onBufferChange.fire(this.active))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw new Error("Active buffer is neither normal nor alternate")}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}};var Rn=class{constructor(t){this._core=t}registerCsiHandler(t,e){return this._core.registerCsiHandler(t,i=>e(i.toArray()))}addCsiHandler(t,e){return this.registerCsiHandler(t,e)}registerDcsHandler(t,e){return this._core.registerDcsHandler(t,(i,r)=>e(i,r.toArray()))}addDcsHandler(t,e){return this.registerDcsHandler(t,e)}registerEscHandler(t,e){return this._core.registerEscHandler(t,e)}addEscHandler(t,e){return this.registerEscHandler(t,e)}registerOscHandler(t,e){return this._core.registerOscHandler(t,e)}addOscHandler(t,e){return this.registerOscHandler(t,e)}};var Ln=class{constructor(t){this._core=t}register(t){this._core.unicodeService.register(t)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(t){this._core.unicodeService.activeVersion=t}};var Ic=["cols","rows"],Ue=0,Dl=class extends D{constructor(t){super(),this._core=this._register(new yn(t)),this._addonManager=this._register(new xn),this._publicOptions={...this._core.options};let e=r=>this._core.options[r],i=(r,n)=>{this._checkReadonlyOptions(r),this._core.options[r]=n};for(let r in this._core.options){let n={get:e.bind(this,r),set:i.bind(this,r)};Object.defineProperty(this._publicOptions,r,n)}}_checkReadonlyOptions(t){if(Ic.includes(t))throw new Error(`Option "${t}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw new Error("You must set the allowProposedApi option to true to use proposed API")}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onKey(){return this._core.onKey}get onLineFeed(){return this._core.onLineFeed}get onRender(){return this._core.onRender}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onSelectionChange(){return this._core.onSelectionChange}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get element(){return this._core.element}get parser(){return this._parser||(this._parser=new Rn(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new Ln(this._core)}get textarea(){return this._core.textarea}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._buffer||(this._buffer=this._register(new Dn(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let t=this._core.coreService.decPrivateModes,e="none";switch(this._core.coreMouseService.activeProtocol){case"X10":e="x10";break;case"VT200":e="vt200";break;case"DRAG":e="drag";break;case"ANY":e="any";break}return{applicationCursorKeysMode:t.applicationCursorKeys,applicationKeypadMode:t.applicationKeypad,bracketedPasteMode:t.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:e,originMode:t.origin,reverseWraparoundMode:t.reverseWraparound,sendFocusMode:t.sendFocus,synchronizedOutputMode:t.synchronizedOutput,wraparoundMode:t.wraparound}}get options(){return this._publicOptions}set options(t){for(let e in t)this._publicOptions[e]=t[e]}blur(){this._core.blur()}focus(){this._core.focus()}input(t,e=!0){this._core.input(t,e)}resize(t,e){this._verifyIntegers(t,e),this._core.resize(t,e)}open(t){this._core.open(t)}attachCustomKeyEventHandler(t){this._core.attachCustomKeyEventHandler(t)}attachCustomWheelEventHandler(t){this._core.attachCustomWheelEventHandler(t)}registerLinkProvider(t){return this._core.registerLinkProvider(t)}registerCharacterJoiner(t){return this._checkProposedApi(),this._core.registerCharacterJoiner(t)}deregisterCharacterJoiner(t){this._checkProposedApi(),this._core.deregisterCharacterJoiner(t)}registerMarker(t=0){return this._verifyIntegers(t),this._core.registerMarker(t)}registerDecoration(t){return this._checkProposedApi(),this._verifyPositiveIntegers(t.x??0,t.width??0,t.height??0),this._core.registerDecoration(t)}hasSelection(){return this._core.hasSelection()}select(t,e,i){this._verifyIntegers(t,e,i),this._core.select(t,e,i)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(t,e){this._verifyIntegers(t,e),this._core.selectLines(t,e)}dispose(){super.dispose()}scrollLines(t){this._verifyIntegers(t),this._core.scrollLines(t)}scrollPages(t){this._verifyIntegers(t),this._core.scrollPages(t)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(t){this._verifyIntegers(t),this._core.scrollToLine(t)}clear(){this._core.clear()}write(t,e){this._core.write(t,e)}writeln(t,e){this._core.write(t),this._core.write(`\r +`,e)}paste(t){this._core.paste(t)}refresh(t,e){this._verifyIntegers(t,e),this._core.refresh(t,e)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(t){this._addonManager.loadAddon(this,t)}static get strings(){return{get promptLabel(){return mi.get()},set promptLabel(t){mi.set(t)},get tooMuchOutput(){return _i.get()},set tooMuchOutput(t){_i.set(t)}}}_verifyIntegers(...t){for(Ue of t)if(Ue===1/0||isNaN(Ue)||Ue%1!==0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...t){for(Ue of t)if(Ue&&(Ue===1/0||isNaN(Ue)||Ue%1!==0||Ue<0))throw new Error("This API only accepts positive integers")}};export{Dl as Terminal}; +//# sourceMappingURL=xterm.mjs.map diff --git a/node_modules/@xterm/xterm/lib/xterm.mjs.map b/node_modules/@xterm/xterm/lib/xterm.mjs.map new file mode 100644 index 0000000..bafa940 --- /dev/null +++ b/node_modules/@xterm/xterm/lib/xterm.mjs.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../src/browser/LocalizableStrings.ts", "../src/browser/Clipboard.ts", "../src/common/input/TextDecoder.ts", "../src/common/buffer/Constants.ts", "../src/common/buffer/AttributeData.ts", "../src/common/buffer/CellData.ts", "../src/common/services/ServiceRegistry.ts", "../src/common/services/Services.ts", "../src/browser/OscLinkProvider.ts", "../src/browser/services/Services.ts", "../src/vs/base/common/errors.ts", "../src/vs/base/common/arraysFind.ts", "../src/vs/base/common/arrays.ts", "../src/vs/base/common/collections.ts", "../src/vs/base/common/map.ts", "../src/vs/base/common/functional.ts", "../src/vs/base/common/iterator.ts", "../src/vs/base/common/lifecycle.ts", "../src/vs/base/browser/window.ts", "../src/vs/base/common/linkedList.ts", "../src/vs/base/common/stopwatch.ts", "../src/vs/base/common/event.ts", "../src/vs/base/browser/browser.ts", "../src/vs/base/common/platform.ts", "../src/vs/base/browser/canIUse.ts", "../src/vs/base/common/keyCodes.ts", "../src/vs/base/common/keybindings.ts", "../src/vs/base/browser/keyboardEvent.ts", "../src/vs/base/browser/iframe.ts", "../src/vs/base/browser/mouseEvent.ts", "../src/vs/base/common/cancellation.ts", "../src/vs/base/common/symbols.ts", "../src/vs/base/common/async.ts", "../src/vs/base/common/strings.ts", "../src/vs/base/common/hash.ts", "../src/vs/base/browser/dom.ts", "../src/vs/base/browser/fastDomNode.ts", "../src/vs/base/browser/globalPointerMoveMonitor.ts", "../src/vs/base/common/decorators.ts", "../src/vs/base/browser/touch.ts", "../src/vs/base/browser/ui/widget.ts", "../src/vs/base/browser/ui/scrollbar/scrollbarArrow.ts", "../src/vs/base/common/scrollable.ts", "../src/vs/base/browser/ui/scrollbar/scrollbarVisibilityController.ts", "../src/vs/base/browser/ui/scrollbar/abstractScrollbar.ts", "../src/vs/base/browser/ui/scrollbar/scrollbarState.ts", "../src/vs/base/browser/ui/scrollbar/horizontalScrollbar.ts", "../src/vs/base/browser/ui/scrollbar/verticalScrollbar.ts", "../src/vs/base/browser/ui/scrollbar/scrollableElement.ts", "../src/browser/Viewport.ts", "../src/browser/decorations/BufferDecorationRenderer.ts", "../src/browser/decorations/ColorZoneStore.ts", "../src/browser/decorations/OverviewRulerRenderer.ts", "../src/common/data/EscapeSequences.ts", "../src/browser/input/CompositionHelper.ts", "../src/common/Color.ts", "../src/browser/services/CharacterJoinerService.ts", "../src/browser/renderer/shared/RendererUtils.ts", "../src/browser/renderer/dom/DomRendererRowFactory.ts", "../src/browser/renderer/dom/WidthCache.ts", "../src/browser/renderer/shared/SelectionRenderModel.ts", "../src/browser/renderer/dom/DomRenderer.ts", "../src/browser/services/CharSizeService.ts", "../src/browser/services/CoreBrowserService.ts", "../src/browser/services/LinkProviderService.ts", "../src/browser/input/Mouse.ts", "../src/browser/services/MouseService.ts", "../src/browser/RenderDebouncer.ts", "../src/common/Platform.ts", "../src/common/TaskQueue.ts", "../src/browser/services/RenderService.ts", "../src/browser/input/MoveToCell.ts", "../src/browser/selection/SelectionModel.ts", "../src/common/buffer/BufferRange.ts", "../src/browser/services/SelectionService.ts", "../src/common/MultiKeyMap.ts", "../src/browser/ColorContrastCache.ts", "../src/browser/Types.ts", "../src/browser/services/ThemeService.ts", "../src/common/services/InstantiationService.ts", "../src/common/services/LogService.ts", "../src/common/CircularList.ts", "../src/common/buffer/BufferLine.ts", "../src/common/buffer/BufferReflow.ts", "../src/common/buffer/Marker.ts", "../src/common/data/Charsets.ts", "../src/common/buffer/Buffer.ts", "../src/common/buffer/BufferSet.ts", "../src/common/services/BufferService.ts", "../src/common/services/OptionsService.ts", "../src/common/Clone.ts", "../src/common/services/CoreService.ts", "../src/common/services/CoreMouseService.ts", "../src/common/input/UnicodeV6.ts", "../src/common/services/UnicodeService.ts", "../src/common/services/CharsetService.ts", "../src/common/WindowsMode.ts", "../src/common/parser/Params.ts", "../src/common/parser/OscParser.ts", "../src/common/parser/DcsParser.ts", "../src/common/parser/EscapeSequenceParser.ts", "../src/common/input/XParseColor.ts", "../src/common/InputHandler.ts", "../src/common/input/WriteBuffer.ts", "../src/common/services/OscLinkService.ts", "../src/common/CoreTerminal.ts", "../src/common/input/Keyboard.ts", "../src/common/SortedList.ts", "../src/common/services/DecorationService.ts", "../src/browser/TimeBasedDebouncer.ts", "../src/browser/AccessibilityManager.ts", "../src/browser/Linkifier.ts", "../src/browser/CoreBrowserTerminal.ts", "../src/common/public/AddonManager.ts", "../src/common/public/BufferLineApiView.ts", "../src/common/public/BufferApiView.ts", "../src/common/public/BufferNamespaceApi.ts", "../src/common/public/ParserApi.ts", "../src/common/public/UnicodeApi.ts", "../src/browser/public/Terminal.ts"], + "sourcesContent": ["/**\n * Copyright (c) 2018 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\n// This file contains strings that get exported in the API so they can be localized\n\nlet promptLabelInternal = 'Terminal input';\nconst promptLabel = {\n get: () => promptLabelInternal,\n set: (value: string) => promptLabelInternal = value\n};\n\nlet tooMuchOutputInternal = 'Too much output to announce, navigate to rows manually to read';\nconst tooMuchOutput = {\n get: () => tooMuchOutputInternal,\n set: (value: string) => tooMuchOutputInternal = value\n};\n\nexport {\n promptLabel,\n tooMuchOutput\n};\n", "/**\n * Copyright (c) 2016 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { ISelectionService } from 'browser/services/Services';\nimport { ICoreService, IOptionsService } from 'common/services/Services';\n\n/**\n * Prepares text to be pasted into the terminal by normalizing the line endings\n * @param text The pasted text that needs processing before inserting into the terminal\n */\nexport function prepareTextForTerminal(text: string): string {\n return text.replace(/\\r?\\n/g, '\\r');\n}\n\n/**\n * Bracket text for paste, if necessary, as per https://cirw.in/blog/bracketed-paste\n * @param text The pasted text to bracket\n */\nexport function bracketTextForPaste(text: string, bracketedPasteMode: boolean): string {\n if (bracketedPasteMode) {\n return '\\x1b[200~' + text + '\\x1b[201~';\n }\n return text;\n}\n\n/**\n * Binds copy functionality to the given terminal.\n * @param ev The original copy event to be handled\n */\nexport function copyHandler(ev: ClipboardEvent, selectionService: ISelectionService): void {\n if (ev.clipboardData) {\n ev.clipboardData.setData('text/plain', selectionService.selectionText);\n }\n // Prevent or the original text will be copied.\n ev.preventDefault();\n}\n\n/**\n * Redirect the clipboard's data to the terminal's input handler.\n */\nexport function handlePasteEvent(ev: ClipboardEvent, textarea: HTMLTextAreaElement, coreService: ICoreService, optionsService: IOptionsService): void {\n ev.stopPropagation();\n if (ev.clipboardData) {\n const text = ev.clipboardData.getData('text/plain');\n paste(text, textarea, coreService, optionsService);\n }\n}\n\nexport function paste(text: string, textarea: HTMLTextAreaElement, coreService: ICoreService, optionsService: IOptionsService): void {\n text = prepareTextForTerminal(text);\n text = bracketTextForPaste(text, coreService.decPrivateModes.bracketedPasteMode && optionsService.rawOptions.ignoreBracketedPasteMode !== true);\n coreService.triggerDataEvent(text, true);\n textarea.value = '';\n}\n\n/**\n * Moves the textarea under the mouse cursor and focuses it.\n * @param ev The original right click event to be handled.\n * @param textarea The terminal's textarea.\n */\nexport function moveTextAreaUnderMouseCursor(ev: MouseEvent, textarea: HTMLTextAreaElement, screenElement: HTMLElement): void {\n\n // Calculate textarea position relative to the screen element\n const pos = screenElement.getBoundingClientRect();\n const left = ev.clientX - pos.left - 10;\n const top = ev.clientY - pos.top - 10;\n\n // Bring textarea at the cursor position\n textarea.style.width = '20px';\n textarea.style.height = '20px';\n textarea.style.left = `${left}px`;\n textarea.style.top = `${top}px`;\n textarea.style.zIndex = '1000';\n\n textarea.focus();\n}\n\n/**\n * Bind to right-click event and allow right-click copy and paste.\n */\nexport function rightClickHandler(ev: MouseEvent, textarea: HTMLTextAreaElement, screenElement: HTMLElement, selectionService: ISelectionService, shouldSelectWord: boolean): void {\n moveTextAreaUnderMouseCursor(ev, textarea, screenElement);\n\n if (shouldSelectWord) {\n selectionService.rightClickSelect(ev);\n }\n\n // Get textarea ready to copy from the context menu\n textarea.value = selectionService.selectionText;\n textarea.select();\n}\n", "/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\n/**\n * Polyfill - Convert UTF32 codepoint into JS string.\n * Note: The built-in String.fromCodePoint happens to be much slower\n * due to additional sanity checks. We can avoid them since\n * we always operate on legal UTF32 (granted by the input decoders)\n * and use this faster version instead.\n */\nexport function stringFromCodePoint(codePoint: number): string {\n if (codePoint > 0xFFFF) {\n codePoint -= 0x10000;\n return String.fromCharCode((codePoint >> 10) + 0xD800) + String.fromCharCode((codePoint % 0x400) + 0xDC00);\n }\n return String.fromCharCode(codePoint);\n}\n\n/**\n * Convert UTF32 char codes into JS string.\n * Basically the same as `stringFromCodePoint` but for multiple codepoints\n * in a loop (which is a lot faster).\n */\nexport function utf32ToString(data: Uint32Array, start: number = 0, end: number = data.length): string {\n let result = '';\n for (let i = start; i < end; ++i) {\n let codepoint = data[i];\n if (codepoint > 0xFFFF) {\n // JS strings are encoded as UTF16, thus a non BMP codepoint gets converted into a surrogate\n // pair conversion rules:\n // - subtract 0x10000 from code point, leaving a 20 bit number\n // - add high 10 bits to 0xD800 --> first surrogate\n // - add low 10 bits to 0xDC00 --> second surrogate\n codepoint -= 0x10000;\n result += String.fromCharCode((codepoint >> 10) + 0xD800) + String.fromCharCode((codepoint % 0x400) + 0xDC00);\n } else {\n result += String.fromCharCode(codepoint);\n }\n }\n return result;\n}\n\n/**\n * StringToUtf32 - decodes UTF16 sequences into UTF32 codepoints.\n * To keep the decoder in line with JS strings it handles single surrogates as UCS2.\n */\nexport class StringToUtf32 {\n private _interim: number = 0;\n\n /**\n * Clears interim and resets decoder to clean state.\n */\n public clear(): void {\n this._interim = 0;\n }\n\n /**\n * Decode JS string to UTF32 codepoints.\n * The methods assumes stream input and will store partly transmitted\n * surrogate pairs and decode them with the next data chunk.\n * Note: The method does no bound checks for target, therefore make sure\n * the provided input data does not exceed the size of `target`.\n * Returns the number of written codepoints in `target`.\n */\n public decode(input: string, target: Uint32Array): number {\n const length = input.length;\n\n if (!length) {\n return 0;\n }\n\n let size = 0;\n let startPos = 0;\n\n // handle leftover surrogate high\n if (this._interim) {\n const second = input.charCodeAt(startPos++);\n if (0xDC00 <= second && second <= 0xDFFF) {\n target[size++] = (this._interim - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;\n } else {\n // illegal codepoint (USC2 handling)\n target[size++] = this._interim;\n target[size++] = second;\n }\n this._interim = 0;\n }\n\n for (let i = startPos; i < length; ++i) {\n const code = input.charCodeAt(i);\n // surrogate pair first\n if (0xD800 <= code && code <= 0xDBFF) {\n if (++i >= length) {\n this._interim = code;\n return size;\n }\n const second = input.charCodeAt(i);\n if (0xDC00 <= second && second <= 0xDFFF) {\n target[size++] = (code - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;\n } else {\n // illegal codepoint (USC2 handling)\n target[size++] = code;\n target[size++] = second;\n }\n continue;\n }\n if (code === 0xFEFF) {\n // BOM\n continue;\n }\n target[size++] = code;\n }\n return size;\n }\n}\n\n/**\n * Utf8Decoder - decodes UTF8 byte sequences into UTF32 codepoints.\n */\nexport class Utf8ToUtf32 {\n public interim: Uint8Array = new Uint8Array(3);\n\n /**\n * Clears interim bytes and resets decoder to clean state.\n */\n public clear(): void {\n this.interim.fill(0);\n }\n\n /**\n * Decodes UTF8 byte sequences in `input` to UTF32 codepoints in `target`.\n * The methods assumes stream input and will store partly transmitted bytes\n * and decode them with the next data chunk.\n * Note: The method does no bound checks for target, therefore make sure\n * the provided data chunk does not exceed the size of `target`.\n * Returns the number of written codepoints in `target`.\n */\n public decode(input: Uint8Array, target: Uint32Array): number {\n const length = input.length;\n\n if (!length) {\n return 0;\n }\n\n let size = 0;\n let byte1: number;\n let byte2: number;\n let byte3: number;\n let byte4: number;\n let codepoint = 0;\n let startPos = 0;\n\n // handle leftover bytes\n if (this.interim[0]) {\n let discardInterim = false;\n let cp = this.interim[0];\n cp &= ((((cp & 0xE0) === 0xC0)) ? 0x1F : (((cp & 0xF0) === 0xE0)) ? 0x0F : 0x07);\n let pos = 0;\n let tmp: number;\n while ((tmp = this.interim[++pos] & 0x3F) && pos < 4) {\n cp <<= 6;\n cp |= tmp;\n }\n // missing bytes - read ahead from input\n const type = (((this.interim[0] & 0xE0) === 0xC0)) ? 2 : (((this.interim[0] & 0xF0) === 0xE0)) ? 3 : 4;\n const missing = type - pos;\n while (startPos < missing) {\n if (startPos >= length) {\n return 0;\n }\n tmp = input[startPos++];\n if ((tmp & 0xC0) !== 0x80) {\n // wrong continuation, discard interim bytes completely\n startPos--;\n discardInterim = true;\n break;\n } else {\n // need to save so we can continue short inputs in next call\n this.interim[pos++] = tmp;\n cp <<= 6;\n cp |= tmp & 0x3F;\n }\n }\n if (!discardInterim) {\n // final test is type dependent\n if (type === 2) {\n if (cp < 0x80) {\n // wrong starter byte\n startPos--;\n } else {\n target[size++] = cp;\n }\n } else if (type === 3) {\n if (cp < 0x0800 || (cp >= 0xD800 && cp <= 0xDFFF) || cp === 0xFEFF) {\n // illegal codepoint or BOM\n } else {\n target[size++] = cp;\n }\n } else {\n if (cp < 0x010000 || cp > 0x10FFFF) {\n // illegal codepoint\n } else {\n target[size++] = cp;\n }\n }\n }\n this.interim.fill(0);\n }\n\n // loop through input\n const fourStop = length - 4;\n let i = startPos;\n while (i < length) {\n /**\n * ASCII shortcut with loop unrolled to 4 consecutive ASCII chars.\n * This is a compromise between speed gain for ASCII\n * and penalty for non ASCII:\n * For best ASCII performance the char should be stored directly into target,\n * but even a single attempt to write to target and compare afterwards\n * penalizes non ASCII really bad (-50%), thus we load the char into byteX first,\n * which reduces ASCII performance by ~15%.\n * This trial for ASCII reduces non ASCII performance by ~10% which seems acceptible\n * compared to the gains.\n * Note that this optimization only takes place for 4 consecutive ASCII chars,\n * for any shorter it bails out. Worst case - all 4 bytes being read but\n * thrown away due to the last being a non ASCII char (-10% performance).\n */\n while (i < fourStop\n && !((byte1 = input[i]) & 0x80)\n && !((byte2 = input[i + 1]) & 0x80)\n && !((byte3 = input[i + 2]) & 0x80)\n && !((byte4 = input[i + 3]) & 0x80))\n {\n target[size++] = byte1;\n target[size++] = byte2;\n target[size++] = byte3;\n target[size++] = byte4;\n i += 4;\n }\n\n // reread byte1\n byte1 = input[i++];\n\n // 1 byte\n if (byte1 < 0x80) {\n target[size++] = byte1;\n\n // 2 bytes\n } else if ((byte1 & 0xE0) === 0xC0) {\n if (i >= length) {\n this.interim[0] = byte1;\n return size;\n }\n byte2 = input[i++];\n if ((byte2 & 0xC0) !== 0x80) {\n // wrong continuation\n i--;\n continue;\n }\n codepoint = (byte1 & 0x1F) << 6 | (byte2 & 0x3F);\n if (codepoint < 0x80) {\n // wrong starter byte\n i--;\n continue;\n }\n target[size++] = codepoint;\n\n // 3 bytes\n } else if ((byte1 & 0xF0) === 0xE0) {\n if (i >= length) {\n this.interim[0] = byte1;\n return size;\n }\n byte2 = input[i++];\n if ((byte2 & 0xC0) !== 0x80) {\n // wrong continuation\n i--;\n continue;\n }\n if (i >= length) {\n this.interim[0] = byte1;\n this.interim[1] = byte2;\n return size;\n }\n byte3 = input[i++];\n if ((byte3 & 0xC0) !== 0x80) {\n // wrong continuation\n i--;\n continue;\n }\n codepoint = (byte1 & 0x0F) << 12 | (byte2 & 0x3F) << 6 | (byte3 & 0x3F);\n if (codepoint < 0x0800 || (codepoint >= 0xD800 && codepoint <= 0xDFFF) || codepoint === 0xFEFF) {\n // illegal codepoint or BOM, no i-- here\n continue;\n }\n target[size++] = codepoint;\n\n // 4 bytes\n } else if ((byte1 & 0xF8) === 0xF0) {\n if (i >= length) {\n this.interim[0] = byte1;\n return size;\n }\n byte2 = input[i++];\n if ((byte2 & 0xC0) !== 0x80) {\n // wrong continuation\n i--;\n continue;\n }\n if (i >= length) {\n this.interim[0] = byte1;\n this.interim[1] = byte2;\n return size;\n }\n byte3 = input[i++];\n if ((byte3 & 0xC0) !== 0x80) {\n // wrong continuation\n i--;\n continue;\n }\n if (i >= length) {\n this.interim[0] = byte1;\n this.interim[1] = byte2;\n this.interim[2] = byte3;\n return size;\n }\n byte4 = input[i++];\n if ((byte4 & 0xC0) !== 0x80) {\n // wrong continuation\n i--;\n continue;\n }\n codepoint = (byte1 & 0x07) << 18 | (byte2 & 0x3F) << 12 | (byte3 & 0x3F) << 6 | (byte4 & 0x3F);\n if (codepoint < 0x010000 || codepoint > 0x10FFFF) {\n // illegal codepoint, no i-- here\n continue;\n }\n target[size++] = codepoint;\n } else {\n // illegal byte, just skip\n }\n }\n return size;\n }\n}\n", "/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nexport const DEFAULT_COLOR = 0;\nexport const DEFAULT_ATTR = (0 << 18) | (DEFAULT_COLOR << 9) | (256 << 0);\nexport const DEFAULT_EXT = 0;\n\nexport const CHAR_DATA_ATTR_INDEX = 0;\nexport const CHAR_DATA_CHAR_INDEX = 1;\nexport const CHAR_DATA_WIDTH_INDEX = 2;\nexport const CHAR_DATA_CODE_INDEX = 3;\n\n/**\n * Null cell - a real empty cell (containing nothing).\n * Note that code should always be 0 for a null cell as\n * several test condition of the buffer line rely on this.\n */\nexport const NULL_CELL_CHAR = '';\nexport const NULL_CELL_WIDTH = 1;\nexport const NULL_CELL_CODE = 0;\n\n/**\n * Whitespace cell.\n * This is meant as a replacement for empty cells when needed\n * during rendering lines to preserve correct aligment.\n */\nexport const WHITESPACE_CELL_CHAR = ' ';\nexport const WHITESPACE_CELL_WIDTH = 1;\nexport const WHITESPACE_CELL_CODE = 32;\n\n/**\n * Bitmasks for accessing data in `content`.\n */\nexport const enum Content {\n /**\n * bit 1..21 codepoint, max allowed in UTF32 is 0x10FFFF (21 bits taken)\n * read: `codepoint = content & Content.codepointMask;`\n * write: `content |= codepoint & Content.codepointMask;`\n * shortcut if precondition `codepoint <= 0x10FFFF` is met:\n * `content |= codepoint;`\n */\n CODEPOINT_MASK = 0x1FFFFF,\n\n /**\n * bit 22 flag indication whether a cell contains combined content\n * read: `isCombined = content & Content.isCombined;`\n * set: `content |= Content.isCombined;`\n * clear: `content &= ~Content.isCombined;`\n */\n IS_COMBINED_MASK = 0x200000, // 1 << 21\n\n /**\n * bit 1..22 mask to check whether a cell contains any string data\n * we need to check for codepoint and isCombined bits to see\n * whether a cell contains anything\n * read: `isEmpty = !(content & Content.hasContent)`\n */\n HAS_CONTENT_MASK = 0x3FFFFF,\n\n /**\n * bit 23..24 wcwidth value of cell, takes 2 bits (ranges from 0..2)\n * read: `width = (content & Content.widthMask) >> Content.widthShift;`\n * `hasWidth = content & Content.widthMask;`\n * as long as wcwidth is highest value in `content`:\n * `width = content >> Content.widthShift;`\n * write: `content |= (width << Content.widthShift) & Content.widthMask;`\n * shortcut if precondition `0 <= width <= 3` is met:\n * `content |= width << Content.widthShift;`\n */\n WIDTH_MASK = 0xC00000, // 3 << 22\n WIDTH_SHIFT = 22\n}\n\nexport const enum Attributes {\n /**\n * bit 1..8 blue in RGB, color in P256 and P16\n */\n BLUE_MASK = 0xFF,\n BLUE_SHIFT = 0,\n PCOLOR_MASK = 0xFF,\n PCOLOR_SHIFT = 0,\n\n /**\n * bit 9..16 green in RGB\n */\n GREEN_MASK = 0xFF00,\n GREEN_SHIFT = 8,\n\n /**\n * bit 17..24 red in RGB\n */\n RED_MASK = 0xFF0000,\n RED_SHIFT = 16,\n\n /**\n * bit 25..26 color mode: DEFAULT (0) | P16 (1) | P256 (2) | RGB (3)\n */\n CM_MASK = 0x3000000,\n CM_DEFAULT = 0,\n CM_P16 = 0x1000000,\n CM_P256 = 0x2000000,\n CM_RGB = 0x3000000,\n\n /**\n * bit 1..24 RGB room\n */\n RGB_MASK = 0xFFFFFF\n}\n\nexport const enum FgFlags {\n /**\n * bit 27..32\n */\n INVERSE = 0x4000000,\n BOLD = 0x8000000,\n UNDERLINE = 0x10000000,\n BLINK = 0x20000000,\n INVISIBLE = 0x40000000,\n STRIKETHROUGH = 0x80000000,\n}\n\nexport const enum BgFlags {\n /**\n * bit 27..32 (upper 2 unused)\n */\n ITALIC = 0x4000000,\n DIM = 0x8000000,\n HAS_EXTENDED = 0x10000000,\n PROTECTED = 0x20000000,\n OVERLINE = 0x40000000\n}\n\nexport const enum ExtFlags {\n /**\n * bit 27..29\n */\n UNDERLINE_STYLE = 0x1C000000,\n\n /**\n * bit 30..32\n *\n * An optional variant for the glyph, this can be used for example to offset underlines by a\n * number of pixels to create a perfect pattern.\n */\n VARIANT_OFFSET = 0xE0000000\n}\n\nexport const enum UnderlineStyle {\n NONE = 0,\n SINGLE = 1,\n DOUBLE = 2,\n CURLY = 3,\n DOTTED = 4,\n DASHED = 5\n}\n", "/**\n * Copyright (c) 2018 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IAttributeData, IColorRGB, IExtendedAttrs } from 'common/Types';\nimport { Attributes, FgFlags, BgFlags, UnderlineStyle, ExtFlags } from 'common/buffer/Constants';\n\nexport class AttributeData implements IAttributeData {\n public static toColorRGB(value: number): IColorRGB {\n return [\n value >>> Attributes.RED_SHIFT & 255,\n value >>> Attributes.GREEN_SHIFT & 255,\n value & 255\n ];\n }\n\n public static fromColorRGB(value: IColorRGB): number {\n return (value[0] & 255) << Attributes.RED_SHIFT | (value[1] & 255) << Attributes.GREEN_SHIFT | value[2] & 255;\n }\n\n public clone(): IAttributeData {\n const newObj = new AttributeData();\n newObj.fg = this.fg;\n newObj.bg = this.bg;\n newObj.extended = this.extended.clone();\n return newObj;\n }\n\n // data\n public fg = 0;\n public bg = 0;\n public extended: IExtendedAttrs = new ExtendedAttrs();\n\n // flags\n public isInverse(): number { return this.fg & FgFlags.INVERSE; }\n public isBold(): number { return this.fg & FgFlags.BOLD; }\n public isUnderline(): number {\n if (this.hasExtendedAttrs() && this.extended.underlineStyle !== UnderlineStyle.NONE) {\n return 1;\n }\n return this.fg & FgFlags.UNDERLINE;\n }\n public isBlink(): number { return this.fg & FgFlags.BLINK; }\n public isInvisible(): number { return this.fg & FgFlags.INVISIBLE; }\n public isItalic(): number { return this.bg & BgFlags.ITALIC; }\n public isDim(): number { return this.bg & BgFlags.DIM; }\n public isStrikethrough(): number { return this.fg & FgFlags.STRIKETHROUGH; }\n public isProtected(): number { return this.bg & BgFlags.PROTECTED; }\n public isOverline(): number { return this.bg & BgFlags.OVERLINE; }\n\n // color modes\n public getFgColorMode(): number { return this.fg & Attributes.CM_MASK; }\n public getBgColorMode(): number { return this.bg & Attributes.CM_MASK; }\n public isFgRGB(): boolean { return (this.fg & Attributes.CM_MASK) === Attributes.CM_RGB; }\n public isBgRGB(): boolean { return (this.bg & Attributes.CM_MASK) === Attributes.CM_RGB; }\n public isFgPalette(): boolean { return (this.fg & Attributes.CM_MASK) === Attributes.CM_P16 || (this.fg & Attributes.CM_MASK) === Attributes.CM_P256; }\n public isBgPalette(): boolean { return (this.bg & Attributes.CM_MASK) === Attributes.CM_P16 || (this.bg & Attributes.CM_MASK) === Attributes.CM_P256; }\n public isFgDefault(): boolean { return (this.fg & Attributes.CM_MASK) === 0; }\n public isBgDefault(): boolean { return (this.bg & Attributes.CM_MASK) === 0; }\n public isAttributeDefault(): boolean { return this.fg === 0 && this.bg === 0; }\n\n // colors\n public getFgColor(): number {\n switch (this.fg & Attributes.CM_MASK) {\n case Attributes.CM_P16:\n case Attributes.CM_P256: return this.fg & Attributes.PCOLOR_MASK;\n case Attributes.CM_RGB: return this.fg & Attributes.RGB_MASK;\n default: return -1; // CM_DEFAULT defaults to -1\n }\n }\n public getBgColor(): number {\n switch (this.bg & Attributes.CM_MASK) {\n case Attributes.CM_P16:\n case Attributes.CM_P256: return this.bg & Attributes.PCOLOR_MASK;\n case Attributes.CM_RGB: return this.bg & Attributes.RGB_MASK;\n default: return -1; // CM_DEFAULT defaults to -1\n }\n }\n\n // extended attrs\n public hasExtendedAttrs(): number {\n return this.bg & BgFlags.HAS_EXTENDED;\n }\n public updateExtended(): void {\n if (this.extended.isEmpty()) {\n this.bg &= ~BgFlags.HAS_EXTENDED;\n } else {\n this.bg |= BgFlags.HAS_EXTENDED;\n }\n }\n public getUnderlineColor(): number {\n if ((this.bg & BgFlags.HAS_EXTENDED) && ~this.extended.underlineColor) {\n switch (this.extended.underlineColor & Attributes.CM_MASK) {\n case Attributes.CM_P16:\n case Attributes.CM_P256: return this.extended.underlineColor & Attributes.PCOLOR_MASK;\n case Attributes.CM_RGB: return this.extended.underlineColor & Attributes.RGB_MASK;\n default: return this.getFgColor();\n }\n }\n return this.getFgColor();\n }\n public getUnderlineColorMode(): number {\n return (this.bg & BgFlags.HAS_EXTENDED) && ~this.extended.underlineColor\n ? this.extended.underlineColor & Attributes.CM_MASK\n : this.getFgColorMode();\n }\n public isUnderlineColorRGB(): boolean {\n return (this.bg & BgFlags.HAS_EXTENDED) && ~this.extended.underlineColor\n ? (this.extended.underlineColor & Attributes.CM_MASK) === Attributes.CM_RGB\n : this.isFgRGB();\n }\n public isUnderlineColorPalette(): boolean {\n return (this.bg & BgFlags.HAS_EXTENDED) && ~this.extended.underlineColor\n ? (this.extended.underlineColor & Attributes.CM_MASK) === Attributes.CM_P16\n || (this.extended.underlineColor & Attributes.CM_MASK) === Attributes.CM_P256\n : this.isFgPalette();\n }\n public isUnderlineColorDefault(): boolean {\n return (this.bg & BgFlags.HAS_EXTENDED) && ~this.extended.underlineColor\n ? (this.extended.underlineColor & Attributes.CM_MASK) === 0\n : this.isFgDefault();\n }\n public getUnderlineStyle(): UnderlineStyle {\n return this.fg & FgFlags.UNDERLINE\n ? (this.bg & BgFlags.HAS_EXTENDED ? this.extended.underlineStyle : UnderlineStyle.SINGLE)\n : UnderlineStyle.NONE;\n }\n public getUnderlineVariantOffset(): number {\n return this.extended.underlineVariantOffset;\n }\n}\n\n\n/**\n * Extended attributes for a cell.\n * Holds information about different underline styles and color.\n */\nexport class ExtendedAttrs implements IExtendedAttrs {\n private _ext: number = 0;\n public get ext(): number {\n if (this._urlId) {\n return (\n (this._ext & ~ExtFlags.UNDERLINE_STYLE) |\n (this.underlineStyle << 26)\n );\n }\n return this._ext;\n }\n public set ext(value: number) { this._ext = value; }\n\n public get underlineStyle(): UnderlineStyle {\n // Always return the URL style if it has one\n if (this._urlId) {\n return UnderlineStyle.DASHED;\n }\n return (this._ext & ExtFlags.UNDERLINE_STYLE) >> 26;\n }\n public set underlineStyle(value: UnderlineStyle) {\n this._ext &= ~ExtFlags.UNDERLINE_STYLE;\n this._ext |= (value << 26) & ExtFlags.UNDERLINE_STYLE;\n }\n\n public get underlineColor(): number {\n return this._ext & (Attributes.CM_MASK | Attributes.RGB_MASK);\n }\n public set underlineColor(value: number) {\n this._ext &= ~(Attributes.CM_MASK | Attributes.RGB_MASK);\n this._ext |= value & (Attributes.CM_MASK | Attributes.RGB_MASK);\n }\n\n private _urlId: number = 0;\n public get urlId(): number {\n return this._urlId;\n }\n public set urlId(value: number) {\n this._urlId = value;\n }\n\n public get underlineVariantOffset(): number {\n const val = (this._ext & ExtFlags.VARIANT_OFFSET) >> 29;\n if (val < 0) {\n return val ^ 0xFFFFFFF8;\n }\n return val;\n }\n public set underlineVariantOffset(value: number) {\n this._ext &= ~ExtFlags.VARIANT_OFFSET;\n this._ext |= (value << 29) & ExtFlags.VARIANT_OFFSET;\n }\n\n constructor(\n ext: number = 0,\n urlId: number = 0\n ) {\n this._ext = ext;\n this._urlId = urlId;\n }\n\n public clone(): IExtendedAttrs {\n return new ExtendedAttrs(this._ext, this._urlId);\n }\n\n /**\n * Convenient method to indicate whether the object holds no additional information,\n * that needs to be persistant in the buffer.\n */\n public isEmpty(): boolean {\n return this.underlineStyle === UnderlineStyle.NONE && this._urlId === 0;\n }\n}\n", "/**\n * Copyright (c) 2018 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { CharData, ICellData, IExtendedAttrs } from 'common/Types';\nimport { stringFromCodePoint } from 'common/input/TextDecoder';\nimport { CHAR_DATA_CHAR_INDEX, CHAR_DATA_WIDTH_INDEX, CHAR_DATA_ATTR_INDEX, Content } from 'common/buffer/Constants';\nimport { AttributeData, ExtendedAttrs } from 'common/buffer/AttributeData';\n\n/**\n * CellData - represents a single Cell in the terminal buffer.\n */\nexport class CellData extends AttributeData implements ICellData {\n /** Helper to create CellData from CharData. */\n public static fromCharData(value: CharData): CellData {\n const obj = new CellData();\n obj.setFromCharData(value);\n return obj;\n }\n /** Primitives from terminal buffer. */\n public content = 0;\n public fg = 0;\n public bg = 0;\n public extended: IExtendedAttrs = new ExtendedAttrs();\n public combinedData = '';\n /** Whether cell contains a combined string. */\n public isCombined(): number {\n return this.content & Content.IS_COMBINED_MASK;\n }\n /** Width of the cell. */\n public getWidth(): number {\n return this.content >> Content.WIDTH_SHIFT;\n }\n /** JS string of the content. */\n public getChars(): string {\n if (this.content & Content.IS_COMBINED_MASK) {\n return this.combinedData;\n }\n if (this.content & Content.CODEPOINT_MASK) {\n return stringFromCodePoint(this.content & Content.CODEPOINT_MASK);\n }\n return '';\n }\n /**\n * Codepoint of cell\n * Note this returns the UTF32 codepoint of single chars,\n * if content is a combined string it returns the codepoint\n * of the last char in string to be in line with code in CharData.\n */\n public getCode(): number {\n return (this.isCombined())\n ? this.combinedData.charCodeAt(this.combinedData.length - 1)\n : this.content & Content.CODEPOINT_MASK;\n }\n /** Set data from CharData */\n public setFromCharData(value: CharData): void {\n this.fg = value[CHAR_DATA_ATTR_INDEX];\n this.bg = 0;\n let combined = false;\n // surrogates and combined strings need special treatment\n if (value[CHAR_DATA_CHAR_INDEX].length > 2) {\n combined = true;\n }\n else if (value[CHAR_DATA_CHAR_INDEX].length === 2) {\n const code = value[CHAR_DATA_CHAR_INDEX].charCodeAt(0);\n // if the 2-char string is a surrogate create single codepoint\n // everything else is combined\n if (0xD800 <= code && code <= 0xDBFF) {\n const second = value[CHAR_DATA_CHAR_INDEX].charCodeAt(1);\n if (0xDC00 <= second && second <= 0xDFFF) {\n this.content = ((code - 0xD800) * 0x400 + second - 0xDC00 + 0x10000) | (value[CHAR_DATA_WIDTH_INDEX] << Content.WIDTH_SHIFT);\n }\n else {\n combined = true;\n }\n }\n else {\n combined = true;\n }\n }\n else {\n this.content = value[CHAR_DATA_CHAR_INDEX].charCodeAt(0) | (value[CHAR_DATA_WIDTH_INDEX] << Content.WIDTH_SHIFT);\n }\n if (combined) {\n this.combinedData = value[CHAR_DATA_CHAR_INDEX];\n this.content = Content.IS_COMBINED_MASK | (value[CHAR_DATA_WIDTH_INDEX] << Content.WIDTH_SHIFT);\n }\n }\n /** Get data as CharData. */\n public getAsCharData(): CharData {\n return [this.fg, this.getChars(), this.getWidth(), this.getCode()];\n }\n}\n", "/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n *\n * This was heavily inspired from microsoft/vscode's dependency injection system (MIT).\n */\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\nimport { IServiceIdentifier } from 'common/services/Services';\n\nconst DI_TARGET = 'di$target';\nconst DI_DEPENDENCIES = 'di$dependencies';\n\nexport const serviceRegistry: Map> = new Map();\n\nexport function getServiceDependencies(ctor: any): { id: IServiceIdentifier, index: number, optional: boolean }[] {\n return ctor[DI_DEPENDENCIES] || [];\n}\n\nexport function createDecorator(id: string): IServiceIdentifier {\n if (serviceRegistry.has(id)) {\n return serviceRegistry.get(id)!;\n }\n\n const decorator: any = function (target: Function, key: string, index: number): any {\n if (arguments.length !== 3) {\n throw new Error('@IServiceName-decorator can only be used to decorate a parameter');\n }\n\n storeServiceDependency(decorator, target, index);\n };\n\n decorator._id = id;\n\n serviceRegistry.set(id, decorator);\n return decorator;\n}\n\nfunction storeServiceDependency(id: Function, target: Function, index: number): void {\n if ((target as any)[DI_TARGET] === target) {\n (target as any)[DI_DEPENDENCIES].push({ id, index });\n } else {\n (target as any)[DI_DEPENDENCIES] = [{ id, index }];\n (target as any)[DI_TARGET] = target;\n }\n}\n", "/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IDecoration, IDecorationOptions, ILinkHandler, ILogger, IWindowsPty, type IOverviewRulerOptions } from '@xterm/xterm';\nimport { CoreMouseEncoding, CoreMouseEventType, CursorInactiveStyle, CursorStyle, IAttributeData, ICharset, IColor, ICoreMouseEvent, ICoreMouseProtocol, IDecPrivateModes, IDisposable, IModes, IOscLinkData, IWindowOptions } from 'common/Types';\nimport { IBuffer, IBufferSet } from 'common/buffer/Types';\nimport { createDecorator } from 'common/services/ServiceRegistry';\nimport type { Emitter, Event } from 'vs/base/common/event';\n\nexport const IBufferService = createDecorator('BufferService');\nexport interface IBufferService {\n serviceBrand: undefined;\n\n readonly cols: number;\n readonly rows: number;\n readonly buffer: IBuffer;\n readonly buffers: IBufferSet;\n isUserScrolling: boolean;\n onResize: Event;\n onScroll: Event;\n scroll(eraseAttr: IAttributeData, isWrapped?: boolean): void;\n scrollLines(disp: number, suppressScrollEvent?: boolean): void;\n resize(cols: number, rows: number): void;\n reset(): void;\n}\n\nexport interface IBufferResizeEvent {\n cols: number;\n rows: number;\n colsChanged: boolean;\n rowsChanged: boolean;\n}\n\nexport const ICoreMouseService = createDecorator('CoreMouseService');\nexport interface ICoreMouseService {\n serviceBrand: undefined;\n\n activeProtocol: string;\n activeEncoding: string;\n areMouseEventsActive: boolean;\n addProtocol(name: string, protocol: ICoreMouseProtocol): void;\n addEncoding(name: string, encoding: CoreMouseEncoding): void;\n reset(): void;\n\n /**\n * Triggers a mouse event to be sent.\n *\n * Returns true if the event passed all protocol restrictions and a report\n * was sent, otherwise false. The return value may be used to decide whether\n * the default event action in the bowser component should be omitted.\n *\n * Note: The method will change values of the given event object\n * to fullfill protocol and encoding restrictions.\n */\n triggerMouseEvent(event: ICoreMouseEvent): boolean;\n\n /**\n * Event to announce changes in mouse tracking.\n */\n onProtocolChange: Event;\n\n /**\n * Human readable version of mouse events.\n */\n explainEvents(events: CoreMouseEventType): { [event: string]: boolean };\n\n /**\n * Process wheel event taking partial scroll into account.\n */\n consumeWheelEvent(ev: WheelEvent, cellHeight?: number, dpr?: number): number;\n}\n\nexport const ICoreService = createDecorator('CoreService');\nexport interface ICoreService {\n serviceBrand: undefined;\n\n /**\n * Initially the cursor will not be visible until the first time the terminal\n * is focused.\n */\n isCursorInitialized: boolean;\n isCursorHidden: boolean;\n\n readonly modes: IModes;\n readonly decPrivateModes: IDecPrivateModes;\n\n readonly onData: Event;\n readonly onUserInput: Event;\n readonly onBinary: Event;\n readonly onRequestScrollToBottom: Event;\n\n reset(): void;\n\n /**\n * Triggers the onData event in the public API.\n * @param data The data that is being emitted.\n * @param wasUserInput Whether the data originated from the user (as opposed to\n * resulting from parsing incoming data). When true this will also:\n * - Scroll to the bottom of the buffer if option scrollOnUserInput is true.\n * - Fire the `onUserInput` event (so selection can be cleared).\n */\n triggerDataEvent(data: string, wasUserInput?: boolean): void;\n\n /**\n * Triggers the onBinary event in the public API.\n * @param data The data that is being emitted.\n */\n triggerBinaryEvent(data: string): void;\n}\n\nexport const ICharsetService = createDecorator('CharsetService');\nexport interface ICharsetService {\n serviceBrand: undefined;\n\n charset: ICharset | undefined;\n readonly glevel: number;\n\n reset(): void;\n\n /**\n * Set the G level of the terminal.\n * @param g\n */\n setgLevel(g: number): void;\n\n /**\n * Set the charset for the given G level of the terminal.\n * @param g\n * @param charset\n */\n setgCharset(g: number, charset: ICharset | undefined): void;\n}\n\nexport interface IServiceIdentifier {\n (...args: any[]): void;\n type: T;\n _id: string;\n}\n\nexport interface IBrandedService {\n serviceBrand: undefined;\n}\n\ntype GetLeadingNonServiceArgs = TArgs extends [] ? []\n : TArgs extends [...infer TFirst, infer TLast] ? TLast extends IBrandedService ? GetLeadingNonServiceArgs : TArgs\n : never;\n\nexport const IInstantiationService = createDecorator('InstantiationService');\nexport interface IInstantiationService {\n serviceBrand: undefined;\n\n setService(id: IServiceIdentifier, instance: T): void;\n getService(id: IServiceIdentifier): T | undefined;\n createInstance any, R extends InstanceType>(t: Ctor, ...args: GetLeadingNonServiceArgs>): R;\n}\n\nexport enum LogLevelEnum {\n TRACE = 0,\n DEBUG = 1,\n INFO = 2,\n WARN = 3,\n ERROR = 4,\n OFF = 5\n}\n\nexport const ILogService = createDecorator('LogService');\nexport interface ILogService {\n serviceBrand: undefined;\n\n readonly logLevel: LogLevelEnum;\n\n trace(message: any, ...optionalParams: any[]): void;\n debug(message: any, ...optionalParams: any[]): void;\n info(message: any, ...optionalParams: any[]): void;\n warn(message: any, ...optionalParams: any[]): void;\n error(message: any, ...optionalParams: any[]): void;\n}\n\nexport const IOptionsService = createDecorator('OptionsService');\nexport interface IOptionsService {\n serviceBrand: undefined;\n\n /**\n * Read only access to the raw options object, this is an internal-only fast path for accessing\n * single options without any validation as we trust TypeScript to enforce correct usage\n * internally.\n */\n readonly rawOptions: Required;\n\n /**\n * Options as exposed through the public API, this property uses getters and setters with\n * validation which makes it safer but slower. {@link rawOptions} should be used for pretty much\n * all internal usage for performance reasons.\n */\n readonly options: Required;\n\n /**\n * Adds an event listener for when any option changes.\n */\n readonly onOptionChange: Event;\n\n /**\n * Adds an event listener for when a specific option changes, this is a convenience method that is\n * preferred over {@link onOptionChange} when only a single option is being listened to.\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n onSpecificOptionChange(key: T, listener: (arg1: Required[T]) => any): IDisposable;\n\n /**\n * Adds an event listener for when a set of specific options change, this is a convenience method\n * that is preferred over {@link onOptionChange} when multiple options are being listened to and\n * handled the same way.\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n onMultipleOptionChange(keys: (keyof ITerminalOptions)[], listener: () => any): IDisposable;\n}\n\nexport type FontWeight = 'normal' | 'bold' | '100' | '200' | '300' | '400' | '500' | '600' | '700' | '800' | '900' | number;\nexport type LogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'off';\n\nexport interface ITerminalOptions {\n allowProposedApi?: boolean;\n allowTransparency?: boolean;\n altClickMovesCursor?: boolean;\n cols?: number;\n convertEol?: boolean;\n cursorBlink?: boolean;\n cursorStyle?: CursorStyle;\n cursorWidth?: number;\n cursorInactiveStyle?: CursorInactiveStyle;\n customGlyphs?: boolean;\n disableStdin?: boolean;\n documentOverride?: any | null;\n drawBoldTextInBrightColors?: boolean;\n /** @deprecated No longer supported */\n fastScrollModifier?: 'none' | 'alt' | 'ctrl' | 'shift';\n fastScrollSensitivity?: number;\n fontSize?: number;\n fontFamily?: string;\n fontWeight?: FontWeight;\n fontWeightBold?: FontWeight;\n ignoreBracketedPasteMode?: boolean;\n letterSpacing?: number;\n lineHeight?: number;\n linkHandler?: ILinkHandler | null;\n logLevel?: LogLevel;\n logger?: ILogger | null;\n macOptionIsMeta?: boolean;\n macOptionClickForcesSelection?: boolean;\n minimumContrastRatio?: number;\n reflowCursorLine?: boolean;\n rescaleOverlappingGlyphs?: boolean;\n rightClickSelectsWord?: boolean;\n rows?: number;\n screenReaderMode?: boolean;\n scrollback?: number;\n scrollOnUserInput?: boolean;\n scrollSensitivity?: number;\n smoothScrollDuration?: number;\n tabStopWidth?: number;\n theme?: ITheme;\n windowsMode?: boolean;\n windowsPty?: IWindowsPty;\n windowOptions?: IWindowOptions;\n wordSeparator?: string;\n overviewRuler?: IOverviewRulerOptions;\n scrollOnEraseInDisplay?: boolean;\n\n [key: string]: any;\n cancelEvents: boolean;\n termName: string;\n}\n\nexport interface ITheme {\n foreground?: string;\n background?: string;\n cursor?: string;\n cursorAccent?: string;\n selectionForeground?: string;\n selectionBackground?: string;\n selectionInactiveBackground?: string;\n scrollbarSliderBackground?: string;\n scrollbarSliderHoverBackground?: string;\n scrollbarSliderActiveBackground?: string;\n overviewRulerBorder?: string;\n black?: string;\n red?: string;\n green?: string;\n yellow?: string;\n blue?: string;\n magenta?: string;\n cyan?: string;\n white?: string;\n brightBlack?: string;\n brightRed?: string;\n brightGreen?: string;\n brightYellow?: string;\n brightBlue?: string;\n brightMagenta?: string;\n brightCyan?: string;\n brightWhite?: string;\n extendedAnsi?: string[];\n}\n\nexport const IOscLinkService = createDecorator('OscLinkService');\nexport interface IOscLinkService {\n serviceBrand: undefined;\n /**\n * Registers a link to the service, returning the link ID. The link data is managed by this\n * service and will be freed when this current cursor position is trimmed off the buffer.\n */\n registerLink(linkData: IOscLinkData): number;\n /**\n * Adds a line to a link if needed.\n */\n addLineToLink(linkId: number, y: number): void;\n /** Get the link data associated with a link ID. */\n getLinkData(linkId: number): IOscLinkData | undefined;\n}\n\n/*\n * Width and Grapheme_Cluster_Break properties of a character as a bit mask.\n *\n * bit 0: shouldJoin - should combine with preceding character.\n * bit 1..2: wcwidth - see UnicodeCharWidth.\n * bit 3..31: class of character (currently only 4 bits are used).\n * This is used to determined grapheme clustering - i.e. which codepoints\n * are to be combined into a single compound character.\n *\n * Use the UnicodeService static function createPropertyValue to create a\n * UnicodeCharProperties; use extractShouldJoin, extractWidth, and\n * extractCharKind to extract the components.\n */\nexport type UnicodeCharProperties = number;\n\n/**\n * Width in columns of a character.\n * In a CJK context, \"half-width\" characters (such as Latin) are width 1,\n * while \"full-width\" characters (such as Kanji) are 2 columns wide.\n * Combining characters (such as accents) are width 0.\n */\nexport type UnicodeCharWidth = 0 | 1 | 2;\n\nexport const IUnicodeService = createDecorator('UnicodeService');\nexport interface IUnicodeService {\n serviceBrand: undefined;\n /** Register an Unicode version provider. */\n register(provider: IUnicodeVersionProvider): void;\n /** Registered Unicode versions. */\n readonly versions: string[];\n /** Currently active version. */\n activeVersion: string;\n /** Event triggered, when activate version changed. */\n readonly onChange: Event;\n\n /**\n * Unicode version dependent\n */\n wcwidth(codepoint: number): UnicodeCharWidth;\n getStringCellWidth(s: string): number;\n /**\n * Return character width and type for grapheme clustering.\n * If preceding != 0, it is the return code from the previous character;\n * in that case the result specifies if the characters should be joined.\n */\n charProperties(codepoint: number, preceding: UnicodeCharProperties): UnicodeCharProperties;\n}\n\nexport interface IUnicodeVersionProvider {\n readonly version: string;\n wcwidth(ucs: number): UnicodeCharWidth;\n charProperties(codepoint: number, preceding: UnicodeCharProperties): UnicodeCharProperties;\n}\n\nexport const IDecorationService = createDecorator('DecorationService');\nexport interface IDecorationService extends IDisposable {\n serviceBrand: undefined;\n readonly decorations: IterableIterator;\n readonly onDecorationRegistered: Event;\n readonly onDecorationRemoved: Event;\n registerDecoration(decorationOptions: IDecorationOptions): IDecoration | undefined;\n reset(): void;\n /**\n * Trigger a callback over the decoration at a cell (in no particular order). This uses a callback\n * instead of an iterator as it's typically used in hot code paths.\n */\n forEachDecorationAtCell(x: number, line: number, layer: 'bottom' | 'top' | undefined, callback: (decoration: IInternalDecoration) => void): void;\n}\nexport interface IInternalDecoration extends IDecoration {\n readonly options: IDecorationOptions;\n readonly backgroundColorRGB: IColor | undefined;\n readonly foregroundColorRGB: IColor | undefined;\n readonly onRenderEmitter: Emitter;\n}\n", "/**\n * Copyright (c) 2022 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IBufferRange, ILink } from 'browser/Types';\nimport { ILinkProvider } from 'browser/services/Services';\nimport { CellData } from 'common/buffer/CellData';\nimport { IBufferService, IOptionsService, IOscLinkService } from 'common/services/Services';\n\nexport class OscLinkProvider implements ILinkProvider {\n constructor(\n @IBufferService private readonly _bufferService: IBufferService,\n @IOptionsService private readonly _optionsService: IOptionsService,\n @IOscLinkService private readonly _oscLinkService: IOscLinkService\n ) {\n }\n\n public provideLinks(y: number, callback: (links: ILink[] | undefined) => void): void {\n const line = this._bufferService.buffer.lines.get(y - 1);\n if (!line) {\n callback(undefined);\n return;\n }\n\n const result: ILink[] = [];\n const linkHandler = this._optionsService.rawOptions.linkHandler;\n const cell = new CellData();\n const lineLength = line.getTrimmedLength();\n let currentLinkId = -1;\n let currentStart = -1;\n let finishLink = false;\n for (let x = 0; x < lineLength; x++) {\n // Minor optimization, only check for content if there isn't a link in case the link ends with\n // a null cell\n if (currentStart === -1 && !line.hasContent(x)) {\n continue;\n }\n\n line.loadCell(x, cell);\n if (cell.hasExtendedAttrs() && cell.extended.urlId) {\n if (currentStart === -1) {\n currentStart = x;\n currentLinkId = cell.extended.urlId;\n continue;\n } else {\n finishLink = cell.extended.urlId !== currentLinkId;\n }\n } else {\n if (currentStart !== -1) {\n finishLink = true;\n }\n }\n\n if (finishLink || (currentStart !== -1 && x === lineLength - 1)) {\n const text = this._oscLinkService.getLinkData(currentLinkId)?.uri;\n if (text) {\n // These ranges are 1-based\n const range: IBufferRange = {\n start: {\n x: currentStart + 1,\n y\n },\n end: {\n // Offset end x if it's a link that ends on the last cell in the line\n x: x + (!finishLink && x === lineLength - 1 ? 1 : 0),\n y\n }\n };\n\n let ignoreLink = false;\n if (!linkHandler?.allowNonHttpProtocols) {\n try {\n const parsed = new URL(text);\n if (!['http:', 'https:'].includes(parsed.protocol)) {\n ignoreLink = true;\n }\n } catch (e) {\n // Ignore invalid URLs to prevent unexpected behaviors\n ignoreLink = true;\n }\n }\n\n if (!ignoreLink) {\n // OSC links always use underline and pointer decorations\n result.push({\n text,\n range,\n activate: (e, text) => (linkHandler ? linkHandler.activate(e, text, range) : defaultActivate(e, text)),\n hover: (e, text) => linkHandler?.hover?.(e, text, range),\n leave: (e, text) => linkHandler?.leave?.(e, text, range)\n });\n }\n }\n finishLink = false;\n\n // Clear link or start a new link if one starts immediately\n if (cell.hasExtendedAttrs() && cell.extended.urlId) {\n currentStart = x;\n currentLinkId = cell.extended.urlId;\n } else {\n currentStart = -1;\n currentLinkId = -1;\n }\n }\n }\n\n // TODO: Handle fetching and returning other link ranges to underline other links with the same\n // id\n callback(result);\n }\n}\n\nfunction defaultActivate(e: MouseEvent, uri: string): void {\n const answer = confirm(`Do you want to navigate to ${uri}?\\n\\nWARNING: This link could potentially be dangerous`);\n if (answer) {\n const newWindow = window.open();\n if (newWindow) {\n try {\n newWindow.opener = null;\n } catch {\n // no-op, Electron can throw\n }\n newWindow.location.href = uri;\n } else {\n console.warn('Opening link blocked as opener could not be cleared');\n }\n }\n}\n", "/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IRenderDimensions, IRenderer } from 'browser/renderer/shared/Types';\nimport { IColorSet, ILink, ReadonlyColorSet } from 'browser/Types';\nimport { ISelectionRedrawRequestEvent as ISelectionRequestRedrawEvent, ISelectionRequestScrollLinesEvent } from 'browser/selection/Types';\nimport { createDecorator } from 'common/services/ServiceRegistry';\nimport { AllColorIndex, IDisposable } from 'common/Types';\nimport type { Event } from 'vs/base/common/event';\n\nexport const ICharSizeService = createDecorator('CharSizeService');\nexport interface ICharSizeService {\n serviceBrand: undefined;\n\n readonly width: number;\n readonly height: number;\n readonly hasValidSize: boolean;\n\n readonly onCharSizeChange: Event;\n\n measure(): void;\n}\n\nexport const ICoreBrowserService = createDecorator('CoreBrowserService');\nexport interface ICoreBrowserService {\n serviceBrand: undefined;\n\n readonly isFocused: boolean;\n\n readonly onDprChange: Event;\n readonly onWindowChange: Event;\n\n /**\n * Gets or sets the parent window that the terminal is rendered into. DOM and rendering APIs (e.g.\n * requestAnimationFrame) should be invoked in the context of this window. This should be set when\n * the window hosting the xterm.js instance changes.\n */\n window: Window & typeof globalThis;\n /**\n * The document of the primary window to be used to create elements when working with multiple\n * windows. This is defined by the documentOverride setting.\n */\n readonly mainDocument: Document;\n /**\n * Helper for getting the devicePixelRatio of the parent window.\n */\n readonly dpr: number;\n}\n\nexport const IMouseService = createDecorator('MouseService');\nexport interface IMouseService {\n serviceBrand: undefined;\n\n getCoords(event: {clientX: number, clientY: number}, element: HTMLElement, colCount: number, rowCount: number, isSelection?: boolean): [number, number] | undefined;\n getMouseReportCoords(event: MouseEvent, element: HTMLElement): { col: number, row: number, x: number, y: number } | undefined;\n}\n\nexport const IRenderService = createDecorator('RenderService');\nexport interface IRenderService extends IDisposable {\n serviceBrand: undefined;\n\n onDimensionsChange: Event;\n /**\n * Fires when buffer changes are rendered. This does not fire when only cursor\n * or selections are rendered.\n */\n onRenderedViewportChange: Event<{ start: number, end: number }>;\n /**\n * Fires on render\n */\n onRender: Event<{ start: number, end: number }>;\n onRefreshRequest: Event<{ start: number, end: number }>;\n\n dimensions: IRenderDimensions;\n\n addRefreshCallback(callback: FrameRequestCallback): number;\n\n refreshRows(start: number, end: number): void;\n clearTextureAtlas(): void;\n resize(cols: number, rows: number): void;\n hasRenderer(): boolean;\n setRenderer(renderer: IRenderer): void;\n handleDevicePixelRatioChange(): void;\n handleResize(cols: number, rows: number): void;\n handleCharSizeChanged(): void;\n handleBlur(): void;\n handleFocus(): void;\n handleSelectionChanged(start: [number, number] | undefined, end: [number, number] | undefined, columnSelectMode: boolean): void;\n handleCursorMove(): void;\n clear(): void;\n}\n\nexport const ISelectionService = createDecorator('SelectionService');\nexport interface ISelectionService {\n serviceBrand: undefined;\n\n readonly selectionText: string;\n readonly hasSelection: boolean;\n readonly selectionStart: [number, number] | undefined;\n readonly selectionEnd: [number, number] | undefined;\n\n readonly onLinuxMouseSelection: Event;\n readonly onRequestRedraw: Event;\n readonly onRequestScrollLines: Event;\n readonly onSelectionChange: Event;\n\n disable(): void;\n enable(): void;\n reset(): void;\n setSelection(row: number, col: number, length: number): void;\n selectAll(): void;\n selectLines(start: number, end: number): void;\n clearSelection(): void;\n rightClickSelect(event: MouseEvent): void;\n shouldColumnSelect(event: KeyboardEvent | MouseEvent): boolean;\n shouldForceSelection(event: MouseEvent): boolean;\n refresh(isLinuxMouseSelection?: boolean): void;\n handleMouseDown(event: MouseEvent): void;\n isCellInSelection(x: number, y: number): boolean;\n}\n\nexport const ICharacterJoinerService = createDecorator('CharacterJoinerService');\nexport interface ICharacterJoinerService {\n serviceBrand: undefined;\n\n register(handler: (text: string) => [number, number][]): number;\n deregister(joinerId: number): boolean;\n getJoinedCharacters(row: number): [number, number][];\n}\n\nexport const IThemeService = createDecorator('ThemeService');\nexport interface IThemeService {\n serviceBrand: undefined;\n\n readonly colors: ReadonlyColorSet;\n\n readonly onChangeColors: Event;\n\n restoreColor(slot?: AllColorIndex): void;\n /**\n * Allows external modifying of colors in the theme, this is used instead of {@link colors} to\n * prevent accidental writes.\n */\n modifyColors(callback: (colors: IColorSet) => void): void;\n}\n\n\nexport const ILinkProviderService = createDecorator('LinkProviderService');\nexport interface ILinkProviderService extends IDisposable {\n serviceBrand: undefined;\n readonly linkProviders: ReadonlyArray;\n registerLinkProvider(linkProvider: ILinkProvider): IDisposable;\n}\nexport interface ILinkProvider {\n provideLinks(y: number, callback: (links: ILink[] | undefined) => void): void;\n}\n", "/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\nexport interface ErrorListenerCallback {\n\t(error: any): void;\n}\n\nexport interface ErrorListenerUnbind {\n\t(): void;\n}\n\n// Avoid circular dependency on EventEmitter by implementing a subset of the interface.\nexport class ErrorHandler {\n\tprivate unexpectedErrorHandler: (e: any) => void;\n\tprivate listeners: ErrorListenerCallback[];\n\n\tconstructor() {\n\n\t\tthis.listeners = [];\n\n\t\tthis.unexpectedErrorHandler = function (e: any) {\n\t\t\tsetTimeout(() => {\n\t\t\t\tif (e.stack) {\n\t\t\t\t\tif (ErrorNoTelemetry.isErrorNoTelemetry(e)) {\n\t\t\t\t\t\tthrow new ErrorNoTelemetry(e.message + '\\n\\n' + e.stack);\n\t\t\t\t\t}\n\n\t\t\t\t\tthrow new Error(e.message + '\\n\\n' + e.stack);\n\t\t\t\t}\n\n\t\t\t\tthrow e;\n\t\t\t}, 0);\n\t\t};\n\t}\n\n\taddListener(listener: ErrorListenerCallback): ErrorListenerUnbind {\n\t\tthis.listeners.push(listener);\n\n\t\treturn () => {\n\t\t\tthis._removeListener(listener);\n\t\t};\n\t}\n\n\tprivate emit(e: any): void {\n\t\tthis.listeners.forEach((listener) => {\n\t\t\tlistener(e);\n\t\t});\n\t}\n\n\tprivate _removeListener(listener: ErrorListenerCallback): void {\n\t\tthis.listeners.splice(this.listeners.indexOf(listener), 1);\n\t}\n\n\tsetUnexpectedErrorHandler(newUnexpectedErrorHandler: (e: any) => void): void {\n\t\tthis.unexpectedErrorHandler = newUnexpectedErrorHandler;\n\t}\n\n\tgetUnexpectedErrorHandler(): (e: any) => void {\n\t\treturn this.unexpectedErrorHandler;\n\t}\n\n\tonUnexpectedError(e: any): void {\n\t\tthis.unexpectedErrorHandler(e);\n\t\tthis.emit(e);\n\t}\n\n\t// For external errors, we don't want the listeners to be called\n\tonUnexpectedExternalError(e: any): void {\n\t\tthis.unexpectedErrorHandler(e);\n\t}\n}\n\nexport const errorHandler = new ErrorHandler();\n\n/** @skipMangle */\nexport function setUnexpectedErrorHandler(newUnexpectedErrorHandler: (e: any) => void): void {\n\terrorHandler.setUnexpectedErrorHandler(newUnexpectedErrorHandler);\n}\n\n/**\n * Returns if the error is a SIGPIPE error. SIGPIPE errors should generally be\n * logged at most once, to avoid a loop.\n *\n * @see https://github.com/microsoft/vscode-remote-release/issues/6481\n */\nexport function isSigPipeError(e: unknown): e is Error {\n\tif (!e || typeof e !== 'object') {\n\t\treturn false;\n\t}\n\n\tconst cast = e as Record;\n\treturn cast.code === 'EPIPE' && cast.syscall?.toUpperCase() === 'WRITE';\n}\n\nexport function onUnexpectedError(e: any): undefined {\n\t// ignore errors from cancelled promises\n\tif (!isCancellationError(e)) {\n\t\terrorHandler.onUnexpectedError(e);\n\t}\n\treturn undefined;\n}\n\nexport function onUnexpectedExternalError(e: any): undefined {\n\t// ignore errors from cancelled promises\n\tif (!isCancellationError(e)) {\n\t\terrorHandler.onUnexpectedExternalError(e);\n\t}\n\treturn undefined;\n}\n\nexport interface SerializedError {\n\treadonly $isError: true;\n\treadonly name: string;\n\treadonly message: string;\n\treadonly stack: string;\n\treadonly noTelemetry: boolean;\n}\n\nexport function transformErrorForSerialization(error: Error): SerializedError;\nexport function transformErrorForSerialization(error: any): any;\nexport function transformErrorForSerialization(error: any): any {\n\tif (error instanceof Error) {\n\t\tconst { name, message } = error;\n\t\tconst stack: string = (error).stacktrace || (error).stack;\n\t\treturn {\n\t\t\t$isError: true,\n\t\t\tname,\n\t\t\tmessage,\n\t\t\tstack,\n\t\t\tnoTelemetry: ErrorNoTelemetry.isErrorNoTelemetry(error)\n\t\t};\n\t}\n\n\t// return as is\n\treturn error;\n}\n\nexport function transformErrorFromSerialization(data: SerializedError): Error {\n\tlet error: Error;\n\tif (data.noTelemetry) {\n\t\terror = new ErrorNoTelemetry();\n\t} else {\n\t\terror = new Error();\n\t\terror.name = data.name;\n\t}\n\terror.message = data.message;\n\terror.stack = data.stack;\n\treturn error;\n}\n\n// see https://github.com/v8/v8/wiki/Stack%20Trace%20API#basic-stack-traces\nexport interface V8CallSite {\n\tgetThis(): unknown;\n\tgetTypeName(): string | null;\n\tgetFunction(): Function | undefined;\n\tgetFunctionName(): string | null;\n\tgetMethodName(): string | null;\n\tgetFileName(): string | null;\n\tgetLineNumber(): number | null;\n\tgetColumnNumber(): number | null;\n\tgetEvalOrigin(): string | undefined;\n\tisToplevel(): boolean;\n\tisEval(): boolean;\n\tisNative(): boolean;\n\tisConstructor(): boolean;\n\ttoString(): string;\n}\n\nconst canceledName = 'Canceled';\n\n/**\n * Checks if the given error is a promise in canceled state\n */\nexport function isCancellationError(error: any): boolean {\n\tif (error instanceof CancellationError) {\n\t\treturn true;\n\t}\n\treturn error instanceof Error && error.name === canceledName && error.message === canceledName;\n}\n\n// !!!IMPORTANT!!!\n// Do NOT change this class because it is also used as an API-type.\nexport class CancellationError extends Error {\n\tconstructor() {\n\t\tsuper(canceledName);\n\t\tthis.name = this.message;\n\t}\n}\n\n/**\n * @deprecated use {@link CancellationError `new CancellationError()`} instead\n */\nexport function canceled(): Error {\n\tconst error = new Error(canceledName);\n\terror.name = error.message;\n\treturn error;\n}\n\nexport function illegalArgument(name?: string): Error {\n\tif (name) {\n\t\treturn new Error(`Illegal argument: ${name}`);\n\t} else {\n\t\treturn new Error('Illegal argument');\n\t}\n}\n\nexport function illegalState(name?: string): Error {\n\tif (name) {\n\t\treturn new Error(`Illegal state: ${name}`);\n\t} else {\n\t\treturn new Error('Illegal state');\n\t}\n}\n\nexport class ReadonlyError extends TypeError {\n\tconstructor(name?: string) {\n\t\tsuper(name ? `${name} is read-only and cannot be changed` : 'Cannot change read-only property');\n\t}\n}\n\nexport function getErrorMessage(err: any): string {\n\tif (!err) {\n\t\treturn 'Error';\n\t}\n\n\tif (err.message) {\n\t\treturn err.message;\n\t}\n\n\tif (err.stack) {\n\t\treturn err.stack.split('\\n')[0];\n\t}\n\n\treturn String(err);\n}\n\nexport class NotImplementedError extends Error {\n\tconstructor(message?: string) {\n\t\tsuper('NotImplemented');\n\t\tif (message) {\n\t\t\tthis.message = message;\n\t\t}\n\t}\n}\n\nexport class NotSupportedError extends Error {\n\tconstructor(message?: string) {\n\t\tsuper('NotSupported');\n\t\tif (message) {\n\t\t\tthis.message = message;\n\t\t}\n\t}\n}\n\nexport class ExpectedError extends Error {\n\treadonly isExpected = true;\n}\n\n/**\n * Error that when thrown won't be logged in telemetry as an unhandled error.\n */\nexport class ErrorNoTelemetry extends Error {\n\toverride readonly name: string;\n\n\tconstructor(msg?: string) {\n\t\tsuper(msg);\n\t\tthis.name = 'CodeExpectedError';\n\t}\n\n\tpublic static fromError(err: Error): ErrorNoTelemetry {\n\t\tif (err instanceof ErrorNoTelemetry) {\n\t\t\treturn err;\n\t\t}\n\n\t\tconst result = new ErrorNoTelemetry();\n\t\tresult.message = err.message;\n\t\tresult.stack = err.stack;\n\t\treturn result;\n\t}\n\n\tpublic static isErrorNoTelemetry(err: Error): err is ErrorNoTelemetry {\n\t\treturn err.name === 'CodeExpectedError';\n\t}\n}\n\n/**\n * This error indicates a bug.\n * Do not throw this for invalid user input.\n * Only catch this error to recover gracefully from bugs.\n */\nexport class BugIndicatingError extends Error {\n\tconstructor(message?: string) {\n\t\tsuper(message || 'An unexpected bug occurred.');\n\t\tObject.setPrototypeOf(this, BugIndicatingError.prototype);\n\n\t\t// Because we know for sure only buggy code throws this,\n\t\t// we definitely want to break here and fix the bug.\n\t\t// eslint-disable-next-line no-debugger\n\t\t// debugger;\n\t}\n}\n", "/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\nimport { Comparator } from './arrays';\n\nexport function findLast(array: readonly T[], predicate: (item: T) => boolean): T | undefined {\n\tconst idx = findLastIdx(array, predicate);\n\tif (idx === -1) {\n\t\treturn undefined;\n\t}\n\treturn array[idx];\n}\n\nexport function findLastIdx(array: readonly T[], predicate: (item: T) => boolean, fromIndex = array.length - 1): number {\n\tfor (let i = fromIndex; i >= 0; i--) {\n\t\tconst element = array[i];\n\n\t\tif (predicate(element)) {\n\t\t\treturn i;\n\t\t}\n\t}\n\n\treturn -1;\n}\n\n/**\n * Finds the last item where predicate is true using binary search.\n * `predicate` must be monotonous, i.e. `arr.map(predicate)` must be like `[true, ..., true, false, ..., false]`!\n *\n * @returns `undefined` if no item matches, otherwise the last item that matches the predicate.\n */\nexport function findLastMonotonous(array: readonly T[], predicate: (item: T) => boolean): T | undefined {\n\tconst idx = findLastIdxMonotonous(array, predicate);\n\treturn idx === -1 ? undefined : array[idx];\n}\n\n/**\n * Finds the last item where predicate is true using binary search.\n * `predicate` must be monotonous, i.e. `arr.map(predicate)` must be like `[true, ..., true, false, ..., false]`!\n *\n * @returns `startIdx - 1` if predicate is false for all items, otherwise the index of the last item that matches the predicate.\n */\nexport function findLastIdxMonotonous(array: readonly T[], predicate: (item: T) => boolean, startIdx = 0, endIdxEx = array.length): number {\n\tlet i = startIdx;\n\tlet j = endIdxEx;\n\twhile (i < j) {\n\t\tconst k = Math.floor((i + j) / 2);\n\t\tif (predicate(array[k])) {\n\t\t\ti = k + 1;\n\t\t} else {\n\t\t\tj = k;\n\t\t}\n\t}\n\treturn i - 1;\n}\n\n/**\n * Finds the first item where predicate is true using binary search.\n * `predicate` must be monotonous, i.e. `arr.map(predicate)` must be like `[false, ..., false, true, ..., true]`!\n *\n * @returns `undefined` if no item matches, otherwise the first item that matches the predicate.\n */\nexport function findFirstMonotonous(array: readonly T[], predicate: (item: T) => boolean): T | undefined {\n\tconst idx = findFirstIdxMonotonousOrArrLen(array, predicate);\n\treturn idx === array.length ? undefined : array[idx];\n}\n\n/**\n * Finds the first item where predicate is true using binary search.\n * `predicate` must be monotonous, i.e. `arr.map(predicate)` must be like `[false, ..., false, true, ..., true]`!\n *\n * @returns `endIdxEx` if predicate is false for all items, otherwise the index of the first item that matches the predicate.\n */\nexport function findFirstIdxMonotonousOrArrLen(array: readonly T[], predicate: (item: T) => boolean, startIdx = 0, endIdxEx = array.length): number {\n\tlet i = startIdx;\n\tlet j = endIdxEx;\n\twhile (i < j) {\n\t\tconst k = Math.floor((i + j) / 2);\n\t\tif (predicate(array[k])) {\n\t\t\tj = k;\n\t\t} else {\n\t\t\ti = k + 1;\n\t\t}\n\t}\n\treturn i;\n}\n\nexport function findFirstIdxMonotonous(array: readonly T[], predicate: (item: T) => boolean, startIdx = 0, endIdxEx = array.length): number {\n\tconst idx = findFirstIdxMonotonousOrArrLen(array, predicate, startIdx, endIdxEx);\n\treturn idx === array.length ? -1 : idx;\n}\n\n/**\n * Use this when\n * * You have a sorted array\n * * You query this array with a monotonous predicate to find the last item that has a certain property.\n * * You query this array multiple times with monotonous predicates that get weaker and weaker.\n */\nexport class MonotonousArray {\n\tpublic static assertInvariants = false;\n\n\tprivate _findLastMonotonousLastIdx = 0;\n\tprivate _prevFindLastPredicate: ((item: T) => boolean) | undefined;\n\n\tconstructor(private readonly _array: readonly T[]) {\n\t}\n\n\t/**\n\t * The predicate must be monotonous, i.e. `arr.map(predicate)` must be like `[true, ..., true, false, ..., false]`!\n\t * For subsequent calls, current predicate must be weaker than (or equal to) the previous predicate, i.e. more entries must be `true`.\n\t */\n\tfindLastMonotonous(predicate: (item: T) => boolean): T | undefined {\n\t\tif (MonotonousArray.assertInvariants) {\n\t\t\tif (this._prevFindLastPredicate) {\n\t\t\t\tfor (const item of this._array) {\n\t\t\t\t\tif (this._prevFindLastPredicate(item) && !predicate(item)) {\n\t\t\t\t\t\tthrow new Error('MonotonousArray: current predicate must be weaker than (or equal to) the previous predicate.');\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis._prevFindLastPredicate = predicate;\n\t\t}\n\n\t\tconst idx = findLastIdxMonotonous(this._array, predicate, this._findLastMonotonousLastIdx);\n\t\tthis._findLastMonotonousLastIdx = idx + 1;\n\t\treturn idx === -1 ? undefined : this._array[idx];\n\t}\n}\n\n/**\n * Returns the first item that is equal to or greater than every other item.\n*/\nexport function findFirstMax(array: readonly T[], comparator: Comparator): T | undefined {\n\tif (array.length === 0) {\n\t\treturn undefined;\n\t}\n\n\tlet max = array[0];\n\tfor (let i = 1; i < array.length; i++) {\n\t\tconst item = array[i];\n\t\tif (comparator(item, max) > 0) {\n\t\t\tmax = item;\n\t\t}\n\t}\n\treturn max;\n}\n\n/**\n * Returns the last item that is equal to or greater than every other item.\n*/\nexport function findLastMax(array: readonly T[], comparator: Comparator): T | undefined {\n\tif (array.length === 0) {\n\t\treturn undefined;\n\t}\n\n\tlet max = array[0];\n\tfor (let i = 1; i < array.length; i++) {\n\t\tconst item = array[i];\n\t\tif (comparator(item, max) >= 0) {\n\t\t\tmax = item;\n\t\t}\n\t}\n\treturn max;\n}\n\n/**\n * Returns the first item that is equal to or less than every other item.\n*/\nexport function findFirstMin(array: readonly T[], comparator: Comparator): T | undefined {\n\treturn findFirstMax(array, (a, b) => -comparator(a, b));\n}\n\nexport function findMaxIdx(array: readonly T[], comparator: Comparator): number {\n\tif (array.length === 0) {\n\t\treturn -1;\n\t}\n\n\tlet maxIdx = 0;\n\tfor (let i = 1; i < array.length; i++) {\n\t\tconst item = array[i];\n\t\tif (comparator(item, array[maxIdx]) > 0) {\n\t\t\tmaxIdx = i;\n\t\t}\n\t}\n\treturn maxIdx;\n}\n\n/**\n * Returns the first mapped value of the array which is not undefined.\n */\nexport function mapFindFirst(items: Iterable, mapFn: (value: T) => R | undefined): R | undefined {\n\tfor (const value of items) {\n\t\tconst mapped = mapFn(value);\n\t\tif (mapped !== undefined) {\n\t\t\treturn mapped;\n\t\t}\n\t}\n\n\treturn undefined;\n}\n", "/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\nimport { CancellationToken } from 'vs/base/common/cancellation';\nimport { CancellationError } from 'vs/base/common/errors';\nimport { ISplice } from 'vs/base/common/sequence';\nimport { findFirstIdxMonotonousOrArrLen } from './arraysFind';\n\n/**\n * Returns the last element of an array.\n * @param array The array.\n * @param n Which element from the end (default is zero).\n */\nexport function tail(array: ArrayLike, n: number = 0): T | undefined {\n\treturn array[array.length - (1 + n)];\n}\n\nexport function tail2(arr: T[]): [T[], T] {\n\tif (arr.length === 0) {\n\t\tthrow new Error('Invalid tail call');\n\t}\n\n\treturn [arr.slice(0, arr.length - 1), arr[arr.length - 1]];\n}\n\nexport function equals(one: ReadonlyArray | undefined, other: ReadonlyArray | undefined, itemEquals: (a: T, b: T) => boolean = (a, b) => a === b): boolean {\n\tif (one === other) {\n\t\treturn true;\n\t}\n\n\tif (!one || !other) {\n\t\treturn false;\n\t}\n\n\tif (one.length !== other.length) {\n\t\treturn false;\n\t}\n\n\tfor (let i = 0, len = one.length; i < len; i++) {\n\t\tif (!itemEquals(one[i], other[i])) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn true;\n}\n\n/**\n * Remove the element at `index` by replacing it with the last element. This is faster than `splice`\n * but changes the order of the array\n */\nexport function removeFastWithoutKeepingOrder(array: T[], index: number) {\n\tconst last = array.length - 1;\n\tif (index < last) {\n\t\tarray[index] = array[last];\n\t}\n\tarray.pop();\n}\n\n/**\n * Performs a binary search algorithm over a sorted array.\n *\n * @param array The array being searched.\n * @param key The value we search for.\n * @param comparator A function that takes two array elements and returns zero\n * if they are equal, a negative number if the first element precedes the\n * second one in the sorting order, or a positive number if the second element\n * precedes the first one.\n * @return See {@link binarySearch2}\n */\nexport function binarySearch(array: ReadonlyArray, key: T, comparator: (op1: T, op2: T) => number): number {\n\treturn binarySearch2(array.length, i => comparator(array[i], key));\n}\n\n/**\n * Performs a binary search algorithm over a sorted collection. Useful for cases\n * when we need to perform a binary search over something that isn't actually an\n * array, and converting data to an array would defeat the use of binary search\n * in the first place.\n *\n * @param length The collection length.\n * @param compareToKey A function that takes an index of an element in the\n * collection and returns zero if the value at this index is equal to the\n * search key, a negative number if the value precedes the search key in the\n * sorting order, or a positive number if the search key precedes the value.\n * @return A non-negative index of an element, if found. If not found, the\n * result is -(n+1) (or ~n, using bitwise notation), where n is the index\n * where the key should be inserted to maintain the sorting order.\n */\nexport function binarySearch2(length: number, compareToKey: (index: number) => number): number {\n\tlet low = 0,\n\t\thigh = length - 1;\n\n\twhile (low <= high) {\n\t\tconst mid = ((low + high) / 2) | 0;\n\t\tconst comp = compareToKey(mid);\n\t\tif (comp < 0) {\n\t\t\tlow = mid + 1;\n\t\t} else if (comp > 0) {\n\t\t\thigh = mid - 1;\n\t\t} else {\n\t\t\treturn mid;\n\t\t}\n\t}\n\treturn -(low + 1);\n}\n\ntype Compare = (a: T, b: T) => number;\n\n\nexport function quickSelect(nth: number, data: T[], compare: Compare): T {\n\n\tnth = nth | 0;\n\n\tif (nth >= data.length) {\n\t\tthrow new TypeError('invalid index');\n\t}\n\n\tconst pivotValue = data[Math.floor(data.length * Math.random())];\n\tconst lower: T[] = [];\n\tconst higher: T[] = [];\n\tconst pivots: T[] = [];\n\n\tfor (const value of data) {\n\t\tconst val = compare(value, pivotValue);\n\t\tif (val < 0) {\n\t\t\tlower.push(value);\n\t\t} else if (val > 0) {\n\t\t\thigher.push(value);\n\t\t} else {\n\t\t\tpivots.push(value);\n\t\t}\n\t}\n\n\tif (nth < lower.length) {\n\t\treturn quickSelect(nth, lower, compare);\n\t} else if (nth < lower.length + pivots.length) {\n\t\treturn pivots[0];\n\t} else {\n\t\treturn quickSelect(nth - (lower.length + pivots.length), higher, compare);\n\t}\n}\n\nexport function groupBy(data: ReadonlyArray, compare: (a: T, b: T) => number): T[][] {\n\tconst result: T[][] = [];\n\tlet currentGroup: T[] | undefined = undefined;\n\tfor (const element of data.slice(0).sort(compare)) {\n\t\tif (!currentGroup || compare(currentGroup[0], element) !== 0) {\n\t\t\tcurrentGroup = [element];\n\t\t\tresult.push(currentGroup);\n\t\t} else {\n\t\t\tcurrentGroup.push(element);\n\t\t}\n\t}\n\treturn result;\n}\n\n/**\n * Splits the given items into a list of (non-empty) groups.\n * `shouldBeGrouped` is used to decide if two consecutive items should be in the same group.\n * The order of the items is preserved.\n */\nexport function* groupAdjacentBy(items: Iterable, shouldBeGrouped: (item1: T, item2: T) => boolean): Iterable {\n\tlet currentGroup: T[] | undefined;\n\tlet last: T | undefined;\n\tfor (const item of items) {\n\t\tif (last !== undefined && shouldBeGrouped(last, item)) {\n\t\t\tcurrentGroup!.push(item);\n\t\t} else {\n\t\t\tif (currentGroup) {\n\t\t\t\tyield currentGroup;\n\t\t\t}\n\t\t\tcurrentGroup = [item];\n\t\t}\n\t\tlast = item;\n\t}\n\tif (currentGroup) {\n\t\tyield currentGroup;\n\t}\n}\n\nexport function forEachAdjacent(arr: T[], f: (item1: T | undefined, item2: T | undefined) => void): void {\n\tfor (let i = 0; i <= arr.length; i++) {\n\t\tf(i === 0 ? undefined : arr[i - 1], i === arr.length ? undefined : arr[i]);\n\t}\n}\n\nexport function forEachWithNeighbors(arr: T[], f: (before: T | undefined, element: T, after: T | undefined) => void): void {\n\tfor (let i = 0; i < arr.length; i++) {\n\t\tf(i === 0 ? undefined : arr[i - 1], arr[i], i + 1 === arr.length ? undefined : arr[i + 1]);\n\t}\n}\n\ninterface IMutableSplice extends ISplice {\n\treadonly toInsert: T[];\n\tdeleteCount: number;\n}\n\n/**\n * Diffs two *sorted* arrays and computes the splices which apply the diff.\n */\nexport function sortedDiff(before: ReadonlyArray, after: ReadonlyArray, compare: (a: T, b: T) => number): ISplice[] {\n\tconst result: IMutableSplice[] = [];\n\n\tfunction pushSplice(start: number, deleteCount: number, toInsert: T[]): void {\n\t\tif (deleteCount === 0 && toInsert.length === 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst latest = result[result.length - 1];\n\n\t\tif (latest && latest.start + latest.deleteCount === start) {\n\t\t\tlatest.deleteCount += deleteCount;\n\t\t\tlatest.toInsert.push(...toInsert);\n\t\t} else {\n\t\t\tresult.push({ start, deleteCount, toInsert });\n\t\t}\n\t}\n\n\tlet beforeIdx = 0;\n\tlet afterIdx = 0;\n\n\twhile (true) {\n\t\tif (beforeIdx === before.length) {\n\t\t\tpushSplice(beforeIdx, 0, after.slice(afterIdx));\n\t\t\tbreak;\n\t\t}\n\t\tif (afterIdx === after.length) {\n\t\t\tpushSplice(beforeIdx, before.length - beforeIdx, []);\n\t\t\tbreak;\n\t\t}\n\n\t\tconst beforeElement = before[beforeIdx];\n\t\tconst afterElement = after[afterIdx];\n\t\tconst n = compare(beforeElement, afterElement);\n\t\tif (n === 0) {\n\t\t\t// equal\n\t\t\tbeforeIdx += 1;\n\t\t\tafterIdx += 1;\n\t\t} else if (n < 0) {\n\t\t\t// beforeElement is smaller -> before element removed\n\t\t\tpushSplice(beforeIdx, 1, []);\n\t\t\tbeforeIdx += 1;\n\t\t} else if (n > 0) {\n\t\t\t// beforeElement is greater -> after element added\n\t\t\tpushSplice(beforeIdx, 0, [afterElement]);\n\t\t\tafterIdx += 1;\n\t\t}\n\t}\n\n\treturn result;\n}\n\n/**\n * Takes two *sorted* arrays and computes their delta (removed, added elements).\n * Finishes in `Math.min(before.length, after.length)` steps.\n */\nexport function delta(before: ReadonlyArray, after: ReadonlyArray, compare: (a: T, b: T) => number): { removed: T[]; added: T[] } {\n\tconst splices = sortedDiff(before, after, compare);\n\tconst removed: T[] = [];\n\tconst added: T[] = [];\n\n\tfor (const splice of splices) {\n\t\tremoved.push(...before.slice(splice.start, splice.start + splice.deleteCount));\n\t\tadded.push(...splice.toInsert);\n\t}\n\n\treturn { removed, added };\n}\n\n/**\n * Returns the top N elements from the array.\n *\n * Faster than sorting the entire array when the array is a lot larger than N.\n *\n * @param array The unsorted array.\n * @param compare A sort function for the elements.\n * @param n The number of elements to return.\n * @return The first n elements from array when sorted with compare.\n */\nexport function top(array: ReadonlyArray, compare: (a: T, b: T) => number, n: number): T[] {\n\tif (n === 0) {\n\t\treturn [];\n\t}\n\tconst result = array.slice(0, n).sort(compare);\n\ttopStep(array, compare, result, n, array.length);\n\treturn result;\n}\n\n/**\n * Asynchronous variant of `top()` allowing for splitting up work in batches between which the event loop can run.\n *\n * Returns the top N elements from the array.\n *\n * Faster than sorting the entire array when the array is a lot larger than N.\n *\n * @param array The unsorted array.\n * @param compare A sort function for the elements.\n * @param n The number of elements to return.\n * @param batch The number of elements to examine before yielding to the event loop.\n * @return The first n elements from array when sorted with compare.\n */\nexport function topAsync(array: T[], compare: (a: T, b: T) => number, n: number, batch: number, token?: CancellationToken): Promise {\n\tif (n === 0) {\n\t\treturn Promise.resolve([]);\n\t}\n\n\treturn new Promise((resolve, reject) => {\n\t\t(async () => {\n\t\t\tconst o = array.length;\n\t\t\tconst result = array.slice(0, n).sort(compare);\n\t\t\tfor (let i = n, m = Math.min(n + batch, o); i < o; i = m, m = Math.min(m + batch, o)) {\n\t\t\t\tif (i > n) {\n\t\t\t\t\tawait new Promise(resolve => setTimeout(resolve)); // any other delay function would starve I/O\n\t\t\t\t}\n\t\t\t\tif (token && token.isCancellationRequested) {\n\t\t\t\t\tthrow new CancellationError();\n\t\t\t\t}\n\t\t\t\ttopStep(array, compare, result, i, m);\n\t\t\t}\n\t\t\treturn result;\n\t\t})()\n\t\t\t.then(resolve, reject);\n\t});\n}\n\nfunction topStep(array: ReadonlyArray, compare: (a: T, b: T) => number, result: T[], i: number, m: number): void {\n\tfor (const n = result.length; i < m; i++) {\n\t\tconst element = array[i];\n\t\tif (compare(element, result[n - 1]) < 0) {\n\t\t\tresult.pop();\n\t\t\tconst j = findFirstIdxMonotonousOrArrLen(result, e => compare(element, e) < 0);\n\t\t\tresult.splice(j, 0, element);\n\t\t}\n\t}\n}\n\n/**\n * @returns New array with all falsy values removed. The original array IS NOT modified.\n */\nexport function coalesce(array: ReadonlyArray): T[] {\n\treturn array.filter((e): e is T => !!e);\n}\n\n/**\n * Remove all falsy values from `array`. The original array IS modified.\n */\nexport function coalesceInPlace(array: Array): asserts array is Array {\n\tlet to = 0;\n\tfor (let i = 0; i < array.length; i++) {\n\t\tif (!!array[i]) {\n\t\t\tarray[to] = array[i];\n\t\t\tto += 1;\n\t\t}\n\t}\n\tarray.length = to;\n}\n\n/**\n * @deprecated Use `Array.copyWithin` instead\n */\nexport function move(array: any[], from: number, to: number): void {\n\tarray.splice(to, 0, array.splice(from, 1)[0]);\n}\n\n/**\n * @returns false if the provided object is an array and not empty.\n */\nexport function isFalsyOrEmpty(obj: any): boolean {\n\treturn !Array.isArray(obj) || obj.length === 0;\n}\n\n/**\n * @returns True if the provided object is an array and has at least one element.\n */\nexport function isNonEmptyArray(obj: T[] | undefined | null): obj is T[];\nexport function isNonEmptyArray(obj: readonly T[] | undefined | null): obj is readonly T[];\nexport function isNonEmptyArray(obj: T[] | readonly T[] | undefined | null): obj is T[] | readonly T[] {\n\treturn Array.isArray(obj) && obj.length > 0;\n}\n\n/**\n * Removes duplicates from the given array. The optional keyFn allows to specify\n * how elements are checked for equality by returning an alternate value for each.\n */\nexport function distinct(array: ReadonlyArray, keyFn: (value: T) => any = value => value): T[] {\n\tconst seen = new Set();\n\n\treturn array.filter(element => {\n\t\tconst key = keyFn!(element);\n\t\tif (seen.has(key)) {\n\t\t\treturn false;\n\t\t}\n\t\tseen.add(key);\n\t\treturn true;\n\t});\n}\n\nexport function uniqueFilter(keyFn: (t: T) => R): (t: T) => boolean {\n\tconst seen = new Set();\n\n\treturn element => {\n\t\tconst key = keyFn(element);\n\n\t\tif (seen.has(key)) {\n\t\t\treturn false;\n\t\t}\n\n\t\tseen.add(key);\n\t\treturn true;\n\t};\n}\n\nexport function firstOrDefault(array: ReadonlyArray, notFoundValue: NotFound): T | NotFound;\nexport function firstOrDefault(array: ReadonlyArray): T | undefined;\nexport function firstOrDefault(array: ReadonlyArray, notFoundValue?: NotFound): T | NotFound | undefined {\n\treturn array.length > 0 ? array[0] : notFoundValue;\n}\n\nexport function lastOrDefault(array: ReadonlyArray, notFoundValue: NotFound): T | NotFound;\nexport function lastOrDefault(array: ReadonlyArray): T | undefined;\nexport function lastOrDefault(array: ReadonlyArray, notFoundValue?: NotFound): T | NotFound | undefined {\n\treturn array.length > 0 ? array[array.length - 1] : notFoundValue;\n}\n\nexport function commonPrefixLength(one: ReadonlyArray, other: ReadonlyArray, equals: (a: T, b: T) => boolean = (a, b) => a === b): number {\n\tlet result = 0;\n\n\tfor (let i = 0, len = Math.min(one.length, other.length); i < len && equals(one[i], other[i]); i++) {\n\t\tresult++;\n\t}\n\n\treturn result;\n}\n\nexport function range(to: number): number[];\nexport function range(from: number, to: number): number[];\nexport function range(arg: number, to?: number): number[] {\n\tlet from = typeof to === 'number' ? arg : 0;\n\n\tif (typeof to === 'number') {\n\t\tfrom = arg;\n\t} else {\n\t\tfrom = 0;\n\t\tto = arg;\n\t}\n\n\tconst result: number[] = [];\n\n\tif (from <= to) {\n\t\tfor (let i = from; i < to; i++) {\n\t\t\tresult.push(i);\n\t\t}\n\t} else {\n\t\tfor (let i = from; i > to; i--) {\n\t\t\tresult.push(i);\n\t\t}\n\t}\n\n\treturn result;\n}\n\nexport function index(array: ReadonlyArray, indexer: (t: T) => string): { [key: string]: T };\nexport function index(array: ReadonlyArray, indexer: (t: T) => string, mapper: (t: T) => R): { [key: string]: R };\nexport function index(array: ReadonlyArray, indexer: (t: T) => string, mapper?: (t: T) => R): { [key: string]: R } {\n\treturn array.reduce((r, t) => {\n\t\tr[indexer(t)] = mapper ? mapper(t) : t;\n\t\treturn r;\n\t}, Object.create(null));\n}\n\n/**\n * Inserts an element into an array. Returns a function which, when\n * called, will remove that element from the array.\n *\n * @deprecated In almost all cases, use a `Set` instead.\n */\nexport function insert(array: T[], element: T): () => void {\n\tarray.push(element);\n\n\treturn () => remove(array, element);\n}\n\n/**\n * Removes an element from an array if it can be found.\n *\n * @deprecated In almost all cases, use a `Set` instead.\n */\nexport function remove(array: T[], element: T): T | undefined {\n\tconst index = array.indexOf(element);\n\tif (index > -1) {\n\t\tarray.splice(index, 1);\n\n\t\treturn element;\n\t}\n\n\treturn undefined;\n}\n\n/**\n * Insert `insertArr` inside `target` at `insertIndex`.\n * Please don't touch unless you understand https://jsperf.com/inserting-an-array-within-an-array\n */\nexport function arrayInsert(target: T[], insertIndex: number, insertArr: T[]): T[] {\n\tconst before = target.slice(0, insertIndex);\n\tconst after = target.slice(insertIndex);\n\treturn before.concat(insertArr, after);\n}\n\n/**\n * Uses Fisher-Yates shuffle to shuffle the given array\n */\nexport function shuffle(array: T[], _seed?: number): void {\n\tlet rand: () => number;\n\n\tif (typeof _seed === 'number') {\n\t\tlet seed = _seed;\n\t\t// Seeded random number generator in JS. Modified from:\n\t\t// https://stackoverflow.com/questions/521295/seeding-the-random-number-generator-in-javascript\n\t\trand = () => {\n\t\t\tconst x = Math.sin(seed++) * 179426549; // throw away most significant digits and reduce any potential bias\n\t\t\treturn x - Math.floor(x);\n\t\t};\n\t} else {\n\t\trand = Math.random;\n\t}\n\n\tfor (let i = array.length - 1; i > 0; i -= 1) {\n\t\tconst j = Math.floor(rand() * (i + 1));\n\t\tconst temp = array[i];\n\t\tarray[i] = array[j];\n\t\tarray[j] = temp;\n\t}\n}\n\n/**\n * Pushes an element to the start of the array, if found.\n */\nexport function pushToStart(arr: T[], value: T): void {\n\tconst index = arr.indexOf(value);\n\n\tif (index > -1) {\n\t\tarr.splice(index, 1);\n\t\tarr.unshift(value);\n\t}\n}\n\n/**\n * Pushes an element to the end of the array, if found.\n */\nexport function pushToEnd(arr: T[], value: T): void {\n\tconst index = arr.indexOf(value);\n\n\tif (index > -1) {\n\t\tarr.splice(index, 1);\n\t\tarr.push(value);\n\t}\n}\n\nexport function pushMany(arr: T[], items: ReadonlyArray): void {\n\tfor (const item of items) {\n\t\tarr.push(item);\n\t}\n}\n\nexport function mapArrayOrNot(items: T | T[], fn: (_: T) => U): U | U[] {\n\treturn Array.isArray(items) ?\n\t\titems.map(fn) :\n\t\tfn(items);\n}\n\nexport function asArray(x: T | T[]): T[];\nexport function asArray(x: T | readonly T[]): readonly T[];\nexport function asArray(x: T | T[]): T[] {\n\treturn Array.isArray(x) ? x : [x];\n}\n\nexport function getRandomElement(arr: T[]): T | undefined {\n\treturn arr[Math.floor(Math.random() * arr.length)];\n}\n\n/**\n * Insert the new items in the array.\n * @param array The original array.\n * @param start The zero-based location in the array from which to start inserting elements.\n * @param newItems The items to be inserted\n */\nexport function insertInto(array: T[], start: number, newItems: T[]): void {\n\tconst startIdx = getActualStartIndex(array, start);\n\tconst originalLength = array.length;\n\tconst newItemsLength = newItems.length;\n\tarray.length = originalLength + newItemsLength;\n\t// Move the items after the start index, start from the end so that we don't overwrite any value.\n\tfor (let i = originalLength - 1; i >= startIdx; i--) {\n\t\tarray[i + newItemsLength] = array[i];\n\t}\n\n\tfor (let i = 0; i < newItemsLength; i++) {\n\t\tarray[i + startIdx] = newItems[i];\n\t}\n}\n\n/**\n * Removes elements from an array and inserts new elements in their place, returning the deleted elements. Alternative to the native Array.splice method, it\n * can only support limited number of items due to the maximum call stack size limit.\n * @param array The original array.\n * @param start The zero-based location in the array from which to start removing elements.\n * @param deleteCount The number of elements to remove.\n * @returns An array containing the elements that were deleted.\n */\nexport function splice(array: T[], start: number, deleteCount: number, newItems: T[]): T[] {\n\tconst index = getActualStartIndex(array, start);\n\tlet result = array.splice(index, deleteCount);\n\tif (result === undefined) {\n\t\t// see https://bugs.webkit.org/show_bug.cgi?id=261140\n\t\tresult = [];\n\t}\n\tinsertInto(array, index, newItems);\n\treturn result;\n}\n\n/**\n * Determine the actual start index (same logic as the native splice() or slice())\n * If greater than the length of the array, start will be set to the length of the array. In this case, no element will be deleted but the method will behave as an adding function, adding as many element as item[n*] provided.\n * If negative, it will begin that many elements from the end of the array. (In this case, the origin -1, meaning -n is the index of the nth last element, and is therefore equivalent to the index of array.length - n.) If array.length + start is less than 0, it will begin from index 0.\n * @param array The target array.\n * @param start The operation index.\n */\nfunction getActualStartIndex(array: T[], start: number): number {\n\treturn start < 0 ? Math.max(start + array.length, 0) : Math.min(start, array.length);\n}\n\n/**\n * When comparing two values,\n * a negative number indicates that the first value is less than the second,\n * a positive number indicates that the first value is greater than the second,\n * and zero indicates that neither is the case.\n*/\nexport type CompareResult = number;\n\nexport namespace CompareResult {\n\texport function isLessThan(result: CompareResult): boolean {\n\t\treturn result < 0;\n\t}\n\n\texport function isLessThanOrEqual(result: CompareResult): boolean {\n\t\treturn result <= 0;\n\t}\n\n\texport function isGreaterThan(result: CompareResult): boolean {\n\t\treturn result > 0;\n\t}\n\n\texport function isNeitherLessOrGreaterThan(result: CompareResult): boolean {\n\t\treturn result === 0;\n\t}\n\n\texport const greaterThan = 1;\n\texport const lessThan = -1;\n\texport const neitherLessOrGreaterThan = 0;\n}\n\n/**\n * A comparator `c` defines a total order `<=` on `T` as following:\n * `c(a, b) <= 0` iff `a` <= `b`.\n * We also have `c(a, b) == 0` iff `c(b, a) == 0`.\n*/\nexport type Comparator = (a: T, b: T) => CompareResult;\n\nexport function compareBy(selector: (item: TItem) => TCompareBy, comparator: Comparator): Comparator {\n\treturn (a, b) => comparator(selector(a), selector(b));\n}\n\nexport function tieBreakComparators(...comparators: Comparator[]): Comparator {\n\treturn (item1, item2) => {\n\t\tfor (const comparator of comparators) {\n\t\t\tconst result = comparator(item1, item2);\n\t\t\tif (!CompareResult.isNeitherLessOrGreaterThan(result)) {\n\t\t\t\treturn result;\n\t\t\t}\n\t\t}\n\t\treturn CompareResult.neitherLessOrGreaterThan;\n\t};\n}\n\n/**\n * The natural order on numbers.\n*/\nexport const numberComparator: Comparator = (a, b) => a - b;\n\nexport const booleanComparator: Comparator = (a, b) => numberComparator(a ? 1 : 0, b ? 1 : 0);\n\nexport function reverseOrder(comparator: Comparator): Comparator {\n\treturn (a, b) => -comparator(a, b);\n}\n\nexport class ArrayQueue {\n\tprivate firstIdx = 0;\n\tprivate lastIdx = this.items.length - 1;\n\n\t/**\n\t * Constructs a queue that is backed by the given array. Runtime is O(1).\n\t*/\n\tconstructor(private readonly items: readonly T[]) { }\n\n\tget length(): number {\n\t\treturn this.lastIdx - this.firstIdx + 1;\n\t}\n\n\t/**\n\t * Consumes elements from the beginning of the queue as long as the predicate returns true.\n\t * If no elements were consumed, `null` is returned. Has a runtime of O(result.length).\n\t*/\n\ttakeWhile(predicate: (value: T) => boolean): T[] | null {\n\t\t// P(k) := k <= this.lastIdx && predicate(this.items[k])\n\t\t// Find s := min { k | k >= this.firstIdx && !P(k) } and return this.data[this.firstIdx...s)\n\n\t\tlet startIdx = this.firstIdx;\n\t\twhile (startIdx < this.items.length && predicate(this.items[startIdx])) {\n\t\t\tstartIdx++;\n\t\t}\n\t\tconst result = startIdx === this.firstIdx ? null : this.items.slice(this.firstIdx, startIdx);\n\t\tthis.firstIdx = startIdx;\n\t\treturn result;\n\t}\n\n\t/**\n\t * Consumes elements from the end of the queue as long as the predicate returns true.\n\t * If no elements were consumed, `null` is returned.\n\t * The result has the same order as the underlying array!\n\t*/\n\ttakeFromEndWhile(predicate: (value: T) => boolean): T[] | null {\n\t\t// P(k) := this.firstIdx >= k && predicate(this.items[k])\n\t\t// Find s := max { k | k <= this.lastIdx && !P(k) } and return this.data(s...this.lastIdx]\n\n\t\tlet endIdx = this.lastIdx;\n\t\twhile (endIdx >= 0 && predicate(this.items[endIdx])) {\n\t\t\tendIdx--;\n\t\t}\n\t\tconst result = endIdx === this.lastIdx ? null : this.items.slice(endIdx + 1, this.lastIdx + 1);\n\t\tthis.lastIdx = endIdx;\n\t\treturn result;\n\t}\n\n\tpeek(): T | undefined {\n\t\tif (this.length === 0) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn this.items[this.firstIdx];\n\t}\n\n\tpeekLast(): T | undefined {\n\t\tif (this.length === 0) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn this.items[this.lastIdx];\n\t}\n\n\tdequeue(): T | undefined {\n\t\tconst result = this.items[this.firstIdx];\n\t\tthis.firstIdx++;\n\t\treturn result;\n\t}\n\n\tremoveLast(): T | undefined {\n\t\tconst result = this.items[this.lastIdx];\n\t\tthis.lastIdx--;\n\t\treturn result;\n\t}\n\n\ttakeCount(count: number): T[] {\n\t\tconst result = this.items.slice(this.firstIdx, this.firstIdx + count);\n\t\tthis.firstIdx += count;\n\t\treturn result;\n\t}\n}\n\n/**\n * This class is faster than an iterator and array for lazy computed data.\n*/\nexport class CallbackIterable {\n\tpublic static readonly empty = new CallbackIterable(_callback => { });\n\n\tconstructor(\n\t\t/**\n\t\t * Calls the callback for every item.\n\t\t * Stops when the callback returns false.\n\t\t*/\n\t\tpublic readonly iterate: (callback: (item: T) => boolean) => void\n\t) {\n\t}\n\n\tforEach(handler: (item: T) => void) {\n\t\tthis.iterate(item => { handler(item); return true; });\n\t}\n\n\ttoArray(): T[] {\n\t\tconst result: T[] = [];\n\t\tthis.iterate(item => { result.push(item); return true; });\n\t\treturn result;\n\t}\n\n\tfilter(predicate: (item: T) => boolean): CallbackIterable {\n\t\treturn new CallbackIterable(cb => this.iterate(item => predicate(item) ? cb(item) : true));\n\t}\n\n\tmap(mapFn: (item: T) => TResult): CallbackIterable {\n\t\treturn new CallbackIterable(cb => this.iterate(item => cb(mapFn(item))));\n\t}\n\n\tsome(predicate: (item: T) => boolean): boolean {\n\t\tlet result = false;\n\t\tthis.iterate(item => { result = predicate(item); return !result; });\n\t\treturn result;\n\t}\n\n\tfindFirst(predicate: (item: T) => boolean): T | undefined {\n\t\tlet result: T | undefined;\n\t\tthis.iterate(item => {\n\t\t\tif (predicate(item)) {\n\t\t\t\tresult = item;\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\treturn true;\n\t\t});\n\t\treturn result;\n\t}\n\n\tfindLast(predicate: (item: T) => boolean): T | undefined {\n\t\tlet result: T | undefined;\n\t\tthis.iterate(item => {\n\t\t\tif (predicate(item)) {\n\t\t\t\tresult = item;\n\t\t\t}\n\t\t\treturn true;\n\t\t});\n\t\treturn result;\n\t}\n\n\tfindLastMaxBy(comparator: Comparator): T | undefined {\n\t\tlet result: T | undefined;\n\t\tlet first = true;\n\t\tthis.iterate(item => {\n\t\t\tif (first || CompareResult.isGreaterThan(comparator(item, result!))) {\n\t\t\t\tfirst = false;\n\t\t\t\tresult = item;\n\t\t\t}\n\t\t\treturn true;\n\t\t});\n\t\treturn result;\n\t}\n}\n\n/**\n * Represents a re-arrangement of items in an array.\n */\nexport class Permutation {\n\tconstructor(private readonly _indexMap: readonly number[]) { }\n\n\t/**\n\t * Returns a permutation that sorts the given array according to the given compare function.\n\t */\n\tpublic static createSortPermutation(arr: readonly T[], compareFn: (a: T, b: T) => number): Permutation {\n\t\tconst sortIndices = Array.from(arr.keys()).sort((index1, index2) => compareFn(arr[index1], arr[index2]));\n\t\treturn new Permutation(sortIndices);\n\t}\n\n\t/**\n\t * Returns a new array with the elements of the given array re-arranged according to this permutation.\n\t */\n\tapply(arr: readonly T[]): T[] {\n\t\treturn arr.map((_, index) => arr[this._indexMap[index]]);\n\t}\n\n\t/**\n\t * Returns a new permutation that undoes the re-arrangement of this permutation.\n\t*/\n\tinverse(): Permutation {\n\t\tconst inverseIndexMap = this._indexMap.slice();\n\t\tfor (let i = 0; i < this._indexMap.length; i++) {\n\t\t\tinverseIndexMap[this._indexMap[i]] = i;\n\t\t}\n\t\treturn new Permutation(inverseIndexMap);\n\t}\n}\n", "/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n/**\n * An interface for a JavaScript object that\n * acts a dictionary. The keys are strings.\n */\nexport type IStringDictionary = Record;\n\n/**\n * An interface for a JavaScript object that\n * acts a dictionary. The keys are numbers.\n */\nexport type INumberDictionary = Record;\n\n/**\n * Groups the collection into a dictionary based on the provided\n * group function.\n */\nexport function groupBy(data: V[], groupFn: (element: V) => K): Record {\n\tconst result: Record = Object.create(null);\n\tfor (const element of data) {\n\t\tconst key = groupFn(element);\n\t\tlet target = result[key];\n\t\tif (!target) {\n\t\t\ttarget = result[key] = [];\n\t\t}\n\t\ttarget.push(element);\n\t}\n\treturn result;\n}\n\nexport function diffSets(before: Set, after: Set): { removed: T[]; added: T[] } {\n\tconst removed: T[] = [];\n\tconst added: T[] = [];\n\tfor (const element of before) {\n\t\tif (!after.has(element)) {\n\t\t\tremoved.push(element);\n\t\t}\n\t}\n\tfor (const element of after) {\n\t\tif (!before.has(element)) {\n\t\t\tadded.push(element);\n\t\t}\n\t}\n\treturn { removed, added };\n}\n\nexport function diffMaps(before: Map, after: Map): { removed: V[]; added: V[] } {\n\tconst removed: V[] = [];\n\tconst added: V[] = [];\n\tfor (const [index, value] of before) {\n\t\tif (!after.has(index)) {\n\t\t\tremoved.push(value);\n\t\t}\n\t}\n\tfor (const [index, value] of after) {\n\t\tif (!before.has(index)) {\n\t\t\tadded.push(value);\n\t\t}\n\t}\n\treturn { removed, added };\n}\n\n/**\n * Computes the intersection of two sets.\n *\n * @param setA - The first set.\n * @param setB - The second iterable.\n * @returns A new set containing the elements that are in both `setA` and `setB`.\n */\nexport function intersection(setA: Set, setB: Iterable): Set {\n\tconst result = new Set();\n\tfor (const elem of setB) {\n\t\tif (setA.has(elem)) {\n\t\t\tresult.add(elem);\n\t\t}\n\t}\n\treturn result;\n}\n\nexport class SetWithKey implements Set {\n\tprivate _map = new Map();\n\n\tconstructor(values: T[], private toKey: (t: T) => any) {\n\t\tfor (const value of values) {\n\t\t\tthis.add(value);\n\t\t}\n\t}\n\n\tget size(): number {\n\t\treturn this._map.size;\n\t}\n\n\tadd(value: T): this {\n\t\tconst key = this.toKey(value);\n\t\tthis._map.set(key, value);\n\t\treturn this;\n\t}\n\n\tdelete(value: T): boolean {\n\t\treturn this._map.delete(this.toKey(value));\n\t}\n\n\thas(value: T): boolean {\n\t\treturn this._map.has(this.toKey(value));\n\t}\n\n\t*entries(): IterableIterator<[T, T]> {\n\t\tfor (const entry of this._map.values()) {\n\t\t\tyield [entry, entry];\n\t\t}\n\t}\n\n\tkeys(): IterableIterator {\n\t\treturn this.values();\n\t}\n\n\t*values(): IterableIterator {\n\t\tfor (const entry of this._map.values()) {\n\t\t\tyield entry;\n\t\t}\n\t}\n\n\tclear(): void {\n\t\tthis._map.clear();\n\t}\n\n\tforEach(callbackfn: (value: T, value2: T, set: Set) => void, thisArg?: any): void {\n\t\tthis._map.forEach(entry => callbackfn.call(thisArg, entry, entry, this));\n\t}\n\n\t[Symbol.iterator](): IterableIterator {\n\t\treturn this.values();\n\t}\n\n\t[Symbol.toStringTag]: string = 'SetWithKey';\n}\n", "/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\nexport function getOrSet(map: Map, key: K, value: V): V {\n\tlet result = map.get(key);\n\tif (result === undefined) {\n\t\tresult = value;\n\t\tmap.set(key, result);\n\t}\n\n\treturn result;\n}\n\nexport function mapToString(map: Map): string {\n\tconst entries: string[] = [];\n\tmap.forEach((value, key) => {\n\t\tentries.push(`${key} => ${value}`);\n\t});\n\n\treturn `Map(${map.size}) {${entries.join(', ')}}`;\n}\n\nexport function setToString(set: Set): string {\n\tconst entries: K[] = [];\n\tset.forEach(value => {\n\t\tentries.push(value);\n\t});\n\n\treturn `Set(${set.size}) {${entries.join(', ')}}`;\n}\n\nexport const enum Touch {\n\tNone = 0,\n\tAsOld = 1,\n\tAsNew = 2\n}\n\nexport class CounterSet {\n\n\tprivate map = new Map();\n\n\tadd(value: T): CounterSet {\n\t\tthis.map.set(value, (this.map.get(value) || 0) + 1);\n\t\treturn this;\n\t}\n\n\tdelete(value: T): boolean {\n\t\tlet counter = this.map.get(value) || 0;\n\n\t\tif (counter === 0) {\n\t\t\treturn false;\n\t\t}\n\n\t\tcounter--;\n\n\t\tif (counter === 0) {\n\t\t\tthis.map.delete(value);\n\t\t} else {\n\t\t\tthis.map.set(value, counter);\n\t\t}\n\n\t\treturn true;\n\t}\n\n\thas(value: T): boolean {\n\t\treturn this.map.has(value);\n\t}\n}\n\n/**\n * A map that allows access both by keys and values.\n * **NOTE**: values need to be unique.\n */\nexport class BidirectionalMap {\n\n\tprivate readonly _m1 = new Map();\n\tprivate readonly _m2 = new Map();\n\n\tconstructor(entries?: readonly (readonly [K, V])[]) {\n\t\tif (entries) {\n\t\t\tfor (const [key, value] of entries) {\n\t\t\t\tthis.set(key, value);\n\t\t\t}\n\t\t}\n\t}\n\n\tclear(): void {\n\t\tthis._m1.clear();\n\t\tthis._m2.clear();\n\t}\n\n\tset(key: K, value: V): void {\n\t\tthis._m1.set(key, value);\n\t\tthis._m2.set(value, key);\n\t}\n\n\tget(key: K): V | undefined {\n\t\treturn this._m1.get(key);\n\t}\n\n\tgetKey(value: V): K | undefined {\n\t\treturn this._m2.get(value);\n\t}\n\n\tdelete(key: K): boolean {\n\t\tconst value = this._m1.get(key);\n\t\tif (value === undefined) {\n\t\t\treturn false;\n\t\t}\n\t\tthis._m1.delete(key);\n\t\tthis._m2.delete(value);\n\t\treturn true;\n\t}\n\n\tforEach(callbackfn: (value: V, key: K, map: BidirectionalMap) => void, thisArg?: any): void {\n\t\tthis._m1.forEach((value, key) => {\n\t\t\tcallbackfn.call(thisArg, value, key, this);\n\t\t});\n\t}\n\n\tkeys(): IterableIterator {\n\t\treturn this._m1.keys();\n\t}\n\n\tvalues(): IterableIterator {\n\t\treturn this._m1.values();\n\t}\n}\n\nexport class SetMap {\n\n\tprivate map = new Map>();\n\n\tadd(key: K, value: V): void {\n\t\tlet values = this.map.get(key);\n\n\t\tif (!values) {\n\t\t\tvalues = new Set();\n\t\t\tthis.map.set(key, values);\n\t\t}\n\n\t\tvalues.add(value);\n\t}\n\n\tdelete(key: K, value: V): void {\n\t\tconst values = this.map.get(key);\n\n\t\tif (!values) {\n\t\t\treturn;\n\t\t}\n\n\t\tvalues.delete(value);\n\n\t\tif (values.size === 0) {\n\t\t\tthis.map.delete(key);\n\t\t}\n\t}\n\n\tforEach(key: K, fn: (value: V) => void): void {\n\t\tconst values = this.map.get(key);\n\n\t\tif (!values) {\n\t\t\treturn;\n\t\t}\n\n\t\tvalues.forEach(fn);\n\t}\n\n\tget(key: K): ReadonlySet {\n\t\tconst values = this.map.get(key);\n\t\tif (!values) {\n\t\t\treturn new Set();\n\t\t}\n\t\treturn values;\n\t}\n}\n\nexport function mapsStrictEqualIgnoreOrder(a: Map, b: Map): boolean {\n\tif (a === b) {\n\t\treturn true;\n\t}\n\n\tif (a.size !== b.size) {\n\t\treturn false;\n\t}\n\n\tfor (const [key, value] of a) {\n\t\tif (!b.has(key) || b.get(key) !== value) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tfor (const [key] of b) {\n\t\tif (!a.has(key)) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn true;\n}\n", "/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n/**\n * Given a function, returns a function that is only calling that function once.\n */\nexport function createSingleCallFunction(this: unknown, fn: T, fnDidRunCallback?: () => void): T {\n\tconst _this = this;\n\tlet didCall = false;\n\tlet result: unknown;\n\n\treturn function () {\n\t\tif (didCall) {\n\t\t\treturn result;\n\t\t}\n\n\t\tdidCall = true;\n\t\tif (fnDidRunCallback) {\n\t\t\ttry {\n\t\t\t\tresult = fn.apply(_this, arguments);\n\t\t\t} finally {\n\t\t\t\tfnDidRunCallback();\n\t\t\t}\n\t\t} else {\n\t\t\tresult = fn.apply(_this, arguments);\n\t\t}\n\n\t\treturn result;\n\t} as unknown as T;\n}\n", "/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\nexport namespace Iterable {\n\n\texport function is(thing: any): thing is Iterable {\n\t\treturn thing && typeof thing === 'object' && typeof thing[Symbol.iterator] === 'function';\n\t}\n\n\tconst _empty: Iterable = Object.freeze([]);\n\texport function empty(): Iterable {\n\t\treturn _empty;\n\t}\n\n\texport function* single(element: T): Iterable {\n\t\tyield element;\n\t}\n\n\texport function wrap(iterableOrElement: Iterable | T): Iterable {\n\t\tif (is(iterableOrElement)) {\n\t\t\treturn iterableOrElement;\n\t\t} else {\n\t\t\treturn single(iterableOrElement);\n\t\t}\n\t}\n\n\texport function from(iterable: Iterable | undefined | null): Iterable {\n\t\treturn iterable || _empty;\n\t}\n\n\texport function* reverse(array: Array): Iterable {\n\t\tfor (let i = array.length - 1; i >= 0; i--) {\n\t\t\tyield array[i];\n\t\t}\n\t}\n\n\texport function isEmpty(iterable: Iterable | undefined | null): boolean {\n\t\treturn !iterable || iterable[Symbol.iterator]().next().done === true;\n\t}\n\n\texport function first(iterable: Iterable): T | undefined {\n\t\treturn iterable[Symbol.iterator]().next().value;\n\t}\n\n\texport function some(iterable: Iterable, predicate: (t: T, i: number) => unknown): boolean {\n\t\tlet i = 0;\n\t\tfor (const element of iterable) {\n\t\t\tif (predicate(element, i++)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\texport function find(iterable: Iterable, predicate: (t: T) => t is R): R | undefined;\n\texport function find(iterable: Iterable, predicate: (t: T) => boolean): T | undefined;\n\texport function find(iterable: Iterable, predicate: (t: T) => boolean): T | undefined {\n\t\tfor (const element of iterable) {\n\t\t\tif (predicate(element)) {\n\t\t\t\treturn element;\n\t\t\t}\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\texport function filter(iterable: Iterable, predicate: (t: T) => t is R): Iterable;\n\texport function filter(iterable: Iterable, predicate: (t: T) => boolean): Iterable;\n\texport function* filter(iterable: Iterable, predicate: (t: T) => boolean): Iterable {\n\t\tfor (const element of iterable) {\n\t\t\tif (predicate(element)) {\n\t\t\t\tyield element;\n\t\t\t}\n\t\t}\n\t}\n\n\texport function* map(iterable: Iterable, fn: (t: T, index: number) => R): Iterable {\n\t\tlet index = 0;\n\t\tfor (const element of iterable) {\n\t\t\tyield fn(element, index++);\n\t\t}\n\t}\n\n\texport function* flatMap(iterable: Iterable, fn: (t: T, index: number) => Iterable): Iterable {\n\t\tlet index = 0;\n\t\tfor (const element of iterable) {\n\t\t\tyield* fn(element, index++);\n\t\t}\n\t}\n\n\texport function* concat(...iterables: Iterable[]): Iterable {\n\t\tfor (const iterable of iterables) {\n\t\t\tyield* iterable;\n\t\t}\n\t}\n\n\texport function reduce(iterable: Iterable, reducer: (previousValue: R, currentValue: T) => R, initialValue: R): R {\n\t\tlet value = initialValue;\n\t\tfor (const element of iterable) {\n\t\t\tvalue = reducer(value, element);\n\t\t}\n\t\treturn value;\n\t}\n\n\t/**\n\t * Returns an iterable slice of the array, with the same semantics as `array.slice()`.\n\t */\n\texport function* slice(arr: ReadonlyArray, from: number, to = arr.length): Iterable {\n\t\tif (from < 0) {\n\t\t\tfrom += arr.length;\n\t\t}\n\n\t\tif (to < 0) {\n\t\t\tto += arr.length;\n\t\t} else if (to > arr.length) {\n\t\t\tto = arr.length;\n\t\t}\n\n\t\tfor (; from < to; from++) {\n\t\t\tyield arr[from];\n\t\t}\n\t}\n\n\t/**\n\t * Consumes `atMost` elements from iterable and returns the consumed elements,\n\t * and an iterable for the rest of the elements.\n\t */\n\texport function consume(iterable: Iterable, atMost: number = Number.POSITIVE_INFINITY): [T[], Iterable] {\n\t\tconst consumed: T[] = [];\n\n\t\tif (atMost === 0) {\n\t\t\treturn [consumed, iterable];\n\t\t}\n\n\t\tconst iterator = iterable[Symbol.iterator]();\n\n\t\tfor (let i = 0; i < atMost; i++) {\n\t\t\tconst next = iterator.next();\n\n\t\t\tif (next.done) {\n\t\t\t\treturn [consumed, Iterable.empty()];\n\t\t\t}\n\n\t\t\tconsumed.push(next.value);\n\t\t}\n\n\t\treturn [consumed, { [Symbol.iterator]() { return iterator; } }];\n\t}\n\n\texport async function asyncToArray(iterable: AsyncIterable): Promise {\n\t\tconst result: T[] = [];\n\t\tfor await (const item of iterable) {\n\t\t\tresult.push(item);\n\t\t}\n\t\treturn Promise.resolve(result);\n\t}\n}\n", "/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\nimport { compareBy, numberComparator } from 'vs/base/common/arrays';\nimport { groupBy } from 'vs/base/common/collections';\nimport { SetMap } from './map';\nimport { createSingleCallFunction } from 'vs/base/common/functional';\nimport { Iterable } from 'vs/base/common/iterator';\n\n// #region Disposable Tracking\n\n/**\n * Enables logging of potentially leaked disposables.\n *\n * A disposable is considered leaked if it is not disposed or not registered as the child of\n * another disposable. This tracking is very simple an only works for classes that either\n * extend Disposable or use a DisposableStore. This means there are a lot of false positives.\n */\nconst TRACK_DISPOSABLES = false;\nlet disposableTracker: IDisposableTracker | null = null;\n\nexport interface IDisposableTracker {\n\t/**\n\t * Is called on construction of a disposable.\n\t*/\n\ttrackDisposable(disposable: IDisposable): void;\n\n\t/**\n\t * Is called when a disposable is registered as child of another disposable (e.g. {@link DisposableStore}).\n\t * If parent is `null`, the disposable is removed from its former parent.\n\t*/\n\tsetParent(child: IDisposable, parent: IDisposable | null): void;\n\n\t/**\n\t * Is called after a disposable is disposed.\n\t*/\n\tmarkAsDisposed(disposable: IDisposable): void;\n\n\t/**\n\t * Indicates that the given object is a singleton which does not need to be disposed.\n\t*/\n\tmarkAsSingleton(disposable: IDisposable): void;\n}\n\nexport interface DisposableInfo {\n\tvalue: IDisposable;\n\tsource: string | null;\n\tparent: IDisposable | null;\n\tisSingleton: boolean;\n\tidx: number;\n}\n\nexport class DisposableTracker implements IDisposableTracker {\n\tprivate static idx = 0;\n\n\tprivate readonly livingDisposables = new Map();\n\n\tprivate getDisposableData(d: IDisposable): DisposableInfo {\n\t\tlet val = this.livingDisposables.get(d);\n\t\tif (!val) {\n\t\t\tval = { parent: null, source: null, isSingleton: false, value: d, idx: DisposableTracker.idx++ };\n\t\t\tthis.livingDisposables.set(d, val);\n\t\t}\n\t\treturn val;\n\t}\n\n\ttrackDisposable(d: IDisposable): void {\n\t\tconst data = this.getDisposableData(d);\n\t\tif (!data.source) {\n\t\t\tdata.source =\n\t\t\t\tnew Error().stack!;\n\t\t}\n\t}\n\n\tsetParent(child: IDisposable, parent: IDisposable | null): void {\n\t\tconst data = this.getDisposableData(child);\n\t\tdata.parent = parent;\n\t}\n\n\tmarkAsDisposed(x: IDisposable): void {\n\t\tthis.livingDisposables.delete(x);\n\t}\n\n\tmarkAsSingleton(disposable: IDisposable): void {\n\t\tthis.getDisposableData(disposable).isSingleton = true;\n\t}\n\n\tprivate getRootParent(data: DisposableInfo, cache: Map): DisposableInfo {\n\t\tconst cacheValue = cache.get(data);\n\t\tif (cacheValue) {\n\t\t\treturn cacheValue;\n\t\t}\n\n\t\tconst result = data.parent ? this.getRootParent(this.getDisposableData(data.parent), cache) : data;\n\t\tcache.set(data, result);\n\t\treturn result;\n\t}\n\n\tgetTrackedDisposables(): IDisposable[] {\n\t\tconst rootParentCache = new Map();\n\n\t\tconst leaking = [...this.livingDisposables.entries()]\n\t\t\t.filter(([, v]) => v.source !== null && !this.getRootParent(v, rootParentCache).isSingleton)\n\t\t\t.flatMap(([k]) => k);\n\n\t\treturn leaking;\n\t}\n\n\tcomputeLeakingDisposables(maxReported = 10, preComputedLeaks?: DisposableInfo[]): { leaks: DisposableInfo[]; details: string } | undefined {\n\t\tlet uncoveredLeakingObjs: DisposableInfo[] | undefined;\n\t\tif (preComputedLeaks) {\n\t\t\tuncoveredLeakingObjs = preComputedLeaks;\n\t\t} else {\n\t\t\tconst rootParentCache = new Map();\n\n\t\t\tconst leakingObjects = [...this.livingDisposables.values()]\n\t\t\t\t.filter((info) => info.source !== null && !this.getRootParent(info, rootParentCache).isSingleton);\n\n\t\t\tif (leakingObjects.length === 0) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst leakingObjsSet = new Set(leakingObjects.map(o => o.value));\n\n\t\t\t// Remove all objects that are a child of other leaking objects. Assumes there are no cycles.\n\t\t\tuncoveredLeakingObjs = leakingObjects.filter(l => {\n\t\t\t\treturn !(l.parent && leakingObjsSet.has(l.parent));\n\t\t\t});\n\n\t\t\tif (uncoveredLeakingObjs.length === 0) {\n\t\t\t\tthrow new Error('There are cyclic diposable chains!');\n\t\t\t}\n\t\t}\n\n\t\tif (!uncoveredLeakingObjs) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tfunction getStackTracePath(leaking: DisposableInfo): string[] {\n\t\t\tfunction removePrefix(array: string[], linesToRemove: (string | RegExp)[]) {\n\t\t\t\twhile (array.length > 0 && linesToRemove.some(regexp => typeof regexp === 'string' ? regexp === array[0] : array[0].match(regexp))) {\n\t\t\t\t\tarray.shift();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst lines = leaking.source!.split('\\n').map(p => p.trim().replace('at ', '')).filter(l => l !== '');\n\t\t\tremovePrefix(lines, ['Error', /^trackDisposable \\(.*\\)$/, /^DisposableTracker.trackDisposable \\(.*\\)$/]);\n\t\t\treturn lines.reverse();\n\t\t}\n\n\t\tconst stackTraceStarts = new SetMap();\n\t\tfor (const leaking of uncoveredLeakingObjs) {\n\t\t\tconst stackTracePath = getStackTracePath(leaking);\n\t\t\tfor (let i = 0; i <= stackTracePath.length; i++) {\n\t\t\t\tstackTraceStarts.add(stackTracePath.slice(0, i).join('\\n'), leaking);\n\t\t\t}\n\t\t}\n\n\t\t// Put earlier leaks first\n\t\tuncoveredLeakingObjs.sort(compareBy(l => l.idx, numberComparator));\n\n\t\tlet message = '';\n\n\t\tlet i = 0;\n\t\tfor (const leaking of uncoveredLeakingObjs.slice(0, maxReported)) {\n\t\t\ti++;\n\t\t\tconst stackTracePath = getStackTracePath(leaking);\n\t\t\tconst stackTraceFormattedLines = [];\n\n\t\t\tfor (let i = 0; i < stackTracePath.length; i++) {\n\t\t\t\tlet line = stackTracePath[i];\n\t\t\t\tconst starts = stackTraceStarts.get(stackTracePath.slice(0, i + 1).join('\\n'));\n\t\t\t\tline = `(shared with ${starts.size}/${uncoveredLeakingObjs.length} leaks) at ${line}`;\n\n\t\t\t\tconst prevStarts = stackTraceStarts.get(stackTracePath.slice(0, i).join('\\n'));\n\t\t\t\tconst continuations = groupBy([...prevStarts].map(d => getStackTracePath(d)[i]), v => v);\n\t\t\t\tdelete continuations[stackTracePath[i]];\n\t\t\t\tfor (const [cont, set] of Object.entries(continuations)) {\n\t\t\t\t\tstackTraceFormattedLines.unshift(` - stacktraces of ${set.length} other leaks continue with ${cont}`);\n\t\t\t\t}\n\n\t\t\t\tstackTraceFormattedLines.unshift(line);\n\t\t\t}\n\n\t\t\tmessage += `\\n\\n\\n==================== Leaking disposable ${i}/${uncoveredLeakingObjs.length}: ${leaking.value.constructor.name} ====================\\n${stackTraceFormattedLines.join('\\n')}\\n============================================================\\n\\n`;\n\t\t}\n\n\t\tif (uncoveredLeakingObjs.length > maxReported) {\n\t\t\tmessage += `\\n\\n\\n... and ${uncoveredLeakingObjs.length - maxReported} more leaking disposables\\n\\n`;\n\t\t}\n\n\t\treturn { leaks: uncoveredLeakingObjs, details: message };\n\t}\n}\n\nexport function setDisposableTracker(tracker: IDisposableTracker | null): void {\n\tdisposableTracker = tracker;\n}\n\nif (TRACK_DISPOSABLES) {\n\tconst __is_disposable_tracked__ = '__is_disposable_tracked__';\n\tsetDisposableTracker(new class implements IDisposableTracker {\n\t\ttrackDisposable(x: IDisposable): void {\n\t\t\tconst stack = new Error('Potentially leaked disposable').stack!;\n\t\t\tsetTimeout(() => {\n\t\t\t\tif (!(x as any)[__is_disposable_tracked__]) {\n\t\t\t\t\tconsole.log(stack);\n\t\t\t\t}\n\t\t\t}, 3000);\n\t\t}\n\n\t\tsetParent(child: IDisposable, parent: IDisposable | null): void {\n\t\t\tif (child && child !== Disposable.None) {\n\t\t\t\ttry {\n\t\t\t\t\t(child as any)[__is_disposable_tracked__] = true;\n\t\t\t\t} catch {\n\t\t\t\t\t// noop\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tmarkAsDisposed(disposable: IDisposable): void {\n\t\t\tif (disposable && disposable !== Disposable.None) {\n\t\t\t\ttry {\n\t\t\t\t\t(disposable as any)[__is_disposable_tracked__] = true;\n\t\t\t\t} catch {\n\t\t\t\t\t// noop\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tmarkAsSingleton(disposable: IDisposable): void { }\n\t});\n}\n\nexport function trackDisposable(x: T): T {\n\tdisposableTracker?.trackDisposable(x);\n\treturn x;\n}\n\nexport function markAsDisposed(disposable: IDisposable): void {\n\tdisposableTracker?.markAsDisposed(disposable);\n}\n\nfunction setParentOfDisposable(child: IDisposable, parent: IDisposable | null): void {\n\tdisposableTracker?.setParent(child, parent);\n}\n\nfunction setParentOfDisposables(children: IDisposable[], parent: IDisposable | null): void {\n\tif (!disposableTracker) {\n\t\treturn;\n\t}\n\tfor (const child of children) {\n\t\tdisposableTracker.setParent(child, parent);\n\t}\n}\n\n/**\n * Indicates that the given object is a singleton which does not need to be disposed.\n*/\nexport function markAsSingleton(singleton: T): T {\n\tdisposableTracker?.markAsSingleton(singleton);\n\treturn singleton;\n}\n\n// #endregion\n\n/**\n * An object that performs a cleanup operation when `.dispose()` is called.\n *\n * Some examples of how disposables are used:\n *\n * - An event listener that removes itself when `.dispose()` is called.\n * - A resource such as a file system watcher that cleans up the resource when `.dispose()` is called.\n * - The return value from registering a provider. When `.dispose()` is called, the provider is unregistered.\n */\nexport interface IDisposable {\n\tdispose(): void;\n}\n\n/**\n * Check if `thing` is {@link IDisposable disposable}.\n */\nexport function isDisposable(thing: E): thing is E & IDisposable {\n\treturn typeof thing === 'object' && thing !== null && typeof (thing).dispose === 'function' && (thing).dispose.length === 0;\n}\n\n/**\n * Disposes of the value(s) passed in.\n */\nexport function dispose(disposable: T): T;\nexport function dispose(disposable: T | undefined): T | undefined;\nexport function dispose = Iterable>(disposables: A): A;\nexport function dispose(disposables: Array): Array;\nexport function dispose(disposables: ReadonlyArray): ReadonlyArray;\nexport function dispose(arg: T | Iterable | undefined): any {\n\tif (Iterable.is(arg)) {\n\t\tconst errors: any[] = [];\n\n\t\tfor (const d of arg) {\n\t\t\tif (d) {\n\t\t\t\ttry {\n\t\t\t\t\td.dispose();\n\t\t\t\t} catch (e) {\n\t\t\t\t\terrors.push(e);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (errors.length === 1) {\n\t\t\tthrow errors[0];\n\t\t} else if (errors.length > 1) {\n\t\t\tthrow new AggregateError(errors, 'Encountered errors while disposing of store');\n\t\t}\n\n\t\treturn Array.isArray(arg) ? [] : arg;\n\t} else if (arg) {\n\t\targ.dispose();\n\t\treturn arg;\n\t}\n}\n\nexport function disposeIfDisposable(disposables: Array): Array {\n\tfor (const d of disposables) {\n\t\tif (isDisposable(d)) {\n\t\t\td.dispose();\n\t\t}\n\t}\n\treturn [];\n}\n\n/**\n * Combine multiple disposable values into a single {@link IDisposable}.\n */\nexport function combinedDisposable(...disposables: IDisposable[]): IDisposable {\n\tconst parent = toDisposable(() => dispose(disposables));\n\tsetParentOfDisposables(disposables, parent);\n\treturn parent;\n}\n\n/**\n * Turn a function that implements dispose into an {@link IDisposable}.\n *\n * @param fn Clean up function, guaranteed to be called only **once**.\n */\nexport function toDisposable(fn: () => void): IDisposable {\n\tconst self = trackDisposable({\n\t\tdispose: createSingleCallFunction(() => {\n\t\t\tmarkAsDisposed(self);\n\t\t\tfn();\n\t\t})\n\t});\n\treturn self;\n}\n\n/**\n * Manages a collection of disposable values.\n *\n * This is the preferred way to manage multiple disposables. A `DisposableStore` is safer to work with than an\n * `IDisposable[]` as it considers edge cases, such as registering the same value multiple times or adding an item to a\n * store that has already been disposed of.\n */\nexport class DisposableStore implements IDisposable {\n\n\tstatic DISABLE_DISPOSED_WARNING = false;\n\n\tprivate readonly _toDispose = new Set();\n\tprivate _isDisposed = false;\n\n\tconstructor() {\n\t\ttrackDisposable(this);\n\t}\n\n\t/**\n\t * Dispose of all registered disposables and mark this object as disposed.\n\t *\n\t * Any future disposables added to this object will be disposed of on `add`.\n\t */\n\tpublic dispose(): void {\n\t\tif (this._isDisposed) {\n\t\t\treturn;\n\t\t}\n\n\t\tmarkAsDisposed(this);\n\t\tthis._isDisposed = true;\n\t\tthis.clear();\n\t}\n\n\t/**\n\t * @return `true` if this object has been disposed of.\n\t */\n\tpublic get isDisposed(): boolean {\n\t\treturn this._isDisposed;\n\t}\n\n\t/**\n\t * Dispose of all registered disposables but do not mark this object as disposed.\n\t */\n\tpublic clear(): void {\n\t\tif (this._toDispose.size === 0) {\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\tdispose(this._toDispose);\n\t\t} finally {\n\t\t\tthis._toDispose.clear();\n\t\t}\n\t}\n\n\t/**\n\t * Add a new {@link IDisposable disposable} to the collection.\n\t */\n\tpublic add(o: T): T {\n\t\tif (!o) {\n\t\t\treturn o;\n\t\t}\n\t\tif ((o as unknown as DisposableStore) === this) {\n\t\t\tthrow new Error('Cannot register a disposable on itself!');\n\t\t}\n\n\t\tsetParentOfDisposable(o, this);\n\t\tif (this._isDisposed) {\n\t\t\tif (!DisposableStore.DISABLE_DISPOSED_WARNING) {\n\t\t\t\tconsole.warn(new Error('Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!').stack);\n\t\t\t}\n\t\t} else {\n\t\t\tthis._toDispose.add(o);\n\t\t}\n\n\t\treturn o;\n\t}\n\n\t/**\n\t * Deletes a disposable from store and disposes of it. This will not throw or warn and proceed to dispose the\n\t * disposable even when the disposable is not part in the store.\n\t */\n\tpublic delete(o: T): void {\n\t\tif (!o) {\n\t\t\treturn;\n\t\t}\n\t\tif ((o as unknown as DisposableStore) === this) {\n\t\t\tthrow new Error('Cannot dispose a disposable on itself!');\n\t\t}\n\t\tthis._toDispose.delete(o);\n\t\to.dispose();\n\t}\n\n\t/**\n\t * Deletes the value from the store, but does not dispose it.\n\t */\n\tpublic deleteAndLeak(o: T): void {\n\t\tif (!o) {\n\t\t\treturn;\n\t\t}\n\t\tif (this._toDispose.has(o)) {\n\t\t\tthis._toDispose.delete(o);\n\t\t\tsetParentOfDisposable(o, null);\n\t\t}\n\t}\n}\n\n/**\n * Abstract base class for a {@link IDisposable disposable} object.\n *\n * Subclasses can {@linkcode _register} disposables that will be automatically cleaned up when this object is disposed of.\n */\nexport abstract class Disposable implements IDisposable {\n\n\t/**\n\t * A disposable that does nothing when it is disposed of.\n\t *\n\t * TODO: This should not be a static property.\n\t */\n\tstatic readonly None = Object.freeze({ dispose() { } });\n\n\tprotected readonly _store = new DisposableStore();\n\n\tconstructor() {\n\t\ttrackDisposable(this);\n\t\tsetParentOfDisposable(this._store, this);\n\t}\n\n\tpublic dispose(): void {\n\t\tmarkAsDisposed(this);\n\n\t\tthis._store.dispose();\n\t}\n\n\t/**\n\t * Adds `o` to the collection of disposables managed by this object.\n\t */\n\tprotected _register(o: T): T {\n\t\tif ((o as unknown as Disposable) === this) {\n\t\t\tthrow new Error('Cannot register a disposable on itself!');\n\t\t}\n\t\treturn this._store.add(o);\n\t}\n}\n\n/**\n * Manages the lifecycle of a disposable value that may be changed.\n *\n * This ensures that when the disposable value is changed, the previously held disposable is disposed of. You can\n * also register a `MutableDisposable` on a `Disposable` to ensure it is automatically cleaned up.\n */\nexport class MutableDisposable implements IDisposable {\n\tprivate _value?: T;\n\tprivate _isDisposed = false;\n\n\tconstructor() {\n\t\ttrackDisposable(this);\n\t}\n\n\tget value(): T | undefined {\n\t\treturn this._isDisposed ? undefined : this._value;\n\t}\n\n\tset value(value: T | undefined) {\n\t\tif (this._isDisposed || value === this._value) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis._value?.dispose();\n\t\tif (value) {\n\t\t\tsetParentOfDisposable(value, this);\n\t\t}\n\t\tthis._value = value;\n\t}\n\n\t/**\n\t * Resets the stored value and disposed of the previously stored value.\n\t */\n\tclear(): void {\n\t\tthis.value = undefined;\n\t}\n\n\tdispose(): void {\n\t\tthis._isDisposed = true;\n\t\tmarkAsDisposed(this);\n\t\tthis._value?.dispose();\n\t\tthis._value = undefined;\n\t}\n\n\t/**\n\t * Clears the value, but does not dispose it.\n\t * The old value is returned.\n\t*/\n\tclearAndLeak(): T | undefined {\n\t\tconst oldValue = this._value;\n\t\tthis._value = undefined;\n\t\tif (oldValue) {\n\t\t\tsetParentOfDisposable(oldValue, null);\n\t\t}\n\t\treturn oldValue;\n\t}\n}\n\n/**\n * Manages the lifecycle of a disposable value that may be changed like {@link MutableDisposable}, but the value must\n * exist and cannot be undefined.\n */\nexport class MandatoryMutableDisposable implements IDisposable {\n\tprivate readonly _disposable = new MutableDisposable();\n\tprivate _isDisposed = false;\n\n\tconstructor(initialValue: T) {\n\t\tthis._disposable.value = initialValue;\n\t}\n\n\tget value(): T {\n\t\treturn this._disposable.value!;\n\t}\n\n\tset value(value: T) {\n\t\tif (this._isDisposed || value === this._disposable.value) {\n\t\t\treturn;\n\t\t}\n\t\tthis._disposable.value = value;\n\t}\n\n\tdispose() {\n\t\tthis._isDisposed = true;\n\t\tthis._disposable.dispose();\n\t}\n}\n\nexport class RefCountedDisposable {\n\n\tprivate _counter: number = 1;\n\n\tconstructor(\n\t\tprivate readonly _disposable: IDisposable,\n\t) { }\n\n\tacquire() {\n\t\tthis._counter++;\n\t\treturn this;\n\t}\n\n\trelease() {\n\t\tif (--this._counter === 0) {\n\t\t\tthis._disposable.dispose();\n\t\t}\n\t\treturn this;\n\t}\n}\n\n/**\n * A safe disposable can be `unset` so that a leaked reference (listener)\n * can be cut-off.\n */\nexport class SafeDisposable implements IDisposable {\n\n\tdispose: () => void = () => { };\n\tunset: () => void = () => { };\n\tisset: () => boolean = () => false;\n\n\tconstructor() {\n\t\ttrackDisposable(this);\n\t}\n\n\tset(fn: Function) {\n\t\tlet callback: Function | undefined = fn;\n\t\tthis.unset = () => callback = undefined;\n\t\tthis.isset = () => callback !== undefined;\n\t\tthis.dispose = () => {\n\t\t\tif (callback) {\n\t\t\t\tcallback();\n\t\t\t\tcallback = undefined;\n\t\t\t\tmarkAsDisposed(this);\n\t\t\t}\n\t\t};\n\t\treturn this;\n\t}\n}\n\nexport interface IReference extends IDisposable {\n\treadonly object: T;\n}\n\nexport abstract class ReferenceCollection {\n\n\tprivate readonly references: Map = new Map();\n\n\tacquire(key: string, ...args: any[]): IReference {\n\t\tlet reference = this.references.get(key);\n\n\t\tif (!reference) {\n\t\t\treference = { counter: 0, object: this.createReferencedObject(key, ...args) };\n\t\t\tthis.references.set(key, reference);\n\t\t}\n\n\t\tconst { object } = reference;\n\t\tconst dispose = createSingleCallFunction(() => {\n\t\t\tif (--reference.counter === 0) {\n\t\t\t\tthis.destroyReferencedObject(key, reference.object);\n\t\t\t\tthis.references.delete(key);\n\t\t\t}\n\t\t});\n\n\t\treference.counter++;\n\n\t\treturn { object, dispose };\n\t}\n\n\tprotected abstract createReferencedObject(key: string, ...args: any[]): T;\n\tprotected abstract destroyReferencedObject(key: string, object: T): void;\n}\n\n/**\n * Unwraps a reference collection of promised values. Makes sure\n * references are disposed whenever promises get rejected.\n */\nexport class AsyncReferenceCollection {\n\n\tconstructor(private referenceCollection: ReferenceCollection>) { }\n\n\tasync acquire(key: string, ...args: any[]): Promise> {\n\t\tconst ref = this.referenceCollection.acquire(key, ...args);\n\n\t\ttry {\n\t\t\tconst object = await ref.object;\n\n\t\t\treturn {\n\t\t\t\tobject,\n\t\t\t\tdispose: () => ref.dispose()\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tref.dispose();\n\t\t\tthrow error;\n\t\t}\n\t}\n}\n\nexport class ImmortalReference implements IReference {\n\tconstructor(public object: T) { }\n\tdispose(): void { /* noop */ }\n}\n\nexport function disposeOnReturn(fn: (store: DisposableStore) => void): void {\n\tconst store = new DisposableStore();\n\ttry {\n\t\tfn(store);\n\t} finally {\n\t\tstore.dispose();\n\t}\n}\n\n/**\n * A map the manages the lifecycle of the values that it stores.\n */\nexport class DisposableMap implements IDisposable {\n\n\tprivate readonly _store = new Map();\n\tprivate _isDisposed = false;\n\n\tconstructor() {\n\t\ttrackDisposable(this);\n\t}\n\n\t/**\n\t * Disposes of all stored values and mark this object as disposed.\n\t *\n\t * Trying to use this object after it has been disposed of is an error.\n\t */\n\tdispose(): void {\n\t\tmarkAsDisposed(this);\n\t\tthis._isDisposed = true;\n\t\tthis.clearAndDisposeAll();\n\t}\n\n\t/**\n\t * Disposes of all stored values and clear the map, but DO NOT mark this object as disposed.\n\t */\n\tclearAndDisposeAll(): void {\n\t\tif (!this._store.size) {\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\tdispose(this._store.values());\n\t\t} finally {\n\t\t\tthis._store.clear();\n\t\t}\n\t}\n\n\thas(key: K): boolean {\n\t\treturn this._store.has(key);\n\t}\n\n\tget size(): number {\n\t\treturn this._store.size;\n\t}\n\n\tget(key: K): V | undefined {\n\t\treturn this._store.get(key);\n\t}\n\n\tset(key: K, value: V, skipDisposeOnOverwrite = false): void {\n\t\tif (this._isDisposed) {\n\t\t\tconsole.warn(new Error('Trying to add a disposable to a DisposableMap that has already been disposed of. The added object will be leaked!').stack);\n\t\t}\n\n\t\tif (!skipDisposeOnOverwrite) {\n\t\t\tthis._store.get(key)?.dispose();\n\t\t}\n\n\t\tthis._store.set(key, value);\n\t}\n\n\t/**\n\t * Delete the value stored for `key` from this map and also dispose of it.\n\t */\n\tdeleteAndDispose(key: K): void {\n\t\tthis._store.get(key)?.dispose();\n\t\tthis._store.delete(key);\n\t}\n\n\t/**\n\t * Delete the value stored for `key` from this map but return it. The caller is\n\t * responsible for disposing of the value.\n\t */\n\tdeleteAndLeak(key: K): V | undefined {\n\t\tconst value = this._store.get(key);\n\t\tthis._store.delete(key);\n\t\treturn value;\n\t}\n\n\tkeys(): IterableIterator {\n\t\treturn this._store.keys();\n\t}\n\n\tvalues(): IterableIterator {\n\t\treturn this._store.values();\n\t}\n\n\t[Symbol.iterator](): IterableIterator<[K, V]> {\n\t\treturn this._store[Symbol.iterator]();\n\t}\n}\n", "/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\nexport type CodeWindow = Window & typeof globalThis & {\n\treadonly vscodeWindowId: number;\n};\n\nexport function ensureCodeWindow(targetWindow: Window, fallbackWindowId: number): asserts targetWindow is CodeWindow {\n}\n\n// eslint-disable-next-line no-restricted-globals\nexport const mainWindow = (typeof window === 'object' ? window : globalThis) as CodeWindow;\n", "/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\nclass Node {\n\n\tstatic readonly Undefined = new Node(undefined);\n\n\telement: E;\n\tnext: Node;\n\tprev: Node;\n\n\tconstructor(element: E) {\n\t\tthis.element = element;\n\t\tthis.next = Node.Undefined;\n\t\tthis.prev = Node.Undefined;\n\t}\n}\n\nexport class LinkedList {\n\n\tprivate _first: Node = Node.Undefined;\n\tprivate _last: Node = Node.Undefined;\n\tprivate _size: number = 0;\n\n\tget size(): number {\n\t\treturn this._size;\n\t}\n\n\tisEmpty(): boolean {\n\t\treturn this._first === Node.Undefined;\n\t}\n\n\tclear(): void {\n\t\tlet node = this._first;\n\t\twhile (node !== Node.Undefined) {\n\t\t\tconst next = node.next;\n\t\t\tnode.prev = Node.Undefined;\n\t\t\tnode.next = Node.Undefined;\n\t\t\tnode = next;\n\t\t}\n\n\t\tthis._first = Node.Undefined;\n\t\tthis._last = Node.Undefined;\n\t\tthis._size = 0;\n\t}\n\n\tunshift(element: E): () => void {\n\t\treturn this._insert(element, false);\n\t}\n\n\tpush(element: E): () => void {\n\t\treturn this._insert(element, true);\n\t}\n\n\tprivate _insert(element: E, atTheEnd: boolean): () => void {\n\t\tconst newNode = new Node(element);\n\t\tif (this._first === Node.Undefined) {\n\t\t\tthis._first = newNode;\n\t\t\tthis._last = newNode;\n\n\t\t} else if (atTheEnd) {\n\t\t\t// push\n\t\t\tconst oldLast = this._last;\n\t\t\tthis._last = newNode;\n\t\t\tnewNode.prev = oldLast;\n\t\t\toldLast.next = newNode;\n\n\t\t} else {\n\t\t\t// unshift\n\t\t\tconst oldFirst = this._first;\n\t\t\tthis._first = newNode;\n\t\t\tnewNode.next = oldFirst;\n\t\t\toldFirst.prev = newNode;\n\t\t}\n\t\tthis._size += 1;\n\n\t\tlet didRemove = false;\n\t\treturn () => {\n\t\t\tif (!didRemove) {\n\t\t\t\tdidRemove = true;\n\t\t\t\tthis._remove(newNode);\n\t\t\t}\n\t\t};\n\t}\n\n\tshift(): E | undefined {\n\t\tif (this._first === Node.Undefined) {\n\t\t\treturn undefined;\n\t\t} else {\n\t\t\tconst res = this._first.element;\n\t\t\tthis._remove(this._first);\n\t\t\treturn res;\n\t\t}\n\t}\n\n\tpop(): E | undefined {\n\t\tif (this._last === Node.Undefined) {\n\t\t\treturn undefined;\n\t\t} else {\n\t\t\tconst res = this._last.element;\n\t\t\tthis._remove(this._last);\n\t\t\treturn res;\n\t\t}\n\t}\n\n\tprivate _remove(node: Node): void {\n\t\tif (node.prev !== Node.Undefined && node.next !== Node.Undefined) {\n\t\t\t// middle\n\t\t\tconst anchor = node.prev;\n\t\t\tanchor.next = node.next;\n\t\t\tnode.next.prev = anchor;\n\n\t\t} else if (node.prev === Node.Undefined && node.next === Node.Undefined) {\n\t\t\t// only node\n\t\t\tthis._first = Node.Undefined;\n\t\t\tthis._last = Node.Undefined;\n\n\t\t} else if (node.next === Node.Undefined) {\n\t\t\t// last\n\t\t\tthis._last = this._last.prev!;\n\t\t\tthis._last.next = Node.Undefined;\n\n\t\t} else if (node.prev === Node.Undefined) {\n\t\t\t// first\n\t\t\tthis._first = this._first.next!;\n\t\t\tthis._first.prev = Node.Undefined;\n\t\t}\n\n\t\t// done\n\t\tthis._size -= 1;\n\t}\n\n\t*[Symbol.iterator](): Iterator {\n\t\tlet node = this._first;\n\t\twhile (node !== Node.Undefined) {\n\t\t\tyield node.element;\n\t\t\tnode = node.next;\n\t\t}\n\t}\n}\n", "/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n// fake definition so that the valid layers check won't trip on this\ndeclare const globalThis: { performance?: { now(): number } };\n\nconst hasPerformanceNow = (globalThis.performance && typeof globalThis.performance.now === 'function');\n\nexport class StopWatch {\n\n\tprivate _startTime: number;\n\tprivate _stopTime: number;\n\n\tprivate readonly _now: () => number;\n\n\tpublic static create(highResolution?: boolean): StopWatch {\n\t\treturn new StopWatch(highResolution);\n\t}\n\n\tconstructor(highResolution?: boolean) {\n\t\tthis._now = hasPerformanceNow && highResolution === false ? Date.now : globalThis.performance!.now.bind(globalThis.performance);\n\t\tthis._startTime = this._now();\n\t\tthis._stopTime = -1;\n\t}\n\n\tpublic stop(): void {\n\t\tthis._stopTime = this._now();\n\t}\n\n\tpublic reset(): void {\n\t\tthis._startTime = this._now();\n\t\tthis._stopTime = -1;\n\t}\n\n\tpublic elapsed(): number {\n\t\tif (this._stopTime !== -1) {\n\t\t\treturn this._stopTime - this._startTime;\n\t\t}\n\t\treturn this._now() - this._startTime;\n\t}\n}\n", "/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\nimport { CancellationToken } from 'vs/base/common/cancellation';\nimport { onUnexpectedError } from 'vs/base/common/errors';\nimport { createSingleCallFunction } from 'vs/base/common/functional';\nimport { combinedDisposable, Disposable, DisposableMap, DisposableStore, IDisposable, toDisposable } from 'vs/base/common/lifecycle';\nimport { LinkedList } from 'vs/base/common/linkedList';\nimport { IObservable, IObserver } from 'vs/base/common/observable';\nimport { StopWatch } from 'vs/base/common/stopwatch';\nimport { MicrotaskDelay } from 'vs/base/common/symbols';\n\n\n// -----------------------------------------------------------------------------------------------------------------------\n// Uncomment the next line to print warnings whenever a listener is GC'ed without having been disposed. This is a LEAK.\n// -----------------------------------------------------------------------------------------------------------------------\nconst _enableListenerGCedWarning = false\n\t// || Boolean(\"TRUE\") // causes a linter warning so that it cannot be pushed\n\t;\n\n// -----------------------------------------------------------------------------------------------------------------------\n// Uncomment the next line to print warnings whenever an emitter with listeners is disposed. That is a sign of code smell.\n// -----------------------------------------------------------------------------------------------------------------------\nconst _enableDisposeWithListenerWarning = false\n\t// || Boolean(\"TRUE\") // causes a linter warning so that it cannot be pushed\n\t;\n\n\n// -----------------------------------------------------------------------------------------------------------------------\n// Uncomment the next line to print warnings whenever a snapshotted event is used repeatedly without cleanup.\n// See https://github.com/microsoft/vscode/issues/142851\n// -----------------------------------------------------------------------------------------------------------------------\nconst _enableSnapshotPotentialLeakWarning = false\n\t// || Boolean(\"TRUE\") // causes a linter warning so that it cannot be pushed\n\t;\n\n/**\n * An event with zero or one parameters that can be subscribed to. The event is a function itself.\n */\nexport interface Event {\n\t(listener: (e: T) => any, thisArgs?: any, disposables?: IDisposable[] | DisposableStore): IDisposable;\n}\n\nexport namespace Event {\n\texport const None: Event = () => Disposable.None;\n\n\tfunction _addLeakageTraceLogic(options: EmitterOptions) {\n\t\tif (_enableSnapshotPotentialLeakWarning) {\n\t\t\tconst { onDidAddListener: origListenerDidAdd } = options;\n\t\t\tconst stack = Stacktrace.create();\n\t\t\tlet count = 0;\n\t\t\toptions.onDidAddListener = () => {\n\t\t\t\tif (++count === 2) {\n\t\t\t\t\tconsole.warn('snapshotted emitter LIKELY used public and SHOULD HAVE BEEN created with DisposableStore. snapshotted here');\n\t\t\t\t\tstack.print();\n\t\t\t\t}\n\t\t\t\torigListenerDidAdd?.();\n\t\t\t};\n\t\t}\n\t}\n\n\t/**\n\t * Given an event, returns another event which debounces calls and defers the listeners to a later task via a shared\n\t * `setTimeout`. The event is converted into a signal (`Event`) to avoid additional object creation as a\n\t * result of merging events and to try prevent race conditions that could arise when using related deferred and\n\t * non-deferred events.\n\t *\n\t * This is useful for deferring non-critical work (eg. general UI updates) to ensure it does not block critical work\n\t * (eg. latency of keypress to text rendered).\n\t *\n\t * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned\n\t * event is accessible to \"third parties\", e.g the event is a public property. Otherwise a leaked listener on the\n\t * returned event causes this utility to leak a listener on the original event.\n\t *\n\t * @param event The event source for the new event.\n\t * @param disposable A disposable store to add the new EventEmitter to.\n\t */\n\texport function defer(event: Event, disposable?: DisposableStore): Event {\n\t\treturn debounce(event, () => void 0, 0, undefined, true, undefined, disposable);\n\t}\n\n\t/**\n\t * Given an event, returns another event which only fires once.\n\t *\n\t * @param event The event source for the new event.\n\t */\n\texport function once(event: Event): Event {\n\t\treturn (listener, thisArgs = null, disposables?) => {\n\t\t\t// we need this, in case the event fires during the listener call\n\t\t\tlet didFire = false;\n\t\t\tlet result: IDisposable | undefined = undefined;\n\t\t\tresult = event(e => {\n\t\t\t\tif (didFire) {\n\t\t\t\t\treturn;\n\t\t\t\t} else if (result) {\n\t\t\t\t\tresult.dispose();\n\t\t\t\t} else {\n\t\t\t\t\tdidFire = true;\n\t\t\t\t}\n\n\t\t\t\treturn listener.call(thisArgs, e);\n\t\t\t}, null, disposables);\n\n\t\t\tif (didFire) {\n\t\t\t\tresult.dispose();\n\t\t\t}\n\n\t\t\treturn result;\n\t\t};\n\t}\n\n\t/**\n\t * Maps an event of one type into an event of another type using a mapping function, similar to how\n\t * `Array.prototype.map` works.\n\t *\n\t * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned\n\t * event is accessible to \"third parties\", e.g the event is a public property. Otherwise a leaked listener on the\n\t * returned event causes this utility to leak a listener on the original event.\n\t *\n\t * @param event The event source for the new event.\n\t * @param map The mapping function.\n\t * @param disposable A disposable store to add the new EventEmitter to.\n\t */\n\texport function map(event: Event, map: (i: I) => O, disposable?: DisposableStore): Event {\n\t\treturn snapshot((listener, thisArgs = null, disposables?) => event(i => listener.call(thisArgs, map(i)), null, disposables), disposable);\n\t}\n\n\t/**\n\t * Wraps an event in another event that performs some function on the event object before firing.\n\t *\n\t * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned\n\t * event is accessible to \"third parties\", e.g the event is a public property. Otherwise a leaked listener on the\n\t * returned event causes this utility to leak a listener on the original event.\n\t *\n\t * @param event The event source for the new event.\n\t * @param each The function to perform on the event object.\n\t * @param disposable A disposable store to add the new EventEmitter to.\n\t */\n\texport function forEach(event: Event, each: (i: I) => void, disposable?: DisposableStore): Event {\n\t\treturn snapshot((listener, thisArgs = null, disposables?) => event(i => { each(i); listener.call(thisArgs, i); }, null, disposables), disposable);\n\t}\n\n\t/**\n\t * Wraps an event in another event that fires only when some condition is met.\n\t *\n\t * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned\n\t * event is accessible to \"third parties\", e.g the event is a public property. Otherwise a leaked listener on the\n\t * returned event causes this utility to leak a listener on the original event.\n\t *\n\t * @param event The event source for the new event.\n\t * @param filter The filter function that defines the condition. The event will fire for the object if this function\n\t * returns true.\n\t * @param disposable A disposable store to add the new EventEmitter to.\n\t */\n\texport function filter(event: Event, filter: (e: T | U) => e is T, disposable?: DisposableStore): Event;\n\texport function filter(event: Event, filter: (e: T) => boolean, disposable?: DisposableStore): Event;\n\texport function filter(event: Event, filter: (e: T | R) => e is R, disposable?: DisposableStore): Event;\n\texport function filter(event: Event, filter: (e: T) => boolean, disposable?: DisposableStore): Event {\n\t\treturn snapshot((listener, thisArgs = null, disposables?) => event(e => filter(e) && listener.call(thisArgs, e), null, disposables), disposable);\n\t}\n\n\t/**\n\t * Given an event, returns the same event but typed as `Event`.\n\t */\n\texport function signal(event: Event): Event {\n\t\treturn event as Event as Event;\n\t}\n\n\t/**\n\t * Given a collection of events, returns a single event which emits whenever any of the provided events emit.\n\t */\n\texport function any(...events: Event[]): Event;\n\texport function any(...events: Event[]): Event;\n\texport function any(...events: Event[]): Event {\n\t\treturn (listener, thisArgs = null, disposables?) => {\n\t\t\tconst disposable = combinedDisposable(...events.map(event => event(e => listener.call(thisArgs, e))));\n\t\t\treturn addAndReturnDisposable(disposable, disposables);\n\t\t};\n\t}\n\n\t/**\n\t * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned\n\t * event is accessible to \"third parties\", e.g the event is a public property. Otherwise a leaked listener on the\n\t * returned event causes this utility to leak a listener on the original event.\n\t */\n\texport function reduce(event: Event, merge: (last: O | undefined, event: I) => O, initial?: O, disposable?: DisposableStore): Event {\n\t\tlet output: O | undefined = initial;\n\n\t\treturn map(event, e => {\n\t\t\toutput = merge(output, e);\n\t\t\treturn output;\n\t\t}, disposable);\n\t}\n\n\tfunction snapshot(event: Event, disposable: DisposableStore | undefined): Event {\n\t\tlet listener: IDisposable | undefined;\n\n\t\tconst options: EmitterOptions | undefined = {\n\t\t\tonWillAddFirstListener() {\n\t\t\t\tlistener = event(emitter.fire, emitter);\n\t\t\t},\n\t\t\tonDidRemoveLastListener() {\n\t\t\t\tlistener?.dispose();\n\t\t\t}\n\t\t};\n\n\t\tif (!disposable) {\n\t\t\t_addLeakageTraceLogic(options);\n\t\t}\n\n\t\tconst emitter = new Emitter(options);\n\n\t\tdisposable?.add(emitter);\n\n\t\treturn emitter.event;\n\t}\n\n\t/**\n\t * Adds the IDisposable to the store if it's set, and returns it. Useful to\n\t * Event function implementation.\n\t */\n\tfunction addAndReturnDisposable(d: T, store: DisposableStore | IDisposable[] | undefined): T {\n\t\tif (store instanceof Array) {\n\t\t\tstore.push(d);\n\t\t} else if (store) {\n\t\t\tstore.add(d);\n\t\t}\n\t\treturn d;\n\t}\n\n\t/**\n\t * Given an event, creates a new emitter that event that will debounce events based on {@link delay} and give an\n\t * array event object of all events that fired.\n\t *\n\t * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned\n\t * event is accessible to \"third parties\", e.g the event is a public property. Otherwise a leaked listener on the\n\t * returned event causes this utility to leak a listener on the original event.\n\t *\n\t * @param event The original event to debounce.\n\t * @param merge A function that reduces all events into a single event.\n\t * @param delay The number of milliseconds to debounce.\n\t * @param leading Whether to fire a leading event without debouncing.\n\t * @param flushOnListenerRemove Whether to fire all debounced events when a listener is removed. If this is not\n\t * specified, some events could go missing. Use this if it's important that all events are processed, even if the\n\t * listener gets disposed before the debounced event fires.\n\t * @param leakWarningThreshold See {@link EmitterOptions.leakWarningThreshold}.\n\t * @param disposable A disposable store to register the debounce emitter to.\n\t */\n\texport function debounce(event: Event, merge: (last: T | undefined, event: T) => T, delay?: number | typeof MicrotaskDelay, leading?: boolean, flushOnListenerRemove?: boolean, leakWarningThreshold?: number, disposable?: DisposableStore): Event;\n\texport function debounce(event: Event, merge: (last: O | undefined, event: I) => O, delay?: number | typeof MicrotaskDelay, leading?: boolean, flushOnListenerRemove?: boolean, leakWarningThreshold?: number, disposable?: DisposableStore): Event;\n\texport function debounce(event: Event, merge: (last: O | undefined, event: I) => O, delay: number | typeof MicrotaskDelay = 100, leading = false, flushOnListenerRemove = false, leakWarningThreshold?: number, disposable?: DisposableStore): Event {\n\t\tlet subscription: IDisposable;\n\t\tlet output: O | undefined = undefined;\n\t\tlet handle: any = undefined;\n\t\tlet numDebouncedCalls = 0;\n\t\tlet doFire: (() => void) | undefined;\n\n\t\tconst options: EmitterOptions | undefined = {\n\t\t\tleakWarningThreshold,\n\t\t\tonWillAddFirstListener() {\n\t\t\t\tsubscription = event(cur => {\n\t\t\t\t\tnumDebouncedCalls++;\n\t\t\t\t\toutput = merge(output, cur);\n\n\t\t\t\t\tif (leading && !handle) {\n\t\t\t\t\t\temitter.fire(output);\n\t\t\t\t\t\toutput = undefined;\n\t\t\t\t\t}\n\n\t\t\t\t\tdoFire = () => {\n\t\t\t\t\t\tconst _output = output;\n\t\t\t\t\t\toutput = undefined;\n\t\t\t\t\t\thandle = undefined;\n\t\t\t\t\t\tif (!leading || numDebouncedCalls > 1) {\n\t\t\t\t\t\t\temitter.fire(_output!);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tnumDebouncedCalls = 0;\n\t\t\t\t\t};\n\n\t\t\t\t\tif (typeof delay === 'number') {\n\t\t\t\t\t\tclearTimeout(handle);\n\t\t\t\t\t\thandle = setTimeout(doFire, delay);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (handle === undefined) {\n\t\t\t\t\t\t\thandle = 0;\n\t\t\t\t\t\t\tqueueMicrotask(doFire);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t},\n\t\t\tonWillRemoveListener() {\n\t\t\t\tif (flushOnListenerRemove && numDebouncedCalls > 0) {\n\t\t\t\t\tdoFire?.();\n\t\t\t\t}\n\t\t\t},\n\t\t\tonDidRemoveLastListener() {\n\t\t\t\tdoFire = undefined;\n\t\t\t\tsubscription.dispose();\n\t\t\t}\n\t\t};\n\n\t\tif (!disposable) {\n\t\t\t_addLeakageTraceLogic(options);\n\t\t}\n\n\t\tconst emitter = new Emitter(options);\n\n\t\tdisposable?.add(emitter);\n\n\t\treturn emitter.event;\n\t}\n\n\t/**\n\t * Debounces an event, firing after some delay (default=0) with an array of all event original objects.\n\t *\n\t * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned\n\t * event is accessible to \"third parties\", e.g the event is a public property. Otherwise a leaked listener on the\n\t * returned event causes this utility to leak a listener on the original event.\n\t */\n\texport function accumulate(event: Event, delay: number = 0, disposable?: DisposableStore): Event {\n\t\treturn Event.debounce(event, (last, e) => {\n\t\t\tif (!last) {\n\t\t\t\treturn [e];\n\t\t\t}\n\t\t\tlast.push(e);\n\t\t\treturn last;\n\t\t}, delay, undefined, true, undefined, disposable);\n\t}\n\n\t/**\n\t * Filters an event such that some condition is _not_ met more than once in a row, effectively ensuring duplicate\n\t * event objects from different sources do not fire the same event object.\n\t *\n\t * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned\n\t * event is accessible to \"third parties\", e.g the event is a public property. Otherwise a leaked listener on the\n\t * returned event causes this utility to leak a listener on the original event.\n\t *\n\t * @param event The event source for the new event.\n\t * @param equals The equality condition.\n\t * @param disposable A disposable store to add the new EventEmitter to.\n\t *\n\t * @example\n\t * ```\n\t * // Fire only one time when a single window is opened or focused\n\t * Event.latch(Event.any(onDidOpenWindow, onDidFocusWindow))\n\t * ```\n\t */\n\texport function latch(event: Event, equals: (a: T, b: T) => boolean = (a, b) => a === b, disposable?: DisposableStore): Event {\n\t\tlet firstCall = true;\n\t\tlet cache: T;\n\n\t\treturn filter(event, value => {\n\t\t\tconst shouldEmit = firstCall || !equals(value, cache);\n\t\t\tfirstCall = false;\n\t\t\tcache = value;\n\t\t\treturn shouldEmit;\n\t\t}, disposable);\n\t}\n\n\t/**\n\t * Splits an event whose parameter is a union type into 2 separate events for each type in the union.\n\t *\n\t * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned\n\t * event is accessible to \"third parties\", e.g the event is a public property. Otherwise a leaked listener on the\n\t * returned event causes this utility to leak a listener on the original event.\n\t *\n\t * @example\n\t * ```\n\t * const event = new EventEmitter().event;\n\t * const [numberEvent, undefinedEvent] = Event.split(event, isUndefined);\n\t * ```\n\t *\n\t * @param event The event source for the new event.\n\t * @param isT A function that determines what event is of the first type.\n\t * @param disposable A disposable store to add the new EventEmitter to.\n\t */\n\texport function split(event: Event, isT: (e: T | U) => e is T, disposable?: DisposableStore): [Event, Event] {\n\t\treturn [\n\t\t\tEvent.filter(event, isT, disposable),\n\t\t\tEvent.filter(event, e => !isT(e), disposable) as Event,\n\t\t];\n\t}\n\n\t/**\n\t * Buffers an event until it has a listener attached.\n\t *\n\t * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned\n\t * event is accessible to \"third parties\", e.g the event is a public property. Otherwise a leaked listener on the\n\t * returned event causes this utility to leak a listener on the original event.\n\t *\n\t * @param event The event source for the new event.\n\t * @param flushAfterTimeout Determines whether to flush the buffer after a timeout immediately or after a\n\t * `setTimeout` when the first event listener is added.\n\t * @param _buffer Internal: A source event array used for tests.\n\t *\n\t * @example\n\t * ```\n\t * // Start accumulating events, when the first listener is attached, flush\n\t * // the event after a timeout such that multiple listeners attached before\n\t * // the timeout would receive the event\n\t * this.onInstallExtension = Event.buffer(service.onInstallExtension, true);\n\t * ```\n\t */\n\texport function buffer(event: Event, flushAfterTimeout = false, _buffer: T[] = [], disposable?: DisposableStore): Event {\n\t\tlet buffer: T[] | null = _buffer.slice();\n\n\t\tlet listener: IDisposable | null = event(e => {\n\t\t\tif (buffer) {\n\t\t\t\tbuffer.push(e);\n\t\t\t} else {\n\t\t\t\temitter.fire(e);\n\t\t\t}\n\t\t});\n\n\t\tif (disposable) {\n\t\t\tdisposable.add(listener);\n\t\t}\n\n\t\tconst flush = () => {\n\t\t\tbuffer?.forEach(e => emitter.fire(e));\n\t\t\tbuffer = null;\n\t\t};\n\n\t\tconst emitter = new Emitter({\n\t\t\tonWillAddFirstListener() {\n\t\t\t\tif (!listener) {\n\t\t\t\t\tlistener = event(e => emitter.fire(e));\n\t\t\t\t\tif (disposable) {\n\t\t\t\t\t\tdisposable.add(listener);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t},\n\n\t\t\tonDidAddFirstListener() {\n\t\t\t\tif (buffer) {\n\t\t\t\t\tif (flushAfterTimeout) {\n\t\t\t\t\t\tsetTimeout(flush);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tflush();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t},\n\n\t\t\tonDidRemoveLastListener() {\n\t\t\t\tif (listener) {\n\t\t\t\t\tlistener.dispose();\n\t\t\t\t}\n\t\t\t\tlistener = null;\n\t\t\t}\n\t\t});\n\n\t\tif (disposable) {\n\t\t\tdisposable.add(emitter);\n\t\t}\n\n\t\treturn emitter.event;\n\t}\n\t/**\n\t * Wraps the event in an {@link IChainableEvent}, allowing a more functional programming style.\n\t *\n\t * @example\n\t * ```\n\t * // Normal\n\t * const onEnterPressNormal = Event.filter(\n\t * Event.map(onKeyPress.event, e => new StandardKeyboardEvent(e)),\n\t * e.keyCode === KeyCode.Enter\n\t * ).event;\n\t *\n\t * // Using chain\n\t * const onEnterPressChain = Event.chain(onKeyPress.event, $ => $\n\t * .map(e => new StandardKeyboardEvent(e))\n\t * .filter(e => e.keyCode === KeyCode.Enter)\n\t * );\n\t * ```\n\t */\n\texport function chain(event: Event, sythensize: ($: IChainableSythensis) => IChainableSythensis): Event {\n\t\tconst fn: Event = (listener, thisArgs, disposables) => {\n\t\t\tconst cs = sythensize(new ChainableSynthesis()) as ChainableSynthesis;\n\t\t\treturn event(function (value) {\n\t\t\t\tconst result = cs.evaluate(value);\n\t\t\t\tif (result !== HaltChainable) {\n\t\t\t\t\tlistener.call(thisArgs, result);\n\t\t\t\t}\n\t\t\t}, undefined, disposables);\n\t\t};\n\n\t\treturn fn;\n\t}\n\n\tconst HaltChainable = Symbol('HaltChainable');\n\n\tclass ChainableSynthesis implements IChainableSythensis {\n\t\tprivate readonly steps: ((input: any) => any)[] = [];\n\n\t\tmap(fn: (i: any) => O): this {\n\t\t\tthis.steps.push(fn);\n\t\t\treturn this;\n\t\t}\n\n\t\tforEach(fn: (i: any) => void): this {\n\t\t\tthis.steps.push(v => {\n\t\t\t\tfn(v);\n\t\t\t\treturn v;\n\t\t\t});\n\t\t\treturn this;\n\t\t}\n\n\t\tfilter(fn: (e: any) => boolean): this {\n\t\t\tthis.steps.push(v => fn(v) ? v : HaltChainable);\n\t\t\treturn this;\n\t\t}\n\n\t\treduce(merge: (last: R | undefined, event: any) => R, initial?: R | undefined): this {\n\t\t\tlet last = initial;\n\t\t\tthis.steps.push(v => {\n\t\t\t\tlast = merge(last, v);\n\t\t\t\treturn last;\n\t\t\t});\n\t\t\treturn this;\n\t\t}\n\n\t\tlatch(equals: (a: any, b: any) => boolean = (a, b) => a === b): ChainableSynthesis {\n\t\t\tlet firstCall = true;\n\t\t\tlet cache: any;\n\t\t\tthis.steps.push(value => {\n\t\t\t\tconst shouldEmit = firstCall || !equals(value, cache);\n\t\t\t\tfirstCall = false;\n\t\t\t\tcache = value;\n\t\t\t\treturn shouldEmit ? value : HaltChainable;\n\t\t\t});\n\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic evaluate(value: any) {\n\t\t\tfor (const step of this.steps) {\n\t\t\t\tvalue = step(value);\n\t\t\t\tif (value === HaltChainable) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn value;\n\t\t}\n\t}\n\n\texport interface IChainableSythensis {\n\t\tmap(fn: (i: T) => O): IChainableSythensis;\n\t\tforEach(fn: (i: T) => void): IChainableSythensis;\n\t\tfilter(fn: (e: T) => e is R): IChainableSythensis;\n\t\tfilter(fn: (e: T) => boolean): IChainableSythensis;\n\t\treduce(merge: (last: R, event: T) => R, initial: R): IChainableSythensis;\n\t\treduce(merge: (last: R | undefined, event: T) => R): IChainableSythensis;\n\t\tlatch(equals?: (a: T, b: T) => boolean): IChainableSythensis;\n\t}\n\n\texport interface NodeEventEmitter {\n\t\ton(event: string | symbol, listener: Function): unknown;\n\t\tremoveListener(event: string | symbol, listener: Function): unknown;\n\t}\n\n\t/**\n\t * Creates an {@link Event} from a node event emitter.\n\t */\n\texport function fromNodeEventEmitter(emitter: NodeEventEmitter, eventName: string, map: (...args: any[]) => T = id => id): Event {\n\t\tconst fn = (...args: any[]) => result.fire(map(...args));\n\t\tconst onFirstListenerAdd = () => emitter.on(eventName, fn);\n\t\tconst onLastListenerRemove = () => emitter.removeListener(eventName, fn);\n\t\tconst result = new Emitter({ onWillAddFirstListener: onFirstListenerAdd, onDidRemoveLastListener: onLastListenerRemove });\n\n\t\treturn result.event;\n\t}\n\n\texport interface DOMEventEmitter {\n\t\taddEventListener(event: string | symbol, listener: Function): void;\n\t\tremoveEventListener(event: string | symbol, listener: Function): void;\n\t}\n\n\t/**\n\t * Creates an {@link Event} from a DOM event emitter.\n\t */\n\texport function fromDOMEventEmitter(emitter: DOMEventEmitter, eventName: string, map: (...args: any[]) => T = id => id): Event {\n\t\tconst fn = (...args: any[]) => result.fire(map(...args));\n\t\tconst onFirstListenerAdd = () => emitter.addEventListener(eventName, fn);\n\t\tconst onLastListenerRemove = () => emitter.removeEventListener(eventName, fn);\n\t\tconst result = new Emitter({ onWillAddFirstListener: onFirstListenerAdd, onDidRemoveLastListener: onLastListenerRemove });\n\n\t\treturn result.event;\n\t}\n\n\t/**\n\t * Creates a promise out of an event, using the {@link Event.once} helper.\n\t */\n\texport function toPromise(event: Event): Promise {\n\t\treturn new Promise(resolve => once(event)(resolve));\n\t}\n\n\t/**\n\t * Creates an event out of a promise that fires once when the promise is\n\t * resolved with the result of the promise or `undefined`.\n\t */\n\texport function fromPromise(promise: Promise): Event {\n\t\tconst result = new Emitter();\n\n\t\tpromise.then(res => {\n\t\t\tresult.fire(res);\n\t\t}, () => {\n\t\t\tresult.fire(undefined);\n\t\t}).finally(() => {\n\t\t\tresult.dispose();\n\t\t});\n\n\t\treturn result.event;\n\t}\n\n\t/**\n\t * A convenience function for forwarding an event to another emitter which\n\t * improves readability.allows Event.forward(event, emitter) instead of `event(e => emitter.fire(e))`.\n\t * @param from The event to forward.\n\t * @param to The emitter to forward the event to.\n\t * @example\n\t * Event.forward(event, emitter);\n\t * // equivalent to\n\t * event(e => emitter.fire(e));\n\t * // equivalent to\n\t * event(emitter.fire, emitter);\n\t */\n\texport function forward(from: Event, to: Emitter): IDisposable {\n\t\treturn from(e => to.fire(e));\n\t}\n\n\t/**\n\t * Adds a listener to an event and calls the listener immediately with undefined as the event object.\n\t *\n\t * @example\n\t * ```\n\t * // Initialize the UI and update it when dataChangeEvent fires\n\t * runAndSubscribe(dataChangeEvent, () => this._updateUI());\n\t * ```\n\t */\n\texport function runAndSubscribe(event: Event, handler: (e: T) => any, initial: T): IDisposable;\n\texport function runAndSubscribe(event: Event, handler: (e: T | undefined) => any): IDisposable;\n\texport function runAndSubscribe(event: Event, handler: (e: T | undefined) => any, initial?: T): IDisposable {\n\t\thandler(initial);\n\t\treturn event(e => handler(e));\n\t}\n\n\tclass EmitterObserver implements IObserver {\n\n\t\treadonly emitter: Emitter;\n\n\t\tprivate _counter = 0;\n\t\tprivate _hasChanged = false;\n\n\t\tconstructor(readonly _observable: IObservable, store: DisposableStore | undefined) {\n\t\t\tconst options: EmitterOptions = {\n\t\t\t\tonWillAddFirstListener: () => {\n\t\t\t\t\t_observable.addObserver(this);\n\t\t\t\t},\n\t\t\t\tonDidRemoveLastListener: () => {\n\t\t\t\t\t_observable.removeObserver(this);\n\t\t\t\t}\n\t\t\t};\n\t\t\tif (!store) {\n\t\t\t\t_addLeakageTraceLogic(options);\n\t\t\t}\n\t\t\tthis.emitter = new Emitter(options);\n\t\t\tif (store) {\n\t\t\t\tstore.add(this.emitter);\n\t\t\t}\n\t\t}\n\n\t\tbeginUpdate(_observable: IObservable): void {\n\t\t\t// assert(_observable === this.obs);\n\t\t\tthis._counter++;\n\t\t}\n\n\t\thandlePossibleChange(_observable: IObservable): void {\n\t\t\t// assert(_observable === this.obs);\n\t\t}\n\n\t\thandleChange(_observable: IObservable, _change: TChange): void {\n\t\t\t// assert(_observable === this.obs);\n\t\t\tthis._hasChanged = true;\n\t\t}\n\n\t\tendUpdate(_observable: IObservable): void {\n\t\t\t// assert(_observable === this.obs);\n\t\t\tthis._counter--;\n\t\t\tif (this._counter === 0) {\n\t\t\t\tthis._observable.reportChanges();\n\t\t\t\tif (this._hasChanged) {\n\t\t\t\t\tthis._hasChanged = false;\n\t\t\t\t\tthis.emitter.fire(this._observable.get());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Creates an event emitter that is fired when the observable changes.\n\t * Each listeners subscribes to the emitter.\n\t */\n\texport function fromObservable(obs: IObservable, store?: DisposableStore): Event {\n\t\tconst observer = new EmitterObserver(obs, store);\n\t\treturn observer.emitter.event;\n\t}\n\n\t/**\n\t * Each listener is attached to the observable directly.\n\t */\n\texport function fromObservableLight(observable: IObservable): Event {\n\t\treturn (listener, thisArgs, disposables) => {\n\t\t\tlet count = 0;\n\t\t\tlet didChange = false;\n\t\t\tconst observer: IObserver = {\n\t\t\t\tbeginUpdate() {\n\t\t\t\t\tcount++;\n\t\t\t\t},\n\t\t\t\tendUpdate() {\n\t\t\t\t\tcount--;\n\t\t\t\t\tif (count === 0) {\n\t\t\t\t\t\tobservable.reportChanges();\n\t\t\t\t\t\tif (didChange) {\n\t\t\t\t\t\t\tdidChange = false;\n\t\t\t\t\t\t\tlistener.call(thisArgs);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\thandlePossibleChange() {\n\t\t\t\t\t// noop\n\t\t\t\t},\n\t\t\t\thandleChange() {\n\t\t\t\t\tdidChange = true;\n\t\t\t\t}\n\t\t\t};\n\t\t\tobservable.addObserver(observer);\n\t\t\tobservable.reportChanges();\n\t\t\tconst disposable = {\n\t\t\t\tdispose() {\n\t\t\t\t\tobservable.removeObserver(observer);\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tif (disposables instanceof DisposableStore) {\n\t\t\t\tdisposables.add(disposable);\n\t\t\t} else if (Array.isArray(disposables)) {\n\t\t\t\tdisposables.push(disposable);\n\t\t\t}\n\n\t\t\treturn disposable;\n\t\t};\n\t}\n}\n\nexport interface EmitterOptions {\n\t/**\n\t * Optional function that's called *before* the very first listener is added\n\t */\n\tonWillAddFirstListener?: Function;\n\t/**\n\t * Optional function that's called *after* the very first listener is added\n\t */\n\tonDidAddFirstListener?: Function;\n\t/**\n\t * Optional function that's called after a listener is added\n\t */\n\tonDidAddListener?: Function;\n\t/**\n\t * Optional function that's called *after* remove the very last listener\n\t */\n\tonDidRemoveLastListener?: Function;\n\t/**\n\t * Optional function that's called *before* a listener is removed\n\t */\n\tonWillRemoveListener?: Function;\n\t/**\n\t * Optional function that's called when a listener throws an error. Defaults to\n\t * {@link onUnexpectedError}\n\t */\n\tonListenerError?: (e: any) => void;\n\t/**\n\t * Number of listeners that are allowed before assuming a leak. Default to\n\t * a globally configured value\n\t *\n\t * @see setGlobalLeakWarningThreshold\n\t */\n\tleakWarningThreshold?: number;\n\t/**\n\t * Pass in a delivery queue, which is useful for ensuring\n\t * in order event delivery across multiple emitters.\n\t */\n\tdeliveryQueue?: EventDeliveryQueue;\n\n\t/** ONLY enable this during development */\n\t_profName?: string;\n}\n\n\nexport class EventProfiling {\n\n\tstatic readonly all = new Set();\n\n\tprivate static _idPool = 0;\n\n\treadonly name: string;\n\tpublic listenerCount: number = 0;\n\tpublic invocationCount = 0;\n\tpublic elapsedOverall = 0;\n\tpublic durations: number[] = [];\n\n\tprivate _stopWatch?: StopWatch;\n\n\tconstructor(name: string) {\n\t\tthis.name = `${name}_${EventProfiling._idPool++}`;\n\t\tEventProfiling.all.add(this);\n\t}\n\n\tstart(listenerCount: number): void {\n\t\tthis._stopWatch = new StopWatch();\n\t\tthis.listenerCount = listenerCount;\n\t}\n\n\tstop(): void {\n\t\tif (this._stopWatch) {\n\t\t\tconst elapsed = this._stopWatch.elapsed();\n\t\t\tthis.durations.push(elapsed);\n\t\t\tthis.elapsedOverall += elapsed;\n\t\t\tthis.invocationCount += 1;\n\t\t\tthis._stopWatch = undefined;\n\t\t}\n\t}\n}\n\nlet _globalLeakWarningThreshold = -1;\nexport function setGlobalLeakWarningThreshold(n: number): IDisposable {\n\tconst oldValue = _globalLeakWarningThreshold;\n\t_globalLeakWarningThreshold = n;\n\treturn {\n\t\tdispose() {\n\t\t\t_globalLeakWarningThreshold = oldValue;\n\t\t}\n\t};\n}\n\nclass LeakageMonitor {\n\n\tprivate static _idPool = 1;\n\n\tprivate _stacks: Map | undefined;\n\tprivate _warnCountdown: number = 0;\n\n\tconstructor(\n\t\tprivate readonly _errorHandler: (err: Error) => void,\n\t\treadonly threshold: number,\n\t\treadonly name: string = (LeakageMonitor._idPool++).toString(16).padStart(3, '0')\n\t) { }\n\n\tdispose(): void {\n\t\tthis._stacks?.clear();\n\t}\n\n\tcheck(stack: Stacktrace, listenerCount: number): undefined | (() => void) {\n\n\t\tconst threshold = this.threshold;\n\t\tif (threshold <= 0 || listenerCount < threshold) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tif (!this._stacks) {\n\t\t\tthis._stacks = new Map();\n\t\t}\n\t\tconst count = (this._stacks.get(stack.value) || 0);\n\t\tthis._stacks.set(stack.value, count + 1);\n\t\tthis._warnCountdown -= 1;\n\n\t\tif (this._warnCountdown <= 0) {\n\t\t\t// only warn on first exceed and then every time the limit\n\t\t\t// is exceeded by 50% again\n\t\t\tthis._warnCountdown = threshold * 0.5;\n\n\t\t\tconst [topStack, topCount] = this.getMostFrequentStack()!;\n\t\t\tconst message = `[${this.name}] potential listener LEAK detected, having ${listenerCount} listeners already. MOST frequent listener (${topCount}):`;\n\t\t\tconsole.warn(message);\n\t\t\tconsole.warn(topStack!);\n\n\t\t\tconst error = new ListenerLeakError(message, topStack);\n\t\t\tthis._errorHandler(error);\n\t\t}\n\n\t\treturn () => {\n\t\t\tconst count = (this._stacks!.get(stack.value) || 0);\n\t\t\tthis._stacks!.set(stack.value, count - 1);\n\t\t};\n\t}\n\n\tgetMostFrequentStack(): [string, number] | undefined {\n\t\tif (!this._stacks) {\n\t\t\treturn undefined;\n\t\t}\n\t\tlet topStack: [string, number] | undefined;\n\t\tlet topCount: number = 0;\n\t\tfor (const [stack, count] of this._stacks) {\n\t\t\tif (!topStack || topCount < count) {\n\t\t\t\ttopStack = [stack, count];\n\t\t\t\ttopCount = count;\n\t\t\t}\n\t\t}\n\t\treturn topStack;\n\t}\n}\n\nclass Stacktrace {\n\n\tstatic create() {\n\t\tconst err = new Error();\n\t\treturn new Stacktrace(err.stack ?? '');\n\t}\n\n\tprivate constructor(readonly value: string) { }\n\n\tprint() {\n\t\tconsole.warn(this.value.split('\\n').slice(2).join('\\n'));\n\t}\n}\n\n// error that is logged when going over the configured listener threshold\nexport class ListenerLeakError extends Error {\n\tconstructor(message: string, stack: string) {\n\t\tsuper(message);\n\t\tthis.name = 'ListenerLeakError';\n\t\tthis.stack = stack;\n\t}\n}\n\n// SEVERE error that is logged when having gone way over the configured listener\n// threshold so that the emitter refuses to accept more listeners\nexport class ListenerRefusalError extends Error {\n\tconstructor(message: string, stack: string) {\n\t\tsuper(message);\n\t\tthis.name = 'ListenerRefusalError';\n\t\tthis.stack = stack;\n\t}\n}\n\nlet id = 0;\nclass UniqueContainer {\n\tstack?: Stacktrace;\n\tpublic id = id++;\n\tconstructor(public readonly value: T) { }\n}\nconst compactionThreshold = 2;\n\ntype ListenerContainer = UniqueContainer<(data: T) => void>;\ntype ListenerOrListeners = (ListenerContainer | undefined)[] | ListenerContainer;\n\nconst forEachListener = (listeners: ListenerOrListeners, fn: (c: ListenerContainer) => void) => {\n\tif (listeners instanceof UniqueContainer) {\n\t\tfn(listeners);\n\t} else {\n\t\tfor (let i = 0; i < listeners.length; i++) {\n\t\t\tconst l = listeners[i];\n\t\t\tif (l) {\n\t\t\t\tfn(l);\n\t\t\t}\n\t\t}\n\t}\n};\n\n\nlet _listenerFinalizers: FinalizationRegistry | undefined;\n\nif (_enableListenerGCedWarning) {\n\tconst leaks: string[] = [];\n\n\tsetInterval(() => {\n\t\tif (leaks.length === 0) {\n\t\t\treturn;\n\t\t}\n\t\tconsole.warn('[LEAKING LISTENERS] GC\\'ed these listeners that were NOT yet disposed:');\n\t\tconsole.warn(leaks.join('\\n'));\n\t\tleaks.length = 0;\n\t}, 3000);\n\n\t_listenerFinalizers = new FinalizationRegistry(heldValue => {\n\t\tif (typeof heldValue === 'string') {\n\t\t\tleaks.push(heldValue);\n\t\t}\n\t});\n}\n\n/**\n * The Emitter can be used to expose an Event to the public\n * to fire it from the insides.\n * Sample:\n\tclass Document {\n\n\t\tprivate readonly _onDidChange = new Emitter<(value:string)=>any>();\n\n\t\tpublic onDidChange = this._onDidChange.event;\n\n\t\t// getter-style\n\t\t// get onDidChange(): Event<(value:string)=>any> {\n\t\t// \treturn this._onDidChange.event;\n\t\t// }\n\n\t\tprivate _doIt() {\n\t\t\t//...\n\t\t\tthis._onDidChange.fire(value);\n\t\t}\n\t}\n */\nexport class Emitter {\n\n\tprivate readonly _options?: EmitterOptions;\n\tprivate readonly _leakageMon?: LeakageMonitor;\n\tprivate readonly _perfMon?: EventProfiling;\n\tprivate _disposed?: true;\n\tprivate _event?: Event;\n\n\t/**\n\t * A listener, or list of listeners. A single listener is the most common\n\t * for event emitters (#185789), so we optimize that special case to avoid\n\t * wrapping it in an array (just like Node.js itself.)\n\t *\n\t * A list of listeners never 'downgrades' back to a plain function if\n\t * listeners are removed, for two reasons:\n\t *\n\t * 1. That's complicated (especially with the deliveryQueue)\n\t * 2. A listener with >1 listener is likely to have >1 listener again at\n\t * some point, and swapping between arrays and functions may[citation needed]\n\t * introduce unnecessary work and garbage.\n\t *\n\t * The array listeners can be 'sparse', to avoid reallocating the array\n\t * whenever any listener is added or removed. If more than `1 / compactionThreshold`\n\t * of the array is empty, only then is it resized.\n\t */\n\tprotected _listeners?: ListenerOrListeners;\n\n\t/**\n\t * Always to be defined if _listeners is an array. It's no longer a true\n\t * queue, but holds the dispatching 'state'. If `fire()` is called on an\n\t * emitter, any work left in the _deliveryQueue is finished first.\n\t */\n\tprivate _deliveryQueue?: EventDeliveryQueuePrivate;\n\tprotected _size = 0;\n\n\tconstructor(options?: EmitterOptions) {\n\t\tthis._options = options;\n\t\tthis._leakageMon = (_globalLeakWarningThreshold > 0 || this._options?.leakWarningThreshold)\n\t\t\t? new LeakageMonitor(options?.onListenerError ?? onUnexpectedError, this._options?.leakWarningThreshold ?? _globalLeakWarningThreshold) :\n\t\t\tundefined;\n\t\tthis._perfMon = this._options?._profName ? new EventProfiling(this._options._profName) : undefined;\n\t\tthis._deliveryQueue = this._options?.deliveryQueue as EventDeliveryQueuePrivate | undefined;\n\t}\n\n\tdispose() {\n\t\tif (!this._disposed) {\n\t\t\tthis._disposed = true;\n\n\t\t\t// It is bad to have listeners at the time of disposing an emitter, it is worst to have listeners keep the emitter\n\t\t\t// alive via the reference that's embedded in their disposables. Therefore we loop over all remaining listeners and\n\t\t\t// unset their subscriptions/disposables. Looping and blaming remaining listeners is done on next tick because the\n\t\t\t// the following programming pattern is very popular:\n\t\t\t//\n\t\t\t// const someModel = this._disposables.add(new ModelObject()); // (1) create and register model\n\t\t\t// this._disposables.add(someModel.onDidChange(() => { ... }); // (2) subscribe and register model-event listener\n\t\t\t// ...later...\n\t\t\t// this._disposables.dispose(); disposes (1) then (2): don't warn after (1) but after the \"overall dispose\" is done\n\n\t\t\tif (this._deliveryQueue?.current === this) {\n\t\t\t\tthis._deliveryQueue.reset();\n\t\t\t}\n\t\t\tif (this._listeners) {\n\t\t\t\tif (_enableDisposeWithListenerWarning) {\n\t\t\t\t\tconst listeners = this._listeners;\n\t\t\t\t\tqueueMicrotask(() => {\n\t\t\t\t\t\tforEachListener(listeners, l => l.stack?.print());\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tthis._listeners = undefined;\n\t\t\t\tthis._size = 0;\n\t\t\t}\n\t\t\tthis._options?.onDidRemoveLastListener?.();\n\t\t\tthis._leakageMon?.dispose();\n\t\t}\n\t}\n\n\t/**\n\t * For the public to allow to subscribe\n\t * to events from this Emitter\n\t */\n\tget event(): Event {\n\t\tthis._event ??= (callback: (e: T) => any, thisArgs?: any, disposables?: IDisposable[] | DisposableStore) => {\n\t\t\tif (this._leakageMon && this._size > this._leakageMon.threshold ** 2) {\n\t\t\t\tconst message = `[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;\n\t\t\t\tconsole.warn(message);\n\n\t\t\t\tconst tuple = this._leakageMon.getMostFrequentStack() ?? ['UNKNOWN stack', -1];\n\t\t\t\tconst error = new ListenerRefusalError(`${message}. HINT: Stack shows most frequent listener (${tuple[1]}-times)`, tuple[0]);\n\t\t\t\tconst errorHandler = this._options?.onListenerError || onUnexpectedError;\n\t\t\t\terrorHandler(error);\n\n\t\t\t\treturn Disposable.None;\n\t\t\t}\n\n\t\t\tif (this._disposed) {\n\t\t\t\t// todo: should we warn if a listener is added to a disposed emitter? This happens often\n\t\t\t\treturn Disposable.None;\n\t\t\t}\n\n\t\t\tif (thisArgs) {\n\t\t\t\tcallback = callback.bind(thisArgs);\n\t\t\t}\n\n\t\t\tconst contained = new UniqueContainer(callback);\n\n\t\t\tlet removeMonitor: Function | undefined;\n\t\t\tlet stack: Stacktrace | undefined;\n\t\t\tif (this._leakageMon && this._size >= Math.ceil(this._leakageMon.threshold * 0.2)) {\n\t\t\t\t// check and record this emitter for potential leakage\n\t\t\t\tcontained.stack = Stacktrace.create();\n\t\t\t\tremoveMonitor = this._leakageMon.check(contained.stack, this._size + 1);\n\t\t\t}\n\n\t\t\tif (_enableDisposeWithListenerWarning) {\n\t\t\t\tcontained.stack = stack ?? Stacktrace.create();\n\t\t\t}\n\n\t\t\tif (!this._listeners) {\n\t\t\t\tthis._options?.onWillAddFirstListener?.(this);\n\t\t\t\tthis._listeners = contained;\n\t\t\t\tthis._options?.onDidAddFirstListener?.(this);\n\t\t\t} else if (this._listeners instanceof UniqueContainer) {\n\t\t\t\tthis._deliveryQueue ??= new EventDeliveryQueuePrivate();\n\t\t\t\tthis._listeners = [this._listeners, contained];\n\t\t\t} else {\n\t\t\t\tthis._listeners.push(contained);\n\t\t\t}\n\n\t\t\tthis._size++;\n\n\n\t\t\tconst result = toDisposable(() => {\n\t\t\t\t_listenerFinalizers?.unregister(result);\n\t\t\t\tremoveMonitor?.();\n\t\t\t\tthis._removeListener(contained);\n\t\t\t});\n\t\t\tif (disposables instanceof DisposableStore) {\n\t\t\t\tdisposables.add(result);\n\t\t\t} else if (Array.isArray(disposables)) {\n\t\t\t\tdisposables.push(result);\n\t\t\t}\n\n\t\t\tif (_listenerFinalizers) {\n\t\t\t\tconst stack = new Error().stack!.split('\\n').slice(2, 3).join('\\n').trim();\n\t\t\t\tconst match = /(file:|vscode-file:\\/\\/vscode-app)?(\\/[^:]*:\\d+:\\d+)/.exec(stack);\n\t\t\t\t_listenerFinalizers.register(result, match?.[2] ?? stack, result);\n\t\t\t}\n\n\t\t\treturn result;\n\t\t};\n\n\t\treturn this._event;\n\t}\n\n\tprivate _removeListener(listener: ListenerContainer) {\n\t\tthis._options?.onWillRemoveListener?.(this);\n\n\t\tif (!this._listeners) {\n\t\t\treturn; // expected if a listener gets disposed\n\t\t}\n\n\t\tif (this._size === 1) {\n\t\t\tthis._listeners = undefined;\n\t\t\tthis._options?.onDidRemoveLastListener?.(this);\n\t\t\tthis._size = 0;\n\t\t\treturn;\n\t\t}\n\n\t\t// size > 1 which requires that listeners be a list:\n\t\tconst listeners = this._listeners as (ListenerContainer | undefined)[];\n\n\t\tconst index = listeners.indexOf(listener);\n\t\tif (index === -1) {\n\t\t\tconsole.log('disposed?', this._disposed);\n\t\t\tconsole.log('size?', this._size);\n\t\t\tconsole.log('arr?', JSON.stringify(this._listeners));\n\t\t\tthrow new Error('Attempted to dispose unknown listener');\n\t\t}\n\n\t\tthis._size--;\n\t\tlisteners[index] = undefined;\n\n\t\tconst adjustDeliveryQueue = this._deliveryQueue!.current === this;\n\t\tif (this._size * compactionThreshold <= listeners.length) {\n\t\t\tlet n = 0;\n\t\t\tfor (let i = 0; i < listeners.length; i++) {\n\t\t\t\tif (listeners[i]) {\n\t\t\t\t\tlisteners[n++] = listeners[i];\n\t\t\t\t} else if (adjustDeliveryQueue) {\n\t\t\t\t\tthis._deliveryQueue!.end--;\n\t\t\t\t\tif (n < this._deliveryQueue!.i) {\n\t\t\t\t\t\tthis._deliveryQueue!.i--;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tlisteners.length = n;\n\t\t}\n\t}\n\n\tprivate _deliver(listener: undefined | UniqueContainer<(value: T) => void>, value: T) {\n\t\tif (!listener) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst errorHandler = this._options?.onListenerError || onUnexpectedError;\n\t\tif (!errorHandler) {\n\t\t\tlistener.value(value);\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\tlistener.value(value);\n\t\t} catch (e) {\n\t\t\terrorHandler(e);\n\t\t}\n\t}\n\n\t/** Delivers items in the queue. Assumes the queue is ready to go. */\n\tprivate _deliverQueue(dq: EventDeliveryQueuePrivate) {\n\t\tconst listeners = dq.current!._listeners! as (ListenerContainer | undefined)[];\n\t\twhile (dq.i < dq.end) {\n\t\t\t// important: dq.i is incremented before calling deliver() because it might reenter deliverQueue()\n\t\t\tthis._deliver(listeners[dq.i++], dq.value as T);\n\t\t}\n\t\tdq.reset();\n\t}\n\n\t/**\n\t * To be kept private to fire an event to\n\t * subscribers\n\t */\n\tfire(event: T): void {\n\t\tif (this._deliveryQueue?.current) {\n\t\t\tthis._deliverQueue(this._deliveryQueue);\n\t\t\tthis._perfMon?.stop(); // last fire() will have starting perfmon, stop it before starting the next dispatch\n\t\t}\n\n\t\tthis._perfMon?.start(this._size);\n\n\t\tif (!this._listeners) {\n\t\t\t// no-op\n\t\t} else if (this._listeners instanceof UniqueContainer) {\n\t\t\tthis._deliver(this._listeners, event);\n\t\t} else {\n\t\t\tconst dq = this._deliveryQueue!;\n\t\t\tdq.enqueue(this, event, this._listeners.length);\n\t\t\tthis._deliverQueue(dq);\n\t\t}\n\n\t\tthis._perfMon?.stop();\n\t}\n\n\thasListeners(): boolean {\n\t\treturn this._size > 0;\n\t}\n}\n\nexport interface EventDeliveryQueue {\n\t_isEventDeliveryQueue: true;\n}\n\nexport const createEventDeliveryQueue = (): EventDeliveryQueue => new EventDeliveryQueuePrivate();\n\nclass EventDeliveryQueuePrivate implements EventDeliveryQueue {\n\tdeclare _isEventDeliveryQueue: true;\n\n\t/**\n\t * Index in current's listener list.\n\t */\n\tpublic i = -1;\n\n\t/**\n\t * The last index in the listener's list to deliver.\n\t */\n\tpublic end = 0;\n\n\t/**\n\t * Emitter currently being dispatched on. Emitter._listeners is always an array.\n\t */\n\tpublic current?: Emitter;\n\t/**\n\t * Currently emitting value. Defined whenever `current` is.\n\t */\n\tpublic value?: unknown;\n\n\tpublic enqueue(emitter: Emitter, value: T, end: number) {\n\t\tthis.i = 0;\n\t\tthis.end = end;\n\t\tthis.current = emitter;\n\t\tthis.value = value;\n\t}\n\n\tpublic reset() {\n\t\tthis.i = this.end; // force any current emission loop to stop, mainly for during dispose\n\t\tthis.current = undefined;\n\t\tthis.value = undefined;\n\t}\n}\n\nexport interface IWaitUntil {\n\ttoken: CancellationToken;\n\twaitUntil(thenable: Promise): void;\n}\n\nexport type IWaitUntilData = Omit, 'token'>;\n\nexport class AsyncEmitter extends Emitter {\n\n\tprivate _asyncDeliveryQueue?: LinkedList<[(ev: T) => void, IWaitUntilData]>;\n\n\tasync fireAsync(data: IWaitUntilData, token: CancellationToken, promiseJoin?: (p: Promise, listener: Function) => Promise): Promise {\n\t\tif (!this._listeners) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (!this._asyncDeliveryQueue) {\n\t\t\tthis._asyncDeliveryQueue = new LinkedList();\n\t\t}\n\n\t\tforEachListener(this._listeners, listener => this._asyncDeliveryQueue!.push([listener.value, data]));\n\n\t\twhile (this._asyncDeliveryQueue.size > 0 && !token.isCancellationRequested) {\n\n\t\t\tconst [listener, data] = this._asyncDeliveryQueue.shift()!;\n\t\t\tconst thenables: Promise[] = [];\n\n\t\t\tconst event = {\n\t\t\t\t...data,\n\t\t\t\ttoken,\n\t\t\t\twaitUntil: (p: Promise): void => {\n\t\t\t\t\tif (Object.isFrozen(thenables)) {\n\t\t\t\t\t\tthrow new Error('waitUntil can NOT be called asynchronous');\n\t\t\t\t\t}\n\t\t\t\t\tif (promiseJoin) {\n\t\t\t\t\t\tp = promiseJoin(p, listener);\n\t\t\t\t\t}\n\t\t\t\t\tthenables.push(p);\n\t\t\t\t}\n\t\t\t};\n\n\t\t\ttry {\n\t\t\t\tlistener(event);\n\t\t\t} catch (e) {\n\t\t\t\tonUnexpectedError(e);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// freeze thenables-collection to enforce sync-calls to\n\t\t\t// wait until and then wait for all thenables to resolve\n\t\t\tObject.freeze(thenables);\n\n\t\t\tawait Promise.allSettled(thenables).then(values => {\n\t\t\t\tfor (const value of values) {\n\t\t\t\t\tif (value.status === 'rejected') {\n\t\t\t\t\t\tonUnexpectedError(value.reason);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t}\n}\n\n\nexport class PauseableEmitter extends Emitter {\n\n\tprivate _isPaused = 0;\n\tprotected _eventQueue = new LinkedList();\n\tprivate _mergeFn?: (input: T[]) => T;\n\n\tpublic get isPaused(): boolean {\n\t\treturn this._isPaused !== 0;\n\t}\n\n\tconstructor(options?: EmitterOptions & { merge?: (input: T[]) => T }) {\n\t\tsuper(options);\n\t\tthis._mergeFn = options?.merge;\n\t}\n\n\tpause(): void {\n\t\tthis._isPaused++;\n\t}\n\n\tresume(): void {\n\t\tif (this._isPaused !== 0 && --this._isPaused === 0) {\n\t\t\tif (this._mergeFn) {\n\t\t\t\t// use the merge function to create a single composite\n\t\t\t\t// event. make a copy in case firing pauses this emitter\n\t\t\t\tif (this._eventQueue.size > 0) {\n\t\t\t\t\tconst events = Array.from(this._eventQueue);\n\t\t\t\t\tthis._eventQueue.clear();\n\t\t\t\t\tsuper.fire(this._mergeFn(events));\n\t\t\t\t}\n\n\t\t\t} else {\n\t\t\t\t// no merging, fire each event individually and test\n\t\t\t\t// that this emitter isn't paused halfway through\n\t\t\t\twhile (!this._isPaused && this._eventQueue.size !== 0) {\n\t\t\t\t\tsuper.fire(this._eventQueue.shift()!);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\toverride fire(event: T): void {\n\t\tif (this._size) {\n\t\t\tif (this._isPaused !== 0) {\n\t\t\t\tthis._eventQueue.push(event);\n\t\t\t} else {\n\t\t\t\tsuper.fire(event);\n\t\t\t}\n\t\t}\n\t}\n}\n\nexport class DebounceEmitter extends PauseableEmitter {\n\n\tprivate readonly _delay: number;\n\tprivate _handle: any | undefined;\n\n\tconstructor(options: EmitterOptions & { merge: (input: T[]) => T; delay?: number }) {\n\t\tsuper(options);\n\t\tthis._delay = options.delay ?? 100;\n\t}\n\n\toverride fire(event: T): void {\n\t\tif (!this._handle) {\n\t\t\tthis.pause();\n\t\t\tthis._handle = setTimeout(() => {\n\t\t\t\tthis._handle = undefined;\n\t\t\t\tthis.resume();\n\t\t\t}, this._delay);\n\t\t}\n\t\tsuper.fire(event);\n\t}\n}\n\n/**\n * An emitter which queue all events and then process them at the\n * end of the event loop.\n */\nexport class MicrotaskEmitter extends Emitter {\n\tprivate _queuedEvents: T[] = [];\n\tprivate _mergeFn?: (input: T[]) => T;\n\n\tconstructor(options?: EmitterOptions & { merge?: (input: T[]) => T }) {\n\t\tsuper(options);\n\t\tthis._mergeFn = options?.merge;\n\t}\n\toverride fire(event: T): void {\n\n\t\tif (!this.hasListeners()) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis._queuedEvents.push(event);\n\t\tif (this._queuedEvents.length === 1) {\n\t\t\tqueueMicrotask(() => {\n\t\t\t\tif (this._mergeFn) {\n\t\t\t\t\tsuper.fire(this._mergeFn(this._queuedEvents));\n\t\t\t\t} else {\n\t\t\t\t\tthis._queuedEvents.forEach(e => super.fire(e));\n\t\t\t\t}\n\t\t\t\tthis._queuedEvents = [];\n\t\t\t});\n\t\t}\n\t}\n}\n\n/**\n * An event emitter that multiplexes many events into a single event.\n *\n * @example Listen to the `onData` event of all `Thing`s, dynamically adding and removing `Thing`s\n * to the multiplexer as needed.\n *\n * ```typescript\n * const anythingDataMultiplexer = new EventMultiplexer<{ data: string }>();\n *\n * const thingListeners = DisposableMap();\n *\n * thingService.onDidAddThing(thing => {\n * thingListeners.set(thing, anythingDataMultiplexer.add(thing.onData);\n * });\n * thingService.onDidRemoveThing(thing => {\n * thingListeners.deleteAndDispose(thing);\n * });\n *\n * anythingDataMultiplexer.event(e => {\n * console.log('Something fired data ' + e.data)\n * });\n * ```\n */\nexport class EventMultiplexer implements IDisposable {\n\n\tprivate readonly emitter: Emitter;\n\tprivate hasListeners = false;\n\tprivate events: { event: Event; listener: IDisposable | null }[] = [];\n\n\tconstructor() {\n\t\tthis.emitter = new Emitter({\n\t\t\tonWillAddFirstListener: () => this.onFirstListenerAdd(),\n\t\t\tonDidRemoveLastListener: () => this.onLastListenerRemove()\n\t\t});\n\t}\n\n\tget event(): Event {\n\t\treturn this.emitter.event;\n\t}\n\n\tadd(event: Event): IDisposable {\n\t\tconst e = { event: event, listener: null };\n\t\tthis.events.push(e);\n\n\t\tif (this.hasListeners) {\n\t\t\tthis.hook(e);\n\t\t}\n\n\t\tconst dispose = () => {\n\t\t\tif (this.hasListeners) {\n\t\t\t\tthis.unhook(e);\n\t\t\t}\n\n\t\t\tconst idx = this.events.indexOf(e);\n\t\t\tthis.events.splice(idx, 1);\n\t\t};\n\n\t\treturn toDisposable(createSingleCallFunction(dispose));\n\t}\n\n\tprivate onFirstListenerAdd(): void {\n\t\tthis.hasListeners = true;\n\t\tthis.events.forEach(e => this.hook(e));\n\t}\n\n\tprivate onLastListenerRemove(): void {\n\t\tthis.hasListeners = false;\n\t\tthis.events.forEach(e => this.unhook(e));\n\t}\n\n\tprivate hook(e: { event: Event; listener: IDisposable | null }): void {\n\t\te.listener = e.event(r => this.emitter.fire(r));\n\t}\n\n\tprivate unhook(e: { event: Event; listener: IDisposable | null }): void {\n\t\te.listener?.dispose();\n\t\te.listener = null;\n\t}\n\n\tdispose(): void {\n\t\tthis.emitter.dispose();\n\n\t\tfor (const e of this.events) {\n\t\t\te.listener?.dispose();\n\t\t}\n\t\tthis.events = [];\n\t}\n}\n\nexport interface IDynamicListEventMultiplexer extends IDisposable {\n\treadonly event: Event;\n}\nexport class DynamicListEventMultiplexer implements IDynamicListEventMultiplexer {\n\tprivate readonly _store = new DisposableStore();\n\n\treadonly event: Event;\n\n\tconstructor(\n\t\titems: TItem[],\n\t\tonAddItem: Event,\n\t\tonRemoveItem: Event,\n\t\tgetEvent: (item: TItem) => Event\n\t) {\n\t\tconst multiplexer = this._store.add(new EventMultiplexer());\n\t\tconst itemListeners = this._store.add(new DisposableMap());\n\n\t\tfunction addItem(instance: TItem) {\n\t\t\titemListeners.set(instance, multiplexer.add(getEvent(instance)));\n\t\t}\n\n\t\t// Existing items\n\t\tfor (const instance of items) {\n\t\t\taddItem(instance);\n\t\t}\n\n\t\t// Added items\n\t\tthis._store.add(onAddItem(instance => {\n\t\t\taddItem(instance);\n\t\t}));\n\n\t\t// Removed items\n\t\tthis._store.add(onRemoveItem(instance => {\n\t\t\titemListeners.deleteAndDispose(instance);\n\t\t}));\n\n\t\tthis.event = multiplexer.event;\n\t}\n\n\tdispose() {\n\t\tthis._store.dispose();\n\t}\n}\n\n/**\n * The EventBufferer is useful in situations in which you want\n * to delay firing your events during some code.\n * You can wrap that code and be sure that the event will not\n * be fired during that wrap.\n *\n * ```\n * const emitter: Emitter;\n * const delayer = new EventDelayer();\n * const delayedEvent = delayer.wrapEvent(emitter.event);\n *\n * delayedEvent(console.log);\n *\n * delayer.bufferEvents(() => {\n * emitter.fire(); // event will not be fired yet\n * });\n *\n * // event will only be fired at this point\n * ```\n */\nexport class EventBufferer {\n\n\tprivate data: { buffers: Function[] }[] = [];\n\n\twrapEvent(event: Event): Event;\n\twrapEvent(event: Event, reduce: (last: T | undefined, event: T) => T): Event;\n\twrapEvent(event: Event, reduce: (last: O | undefined, event: T) => O, initial: O): Event;\n\twrapEvent(event: Event, reduce?: (last: T | O | undefined, event: T) => T | O, initial?: O): Event {\n\t\treturn (listener, thisArgs?, disposables?) => {\n\t\t\treturn event(i => {\n\t\t\t\tconst data = this.data[this.data.length - 1];\n\n\t\t\t\t// Non-reduce scenario\n\t\t\t\tif (!reduce) {\n\t\t\t\t\t// Buffering case\n\t\t\t\t\tif (data) {\n\t\t\t\t\t\tdata.buffers.push(() => listener.call(thisArgs, i));\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Not buffering case\n\t\t\t\t\t\tlistener.call(thisArgs, i);\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// Reduce scenario\n\t\t\t\tconst reduceData = data as typeof data & {\n\t\t\t\t\t/**\n\t\t\t\t\t * The accumulated items that will be reduced.\n\t\t\t\t\t */\n\t\t\t\t\titems?: T[];\n\t\t\t\t\t/**\n\t\t\t\t\t * The reduced result cached to be shared with other listeners.\n\t\t\t\t\t */\n\t\t\t\t\treducedResult?: T | O;\n\t\t\t\t};\n\n\t\t\t\t// Not buffering case\n\t\t\t\tif (!reduceData) {\n\t\t\t\t\t// TODO: Is there a way to cache this reduce call for all listeners?\n\t\t\t\t\tlistener.call(thisArgs, reduce(initial, i));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// Buffering case\n\t\t\t\treduceData.items ??= [];\n\t\t\t\treduceData.items.push(i);\n\t\t\t\tif (reduceData.buffers.length === 0) {\n\t\t\t\t\t// Include a single buffered function that will reduce all events when we're done buffering events\n\t\t\t\t\tdata.buffers.push(() => {\n\t\t\t\t\t\t// cache the reduced result so that the value can be shared across all listeners\n\t\t\t\t\t\treduceData.reducedResult ??= initial\n\t\t\t\t\t\t\t? reduceData.items!.reduce(reduce as (last: O | undefined, event: T) => O, initial)\n\t\t\t\t\t\t\t: reduceData.items!.reduce(reduce as (last: T | undefined, event: T) => T);\n\t\t\t\t\t\tlistener.call(thisArgs, reduceData.reducedResult);\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}, undefined, disposables);\n\t\t};\n\t}\n\n\tbufferEvents(fn: () => R): R {\n\t\tconst data = { buffers: new Array() };\n\t\tthis.data.push(data);\n\t\tconst r = fn();\n\t\tthis.data.pop();\n\t\tdata.buffers.forEach(flush => flush());\n\t\treturn r;\n\t}\n}\n\n/**\n * A Relay is an event forwarder which functions as a replugabble event pipe.\n * Once created, you can connect an input event to it and it will simply forward\n * events from that input event through its own `event` property. The `input`\n * can be changed at any point in time.\n */\nexport class Relay implements IDisposable {\n\n\tprivate listening = false;\n\tprivate inputEvent: Event = Event.None;\n\tprivate inputEventListener: IDisposable = Disposable.None;\n\n\tprivate readonly emitter = new Emitter({\n\t\tonDidAddFirstListener: () => {\n\t\t\tthis.listening = true;\n\t\t\tthis.inputEventListener = this.inputEvent(this.emitter.fire, this.emitter);\n\t\t},\n\t\tonDidRemoveLastListener: () => {\n\t\t\tthis.listening = false;\n\t\t\tthis.inputEventListener.dispose();\n\t\t}\n\t});\n\n\treadonly event: Event = this.emitter.event;\n\n\tset input(event: Event) {\n\t\tthis.inputEvent = event;\n\n\t\tif (this.listening) {\n\t\t\tthis.inputEventListener.dispose();\n\t\t\tthis.inputEventListener = event(this.emitter.fire, this.emitter);\n\t\t}\n\t}\n\n\tdispose() {\n\t\tthis.inputEventListener.dispose();\n\t\tthis.emitter.dispose();\n\t}\n}\n\nexport interface IValueWithChangeEvent {\n\treadonly onDidChange: Event;\n\tget value(): T;\n}\n\nexport class ValueWithChangeEvent implements IValueWithChangeEvent {\n\tpublic static const(value: T): IValueWithChangeEvent {\n\t\treturn new ConstValueWithChangeEvent(value);\n\t}\n\n\tprivate readonly _onDidChange = new Emitter();\n\treadonly onDidChange: Event = this._onDidChange.event;\n\n\tconstructor(private _value: T) { }\n\n\tget value(): T {\n\t\treturn this._value;\n\t}\n\n\tset value(value: T) {\n\t\tif (value !== this._value) {\n\t\t\tthis._value = value;\n\t\t\tthis._onDidChange.fire(undefined);\n\t\t}\n\t}\n}\n\nclass ConstValueWithChangeEvent implements IValueWithChangeEvent {\n\tpublic readonly onDidChange: Event = Event.None;\n\n\tconstructor(readonly value: T) { }\n}\n", "/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\nimport { CodeWindow, mainWindow } from 'vs/base/browser/window';\nimport { Emitter } from 'vs/base/common/event';\n\nclass WindowManager {\n\n\tstatic readonly INSTANCE = new WindowManager();\n\n\t// --- Zoom Level\n\n\tprivate readonly mapWindowIdToZoomLevel = new Map();\n\n\tprivate readonly _onDidChangeZoomLevel = new Emitter();\n\treadonly onDidChangeZoomLevel = this._onDidChangeZoomLevel.event;\n\n\tgetZoomLevel(targetWindow: Window): number {\n\t\treturn this.mapWindowIdToZoomLevel.get(this.getWindowId(targetWindow)) ?? 0;\n\t}\n\tsetZoomLevel(zoomLevel: number, targetWindow: Window): void {\n\t\tif (this.getZoomLevel(targetWindow) === zoomLevel) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst targetWindowId = this.getWindowId(targetWindow);\n\t\tthis.mapWindowIdToZoomLevel.set(targetWindowId, zoomLevel);\n\t\tthis._onDidChangeZoomLevel.fire(targetWindowId);\n\t}\n\n\t// --- Zoom Factor\n\n\tprivate readonly mapWindowIdToZoomFactor = new Map();\n\n\tgetZoomFactor(targetWindow: Window): number {\n\t\treturn this.mapWindowIdToZoomFactor.get(this.getWindowId(targetWindow)) ?? 1;\n\t}\n\tsetZoomFactor(zoomFactor: number, targetWindow: Window): void {\n\t\tthis.mapWindowIdToZoomFactor.set(this.getWindowId(targetWindow), zoomFactor);\n\t}\n\n\t// --- Fullscreen\n\n\tprivate readonly _onDidChangeFullscreen = new Emitter();\n\treadonly onDidChangeFullscreen = this._onDidChangeFullscreen.event;\n\n\tprivate readonly mapWindowIdToFullScreen = new Map();\n\n\tsetFullscreen(fullscreen: boolean, targetWindow: Window): void {\n\t\tif (this.isFullscreen(targetWindow) === fullscreen) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst windowId = this.getWindowId(targetWindow);\n\t\tthis.mapWindowIdToFullScreen.set(windowId, fullscreen);\n\t\tthis._onDidChangeFullscreen.fire(windowId);\n\t}\n\tisFullscreen(targetWindow: Window): boolean {\n\t\treturn !!this.mapWindowIdToFullScreen.get(this.getWindowId(targetWindow));\n\t}\n\n\tprivate getWindowId(targetWindow: Window): number {\n\t\treturn (targetWindow as CodeWindow).vscodeWindowId;\n\t}\n}\n\nexport function addMatchMediaChangeListener(targetWindow: Window, query: string | MediaQueryList, callback: (this: MediaQueryList, ev: MediaQueryListEvent) => any): void {\n\tif (typeof query === 'string') {\n\t\tquery = targetWindow.matchMedia(query);\n\t}\n\tquery.addEventListener('change', callback);\n}\n\n/** A zoom index, e.g. 1, 2, 3 */\nexport function setZoomLevel(zoomLevel: number, targetWindow: Window): void {\n\tWindowManager.INSTANCE.setZoomLevel(zoomLevel, targetWindow);\n}\nexport function getZoomLevel(targetWindow: Window): number {\n\treturn WindowManager.INSTANCE.getZoomLevel(targetWindow);\n}\nexport const onDidChangeZoomLevel = WindowManager.INSTANCE.onDidChangeZoomLevel;\n\n/** The zoom scale for an index, e.g. 1, 1.2, 1.4 */\nexport function getZoomFactor(targetWindow: Window): number {\n\treturn WindowManager.INSTANCE.getZoomFactor(targetWindow);\n}\nexport function setZoomFactor(zoomFactor: number, targetWindow: Window): void {\n\tWindowManager.INSTANCE.setZoomFactor(zoomFactor, targetWindow);\n}\n\nexport function setFullscreen(fullscreen: boolean, targetWindow: Window): void {\n\tWindowManager.INSTANCE.setFullscreen(fullscreen, targetWindow);\n}\nexport function isFullscreen(targetWindow: Window): boolean {\n\treturn WindowManager.INSTANCE.isFullscreen(targetWindow);\n}\nexport const onDidChangeFullscreen = WindowManager.INSTANCE.onDidChangeFullscreen;\n\nconst userAgent = typeof navigator === 'object' ? navigator.userAgent : '';\n\nexport const isFirefox = (userAgent.indexOf('Firefox') >= 0);\nexport const isWebKit = (userAgent.indexOf('AppleWebKit') >= 0);\nexport const isChrome = (userAgent.indexOf('Chrome') >= 0);\nexport const isSafari = (!isChrome && (userAgent.indexOf('Safari') >= 0));\nexport const isWebkitWebView = (!isChrome && !isSafari && isWebKit);\nexport const isElectron = (userAgent.indexOf('Electron/') >= 0);\nexport const isAndroid = (userAgent.indexOf('Android') >= 0);\n\nlet standalone = false;\nif (typeof mainWindow.matchMedia === 'function') {\n\tconst standaloneMatchMedia = mainWindow.matchMedia('(display-mode: standalone) or (display-mode: window-controls-overlay)');\n\tconst fullScreenMatchMedia = mainWindow.matchMedia('(display-mode: fullscreen)');\n\tstandalone = standaloneMatchMedia.matches;\n\taddMatchMediaChangeListener(mainWindow, standaloneMatchMedia, ({ matches }) => {\n\t\t// entering fullscreen would change standaloneMatchMedia.matches to false\n\t\t// if standalone is true (running as PWA) and entering fullscreen, skip this change\n\t\tif (standalone && fullScreenMatchMedia.matches) {\n\t\t\treturn;\n\t\t}\n\t\t// otherwise update standalone (browser to PWA or PWA to browser)\n\t\tstandalone = matches;\n\t});\n}\nexport function isStandalone(): boolean {\n\treturn standalone;\n}\n\n// Visible means that the feature is enabled, not necessarily being rendered\n// e.g. visible is true even in fullscreen mode where the controls are hidden\n// See docs at https://developer.mozilla.org/en-US/docs/Web/API/WindowControlsOverlay/visible\nexport function isWCOEnabled(): boolean {\n\treturn (navigator as any)?.windowControlsOverlay?.visible;\n}\n\n// Returns the bounding rect of the titlebar area if it is supported and defined\n// See docs at https://developer.mozilla.org/en-US/docs/Web/API/WindowControlsOverlay/getTitlebarAreaRect\nexport function getWCOBoundingRect(): DOMRect | undefined {\n\treturn (navigator as any)?.windowControlsOverlay?.getTitlebarAreaRect();\n}\n", "/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\nimport * as nls from 'vs/nls';\n\nexport const LANGUAGE_DEFAULT = 'en';\n\nlet _isWindows = false;\nlet _isMacintosh = false;\nlet _isLinux = false;\nlet _isLinuxSnap = false;\nlet _isNative = false;\nlet _isWeb = false;\nlet _isElectron = false;\nlet _isIOS = false;\nlet _isCI = false;\nlet _isMobile = false;\nlet _locale: string | undefined = undefined;\nlet _language: string = LANGUAGE_DEFAULT;\nlet _platformLocale: string = LANGUAGE_DEFAULT;\nlet _translationsConfigFile: string | undefined = undefined;\nlet _userAgent: string | undefined = undefined;\n\nexport interface IProcessEnvironment {\n\t[key: string]: string | undefined;\n}\n\n/**\n * This interface is intentionally not identical to node.js\n * process because it also works in sandboxed environments\n * where the process object is implemented differently. We\n * define the properties here that we need for `platform`\n * to work and nothing else.\n */\nexport interface INodeProcess {\n\tplatform: string;\n\tarch: string;\n\tenv: IProcessEnvironment;\n\tversions?: {\n\t\tnode?: string;\n\t\telectron?: string;\n\t\tchrome?: string;\n\t};\n\ttype?: string;\n\tcwd: () => string;\n}\n\ndeclare const process: INodeProcess;\n\nconst $globalThis: any = globalThis;\n\nlet nodeProcess: INodeProcess | undefined = undefined;\nif (typeof $globalThis.vscode !== 'undefined' && typeof $globalThis.vscode.process !== 'undefined') {\n\t// Native environment (sandboxed)\n\tnodeProcess = $globalThis.vscode.process;\n} else if (typeof process !== 'undefined' && typeof process?.versions?.node === 'string') {\n\t// Native environment (non-sandboxed)\n\tnodeProcess = process;\n}\n\nconst isElectronProcess = typeof nodeProcess?.versions?.electron === 'string';\nconst isElectronRenderer = isElectronProcess && nodeProcess?.type === 'renderer';\n\ninterface INavigator {\n\tuserAgent: string;\n\tmaxTouchPoints?: number;\n\tlanguage: string;\n}\ndeclare const navigator: INavigator;\n\n// Native environment\nif (typeof nodeProcess === 'object') {\n\t_isWindows = (nodeProcess.platform === 'win32');\n\t_isMacintosh = (nodeProcess.platform === 'darwin');\n\t_isLinux = (nodeProcess.platform === 'linux');\n\t_isLinuxSnap = _isLinux && !!nodeProcess.env['SNAP'] && !!nodeProcess.env['SNAP_REVISION'];\n\t_isElectron = isElectronProcess;\n\t_isCI = !!nodeProcess.env['CI'] || !!nodeProcess.env['BUILD_ARTIFACTSTAGINGDIRECTORY'];\n\t_locale = LANGUAGE_DEFAULT;\n\t_language = LANGUAGE_DEFAULT;\n\tconst rawNlsConfig = nodeProcess.env['VSCODE_NLS_CONFIG'];\n\tif (rawNlsConfig) {\n\t\ttry {\n\t\t\tconst nlsConfig: nls.INLSConfiguration = JSON.parse(rawNlsConfig);\n\t\t\t_locale = nlsConfig.userLocale;\n\t\t\t_platformLocale = nlsConfig.osLocale;\n\t\t\t_language = nlsConfig.resolvedLanguage || LANGUAGE_DEFAULT;\n\t\t\t_translationsConfigFile = nlsConfig.languagePack?.translationsConfigFile;\n\t\t} catch (e) {\n\t\t}\n\t}\n\t_isNative = true;\n}\n\n// Web environment\nelse if (typeof navigator === 'object' && !isElectronRenderer) {\n\t_userAgent = navigator.userAgent;\n\t_isWindows = _userAgent.indexOf('Windows') >= 0;\n\t_isMacintosh = _userAgent.indexOf('Macintosh') >= 0;\n\t_isIOS = (_userAgent.indexOf('Macintosh') >= 0 || _userAgent.indexOf('iPad') >= 0 || _userAgent.indexOf('iPhone') >= 0) && !!navigator.maxTouchPoints && navigator.maxTouchPoints > 0;\n\t_isLinux = _userAgent.indexOf('Linux') >= 0;\n\t_isMobile = _userAgent?.indexOf('Mobi') >= 0;\n\t_isWeb = true;\n\t// VSCODE_GLOBALS: NLS\n\t_language = globalThis._VSCODE_NLS_LANGUAGE || LANGUAGE_DEFAULT;\n\t_locale = navigator.language.toLowerCase();\n\t_platformLocale = _locale;\n}\n\n// Unknown environment\nelse {\n\tconsole.error('Unable to resolve platform.');\n}\n\nexport const enum Platform {\n\tWeb,\n\tMac,\n\tLinux,\n\tWindows\n}\nexport type PlatformName = 'Web' | 'Windows' | 'Mac' | 'Linux';\n\nexport function PlatformToString(platform: Platform): PlatformName {\n\tswitch (platform) {\n\t\tcase Platform.Web: return 'Web';\n\t\tcase Platform.Mac: return 'Mac';\n\t\tcase Platform.Linux: return 'Linux';\n\t\tcase Platform.Windows: return 'Windows';\n\t}\n}\n\nlet _platform: Platform = Platform.Web;\nif (_isMacintosh) {\n\t_platform = Platform.Mac;\n} else if (_isWindows) {\n\t_platform = Platform.Windows;\n} else if (_isLinux) {\n\t_platform = Platform.Linux;\n}\n\nexport const isWindows = _isWindows;\nexport const isMacintosh = _isMacintosh;\nexport const isLinux = _isLinux;\nexport const isLinuxSnap = _isLinuxSnap;\nexport const isNative = _isNative;\nexport const isElectron = _isElectron;\nexport const isWeb = _isWeb;\nexport const isWebWorker = (_isWeb && typeof $globalThis.importScripts === 'function');\nexport const webWorkerOrigin = isWebWorker ? $globalThis.origin : undefined;\nexport const isIOS = _isIOS;\nexport const isMobile = _isMobile;\n/**\n * Whether we run inside a CI environment, such as\n * GH actions or Azure Pipelines.\n */\nexport const isCI = _isCI;\nexport const platform = _platform;\nexport const userAgent = _userAgent;\n\n/**\n * The language used for the user interface. The format of\n * the string is all lower case (e.g. zh-tw for Traditional\n * Chinese or de for German)\n */\nexport const language = _language;\n\nexport namespace Language {\n\n\texport function value(): string {\n\t\treturn language;\n\t}\n\n\texport function isDefaultVariant(): boolean {\n\t\tif (language.length === 2) {\n\t\t\treturn language === 'en';\n\t\t} else if (language.length >= 3) {\n\t\t\treturn language[0] === 'e' && language[1] === 'n' && language[2] === '-';\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\texport function isDefault(): boolean {\n\t\treturn language === 'en';\n\t}\n}\n\n/**\n * Desktop: The OS locale or the locale specified by --locale or `argv.json`.\n * Web: matches `platformLocale`.\n *\n * The UI is not necessarily shown in the provided locale.\n */\nexport const locale = _locale;\n\n/**\n * This will always be set to the OS/browser's locale regardless of\n * what was specified otherwise. The format of the string is all\n * lower case (e.g. zh-tw for Traditional Chinese). The UI is not\n * necessarily shown in the provided locale.\n */\nexport const platformLocale = _platformLocale;\n\n/**\n * The translations that are available through language packs.\n */\nexport const translationsConfigFile = _translationsConfigFile;\n\nexport const setTimeout0IsFaster = (typeof $globalThis.postMessage === 'function' && !$globalThis.importScripts);\n\n/**\n * See https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#:~:text=than%204%2C%20then-,set%20timeout%20to%204,-.\n *\n * Works similarly to `setTimeout(0)` but doesn't suffer from the 4ms artificial delay\n * that browsers set when the nesting level is > 5.\n */\nexport const setTimeout0 = (() => {\n\tif (setTimeout0IsFaster) {\n\t\tinterface IQueueElement {\n\t\t\tid: number;\n\t\t\tcallback: () => void;\n\t\t}\n\t\tconst pending: IQueueElement[] = [];\n\n\t\t$globalThis.addEventListener('message', (e: any) => {\n\t\t\tif (e.data && e.data.vscodeScheduleAsyncWork) {\n\t\t\t\tfor (let i = 0, len = pending.length; i < len; i++) {\n\t\t\t\t\tconst candidate = pending[i];\n\t\t\t\t\tif (candidate.id === e.data.vscodeScheduleAsyncWork) {\n\t\t\t\t\t\tpending.splice(i, 1);\n\t\t\t\t\t\tcandidate.callback();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tlet lastId = 0;\n\t\treturn (callback: () => void) => {\n\t\t\tconst myId = ++lastId;\n\t\t\tpending.push({\n\t\t\t\tid: myId,\n\t\t\t\tcallback: callback\n\t\t\t});\n\t\t\t$globalThis.postMessage({ vscodeScheduleAsyncWork: myId }, '*');\n\t\t};\n\t}\n\treturn (callback: () => void) => setTimeout(callback);\n})();\n\nexport const enum OperatingSystem {\n\tWindows = 1,\n\tMacintosh = 2,\n\tLinux = 3\n}\nexport const OS = (_isMacintosh || _isIOS ? OperatingSystem.Macintosh : (_isWindows ? OperatingSystem.Windows : OperatingSystem.Linux));\n\nlet _isLittleEndian = true;\nlet _isLittleEndianComputed = false;\nexport function isLittleEndian(): boolean {\n\tif (!_isLittleEndianComputed) {\n\t\t_isLittleEndianComputed = true;\n\t\tconst test = new Uint8Array(2);\n\t\ttest[0] = 1;\n\t\ttest[1] = 2;\n\t\tconst view = new Uint16Array(test.buffer);\n\t\t_isLittleEndian = (view[0] === (2 << 8) + 1);\n\t}\n\treturn _isLittleEndian;\n}\n\nexport const isChrome = !!(userAgent && userAgent.indexOf('Chrome') >= 0);\nexport const isFirefox = !!(userAgent && userAgent.indexOf('Firefox') >= 0);\nexport const isSafari = !!(!isChrome && (userAgent && userAgent.indexOf('Safari') >= 0));\nexport const isEdge = !!(userAgent && userAgent.indexOf('Edg/') >= 0);\nexport const isAndroid = !!(userAgent && userAgent.indexOf('Android') >= 0);\n\nexport function isBigSurOrNewer(osVersion: string): boolean {\n\treturn parseFloat(osVersion) >= 20;\n}\n", "/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\nimport * as browser from 'vs/base/browser/browser';\nimport { mainWindow } from 'vs/base/browser/window';\nimport * as platform from 'vs/base/common/platform';\n\nexport const enum KeyboardSupport {\n\tAlways,\n\tFullScreen,\n\tNone\n}\n\nconst safeNavigator = typeof navigator === 'object' ? navigator : {} as { [key: string]: any };\n\n/**\n * Browser feature we can support in current platform, browser and environment.\n */\nexport const BrowserFeatures = {\n\tclipboard: {\n\t\twriteText: (\n\t\t\tplatform.isNative\n\t\t\t|| (document.queryCommandSupported && document.queryCommandSupported('copy'))\n\t\t\t|| !!(safeNavigator && safeNavigator.clipboard && safeNavigator.clipboard.writeText)\n\t\t),\n\t\treadText: (\n\t\t\tplatform.isNative\n\t\t\t|| !!(safeNavigator && safeNavigator.clipboard && safeNavigator.clipboard.readText)\n\t\t)\n\t},\n\tkeyboard: (() => {\n\t\tif (platform.isNative || browser.isStandalone()) {\n\t\t\treturn KeyboardSupport.Always;\n\t\t}\n\n\t\tif ((safeNavigator).keyboard || browser.isSafari) {\n\t\t\treturn KeyboardSupport.FullScreen;\n\t\t}\n\n\t\treturn KeyboardSupport.None;\n\t})(),\n\n\t// 'ontouchstart' in window always evaluates to true with typescript's modern typings. This causes `window` to be\n\t// `never` later in `window.navigator`. That's why we need the explicit `window as Window` cast\n\ttouch: 'ontouchstart' in mainWindow || safeNavigator.maxTouchPoints > 0,\n\tpointerEvents: mainWindow.PointerEvent && ('ontouchstart' in mainWindow || navigator.maxTouchPoints > 0)\n};\n", "/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n/**\n * Virtual Key Codes, the value does not hold any inherent meaning.\n * Inspired somewhat from https://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx\n * But these are \"more general\", as they should work across browsers & OS`s.\n */\nexport const enum KeyCode {\n\tDependsOnKbLayout = -1,\n\n\t/**\n\t * Placed first to cover the 0 value of the enum.\n\t */\n\tUnknown = 0,\n\n\tBackspace,\n\tTab,\n\tEnter,\n\tShift,\n\tCtrl,\n\tAlt,\n\tPauseBreak,\n\tCapsLock,\n\tEscape,\n\tSpace,\n\tPageUp,\n\tPageDown,\n\tEnd,\n\tHome,\n\tLeftArrow,\n\tUpArrow,\n\tRightArrow,\n\tDownArrow,\n\tInsert,\n\tDelete,\n\n\tDigit0,\n\tDigit1,\n\tDigit2,\n\tDigit3,\n\tDigit4,\n\tDigit5,\n\tDigit6,\n\tDigit7,\n\tDigit8,\n\tDigit9,\n\n\tKeyA,\n\tKeyB,\n\tKeyC,\n\tKeyD,\n\tKeyE,\n\tKeyF,\n\tKeyG,\n\tKeyH,\n\tKeyI,\n\tKeyJ,\n\tKeyK,\n\tKeyL,\n\tKeyM,\n\tKeyN,\n\tKeyO,\n\tKeyP,\n\tKeyQ,\n\tKeyR,\n\tKeyS,\n\tKeyT,\n\tKeyU,\n\tKeyV,\n\tKeyW,\n\tKeyX,\n\tKeyY,\n\tKeyZ,\n\n\tMeta,\n\tContextMenu,\n\n\tF1,\n\tF2,\n\tF3,\n\tF4,\n\tF5,\n\tF6,\n\tF7,\n\tF8,\n\tF9,\n\tF10,\n\tF11,\n\tF12,\n\tF13,\n\tF14,\n\tF15,\n\tF16,\n\tF17,\n\tF18,\n\tF19,\n\tF20,\n\tF21,\n\tF22,\n\tF23,\n\tF24,\n\n\tNumLock,\n\tScrollLock,\n\n\t/**\n\t * Used for miscellaneous characters; it can vary by keyboard.\n\t * For the US standard keyboard, the ';:' key\n\t */\n\tSemicolon,\n\t/**\n\t * For any country/region, the '+' key\n\t * For the US standard keyboard, the '=+' key\n\t */\n\tEqual,\n\t/**\n\t * For any country/region, the ',' key\n\t * For the US standard keyboard, the ',<' key\n\t */\n\tComma,\n\t/**\n\t * For any country/region, the '-' key\n\t * For the US standard keyboard, the '-_' key\n\t */\n\tMinus,\n\t/**\n\t * For any country/region, the '.' key\n\t * For the US standard keyboard, the '.>' key\n\t */\n\tPeriod,\n\t/**\n\t * Used for miscellaneous characters; it can vary by keyboard.\n\t * For the US standard keyboard, the '/?' key\n\t */\n\tSlash,\n\t/**\n\t * Used for miscellaneous characters; it can vary by keyboard.\n\t * For the US standard keyboard, the '`~' key\n\t */\n\tBackquote,\n\t/**\n\t * Used for miscellaneous characters; it can vary by keyboard.\n\t * For the US standard keyboard, the '[{' key\n\t */\n\tBracketLeft,\n\t/**\n\t * Used for miscellaneous characters; it can vary by keyboard.\n\t * For the US standard keyboard, the '\\|' key\n\t */\n\tBackslash,\n\t/**\n\t * Used for miscellaneous characters; it can vary by keyboard.\n\t * For the US standard keyboard, the ']}' key\n\t */\n\tBracketRight,\n\t/**\n\t * Used for miscellaneous characters; it can vary by keyboard.\n\t * For the US standard keyboard, the ''\"' key\n\t */\n\tQuote,\n\t/**\n\t * Used for miscellaneous characters; it can vary by keyboard.\n\t */\n\tOEM_8,\n\t/**\n\t * Either the angle bracket key or the backslash key on the RT 102-key keyboard.\n\t */\n\tIntlBackslash,\n\n\tNumpad0, // VK_NUMPAD0, 0x60, Numeric keypad 0 key\n\tNumpad1, // VK_NUMPAD1, 0x61, Numeric keypad 1 key\n\tNumpad2, // VK_NUMPAD2, 0x62, Numeric keypad 2 key\n\tNumpad3, // VK_NUMPAD3, 0x63, Numeric keypad 3 key\n\tNumpad4, // VK_NUMPAD4, 0x64, Numeric keypad 4 key\n\tNumpad5, // VK_NUMPAD5, 0x65, Numeric keypad 5 key\n\tNumpad6, // VK_NUMPAD6, 0x66, Numeric keypad 6 key\n\tNumpad7, // VK_NUMPAD7, 0x67, Numeric keypad 7 key\n\tNumpad8, // VK_NUMPAD8, 0x68, Numeric keypad 8 key\n\tNumpad9, // VK_NUMPAD9, 0x69, Numeric keypad 9 key\n\n\tNumpadMultiply,\t// VK_MULTIPLY, 0x6A, Multiply key\n\tNumpadAdd,\t\t// VK_ADD, 0x6B, Add key\n\tNUMPAD_SEPARATOR,\t// VK_SEPARATOR, 0x6C, Separator key\n\tNumpadSubtract,\t// VK_SUBTRACT, 0x6D, Subtract key\n\tNumpadDecimal,\t// VK_DECIMAL, 0x6E, Decimal key\n\tNumpadDivide,\t// VK_DIVIDE, 0x6F,\n\n\t/**\n\t * Cover all key codes when IME is processing input.\n\t */\n\tKEY_IN_COMPOSITION,\n\n\tABNT_C1, // Brazilian (ABNT) Keyboard\n\tABNT_C2, // Brazilian (ABNT) Keyboard\n\n\tAudioVolumeMute,\n\tAudioVolumeUp,\n\tAudioVolumeDown,\n\n\tBrowserSearch,\n\tBrowserHome,\n\tBrowserBack,\n\tBrowserForward,\n\n\tMediaTrackNext,\n\tMediaTrackPrevious,\n\tMediaStop,\n\tMediaPlayPause,\n\tLaunchMediaPlayer,\n\tLaunchMail,\n\tLaunchApp2,\n\n\t/**\n\t * VK_CLEAR, 0x0C, CLEAR key\n\t */\n\tClear,\n\n\t/**\n\t * Placed last to cover the length of the enum.\n\t * Please do not depend on this value!\n\t */\n\tMAX_VALUE\n}\n\n/**\n * keyboardEvent.code\n */\nexport const enum ScanCode {\n\tDependsOnKbLayout = -1,\n\tNone,\n\tHyper,\n\tSuper,\n\tFn,\n\tFnLock,\n\tSuspend,\n\tResume,\n\tTurbo,\n\tSleep,\n\tWakeUp,\n\tKeyA,\n\tKeyB,\n\tKeyC,\n\tKeyD,\n\tKeyE,\n\tKeyF,\n\tKeyG,\n\tKeyH,\n\tKeyI,\n\tKeyJ,\n\tKeyK,\n\tKeyL,\n\tKeyM,\n\tKeyN,\n\tKeyO,\n\tKeyP,\n\tKeyQ,\n\tKeyR,\n\tKeyS,\n\tKeyT,\n\tKeyU,\n\tKeyV,\n\tKeyW,\n\tKeyX,\n\tKeyY,\n\tKeyZ,\n\tDigit1,\n\tDigit2,\n\tDigit3,\n\tDigit4,\n\tDigit5,\n\tDigit6,\n\tDigit7,\n\tDigit8,\n\tDigit9,\n\tDigit0,\n\tEnter,\n\tEscape,\n\tBackspace,\n\tTab,\n\tSpace,\n\tMinus,\n\tEqual,\n\tBracketLeft,\n\tBracketRight,\n\tBackslash,\n\tIntlHash,\n\tSemicolon,\n\tQuote,\n\tBackquote,\n\tComma,\n\tPeriod,\n\tSlash,\n\tCapsLock,\n\tF1,\n\tF2,\n\tF3,\n\tF4,\n\tF5,\n\tF6,\n\tF7,\n\tF8,\n\tF9,\n\tF10,\n\tF11,\n\tF12,\n\tPrintScreen,\n\tScrollLock,\n\tPause,\n\tInsert,\n\tHome,\n\tPageUp,\n\tDelete,\n\tEnd,\n\tPageDown,\n\tArrowRight,\n\tArrowLeft,\n\tArrowDown,\n\tArrowUp,\n\tNumLock,\n\tNumpadDivide,\n\tNumpadMultiply,\n\tNumpadSubtract,\n\tNumpadAdd,\n\tNumpadEnter,\n\tNumpad1,\n\tNumpad2,\n\tNumpad3,\n\tNumpad4,\n\tNumpad5,\n\tNumpad6,\n\tNumpad7,\n\tNumpad8,\n\tNumpad9,\n\tNumpad0,\n\tNumpadDecimal,\n\tIntlBackslash,\n\tContextMenu,\n\tPower,\n\tNumpadEqual,\n\tF13,\n\tF14,\n\tF15,\n\tF16,\n\tF17,\n\tF18,\n\tF19,\n\tF20,\n\tF21,\n\tF22,\n\tF23,\n\tF24,\n\tOpen,\n\tHelp,\n\tSelect,\n\tAgain,\n\tUndo,\n\tCut,\n\tCopy,\n\tPaste,\n\tFind,\n\tAudioVolumeMute,\n\tAudioVolumeUp,\n\tAudioVolumeDown,\n\tNumpadComma,\n\tIntlRo,\n\tKanaMode,\n\tIntlYen,\n\tConvert,\n\tNonConvert,\n\tLang1,\n\tLang2,\n\tLang3,\n\tLang4,\n\tLang5,\n\tAbort,\n\tProps,\n\tNumpadParenLeft,\n\tNumpadParenRight,\n\tNumpadBackspace,\n\tNumpadMemoryStore,\n\tNumpadMemoryRecall,\n\tNumpadMemoryClear,\n\tNumpadMemoryAdd,\n\tNumpadMemorySubtract,\n\tNumpadClear,\n\tNumpadClearEntry,\n\tControlLeft,\n\tShiftLeft,\n\tAltLeft,\n\tMetaLeft,\n\tControlRight,\n\tShiftRight,\n\tAltRight,\n\tMetaRight,\n\tBrightnessUp,\n\tBrightnessDown,\n\tMediaPlay,\n\tMediaRecord,\n\tMediaFastForward,\n\tMediaRewind,\n\tMediaTrackNext,\n\tMediaTrackPrevious,\n\tMediaStop,\n\tEject,\n\tMediaPlayPause,\n\tMediaSelect,\n\tLaunchMail,\n\tLaunchApp2,\n\tLaunchApp1,\n\tSelectTask,\n\tLaunchScreenSaver,\n\tBrowserSearch,\n\tBrowserHome,\n\tBrowserBack,\n\tBrowserForward,\n\tBrowserStop,\n\tBrowserRefresh,\n\tBrowserFavorites,\n\tZoomToggle,\n\tMailReply,\n\tMailForward,\n\tMailSend,\n\n\tMAX_VALUE\n}\n\nclass KeyCodeStrMap {\n\n\tpublic _keyCodeToStr: string[];\n\tpublic _strToKeyCode: { [str: string]: KeyCode };\n\n\tconstructor() {\n\t\tthis._keyCodeToStr = [];\n\t\tthis._strToKeyCode = Object.create(null);\n\t}\n\n\tdefine(keyCode: KeyCode, str: string): void {\n\t\tthis._keyCodeToStr[keyCode] = str;\n\t\tthis._strToKeyCode[str.toLowerCase()] = keyCode;\n\t}\n\n\tkeyCodeToStr(keyCode: KeyCode): string {\n\t\treturn this._keyCodeToStr[keyCode];\n\t}\n\n\tstrToKeyCode(str: string): KeyCode {\n\t\treturn this._strToKeyCode[str.toLowerCase()] || KeyCode.Unknown;\n\t}\n}\n\nconst uiMap = new KeyCodeStrMap();\nconst userSettingsUSMap = new KeyCodeStrMap();\nconst userSettingsGeneralMap = new KeyCodeStrMap();\nexport const EVENT_KEY_CODE_MAP: { [keyCode: number]: KeyCode } = new Array(230);\nexport const NATIVE_WINDOWS_KEY_CODE_TO_KEY_CODE: { [nativeKeyCode: string]: KeyCode } = {};\nconst scanCodeIntToStr: string[] = [];\nconst scanCodeStrToInt: { [code: string]: number } = Object.create(null);\nconst scanCodeLowerCaseStrToInt: { [code: string]: number } = Object.create(null);\n\nexport const ScanCodeUtils = {\n\tlowerCaseToEnum: (scanCode: string) => scanCodeLowerCaseStrToInt[scanCode] || ScanCode.None,\n\ttoEnum: (scanCode: string) => scanCodeStrToInt[scanCode] || ScanCode.None,\n\ttoString: (scanCode: ScanCode) => scanCodeIntToStr[scanCode] || 'None'\n};\n\n\nexport namespace KeyCodeUtils {\n\texport function toString(keyCode: KeyCode): string {\n\t\treturn uiMap.keyCodeToStr(keyCode);\n\t}\n\texport function fromString(key: string): KeyCode {\n\t\treturn uiMap.strToKeyCode(key);\n\t}\n\n\texport function toUserSettingsUS(keyCode: KeyCode): string {\n\t\treturn userSettingsUSMap.keyCodeToStr(keyCode);\n\t}\n\texport function toUserSettingsGeneral(keyCode: KeyCode): string {\n\t\treturn userSettingsGeneralMap.keyCodeToStr(keyCode);\n\t}\n\texport function fromUserSettings(key: string): KeyCode {\n\t\treturn userSettingsUSMap.strToKeyCode(key) || userSettingsGeneralMap.strToKeyCode(key);\n\t}\n\n\texport function toElectronAccelerator(keyCode: KeyCode): string | null {\n\t\tif (keyCode >= KeyCode.Numpad0 && keyCode <= KeyCode.NumpadDivide) {\n\t\t\t// [Electron Accelerators] Electron is able to parse numpad keys, but unfortunately it\n\t\t\t// renders them just as regular keys in menus. For example, num0 is rendered as \"0\",\n\t\t\t// numdiv is rendered as \"/\", numsub is rendered as \"-\".\n\t\t\t//\n\t\t\t// This can lead to incredible confusion, as it makes numpad based keybindings indistinguishable\n\t\t\t// from keybindings based on regular keys.\n\t\t\t//\n\t\t\t// We therefore need to fall back to custom rendering for numpad keys.\n\t\t\treturn null;\n\t\t}\n\n\t\tswitch (keyCode) {\n\t\t\tcase KeyCode.UpArrow:\n\t\t\t\treturn 'Up';\n\t\t\tcase KeyCode.DownArrow:\n\t\t\t\treturn 'Down';\n\t\t\tcase KeyCode.LeftArrow:\n\t\t\t\treturn 'Left';\n\t\t\tcase KeyCode.RightArrow:\n\t\t\t\treturn 'Right';\n\t\t}\n\n\t\treturn uiMap.keyCodeToStr(keyCode);\n\t}\n}\n\nexport const enum KeyMod {\n\tCtrlCmd = (1 << 11) >>> 0,\n\tShift = (1 << 10) >>> 0,\n\tAlt = (1 << 9) >>> 0,\n\tWinCtrl = (1 << 8) >>> 0,\n}\n\nexport function KeyChord(firstPart: number, secondPart: number): number {\n\tconst chordPart = ((secondPart & 0x0000FFFF) << 16) >>> 0;\n\treturn (firstPart | chordPart) >>> 0;\n}\n", "/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\nimport { illegalArgument } from 'vs/base/common/errors';\nimport { KeyCode, ScanCode } from 'vs/base/common/keyCodes';\nimport { OperatingSystem } from 'vs/base/common/platform';\n\n/**\n * Binary encoding strategy:\n * ```\n * 1111 11\n * 5432 1098 7654 3210\n * ---- CSAW KKKK KKKK\n * C = bit 11 = ctrlCmd flag\n * S = bit 10 = shift flag\n * A = bit 9 = alt flag\n * W = bit 8 = winCtrl flag\n * K = bits 0-7 = key code\n * ```\n */\nconst enum BinaryKeybindingsMask {\n\tCtrlCmd = (1 << 11) >>> 0,\n\tShift = (1 << 10) >>> 0,\n\tAlt = (1 << 9) >>> 0,\n\tWinCtrl = (1 << 8) >>> 0,\n\tKeyCode = 0x000000FF\n}\n\nexport function decodeKeybinding(keybinding: number | number[], OS: OperatingSystem): Keybinding | null {\n\tif (typeof keybinding === 'number') {\n\t\tif (keybinding === 0) {\n\t\t\treturn null;\n\t\t}\n\t\tconst firstChord = (keybinding & 0x0000FFFF) >>> 0;\n\t\tconst secondChord = (keybinding & 0xFFFF0000) >>> 16;\n\t\tif (secondChord !== 0) {\n\t\t\treturn new Keybinding([\n\t\t\t\tcreateSimpleKeybinding(firstChord, OS),\n\t\t\t\tcreateSimpleKeybinding(secondChord, OS)\n\t\t\t]);\n\t\t}\n\t\treturn new Keybinding([createSimpleKeybinding(firstChord, OS)]);\n\t} else {\n\t\tconst chords = [];\n\t\tfor (let i = 0; i < keybinding.length; i++) {\n\t\t\tchords.push(createSimpleKeybinding(keybinding[i], OS));\n\t\t}\n\t\treturn new Keybinding(chords);\n\t}\n}\n\nexport function createSimpleKeybinding(keybinding: number, OS: OperatingSystem): KeyCodeChord {\n\n\tconst ctrlCmd = (keybinding & BinaryKeybindingsMask.CtrlCmd ? true : false);\n\tconst winCtrl = (keybinding & BinaryKeybindingsMask.WinCtrl ? true : false);\n\n\tconst ctrlKey = (OS === OperatingSystem.Macintosh ? winCtrl : ctrlCmd);\n\tconst shiftKey = (keybinding & BinaryKeybindingsMask.Shift ? true : false);\n\tconst altKey = (keybinding & BinaryKeybindingsMask.Alt ? true : false);\n\tconst metaKey = (OS === OperatingSystem.Macintosh ? ctrlCmd : winCtrl);\n\tconst keyCode = (keybinding & BinaryKeybindingsMask.KeyCode);\n\n\treturn new KeyCodeChord(ctrlKey, shiftKey, altKey, metaKey, keyCode);\n}\n\nexport interface Modifiers {\n\treadonly ctrlKey: boolean;\n\treadonly shiftKey: boolean;\n\treadonly altKey: boolean;\n\treadonly metaKey: boolean;\n}\n\n/**\n * Represents a chord which uses the `keyCode` field of keyboard events.\n * A chord is a combination of keys pressed simultaneously.\n */\nexport class KeyCodeChord implements Modifiers {\n\n\tconstructor(\n\t\tpublic readonly ctrlKey: boolean,\n\t\tpublic readonly shiftKey: boolean,\n\t\tpublic readonly altKey: boolean,\n\t\tpublic readonly metaKey: boolean,\n\t\tpublic readonly keyCode: KeyCode\n\t) { }\n\n\tpublic equals(other: Chord): boolean {\n\t\treturn (\n\t\t\tother instanceof KeyCodeChord\n\t\t\t&& this.ctrlKey === other.ctrlKey\n\t\t\t&& this.shiftKey === other.shiftKey\n\t\t\t&& this.altKey === other.altKey\n\t\t\t&& this.metaKey === other.metaKey\n\t\t\t&& this.keyCode === other.keyCode\n\t\t);\n\t}\n\n\tpublic getHashCode(): string {\n\t\tconst ctrl = this.ctrlKey ? '1' : '0';\n\t\tconst shift = this.shiftKey ? '1' : '0';\n\t\tconst alt = this.altKey ? '1' : '0';\n\t\tconst meta = this.metaKey ? '1' : '0';\n\t\treturn `K${ctrl}${shift}${alt}${meta}${this.keyCode}`;\n\t}\n\n\tpublic isModifierKey(): boolean {\n\t\treturn (\n\t\t\tthis.keyCode === KeyCode.Unknown\n\t\t\t|| this.keyCode === KeyCode.Ctrl\n\t\t\t|| this.keyCode === KeyCode.Meta\n\t\t\t|| this.keyCode === KeyCode.Alt\n\t\t\t|| this.keyCode === KeyCode.Shift\n\t\t);\n\t}\n\n\tpublic toKeybinding(): Keybinding {\n\t\treturn new Keybinding([this]);\n\t}\n\n\t/**\n\t * Does this keybinding refer to the key code of a modifier and it also has the modifier flag?\n\t */\n\tpublic isDuplicateModifierCase(): boolean {\n\t\treturn (\n\t\t\t(this.ctrlKey && this.keyCode === KeyCode.Ctrl)\n\t\t\t|| (this.shiftKey && this.keyCode === KeyCode.Shift)\n\t\t\t|| (this.altKey && this.keyCode === KeyCode.Alt)\n\t\t\t|| (this.metaKey && this.keyCode === KeyCode.Meta)\n\t\t);\n\t}\n}\n\n/**\n * Represents a chord which uses the `code` field of keyboard events.\n * A chord is a combination of keys pressed simultaneously.\n */\nexport class ScanCodeChord implements Modifiers {\n\n\tconstructor(\n\t\tpublic readonly ctrlKey: boolean,\n\t\tpublic readonly shiftKey: boolean,\n\t\tpublic readonly altKey: boolean,\n\t\tpublic readonly metaKey: boolean,\n\t\tpublic readonly scanCode: ScanCode\n\t) { }\n\n\tpublic equals(other: Chord): boolean {\n\t\treturn (\n\t\t\tother instanceof ScanCodeChord\n\t\t\t&& this.ctrlKey === other.ctrlKey\n\t\t\t&& this.shiftKey === other.shiftKey\n\t\t\t&& this.altKey === other.altKey\n\t\t\t&& this.metaKey === other.metaKey\n\t\t\t&& this.scanCode === other.scanCode\n\t\t);\n\t}\n\n\tpublic getHashCode(): string {\n\t\tconst ctrl = this.ctrlKey ? '1' : '0';\n\t\tconst shift = this.shiftKey ? '1' : '0';\n\t\tconst alt = this.altKey ? '1' : '0';\n\t\tconst meta = this.metaKey ? '1' : '0';\n\t\treturn `S${ctrl}${shift}${alt}${meta}${this.scanCode}`;\n\t}\n\n\t/**\n\t * Does this keybinding refer to the key code of a modifier and it also has the modifier flag?\n\t */\n\tpublic isDuplicateModifierCase(): boolean {\n\t\treturn (\n\t\t\t(this.ctrlKey && (this.scanCode === ScanCode.ControlLeft || this.scanCode === ScanCode.ControlRight))\n\t\t\t|| (this.shiftKey && (this.scanCode === ScanCode.ShiftLeft || this.scanCode === ScanCode.ShiftRight))\n\t\t\t|| (this.altKey && (this.scanCode === ScanCode.AltLeft || this.scanCode === ScanCode.AltRight))\n\t\t\t|| (this.metaKey && (this.scanCode === ScanCode.MetaLeft || this.scanCode === ScanCode.MetaRight))\n\t\t);\n\t}\n}\n\nexport type Chord = KeyCodeChord | ScanCodeChord;\n\n/**\n * A keybinding is a sequence of chords.\n */\nexport class Keybinding {\n\n\tpublic readonly chords: Chord[];\n\n\tconstructor(chords: Chord[]) {\n\t\tif (chords.length === 0) {\n\t\t\tthrow illegalArgument(`chords`);\n\t\t}\n\t\tthis.chords = chords;\n\t}\n\n\tpublic getHashCode(): string {\n\t\tlet result = '';\n\t\tfor (let i = 0, len = this.chords.length; i < len; i++) {\n\t\t\tif (i !== 0) {\n\t\t\t\tresult += ';';\n\t\t\t}\n\t\t\tresult += this.chords[i].getHashCode();\n\t\t}\n\t\treturn result;\n\t}\n\n\tpublic equals(other: Keybinding | null): boolean {\n\t\tif (other === null) {\n\t\t\treturn false;\n\t\t}\n\t\tif (this.chords.length !== other.chords.length) {\n\t\t\treturn false;\n\t\t}\n\t\tfor (let i = 0; i < this.chords.length; i++) {\n\t\t\tif (!this.chords[i].equals(other.chords[i])) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n}\n\nexport class ResolvedChord {\n\tconstructor(\n\t\tpublic readonly ctrlKey: boolean,\n\t\tpublic readonly shiftKey: boolean,\n\t\tpublic readonly altKey: boolean,\n\t\tpublic readonly metaKey: boolean,\n\t\tpublic readonly keyLabel: string | null,\n\t\tpublic readonly keyAriaLabel: string | null\n\t) { }\n}\n\nexport type SingleModifierChord = 'ctrl' | 'shift' | 'alt' | 'meta';\n\n/**\n * A resolved keybinding. Consists of one or multiple chords.\n */\nexport abstract class ResolvedKeybinding {\n\t/**\n\t * This prints the binding in a format suitable for displaying in the UI.\n\t */\n\tpublic abstract getLabel(): string | null;\n\t/**\n\t * This prints the binding in a format suitable for ARIA.\n\t */\n\tpublic abstract getAriaLabel(): string | null;\n\t/**\n\t * This prints the binding in a format suitable for electron's accelerators.\n\t * See https://github.com/electron/electron/blob/master/docs/api/accelerator.md\n\t */\n\tpublic abstract getElectronAccelerator(): string | null;\n\t/**\n\t * This prints the binding in a format suitable for user settings.\n\t */\n\tpublic abstract getUserSettingsLabel(): string | null;\n\t/**\n\t * Is the user settings label reflecting the label?\n\t */\n\tpublic abstract isWYSIWYG(): boolean;\n\t/**\n\t * Does the keybinding consist of more than one chord?\n\t */\n\tpublic abstract hasMultipleChords(): boolean;\n\t/**\n\t * Returns the chords that comprise of the keybinding.\n\t */\n\tpublic abstract getChords(): ResolvedChord[];\n\t/**\n\t * Returns the chords as strings useful for dispatching.\n\t * Returns null for modifier only chords.\n\t * @example keybinding \"Shift\" -> null\n\t * @example keybinding (\"D\" with shift == true) -> \"shift+D\"\n\t */\n\tpublic abstract getDispatchChords(): (string | null)[];\n\t/**\n\t * Returns the modifier only chords as strings useful for dispatching.\n\t * Returns null for chords that contain more than one modifier or a regular key.\n\t * @example keybinding \"Shift\" -> \"shift\"\n\t * @example keybinding (\"D\" with shift == true\") -> null\n\t */\n\tpublic abstract getSingleModifierDispatchChords(): (SingleModifierChord | null)[];\n}\n", "/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\nimport * as browser from 'vs/base/browser/browser';\nimport { EVENT_KEY_CODE_MAP, KeyCode, KeyCodeUtils, KeyMod } from 'vs/base/common/keyCodes';\nimport { KeyCodeChord } from 'vs/base/common/keybindings';\nimport * as platform from 'vs/base/common/platform';\n\n\n\nfunction extractKeyCode(e: KeyboardEvent): KeyCode {\n\tif (e.charCode) {\n\t\t// \"keypress\" events mostly\n\t\tconst char = String.fromCharCode(e.charCode).toUpperCase();\n\t\treturn KeyCodeUtils.fromString(char);\n\t}\n\n\tconst keyCode = e.keyCode;\n\n\t// browser quirks\n\tif (keyCode === 3) {\n\t\treturn KeyCode.PauseBreak;\n\t} else if (browser.isFirefox) {\n\t\tswitch (keyCode) {\n\t\t\tcase 59: return KeyCode.Semicolon;\n\t\t\tcase 60:\n\t\t\t\tif (platform.isLinux) { return KeyCode.IntlBackslash; }\n\t\t\t\tbreak;\n\t\t\tcase 61: return KeyCode.Equal;\n\t\t\t// based on: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode#numpad_keys\n\t\t\tcase 107: return KeyCode.NumpadAdd;\n\t\t\tcase 109: return KeyCode.NumpadSubtract;\n\t\t\tcase 173: return KeyCode.Minus;\n\t\t\tcase 224:\n\t\t\t\tif (platform.isMacintosh) { return KeyCode.Meta; }\n\t\t\t\tbreak;\n\t\t}\n\t} else if (browser.isWebKit) {\n\t\tif (platform.isMacintosh && keyCode === 93) {\n\t\t\t// the two meta keys in the Mac have different key codes (91 and 93)\n\t\t\treturn KeyCode.Meta;\n\t\t} else if (!platform.isMacintosh && keyCode === 92) {\n\t\t\treturn KeyCode.Meta;\n\t\t}\n\t}\n\n\t// cross browser keycodes:\n\treturn EVENT_KEY_CODE_MAP[keyCode] || KeyCode.Unknown;\n}\n\nexport interface IKeyboardEvent {\n\n\treadonly _standardKeyboardEventBrand: true;\n\n\treadonly browserEvent: KeyboardEvent;\n\treadonly target: HTMLElement;\n\n\treadonly ctrlKey: boolean;\n\treadonly shiftKey: boolean;\n\treadonly altKey: boolean;\n\treadonly metaKey: boolean;\n\treadonly altGraphKey: boolean;\n\treadonly keyCode: KeyCode;\n\treadonly code: string;\n\n\t/**\n\t * @internal\n\t */\n\ttoKeyCodeChord(): KeyCodeChord;\n\tequals(keybinding: number): boolean;\n\n\tpreventDefault(): void;\n\tstopPropagation(): void;\n}\n\nconst ctrlKeyMod = (platform.isMacintosh ? KeyMod.WinCtrl : KeyMod.CtrlCmd);\nconst altKeyMod = KeyMod.Alt;\nconst shiftKeyMod = KeyMod.Shift;\nconst metaKeyMod = (platform.isMacintosh ? KeyMod.CtrlCmd : KeyMod.WinCtrl);\n\nexport function printKeyboardEvent(e: KeyboardEvent): string {\n\tconst modifiers: string[] = [];\n\tif (e.ctrlKey) {\n\t\tmodifiers.push(`ctrl`);\n\t}\n\tif (e.shiftKey) {\n\t\tmodifiers.push(`shift`);\n\t}\n\tif (e.altKey) {\n\t\tmodifiers.push(`alt`);\n\t}\n\tif (e.metaKey) {\n\t\tmodifiers.push(`meta`);\n\t}\n\treturn `modifiers: [${modifiers.join(',')}], code: ${e.code}, keyCode: ${e.keyCode}, key: ${e.key}`;\n}\n\nexport function printStandardKeyboardEvent(e: StandardKeyboardEvent): string {\n\tconst modifiers: string[] = [];\n\tif (e.ctrlKey) {\n\t\tmodifiers.push(`ctrl`);\n\t}\n\tif (e.shiftKey) {\n\t\tmodifiers.push(`shift`);\n\t}\n\tif (e.altKey) {\n\t\tmodifiers.push(`alt`);\n\t}\n\tif (e.metaKey) {\n\t\tmodifiers.push(`meta`);\n\t}\n\treturn `modifiers: [${modifiers.join(',')}], code: ${e.code}, keyCode: ${e.keyCode} ('${KeyCodeUtils.toString(e.keyCode)}')`;\n}\n\nexport class StandardKeyboardEvent implements IKeyboardEvent {\n\n\treadonly _standardKeyboardEventBrand = true;\n\n\tpublic readonly browserEvent: KeyboardEvent;\n\tpublic readonly target: HTMLElement;\n\n\tpublic readonly ctrlKey: boolean;\n\tpublic readonly shiftKey: boolean;\n\tpublic readonly altKey: boolean;\n\tpublic readonly metaKey: boolean;\n\tpublic readonly altGraphKey: boolean;\n\tpublic readonly keyCode: KeyCode;\n\tpublic readonly code: string;\n\n\tprivate _asKeybinding: number;\n\tprivate _asKeyCodeChord: KeyCodeChord;\n\n\tconstructor(source: KeyboardEvent) {\n\t\tconst e = source;\n\n\t\tthis.browserEvent = e;\n\t\tthis.target = e.target;\n\n\t\tthis.ctrlKey = e.ctrlKey;\n\t\tthis.shiftKey = e.shiftKey;\n\t\tthis.altKey = e.altKey;\n\t\tthis.metaKey = e.metaKey;\n\t\tthis.altGraphKey = e.getModifierState?.('AltGraph');\n\t\tthis.keyCode = extractKeyCode(e);\n\t\tthis.code = e.code;\n\n\t\t// console.info(e.type + \": keyCode: \" + e.keyCode + \", which: \" + e.which + \", charCode: \" + e.charCode + \", detail: \" + e.detail + \" ====> \" + this.keyCode + ' -- ' + KeyCode[this.keyCode]);\n\n\t\tthis.ctrlKey = this.ctrlKey || this.keyCode === KeyCode.Ctrl;\n\t\tthis.altKey = this.altKey || this.keyCode === KeyCode.Alt;\n\t\tthis.shiftKey = this.shiftKey || this.keyCode === KeyCode.Shift;\n\t\tthis.metaKey = this.metaKey || this.keyCode === KeyCode.Meta;\n\n\t\tthis._asKeybinding = this._computeKeybinding();\n\t\tthis._asKeyCodeChord = this._computeKeyCodeChord();\n\n\t\t// console.log(`code: ${e.code}, keyCode: ${e.keyCode}, key: ${e.key}`);\n\t}\n\n\tpublic preventDefault(): void {\n\t\tif (this.browserEvent && this.browserEvent.preventDefault) {\n\t\t\tthis.browserEvent.preventDefault();\n\t\t}\n\t}\n\n\tpublic stopPropagation(): void {\n\t\tif (this.browserEvent && this.browserEvent.stopPropagation) {\n\t\t\tthis.browserEvent.stopPropagation();\n\t\t}\n\t}\n\n\tpublic toKeyCodeChord(): KeyCodeChord {\n\t\treturn this._asKeyCodeChord;\n\t}\n\n\tpublic equals(other: number): boolean {\n\t\treturn this._asKeybinding === other;\n\t}\n\n\tprivate _computeKeybinding(): number {\n\t\tlet key = KeyCode.Unknown;\n\t\tif (this.keyCode !== KeyCode.Ctrl && this.keyCode !== KeyCode.Shift && this.keyCode !== KeyCode.Alt && this.keyCode !== KeyCode.Meta) {\n\t\t\tkey = this.keyCode;\n\t\t}\n\n\t\tlet result = 0;\n\t\tif (this.ctrlKey) {\n\t\t\tresult |= ctrlKeyMod;\n\t\t}\n\t\tif (this.altKey) {\n\t\t\tresult |= altKeyMod;\n\t\t}\n\t\tif (this.shiftKey) {\n\t\t\tresult |= shiftKeyMod;\n\t\t}\n\t\tif (this.metaKey) {\n\t\t\tresult |= metaKeyMod;\n\t\t}\n\t\tresult |= key;\n\n\t\treturn result;\n\t}\n\n\tprivate _computeKeyCodeChord(): KeyCodeChord {\n\t\tlet key = KeyCode.Unknown;\n\t\tif (this.keyCode !== KeyCode.Ctrl && this.keyCode !== KeyCode.Shift && this.keyCode !== KeyCode.Alt && this.keyCode !== KeyCode.Meta) {\n\t\t\tkey = this.keyCode;\n\t\t}\n\t\treturn new KeyCodeChord(this.ctrlKey, this.shiftKey, this.altKey, this.metaKey, key);\n\t}\n}\n", "/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n/**\n * Represents a window in a possible chain of iframes\n */\ninterface IWindowChainElement {\n\t/**\n\t * The window object for it\n\t */\n\treadonly window: WeakRef;\n\t/**\n\t * The iframe element inside the window.parent corresponding to window\n\t */\n\treadonly iframeElement: Element | null;\n}\n\nconst sameOriginWindowChainCache = new WeakMap();\n\nfunction getParentWindowIfSameOrigin(w: Window): Window | null {\n\tif (!w.parent || w.parent === w) {\n\t\treturn null;\n\t}\n\n\t// Cannot really tell if we have access to the parent window unless we try to access something in it\n\ttry {\n\t\tconst location = w.location;\n\t\tconst parentLocation = w.parent.location;\n\t\tif (location.origin !== 'null' && parentLocation.origin !== 'null' && location.origin !== parentLocation.origin) {\n\t\t\treturn null;\n\t\t}\n\t} catch (e) {\n\t\treturn null;\n\t}\n\n\treturn w.parent;\n}\n\nexport class IframeUtils {\n\n\t/**\n\t * Returns a chain of embedded windows with the same origin (which can be accessed programmatically).\n\t * Having a chain of length 1 might mean that the current execution environment is running outside of an iframe or inside an iframe embedded in a window with a different origin.\n\t */\n\tprivate static getSameOriginWindowChain(targetWindow: Window): IWindowChainElement[] {\n\t\tlet windowChainCache = sameOriginWindowChainCache.get(targetWindow);\n\t\tif (!windowChainCache) {\n\t\t\twindowChainCache = [];\n\t\t\tsameOriginWindowChainCache.set(targetWindow, windowChainCache);\n\t\t\tlet w: Window | null = targetWindow;\n\t\t\tlet parent: Window | null;\n\t\t\tdo {\n\t\t\t\tparent = getParentWindowIfSameOrigin(w);\n\t\t\t\tif (parent) {\n\t\t\t\t\twindowChainCache.push({\n\t\t\t\t\t\twindow: new WeakRef(w),\n\t\t\t\t\t\tiframeElement: w.frameElement || null\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\twindowChainCache.push({\n\t\t\t\t\t\twindow: new WeakRef(w),\n\t\t\t\t\t\tiframeElement: null\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tw = parent;\n\t\t\t} while (w);\n\t\t}\n\t\treturn windowChainCache.slice(0);\n\t}\n\n\t/**\n\t * Returns the position of `childWindow` relative to `ancestorWindow`\n\t */\n\tpublic static getPositionOfChildWindowRelativeToAncestorWindow(childWindow: Window, ancestorWindow: Window | null) {\n\n\t\tif (!ancestorWindow || childWindow === ancestorWindow) {\n\t\t\treturn {\n\t\t\t\ttop: 0,\n\t\t\t\tleft: 0\n\t\t\t};\n\t\t}\n\n\t\tlet top = 0, left = 0;\n\n\t\tconst windowChain = this.getSameOriginWindowChain(childWindow);\n\n\t\tfor (const windowChainEl of windowChain) {\n\t\t\tconst windowInChain = windowChainEl.window.deref();\n\t\t\ttop += windowInChain?.scrollY ?? 0;\n\t\t\tleft += windowInChain?.scrollX ?? 0;\n\n\t\t\tif (windowInChain === ancestorWindow) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (!windowChainEl.iframeElement) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tconst boundingRect = windowChainEl.iframeElement.getBoundingClientRect();\n\t\t\ttop += boundingRect.top;\n\t\t\tleft += boundingRect.left;\n\t\t}\n\n\t\treturn {\n\t\t\ttop: top,\n\t\t\tleft: left\n\t\t};\n\t}\n}\n\n/**\n * Returns a sha-256 composed of `parentOrigin` and `salt` converted to base 32\n */\nexport async function parentOriginHash(parentOrigin: string, salt: string): Promise {\n\t// This same code is also inlined at `src/vs/workbench/services/extensions/worker/webWorkerExtensionHostIframe.html`\n\tif (!crypto.subtle) {\n\t\tthrow new Error(`'crypto.subtle' is not available so webviews will not work. This is likely because the editor is not running in a secure context (https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts).`);\n\t}\n\n\tconst strData = JSON.stringify({ parentOrigin, salt });\n\tconst encoder = new TextEncoder();\n\tconst arrData = encoder.encode(strData);\n\tconst hash = await crypto.subtle.digest('sha-256', arrData);\n\treturn sha256AsBase32(hash);\n}\n\nfunction sha256AsBase32(bytes: ArrayBuffer): string {\n\tconst array = Array.from(new Uint8Array(bytes));\n\tconst hexArray = array.map(b => b.toString(16).padStart(2, '0')).join('');\n\t// sha256 has 256 bits, so we need at most ceil(lg(2^256-1)/lg(32)) = 52 chars to represent it in base 32\n\treturn BigInt(`0x${hexArray}`).toString(32).padStart(52, '0');\n}\n", "/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\nimport * as browser from 'vs/base/browser/browser';\nimport { IframeUtils } from 'vs/base/browser/iframe';\nimport * as platform from 'vs/base/common/platform';\n\nexport interface IMouseEvent {\n\treadonly browserEvent: MouseEvent;\n\treadonly leftButton: boolean;\n\treadonly middleButton: boolean;\n\treadonly rightButton: boolean;\n\treadonly buttons: number;\n\treadonly target: HTMLElement;\n\treadonly detail: number;\n\treadonly posx: number;\n\treadonly posy: number;\n\treadonly ctrlKey: boolean;\n\treadonly shiftKey: boolean;\n\treadonly altKey: boolean;\n\treadonly metaKey: boolean;\n\treadonly timestamp: number;\n\n\tpreventDefault(): void;\n\tstopPropagation(): void;\n}\n\nexport class StandardMouseEvent implements IMouseEvent {\n\n\tpublic readonly browserEvent: MouseEvent;\n\n\tpublic readonly leftButton: boolean;\n\tpublic readonly middleButton: boolean;\n\tpublic readonly rightButton: boolean;\n\tpublic readonly buttons: number;\n\tpublic readonly target: HTMLElement;\n\tpublic detail: number;\n\tpublic readonly posx: number;\n\tpublic readonly posy: number;\n\tpublic readonly ctrlKey: boolean;\n\tpublic readonly shiftKey: boolean;\n\tpublic readonly altKey: boolean;\n\tpublic readonly metaKey: boolean;\n\tpublic readonly timestamp: number;\n\n\tconstructor(targetWindow: Window, e: MouseEvent) {\n\t\tthis.timestamp = Date.now();\n\t\tthis.browserEvent = e;\n\t\tthis.leftButton = e.button === 0;\n\t\tthis.middleButton = e.button === 1;\n\t\tthis.rightButton = e.button === 2;\n\t\tthis.buttons = e.buttons;\n\n\t\tthis.target = e.target;\n\n\t\tthis.detail = e.detail || 1;\n\t\tif (e.type === 'dblclick') {\n\t\t\tthis.detail = 2;\n\t\t}\n\t\tthis.ctrlKey = e.ctrlKey;\n\t\tthis.shiftKey = e.shiftKey;\n\t\tthis.altKey = e.altKey;\n\t\tthis.metaKey = e.metaKey;\n\n\t\tif (typeof e.pageX === 'number') {\n\t\t\tthis.posx = e.pageX;\n\t\t\tthis.posy = e.pageY;\n\t\t} else {\n\t\t\t// Probably hit by MSGestureEvent\n\t\t\tthis.posx = e.clientX + this.target.ownerDocument.body.scrollLeft + this.target.ownerDocument.documentElement.scrollLeft;\n\t\t\tthis.posy = e.clientY + this.target.ownerDocument.body.scrollTop + this.target.ownerDocument.documentElement.scrollTop;\n\t\t}\n\n\t\t// Find the position of the iframe this code is executing in relative to the iframe where the event was captured.\n\t\tconst iframeOffsets = IframeUtils.getPositionOfChildWindowRelativeToAncestorWindow(targetWindow, e.view);\n\t\tthis.posx -= iframeOffsets.left;\n\t\tthis.posy -= iframeOffsets.top;\n\t}\n\n\tpublic preventDefault(): void {\n\t\tthis.browserEvent.preventDefault();\n\t}\n\n\tpublic stopPropagation(): void {\n\t\tthis.browserEvent.stopPropagation();\n\t}\n}\n\nexport class DragMouseEvent extends StandardMouseEvent {\n\n\tpublic readonly dataTransfer: DataTransfer;\n\n\tconstructor(targetWindow: Window, e: MouseEvent) {\n\t\tsuper(targetWindow, e);\n\t\tthis.dataTransfer = (e).dataTransfer;\n\t}\n}\n\nexport interface IMouseWheelEvent extends MouseEvent {\n\treadonly wheelDelta: number;\n\treadonly wheelDeltaX: number;\n\treadonly wheelDeltaY: number;\n\n\treadonly deltaX: number;\n\treadonly deltaY: number;\n\treadonly deltaZ: number;\n\treadonly deltaMode: number;\n}\n\ninterface IWebKitMouseWheelEvent {\n\twheelDeltaY: number;\n\twheelDeltaX: number;\n}\n\ninterface IGeckoMouseWheelEvent {\n\tHORIZONTAL_AXIS: number;\n\tVERTICAL_AXIS: number;\n\taxis: number;\n\tdetail: number;\n}\n\nexport class StandardWheelEvent {\n\n\tpublic readonly browserEvent: IMouseWheelEvent | null;\n\tpublic readonly deltaY: number;\n\tpublic readonly deltaX: number;\n\tpublic readonly target: Node;\n\n\tconstructor(e: IMouseWheelEvent | null, deltaX: number = 0, deltaY: number = 0) {\n\n\t\tthis.browserEvent = e || null;\n\t\tthis.target = e ? (e.target || (e).targetNode || e.srcElement) : null;\n\n\t\tthis.deltaY = deltaY;\n\t\tthis.deltaX = deltaX;\n\n\t\tlet shouldFactorDPR: boolean = false;\n\t\tif (browser.isChrome) {\n\t\t\t// Chrome version >= 123 contains the fix to factor devicePixelRatio into the wheel event.\n\t\t\t// See https://chromium.googlesource.com/chromium/src.git/+/be51b448441ff0c9d1f17e0f25c4bf1ab3f11f61\n\t\t\tconst chromeVersionMatch = navigator.userAgent.match(/Chrome\\/(\\d+)/);\n\t\t\tconst chromeMajorVersion = chromeVersionMatch ? parseInt(chromeVersionMatch[1]) : 123;\n\t\t\tshouldFactorDPR = chromeMajorVersion <= 122;\n\t\t}\n\n\t\tif (e) {\n\t\t\t// Old (deprecated) wheel events\n\t\t\tconst e1 = e;\n\t\t\tconst e2 = e;\n\t\t\tconst devicePixelRatio = e.view?.devicePixelRatio || 1;\n\n\t\t\t// vertical delta scroll\n\t\t\tif (typeof e1.wheelDeltaY !== 'undefined') {\n\t\t\t\tif (shouldFactorDPR) {\n\t\t\t\t\t// Refs https://github.com/microsoft/vscode/issues/146403#issuecomment-1854538928\n\t\t\t\t\tthis.deltaY = e1.wheelDeltaY / (120 * devicePixelRatio);\n\t\t\t\t} else {\n\t\t\t\t\tthis.deltaY = e1.wheelDeltaY / 120;\n\t\t\t\t}\n\t\t\t} else if (typeof e2.VERTICAL_AXIS !== 'undefined' && e2.axis === e2.VERTICAL_AXIS) {\n\t\t\t\tthis.deltaY = -e2.detail / 3;\n\t\t\t} else if (e.type === 'wheel') {\n\t\t\t\t// Modern wheel event\n\t\t\t\t// https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent\n\t\t\t\tconst ev = e;\n\n\t\t\t\tif (ev.deltaMode === ev.DOM_DELTA_LINE) {\n\t\t\t\t\t// the deltas are expressed in lines\n\t\t\t\t\tif (browser.isFirefox && !platform.isMacintosh) {\n\t\t\t\t\t\tthis.deltaY = -e.deltaY / 3;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.deltaY = -e.deltaY;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tthis.deltaY = -e.deltaY / 40;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// horizontal delta scroll\n\t\t\tif (typeof e1.wheelDeltaX !== 'undefined') {\n\t\t\t\tif (browser.isSafari && platform.isWindows) {\n\t\t\t\t\tthis.deltaX = - (e1.wheelDeltaX / 120);\n\t\t\t\t} else if (shouldFactorDPR) {\n\t\t\t\t\t// Refs https://github.com/microsoft/vscode/issues/146403#issuecomment-1854538928\n\t\t\t\t\tthis.deltaX = e1.wheelDeltaX / (120 * devicePixelRatio);\n\t\t\t\t} else {\n\t\t\t\t\tthis.deltaX = e1.wheelDeltaX / 120;\n\t\t\t\t}\n\t\t\t} else if (typeof e2.HORIZONTAL_AXIS !== 'undefined' && e2.axis === e2.HORIZONTAL_AXIS) {\n\t\t\t\tthis.deltaX = -e.detail / 3;\n\t\t\t} else if (e.type === 'wheel') {\n\t\t\t\t// Modern wheel event\n\t\t\t\t// https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent\n\t\t\t\tconst ev = e;\n\n\t\t\t\tif (ev.deltaMode === ev.DOM_DELTA_LINE) {\n\t\t\t\t\t// the deltas are expressed in lines\n\t\t\t\t\tif (browser.isFirefox && !platform.isMacintosh) {\n\t\t\t\t\t\tthis.deltaX = -e.deltaX / 3;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.deltaX = -e.deltaX;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tthis.deltaX = -e.deltaX / 40;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Assume a vertical scroll if nothing else worked\n\t\t\tif (this.deltaY === 0 && this.deltaX === 0 && e.wheelDelta) {\n\t\t\t\tif (shouldFactorDPR) {\n\t\t\t\t\t// Refs https://github.com/microsoft/vscode/issues/146403#issuecomment-1854538928\n\t\t\t\t\tthis.deltaY = e.wheelDelta / (120 * devicePixelRatio);\n\t\t\t\t} else {\n\t\t\t\t\tthis.deltaY = e.wheelDelta / 120;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic preventDefault(): void {\n\t\tthis.browserEvent?.preventDefault();\n\t}\n\n\tpublic stopPropagation(): void {\n\t\tthis.browserEvent?.stopPropagation();\n\t}\n}\n", "/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\nimport { Emitter, Event } from 'vs/base/common/event';\nimport { DisposableStore, IDisposable } from 'vs/base/common/lifecycle';\n\nexport interface CancellationToken {\n\n\t/**\n\t * A flag signalling is cancellation has been requested.\n\t */\n\treadonly isCancellationRequested: boolean;\n\n\t/**\n\t * An event which fires when cancellation is requested. This event\n\t * only ever fires `once` as cancellation can only happen once. Listeners\n\t * that are registered after cancellation will be called (next event loop run),\n\t * but also only once.\n\t *\n\t * @event\n\t */\n\treadonly onCancellationRequested: (listener: (e: any) => any, thisArgs?: any, disposables?: IDisposable[]) => IDisposable;\n}\n\nconst shortcutEvent: Event = Object.freeze(function (callback, context?): IDisposable {\n\tconst handle = setTimeout(callback.bind(context), 0);\n\treturn { dispose() { clearTimeout(handle); } };\n});\n\nexport namespace CancellationToken {\n\n\texport function isCancellationToken(thing: unknown): thing is CancellationToken {\n\t\tif (thing === CancellationToken.None || thing === CancellationToken.Cancelled) {\n\t\t\treturn true;\n\t\t}\n\t\tif (thing instanceof MutableToken) {\n\t\t\treturn true;\n\t\t}\n\t\tif (!thing || typeof thing !== 'object') {\n\t\t\treturn false;\n\t\t}\n\t\treturn typeof (thing as CancellationToken).isCancellationRequested === 'boolean'\n\t\t\t&& typeof (thing as CancellationToken).onCancellationRequested === 'function';\n\t}\n\n\n\texport const None = Object.freeze({\n\t\tisCancellationRequested: false,\n\t\tonCancellationRequested: Event.None\n\t});\n\n\texport const Cancelled = Object.freeze({\n\t\tisCancellationRequested: true,\n\t\tonCancellationRequested: shortcutEvent\n\t});\n}\n\nclass MutableToken implements CancellationToken {\n\n\tprivate _isCancelled: boolean = false;\n\tprivate _emitter: Emitter | null = null;\n\n\tpublic cancel() {\n\t\tif (!this._isCancelled) {\n\t\t\tthis._isCancelled = true;\n\t\t\tif (this._emitter) {\n\t\t\t\tthis._emitter.fire(undefined);\n\t\t\t\tthis.dispose();\n\t\t\t}\n\t\t}\n\t}\n\n\tget isCancellationRequested(): boolean {\n\t\treturn this._isCancelled;\n\t}\n\n\tget onCancellationRequested(): Event {\n\t\tif (this._isCancelled) {\n\t\t\treturn shortcutEvent;\n\t\t}\n\t\tif (!this._emitter) {\n\t\t\tthis._emitter = new Emitter();\n\t\t}\n\t\treturn this._emitter.event;\n\t}\n\n\tpublic dispose(): void {\n\t\tif (this._emitter) {\n\t\t\tthis._emitter.dispose();\n\t\t\tthis._emitter = null;\n\t\t}\n\t}\n}\n\nexport class CancellationTokenSource {\n\n\tprivate _token?: CancellationToken = undefined;\n\tprivate _parentListener?: IDisposable = undefined;\n\n\tconstructor(parent?: CancellationToken) {\n\t\tthis._parentListener = parent && parent.onCancellationRequested(this.cancel, this);\n\t}\n\n\tget token(): CancellationToken {\n\t\tif (!this._token) {\n\t\t\t// be lazy and create the token only when\n\t\t\t// actually needed\n\t\t\tthis._token = new MutableToken();\n\t\t}\n\t\treturn this._token;\n\t}\n\n\tcancel(): void {\n\t\tif (!this._token) {\n\t\t\t// save an object by returning the default\n\t\t\t// cancelled token when cancellation happens\n\t\t\t// before someone asks for the token\n\t\t\tthis._token = CancellationToken.Cancelled;\n\n\t\t} else if (this._token instanceof MutableToken) {\n\t\t\t// actually cancel\n\t\t\tthis._token.cancel();\n\t\t}\n\t}\n\n\tdispose(cancel: boolean = false): void {\n\t\tif (cancel) {\n\t\t\tthis.cancel();\n\t\t}\n\t\tthis._parentListener?.dispose();\n\t\tif (!this._token) {\n\t\t\t// ensure to initialize with an empty token if we had none\n\t\t\tthis._token = CancellationToken.None;\n\n\t\t} else if (this._token instanceof MutableToken) {\n\t\t\t// actually dispose\n\t\t\tthis._token.dispose();\n\t\t}\n\t}\n}\n\nexport function cancelOnDispose(store: DisposableStore): CancellationToken {\n\tconst source = new CancellationTokenSource();\n\tstore.add({ dispose() { source.cancel(); } });\n\treturn source.token;\n}\n", "/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n/**\n * Can be passed into the Delayed to defer using a microtask\n * */\nexport const MicrotaskDelay = Symbol('MicrotaskDelay');\n", "/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\nimport { CancellationToken, CancellationTokenSource } from 'vs/base/common/cancellation';\nimport { BugIndicatingError, CancellationError } from 'vs/base/common/errors';\nimport { Emitter, Event } from 'vs/base/common/event';\nimport { Disposable, DisposableStore, IDisposable, MutableDisposable, toDisposable } from 'vs/base/common/lifecycle';\nimport { setTimeout0 } from 'vs/base/common/platform';\nimport { MicrotaskDelay } from './symbols';\nimport { Lazy } from 'vs/base/common/lazy';\n\nexport function isThenable(obj: unknown): obj is Promise {\n\treturn !!obj && typeof (obj as unknown as Promise).then === 'function';\n}\n\nexport interface CancelablePromise extends Promise {\n\tcancel(): void;\n}\n\nexport function createCancelablePromise(callback: (token: CancellationToken) => Promise): CancelablePromise {\n\tconst source = new CancellationTokenSource();\n\n\tconst thenable = callback(source.token);\n\tconst promise = new Promise((resolve, reject) => {\n\t\tconst subscription = source.token.onCancellationRequested(() => {\n\t\t\tsubscription.dispose();\n\t\t\treject(new CancellationError());\n\t\t});\n\t\tPromise.resolve(thenable).then(value => {\n\t\t\tsubscription.dispose();\n\t\t\tsource.dispose();\n\t\t\tresolve(value);\n\t\t}, err => {\n\t\t\tsubscription.dispose();\n\t\t\tsource.dispose();\n\t\t\treject(err);\n\t\t});\n\t});\n\n\treturn >new class {\n\t\tcancel() {\n\t\t\tsource.cancel();\n\t\t\tsource.dispose();\n\t\t}\n\t\tthen(resolve?: ((value: T) => TResult1 | Promise) | undefined | null, reject?: ((reason: any) => TResult2 | Promise) | undefined | null): Promise {\n\t\t\treturn promise.then(resolve, reject);\n\t\t}\n\t\tcatch(reject?: ((reason: any) => TResult | Promise) | undefined | null): Promise {\n\t\t\treturn this.then(undefined, reject);\n\t\t}\n\t\tfinally(onfinally?: (() => void) | undefined | null): Promise {\n\t\t\treturn promise.finally(onfinally);\n\t\t}\n\t};\n}\n\n/**\n * Returns a promise that resolves with `undefined` as soon as the passed token is cancelled.\n * @see {@link raceCancellationError}\n */\nexport function raceCancellation(promise: Promise, token: CancellationToken): Promise;\n\n/**\n * Returns a promise that resolves with `defaultValue` as soon as the passed token is cancelled.\n * @see {@link raceCancellationError}\n */\nexport function raceCancellation(promise: Promise, token: CancellationToken, defaultValue: T): Promise;\n\nexport function raceCancellation(promise: Promise, token: CancellationToken, defaultValue?: T): Promise {\n\treturn new Promise((resolve, reject) => {\n\t\tconst ref = token.onCancellationRequested(() => {\n\t\t\tref.dispose();\n\t\t\tresolve(defaultValue);\n\t\t});\n\t\tpromise.then(resolve, reject).finally(() => ref.dispose());\n\t});\n}\n\n/**\n * Returns a promise that rejects with an {@CancellationError} as soon as the passed token is cancelled.\n * @see {@link raceCancellation}\n */\nexport function raceCancellationError(promise: Promise, token: CancellationToken): Promise {\n\treturn new Promise((resolve, reject) => {\n\t\tconst ref = token.onCancellationRequested(() => {\n\t\t\tref.dispose();\n\t\t\treject(new CancellationError());\n\t\t});\n\t\tpromise.then(resolve, reject).finally(() => ref.dispose());\n\t});\n}\n\n/**\n * Returns as soon as one of the promises resolves or rejects and cancels remaining promises\n */\nexport async function raceCancellablePromises(cancellablePromises: CancelablePromise[]): Promise {\n\tlet resolvedPromiseIndex = -1;\n\tconst promises = cancellablePromises.map((promise, index) => promise.then(result => { resolvedPromiseIndex = index; return result; }));\n\ttry {\n\t\tconst result = await Promise.race(promises);\n\t\treturn result;\n\t} finally {\n\t\tcancellablePromises.forEach((cancellablePromise, index) => {\n\t\t\tif (index !== resolvedPromiseIndex) {\n\t\t\t\tcancellablePromise.cancel();\n\t\t\t}\n\t\t});\n\t}\n}\n\nexport function raceTimeout(promise: Promise, timeout: number, onTimeout?: () => void): Promise {\n\tlet promiseResolve: ((value: T | undefined) => void) | undefined = undefined;\n\n\tconst timer = setTimeout(() => {\n\t\tpromiseResolve?.(undefined);\n\t\tonTimeout?.();\n\t}, timeout);\n\n\treturn Promise.race([\n\t\tpromise.finally(() => clearTimeout(timer)),\n\t\tnew Promise(resolve => promiseResolve = resolve)\n\t]);\n}\n\nexport function asPromise(callback: () => T | PromiseLike): Promise {\n\treturn new Promise((resolve, reject) => {\n\t\tconst item = callback();\n\t\tif (isThenable(item)) {\n\t\t\titem.then(resolve, reject);\n\t\t} else {\n\t\t\tresolve(item);\n\t\t}\n\t});\n}\n\n/**\n * Creates and returns a new promise, plus its `resolve` and `reject` callbacks.\n *\n * Replace with standardized [`Promise.withResolvers`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/withResolvers) once it is supported\n */\nexport function promiseWithResolvers(): { promise: Promise; resolve: (value: T | PromiseLike) => void; reject: (err?: any) => void } {\n\tlet resolve: (value: T | PromiseLike) => void;\n\tlet reject: (reason?: any) => void;\n\tconst promise = new Promise((res, rej) => {\n\t\tresolve = res;\n\t\treject = rej;\n\t});\n\treturn { promise, resolve: resolve!, reject: reject! };\n}\n\nexport interface ITask {\n\t(): T;\n}\n\n/**\n * A helper to prevent accumulation of sequential async tasks.\n *\n * Imagine a mail man with the sole task of delivering letters. As soon as\n * a letter submitted for delivery, he drives to the destination, delivers it\n * and returns to his base. Imagine that during the trip, N more letters were submitted.\n * When the mail man returns, he picks those N letters and delivers them all in a\n * single trip. Even though N+1 submissions occurred, only 2 deliveries were made.\n *\n * The throttler implements this via the queue() method, by providing it a task\n * factory. Following the example:\n *\n * \t\tconst throttler = new Throttler();\n * \t\tconst letters = [];\n *\n * \t\tfunction deliver() {\n * \t\t\tconst lettersToDeliver = letters;\n * \t\t\tletters = [];\n * \t\t\treturn makeTheTrip(lettersToDeliver);\n * \t\t}\n *\n * \t\tfunction onLetterReceived(l) {\n * \t\t\tletters.push(l);\n * \t\t\tthrottler.queue(deliver);\n * \t\t}\n */\nexport class Throttler implements IDisposable {\n\n\tprivate activePromise: Promise | null;\n\tprivate queuedPromise: Promise | null;\n\tprivate queuedPromiseFactory: ITask> | null;\n\n\tprivate isDisposed = false;\n\n\tconstructor() {\n\t\tthis.activePromise = null;\n\t\tthis.queuedPromise = null;\n\t\tthis.queuedPromiseFactory = null;\n\t}\n\n\tqueue(promiseFactory: ITask>): Promise {\n\t\tif (this.isDisposed) {\n\t\t\treturn Promise.reject(new Error('Throttler is disposed'));\n\t\t}\n\n\t\tif (this.activePromise) {\n\t\t\tthis.queuedPromiseFactory = promiseFactory;\n\n\t\t\tif (!this.queuedPromise) {\n\t\t\t\tconst onComplete = () => {\n\t\t\t\t\tthis.queuedPromise = null;\n\n\t\t\t\t\tif (this.isDisposed) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tconst result = this.queue(this.queuedPromiseFactory!);\n\t\t\t\t\tthis.queuedPromiseFactory = null;\n\n\t\t\t\t\treturn result;\n\t\t\t\t};\n\n\t\t\t\tthis.queuedPromise = new Promise(resolve => {\n\t\t\t\t\tthis.activePromise!.then(onComplete, onComplete).then(resolve);\n\t\t\t\t});\n\t\t\t}\n\n\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\tthis.queuedPromise!.then(resolve, reject);\n\t\t\t});\n\t\t}\n\n\t\tthis.activePromise = promiseFactory();\n\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tthis.activePromise!.then((result: T) => {\n\t\t\t\tthis.activePromise = null;\n\t\t\t\tresolve(result);\n\t\t\t}, (err: unknown) => {\n\t\t\t\tthis.activePromise = null;\n\t\t\t\treject(err);\n\t\t\t});\n\t\t});\n\t}\n\n\tdispose(): void {\n\t\tthis.isDisposed = true;\n\t}\n}\n\nexport class Sequencer {\n\n\tprivate current: Promise = Promise.resolve(null);\n\n\tqueue(promiseTask: ITask>): Promise {\n\t\treturn this.current = this.current.then(() => promiseTask(), () => promiseTask());\n\t}\n}\n\nexport class SequencerByKey {\n\n\tprivate promiseMap = new Map>();\n\n\tqueue(key: TKey, promiseTask: ITask>): Promise {\n\t\tconst runningPromise = this.promiseMap.get(key) ?? Promise.resolve();\n\t\tconst newPromise = runningPromise\n\t\t\t.catch(() => { })\n\t\t\t.then(promiseTask)\n\t\t\t.finally(() => {\n\t\t\t\tif (this.promiseMap.get(key) === newPromise) {\n\t\t\t\t\tthis.promiseMap.delete(key);\n\t\t\t\t}\n\t\t\t});\n\t\tthis.promiseMap.set(key, newPromise);\n\t\treturn newPromise;\n\t}\n}\n\ninterface IScheduledLater extends IDisposable {\n\tisTriggered(): boolean;\n}\n\nconst timeoutDeferred = (timeout: number, fn: () => void): IScheduledLater => {\n\tlet scheduled = true;\n\tconst handle = setTimeout(() => {\n\t\tscheduled = false;\n\t\tfn();\n\t}, timeout);\n\treturn {\n\t\tisTriggered: () => scheduled,\n\t\tdispose: () => {\n\t\t\tclearTimeout(handle);\n\t\t\tscheduled = false;\n\t\t},\n\t};\n};\n\nconst microtaskDeferred = (fn: () => void): IScheduledLater => {\n\tlet scheduled = true;\n\tqueueMicrotask(() => {\n\t\tif (scheduled) {\n\t\t\tscheduled = false;\n\t\t\tfn();\n\t\t}\n\t});\n\n\treturn {\n\t\tisTriggered: () => scheduled,\n\t\tdispose: () => { scheduled = false; },\n\t};\n};\n\n/**\n * A helper to delay (debounce) execution of a task that is being requested often.\n *\n * Following the throttler, now imagine the mail man wants to optimize the number of\n * trips proactively. The trip itself can be long, so he decides not to make the trip\n * as soon as a letter is submitted. Instead he waits a while, in case more\n * letters are submitted. After said waiting period, if no letters were submitted, he\n * decides to make the trip. Imagine that N more letters were submitted after the first\n * one, all within a short period of time between each other. Even though N+1\n * submissions occurred, only 1 delivery was made.\n *\n * The delayer offers this behavior via the trigger() method, into which both the task\n * to be executed and the waiting period (delay) must be passed in as arguments. Following\n * the example:\n *\n * \t\tconst delayer = new Delayer(WAITING_PERIOD);\n * \t\tconst letters = [];\n *\n * \t\tfunction letterReceived(l) {\n * \t\t\tletters.push(l);\n * \t\t\tdelayer.trigger(() => { return makeTheTrip(); });\n * \t\t}\n */\nexport class Delayer implements IDisposable {\n\n\tprivate deferred: IScheduledLater | null;\n\tprivate completionPromise: Promise | null;\n\tprivate doResolve: ((value?: any | Promise) => void) | null;\n\tprivate doReject: ((err: any) => void) | null;\n\tprivate task: ITask> | null;\n\n\tconstructor(public defaultDelay: number | typeof MicrotaskDelay) {\n\t\tthis.deferred = null;\n\t\tthis.completionPromise = null;\n\t\tthis.doResolve = null;\n\t\tthis.doReject = null;\n\t\tthis.task = null;\n\t}\n\n\ttrigger(task: ITask>, delay = this.defaultDelay): Promise {\n\t\tthis.task = task;\n\t\tthis.cancelTimeout();\n\n\t\tif (!this.completionPromise) {\n\t\t\tthis.completionPromise = new Promise((resolve, reject) => {\n\t\t\t\tthis.doResolve = resolve;\n\t\t\t\tthis.doReject = reject;\n\t\t\t}).then(() => {\n\t\t\t\tthis.completionPromise = null;\n\t\t\t\tthis.doResolve = null;\n\t\t\t\tif (this.task) {\n\t\t\t\t\tconst task = this.task;\n\t\t\t\t\tthis.task = null;\n\t\t\t\t\treturn task();\n\t\t\t\t}\n\t\t\t\treturn undefined;\n\t\t\t});\n\t\t}\n\n\t\tconst fn = () => {\n\t\t\tthis.deferred = null;\n\t\t\tthis.doResolve?.(null);\n\t\t};\n\n\t\tthis.deferred = delay === MicrotaskDelay ? microtaskDeferred(fn) : timeoutDeferred(delay, fn);\n\n\t\treturn this.completionPromise;\n\t}\n\n\tisTriggered(): boolean {\n\t\treturn !!this.deferred?.isTriggered();\n\t}\n\n\tcancel(): void {\n\t\tthis.cancelTimeout();\n\n\t\tif (this.completionPromise) {\n\t\t\tthis.doReject?.(new CancellationError());\n\t\t\tthis.completionPromise = null;\n\t\t}\n\t}\n\n\tprivate cancelTimeout(): void {\n\t\tthis.deferred?.dispose();\n\t\tthis.deferred = null;\n\t}\n\n\tdispose(): void {\n\t\tthis.cancel();\n\t}\n}\n\n/**\n * A helper to delay execution of a task that is being requested often, while\n * preventing accumulation of consecutive executions, while the task runs.\n *\n * The mail man is clever and waits for a certain amount of time, before going\n * out to deliver letters. While the mail man is going out, more letters arrive\n * and can only be delivered once he is back. Once he is back the mail man will\n * do one more trip to deliver the letters that have accumulated while he was out.\n */\nexport class ThrottledDelayer {\n\n\tprivate delayer: Delayer>;\n\tprivate throttler: Throttler;\n\n\tconstructor(defaultDelay: number) {\n\t\tthis.delayer = new Delayer(defaultDelay);\n\t\tthis.throttler = new Throttler();\n\t}\n\n\ttrigger(promiseFactory: ITask>, delay?: number): Promise {\n\t\treturn this.delayer.trigger(() => this.throttler.queue(promiseFactory), delay) as unknown as Promise;\n\t}\n\n\tisTriggered(): boolean {\n\t\treturn this.delayer.isTriggered();\n\t}\n\n\tcancel(): void {\n\t\tthis.delayer.cancel();\n\t}\n\n\tdispose(): void {\n\t\tthis.delayer.dispose();\n\t\tthis.throttler.dispose();\n\t}\n}\n\n/**\n * A barrier that is initially closed and then becomes opened permanently.\n */\nexport class Barrier {\n\tprivate _isOpen: boolean;\n\tprivate _promise: Promise;\n\tprivate _completePromise!: (v: boolean) => void;\n\n\tconstructor() {\n\t\tthis._isOpen = false;\n\t\tthis._promise = new Promise((c, e) => {\n\t\t\tthis._completePromise = c;\n\t\t});\n\t}\n\n\tisOpen(): boolean {\n\t\treturn this._isOpen;\n\t}\n\n\topen(): void {\n\t\tthis._isOpen = true;\n\t\tthis._completePromise(true);\n\t}\n\n\twait(): Promise {\n\t\treturn this._promise;\n\t}\n}\n\n/**\n * A barrier that is initially closed and then becomes opened permanently after a certain period of\n * time or when open is called explicitly\n */\nexport class AutoOpenBarrier extends Barrier {\n\n\tprivate readonly _timeout: any;\n\n\tconstructor(autoOpenTimeMs: number) {\n\t\tsuper();\n\t\tthis._timeout = setTimeout(() => this.open(), autoOpenTimeMs);\n\t}\n\n\toverride open(): void {\n\t\tclearTimeout(this._timeout);\n\t\tsuper.open();\n\t}\n}\n\nexport function timeout(millis: number): CancelablePromise;\nexport function timeout(millis: number, token: CancellationToken): Promise;\nexport function timeout(millis: number, token?: CancellationToken): CancelablePromise | Promise {\n\tif (!token) {\n\t\treturn createCancelablePromise(token => timeout(millis, token));\n\t}\n\n\treturn new Promise((resolve, reject) => {\n\t\tconst handle = setTimeout(() => {\n\t\t\tdisposable.dispose();\n\t\t\tresolve();\n\t\t}, millis);\n\t\tconst disposable = token.onCancellationRequested(() => {\n\t\t\tclearTimeout(handle);\n\t\t\tdisposable.dispose();\n\t\t\treject(new CancellationError());\n\t\t});\n\t});\n}\n\n/**\n * Creates a timeout that can be disposed using its returned value.\n * @param handler The timeout handler.\n * @param timeout An optional timeout in milliseconds.\n * @param store An optional {@link DisposableStore} that will have the timeout disposable managed automatically.\n *\n * @example\n * const store = new DisposableStore;\n * // Call the timeout after 1000ms at which point it will be automatically\n * // evicted from the store.\n * const timeoutDisposable = disposableTimeout(() => {}, 1000, store);\n *\n * if (foo) {\n * // Cancel the timeout and evict it from store.\n * timeoutDisposable.dispose();\n * }\n */\nexport function disposableTimeout(handler: () => void, timeout = 0, store?: DisposableStore): IDisposable {\n\tconst timer = setTimeout(() => {\n\t\thandler();\n\t\tif (store) {\n\t\t\tdisposable.dispose();\n\t\t}\n\t}, timeout);\n\tconst disposable = toDisposable(() => {\n\t\tclearTimeout(timer);\n\t\tstore?.deleteAndLeak(disposable);\n\t});\n\tstore?.add(disposable);\n\treturn disposable;\n}\n\n/**\n * Runs the provided list of promise factories in sequential order. The returned\n * promise will complete to an array of results from each promise.\n */\n\nexport function sequence(promiseFactories: ITask>[]): Promise {\n\tconst results: T[] = [];\n\tlet index = 0;\n\tconst len = promiseFactories.length;\n\n\tfunction next(): Promise | null {\n\t\treturn index < len ? promiseFactories[index++]() : null;\n\t}\n\n\tfunction thenHandler(result: any): Promise {\n\t\tif (result !== undefined && result !== null) {\n\t\t\tresults.push(result);\n\t\t}\n\n\t\tconst n = next();\n\t\tif (n) {\n\t\t\treturn n.then(thenHandler);\n\t\t}\n\n\t\treturn Promise.resolve(results);\n\t}\n\n\treturn Promise.resolve(null).then(thenHandler);\n}\n\nexport function first(promiseFactories: ITask>[], shouldStop: (t: T) => boolean = t => !!t, defaultValue: T | null = null): Promise {\n\tlet index = 0;\n\tconst len = promiseFactories.length;\n\n\tconst loop: () => Promise = () => {\n\t\tif (index >= len) {\n\t\t\treturn Promise.resolve(defaultValue);\n\t\t}\n\n\t\tconst factory = promiseFactories[index++];\n\t\tconst promise = Promise.resolve(factory());\n\n\t\treturn promise.then(result => {\n\t\t\tif (shouldStop(result)) {\n\t\t\t\treturn Promise.resolve(result);\n\t\t\t}\n\n\t\t\treturn loop();\n\t\t});\n\t};\n\n\treturn loop();\n}\n\n/**\n * Returns the result of the first promise that matches the \"shouldStop\",\n * running all promises in parallel. Supports cancelable promises.\n */\nexport function firstParallel(promiseList: Promise[], shouldStop?: (t: T) => boolean, defaultValue?: T | null): Promise;\nexport function firstParallel(promiseList: Promise[], shouldStop: (t: T) => t is R, defaultValue?: R | null): Promise;\nexport function firstParallel(promiseList: Promise[], shouldStop: (t: T) => boolean = t => !!t, defaultValue: T | null = null) {\n\tif (promiseList.length === 0) {\n\t\treturn Promise.resolve(defaultValue);\n\t}\n\n\tlet todo = promiseList.length;\n\tconst finish = () => {\n\t\ttodo = -1;\n\t\tfor (const promise of promiseList) {\n\t\t\t(promise as Partial>).cancel?.();\n\t\t}\n\t};\n\n\treturn new Promise((resolve, reject) => {\n\t\tfor (const promise of promiseList) {\n\t\t\tpromise.then(result => {\n\t\t\t\tif (--todo >= 0 && shouldStop(result)) {\n\t\t\t\t\tfinish();\n\t\t\t\t\tresolve(result);\n\t\t\t\t} else if (todo === 0) {\n\t\t\t\t\tresolve(defaultValue);\n\t\t\t\t}\n\t\t\t})\n\t\t\t\t.catch(err => {\n\t\t\t\t\tif (--todo >= 0) {\n\t\t\t\t\t\tfinish();\n\t\t\t\t\t\treject(err);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t}\n\t});\n}\n\ninterface ILimitedTaskFactory {\n\tfactory: ITask>;\n\tc: (value: T | Promise) => void;\n\te: (error?: unknown) => void;\n}\n\nexport interface ILimiter {\n\n\treadonly size: number;\n\n\tqueue(factory: ITask>): Promise;\n\n\tclear(): void;\n}\n\n/**\n * A helper to queue N promises and run them all with a max degree of parallelism. The helper\n * ensures that at any time no more than M promises are running at the same time.\n */\nexport class Limiter implements ILimiter {\n\n\tprivate _size = 0;\n\tprivate _isDisposed = false;\n\tprivate runningPromises: number;\n\tprivate readonly maxDegreeOfParalellism: number;\n\tprivate readonly outstandingPromises: ILimitedTaskFactory[];\n\tprivate readonly _onDrained: Emitter;\n\n\tconstructor(maxDegreeOfParalellism: number) {\n\t\tthis.maxDegreeOfParalellism = maxDegreeOfParalellism;\n\t\tthis.outstandingPromises = [];\n\t\tthis.runningPromises = 0;\n\t\tthis._onDrained = new Emitter();\n\t}\n\n\t/**\n\t *\n\t * @returns A promise that resolved when all work is done (onDrained) or when\n\t * there is nothing to do\n\t */\n\twhenIdle(): Promise {\n\t\treturn this.size > 0\n\t\t\t? Event.toPromise(this.onDrained)\n\t\t\t: Promise.resolve();\n\t}\n\n\tget onDrained(): Event {\n\t\treturn this._onDrained.event;\n\t}\n\n\tget size(): number {\n\t\treturn this._size;\n\t}\n\n\tqueue(factory: ITask>): Promise {\n\t\tif (this._isDisposed) {\n\t\t\tthrow new Error('Object has been disposed');\n\t\t}\n\t\tthis._size++;\n\n\t\treturn new Promise((c, e) => {\n\t\t\tthis.outstandingPromises.push({ factory, c, e });\n\t\t\tthis.consume();\n\t\t});\n\t}\n\n\tprivate consume(): void {\n\t\twhile (this.outstandingPromises.length && this.runningPromises < this.maxDegreeOfParalellism) {\n\t\t\tconst iLimitedTask = this.outstandingPromises.shift()!;\n\t\t\tthis.runningPromises++;\n\n\t\t\tconst promise = iLimitedTask.factory();\n\t\t\tpromise.then(iLimitedTask.c, iLimitedTask.e);\n\t\t\tpromise.then(() => this.consumed(), () => this.consumed());\n\t\t}\n\t}\n\n\tprivate consumed(): void {\n\t\tif (this._isDisposed) {\n\t\t\treturn;\n\t\t}\n\t\tthis.runningPromises--;\n\t\tif (--this._size === 0) {\n\t\t\tthis._onDrained.fire();\n\t\t}\n\n\t\tif (this.outstandingPromises.length > 0) {\n\t\t\tthis.consume();\n\t\t}\n\t}\n\n\tclear(): void {\n\t\tif (this._isDisposed) {\n\t\t\tthrow new Error('Object has been disposed');\n\t\t}\n\t\tthis.outstandingPromises.length = 0;\n\t\tthis._size = this.runningPromises;\n\t}\n\n\tdispose(): void {\n\t\tthis._isDisposed = true;\n\t\tthis.outstandingPromises.length = 0; // stop further processing\n\t\tthis._size = 0;\n\t\tthis._onDrained.dispose();\n\t}\n}\n\n/**\n * A queue is handles one promise at a time and guarantees that at any time only one promise is executing.\n */\nexport class Queue extends Limiter {\n\n\tconstructor() {\n\t\tsuper(1);\n\t}\n}\n\n/**\n * Same as `Queue`, ensures that only 1 task is executed at the same time. The difference to `Queue` is that\n * there is only 1 task about to be scheduled next. As such, calling `queue` while a task is executing will\n * replace the currently queued task until it executes.\n *\n * As such, the returned promise may not be from the factory that is passed in but from the next factory that\n * is running after having called `queue`.\n */\nexport class LimitedQueue {\n\n\tprivate readonly sequentializer = new TaskSequentializer();\n\n\tprivate tasks = 0;\n\n\tqueue(factory: ITask>): Promise {\n\t\tif (!this.sequentializer.isRunning()) {\n\t\t\treturn this.sequentializer.run(this.tasks++, factory());\n\t\t}\n\n\t\treturn this.sequentializer.queue(() => {\n\t\t\treturn this.sequentializer.run(this.tasks++, factory());\n\t\t});\n\t}\n}\n\nexport class TimeoutTimer implements IDisposable {\n\tprivate _token: any;\n\tprivate _isDisposed = false;\n\n\tconstructor();\n\tconstructor(runner: () => void, timeout: number);\n\tconstructor(runner?: () => void, timeout?: number) {\n\t\tthis._token = -1;\n\n\t\tif (typeof runner === 'function' && typeof timeout === 'number') {\n\t\t\tthis.setIfNotSet(runner, timeout);\n\t\t}\n\t}\n\n\tdispose(): void {\n\t\tthis.cancel();\n\t\tthis._isDisposed = true;\n\t}\n\n\tcancel(): void {\n\t\tif (this._token !== -1) {\n\t\t\tclearTimeout(this._token);\n\t\t\tthis._token = -1;\n\t\t}\n\t}\n\n\tcancelAndSet(runner: () => void, timeout: number): void {\n\t\tif (this._isDisposed) {\n\t\t\tthrow new BugIndicatingError(`Calling 'cancelAndSet' on a disposed TimeoutTimer`);\n\t\t}\n\n\t\tthis.cancel();\n\t\tthis._token = setTimeout(() => {\n\t\t\tthis._token = -1;\n\t\t\trunner();\n\t\t}, timeout);\n\t}\n\n\tsetIfNotSet(runner: () => void, timeout: number): void {\n\t\tif (this._isDisposed) {\n\t\t\tthrow new BugIndicatingError(`Calling 'setIfNotSet' on a disposed TimeoutTimer`);\n\t\t}\n\n\t\tif (this._token !== -1) {\n\t\t\t// timer is already set\n\t\t\treturn;\n\t\t}\n\t\tthis._token = setTimeout(() => {\n\t\t\tthis._token = -1;\n\t\t\trunner();\n\t\t}, timeout);\n\t}\n}\n\nexport class IntervalTimer implements IDisposable {\n\n\tprivate disposable: IDisposable | undefined = undefined;\n\tprivate isDisposed = false;\n\n\tcancel(): void {\n\t\tthis.disposable?.dispose();\n\t\tthis.disposable = undefined;\n\t}\n\n\tcancelAndSet(runner: () => void, interval: number, context = globalThis): void {\n\t\tif (this.isDisposed) {\n\t\t\tthrow new BugIndicatingError(`Calling 'cancelAndSet' on a disposed IntervalTimer`);\n\t\t}\n\n\t\tthis.cancel();\n\t\tconst handle = context.setInterval(() => {\n\t\t\trunner();\n\t\t}, interval);\n\n\t\tthis.disposable = toDisposable(() => {\n\t\t\tcontext.clearInterval(handle);\n\t\t\tthis.disposable = undefined;\n\t\t});\n\t}\n\n\tdispose(): void {\n\t\tthis.cancel();\n\t\tthis.isDisposed = true;\n\t}\n}\n\nexport class RunOnceScheduler implements IDisposable {\n\n\tprotected runner: ((...args: unknown[]) => void) | null;\n\n\tprivate timeoutToken: any;\n\tprivate timeout: number;\n\tprivate timeoutHandler: () => void;\n\n\tconstructor(runner: (...args: any[]) => void, delay: number) {\n\t\tthis.timeoutToken = -1;\n\t\tthis.runner = runner;\n\t\tthis.timeout = delay;\n\t\tthis.timeoutHandler = this.onTimeout.bind(this);\n\t}\n\n\t/**\n\t * Dispose RunOnceScheduler\n\t */\n\tdispose(): void {\n\t\tthis.cancel();\n\t\tthis.runner = null;\n\t}\n\n\t/**\n\t * Cancel current scheduled runner (if any).\n\t */\n\tcancel(): void {\n\t\tif (this.isScheduled()) {\n\t\t\tclearTimeout(this.timeoutToken);\n\t\t\tthis.timeoutToken = -1;\n\t\t}\n\t}\n\n\t/**\n\t * Cancel previous runner (if any) & schedule a new runner.\n\t */\n\tschedule(delay = this.timeout): void {\n\t\tthis.cancel();\n\t\tthis.timeoutToken = setTimeout(this.timeoutHandler, delay);\n\t}\n\n\tget delay(): number {\n\t\treturn this.timeout;\n\t}\n\n\tset delay(value: number) {\n\t\tthis.timeout = value;\n\t}\n\n\t/**\n\t * Returns true if scheduled.\n\t */\n\tisScheduled(): boolean {\n\t\treturn this.timeoutToken !== -1;\n\t}\n\n\tflush(): void {\n\t\tif (this.isScheduled()) {\n\t\t\tthis.cancel();\n\t\t\tthis.doRun();\n\t\t}\n\t}\n\n\tprivate onTimeout() {\n\t\tthis.timeoutToken = -1;\n\t\tif (this.runner) {\n\t\t\tthis.doRun();\n\t\t}\n\t}\n\n\tprotected doRun(): void {\n\t\tthis.runner?.();\n\t}\n}\n\n/**\n * Same as `RunOnceScheduler`, but doesn't count the time spent in sleep mode.\n * > **NOTE**: Only offers 1s resolution.\n *\n * When calling `setTimeout` with 3hrs, and putting the computer immediately to sleep\n * for 8hrs, `setTimeout` will fire **as soon as the computer wakes from sleep**. But\n * this scheduler will execute 3hrs **after waking the computer from sleep**.\n */\nexport class ProcessTimeRunOnceScheduler {\n\n\tprivate runner: (() => void) | null;\n\tprivate timeout: number;\n\n\tprivate counter: number;\n\tprivate intervalToken: any;\n\tprivate intervalHandler: () => void;\n\n\tconstructor(runner: () => void, delay: number) {\n\t\tif (delay % 1000 !== 0) {\n\t\t\tconsole.warn(`ProcessTimeRunOnceScheduler resolution is 1s, ${delay}ms is not a multiple of 1000ms.`);\n\t\t}\n\t\tthis.runner = runner;\n\t\tthis.timeout = delay;\n\t\tthis.counter = 0;\n\t\tthis.intervalToken = -1;\n\t\tthis.intervalHandler = this.onInterval.bind(this);\n\t}\n\n\tdispose(): void {\n\t\tthis.cancel();\n\t\tthis.runner = null;\n\t}\n\n\tcancel(): void {\n\t\tif (this.isScheduled()) {\n\t\t\tclearInterval(this.intervalToken);\n\t\t\tthis.intervalToken = -1;\n\t\t}\n\t}\n\n\t/**\n\t * Cancel previous runner (if any) & schedule a new runner.\n\t */\n\tschedule(delay = this.timeout): void {\n\t\tif (delay % 1000 !== 0) {\n\t\t\tconsole.warn(`ProcessTimeRunOnceScheduler resolution is 1s, ${delay}ms is not a multiple of 1000ms.`);\n\t\t}\n\t\tthis.cancel();\n\t\tthis.counter = Math.ceil(delay / 1000);\n\t\tthis.intervalToken = setInterval(this.intervalHandler, 1000);\n\t}\n\n\t/**\n\t * Returns true if scheduled.\n\t */\n\tisScheduled(): boolean {\n\t\treturn this.intervalToken !== -1;\n\t}\n\n\tprivate onInterval() {\n\t\tthis.counter--;\n\t\tif (this.counter > 0) {\n\t\t\t// still need to wait\n\t\t\treturn;\n\t\t}\n\n\t\t// time elapsed\n\t\tclearInterval(this.intervalToken);\n\t\tthis.intervalToken = -1;\n\t\tthis.runner?.();\n\t}\n}\n\nexport class RunOnceWorker extends RunOnceScheduler {\n\n\tprivate units: T[] = [];\n\n\tconstructor(runner: (units: T[]) => void, timeout: number) {\n\t\tsuper(runner, timeout);\n\t}\n\n\twork(unit: T): void {\n\t\tthis.units.push(unit);\n\n\t\tif (!this.isScheduled()) {\n\t\t\tthis.schedule();\n\t\t}\n\t}\n\n\tprotected override doRun(): void {\n\t\tconst units = this.units;\n\t\tthis.units = [];\n\n\t\tthis.runner?.(units);\n\t}\n\n\toverride dispose(): void {\n\t\tthis.units = [];\n\n\t\tsuper.dispose();\n\t}\n}\n\nexport interface IThrottledWorkerOptions {\n\n\t/**\n\t * maximum of units the worker will pass onto handler at once\n\t */\n\tmaxWorkChunkSize: number;\n\n\t/**\n\t * maximum of units the worker will keep in memory for processing\n\t */\n\tmaxBufferedWork: number | undefined;\n\n\t/**\n\t * delay before processing the next round of chunks when chunk size exceeds limits\n\t */\n\tthrottleDelay: number;\n}\n\n/**\n * The `ThrottledWorker` will accept units of work `T`\n * to handle. The contract is:\n * * there is a maximum of units the worker can handle at once (via `maxWorkChunkSize`)\n * * there is a maximum of units the worker will keep in memory for processing (via `maxBufferedWork`)\n * * after having handled `maxWorkChunkSize` units, the worker needs to rest (via `throttleDelay`)\n */\nexport class ThrottledWorker extends Disposable {\n\n\tprivate readonly pendingWork: T[] = [];\n\n\tprivate readonly throttler = this._register(new MutableDisposable());\n\tprivate disposed = false;\n\n\tconstructor(\n\t\tprivate options: IThrottledWorkerOptions,\n\t\tprivate readonly handler: (units: T[]) => void\n\t) {\n\t\tsuper();\n\t}\n\n\t/**\n\t * The number of work units that are pending to be processed.\n\t */\n\tget pending(): number { return this.pendingWork.length; }\n\n\t/**\n\t * Add units to be worked on. Use `pending` to figure out\n\t * how many units are not yet processed after this method\n\t * was called.\n\t *\n\t * @returns whether the work was accepted or not. If the\n\t * worker is disposed, it will not accept any more work.\n\t * If the number of pending units would become larger\n\t * than `maxPendingWork`, more work will also not be accepted.\n\t */\n\twork(units: readonly T[]): boolean {\n\t\tif (this.disposed) {\n\t\t\treturn false; // work not accepted: disposed\n\t\t}\n\n\t\t// Check for reaching maximum of pending work\n\t\tif (typeof this.options.maxBufferedWork === 'number') {\n\n\t\t\t// Throttled: simple check if pending + units exceeds max pending\n\t\t\tif (this.throttler.value) {\n\t\t\t\tif (this.pending + units.length > this.options.maxBufferedWork) {\n\t\t\t\t\treturn false; // work not accepted: too much pending work\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Unthrottled: same as throttled, but account for max chunk getting\n\t\t\t// worked on directly without being pending\n\t\t\telse {\n\t\t\t\tif (this.pending + units.length - this.options.maxWorkChunkSize > this.options.maxBufferedWork) {\n\t\t\t\t\treturn false; // work not accepted: too much pending work\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Add to pending units first\n\t\tfor (const unit of units) {\n\t\t\tthis.pendingWork.push(unit);\n\t\t}\n\n\t\t// If not throttled, start working directly\n\t\t// Otherwise, when the throttle delay has\n\t\t// past, pending work will be worked again.\n\t\tif (!this.throttler.value) {\n\t\t\tthis.doWork();\n\t\t}\n\n\t\treturn true; // work accepted\n\t}\n\n\tprivate doWork(): void {\n\n\t\t// Extract chunk to handle and handle it\n\t\tthis.handler(this.pendingWork.splice(0, this.options.maxWorkChunkSize));\n\n\t\t// If we have remaining work, schedule it after a delay\n\t\tif (this.pendingWork.length > 0) {\n\t\t\tthis.throttler.value = new RunOnceScheduler(() => {\n\t\t\t\tthis.throttler.clear();\n\n\t\t\t\tthis.doWork();\n\t\t\t}, this.options.throttleDelay);\n\t\t\tthis.throttler.value.schedule();\n\t\t}\n\t}\n\n\toverride dispose(): void {\n\t\tsuper.dispose();\n\n\t\tthis.disposed = true;\n\t}\n}\n\n//#region -- run on idle tricks ------------\n\nexport interface IdleDeadline {\n\treadonly didTimeout: boolean;\n\ttimeRemaining(): number;\n}\n\ntype IdleApi = Pick;\n\n\n/**\n * Execute the callback the next time the browser is idle, returning an\n * {@link IDisposable} that will cancel the callback when disposed. This wraps\n * [requestIdleCallback] so it will fallback to [setTimeout] if the environment\n * doesn't support it.\n *\n * @param callback The callback to run when idle, this includes an\n * [IdleDeadline] that provides the time alloted for the idle callback by the\n * browser. Not respecting this deadline will result in a degraded user\n * experience.\n * @param timeout A timeout at which point to queue no longer wait for an idle\n * callback but queue it on the regular event loop (like setTimeout). Typically\n * this should not be used.\n *\n * [IdleDeadline]: https://developer.mozilla.org/en-US/docs/Web/API/IdleDeadline\n * [requestIdleCallback]: https://developer.mozilla.org/en-US/docs/Web/API/Window/requestIdleCallback\n * [setTimeout]: https://developer.mozilla.org/en-US/docs/Web/API/Window/setTimeout\n *\n * **Note** that there is `dom.ts#runWhenWindowIdle` which is better suited when running inside a browser\n * context\n */\nexport let runWhenGlobalIdle: (callback: (idle: IdleDeadline) => void, timeout?: number) => IDisposable;\n\nexport let _runWhenIdle: (targetWindow: IdleApi, callback: (idle: IdleDeadline) => void, timeout?: number) => IDisposable;\n\n(function () {\n\tif (typeof globalThis.requestIdleCallback !== 'function' || typeof globalThis.cancelIdleCallback !== 'function') {\n\t\t_runWhenIdle = (_targetWindow, runner) => {\n\t\t\tsetTimeout0(() => {\n\t\t\t\tif (disposed) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst end = Date.now() + 15; // one frame at 64fps\n\t\t\t\tconst deadline: IdleDeadline = {\n\t\t\t\t\tdidTimeout: true,\n\t\t\t\t\ttimeRemaining() {\n\t\t\t\t\t\treturn Math.max(0, end - Date.now());\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\trunner(Object.freeze(deadline));\n\t\t\t});\n\t\t\tlet disposed = false;\n\t\t\treturn {\n\t\t\t\tdispose() {\n\t\t\t\t\tif (disposed) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tdisposed = true;\n\t\t\t\t}\n\t\t\t};\n\t\t};\n\t} else {\n\t\t_runWhenIdle = (targetWindow: IdleApi, runner, timeout?) => {\n\t\t\tconst handle: number = targetWindow.requestIdleCallback(runner, typeof timeout === 'number' ? { timeout } : undefined);\n\t\t\tlet disposed = false;\n\t\t\treturn {\n\t\t\t\tdispose() {\n\t\t\t\t\tif (disposed) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tdisposed = true;\n\t\t\t\t\ttargetWindow.cancelIdleCallback(handle);\n\t\t\t\t}\n\t\t\t};\n\t\t};\n\t}\n\trunWhenGlobalIdle = (runner) => _runWhenIdle(globalThis, runner);\n})();\n\nexport abstract class AbstractIdleValue {\n\n\tprivate readonly _executor: () => void;\n\tprivate readonly _handle: IDisposable;\n\n\tprivate _didRun: boolean = false;\n\tprivate _value?: T;\n\tprivate _error: unknown;\n\n\tconstructor(targetWindow: IdleApi, executor: () => T) {\n\t\tthis._executor = () => {\n\t\t\ttry {\n\t\t\t\tthis._value = executor();\n\t\t\t} catch (err) {\n\t\t\t\tthis._error = err;\n\t\t\t} finally {\n\t\t\t\tthis._didRun = true;\n\t\t\t}\n\t\t};\n\t\tthis._handle = _runWhenIdle(targetWindow, () => this._executor());\n\t}\n\n\tdispose(): void {\n\t\tthis._handle.dispose();\n\t}\n\n\tget value(): T {\n\t\tif (!this._didRun) {\n\t\t\tthis._handle.dispose();\n\t\t\tthis._executor();\n\t\t}\n\t\tif (this._error) {\n\t\t\tthrow this._error;\n\t\t}\n\t\treturn this._value!;\n\t}\n\n\tget isInitialized(): boolean {\n\t\treturn this._didRun;\n\t}\n}\n\n/**\n * An `IdleValue` that always uses the current window (which might be throttled or inactive)\n *\n * **Note** that there is `dom.ts#WindowIdleValue` which is better suited when running inside a browser\n * context\n */\nexport class GlobalIdleValue extends AbstractIdleValue {\n\n\tconstructor(executor: () => T) {\n\t\tsuper(globalThis, executor);\n\t}\n}\n\n//#endregion\n\nexport async function retry(task: ITask>, delay: number, retries: number): Promise {\n\tlet lastError: Error | undefined;\n\n\tfor (let i = 0; i < retries; i++) {\n\t\ttry {\n\t\t\treturn await task();\n\t\t} catch (error) {\n\t\t\tlastError = error;\n\n\t\t\tawait timeout(delay);\n\t\t}\n\t}\n\n\tthrow lastError;\n}\n\n//#region Task Sequentializer\n\ninterface IRunningTask {\n\treadonly taskId: number;\n\treadonly cancel: () => void;\n\treadonly promise: Promise;\n}\n\ninterface IQueuedTask {\n\treadonly promise: Promise;\n\treadonly promiseResolve: () => void;\n\treadonly promiseReject: (error: Error) => void;\n\trun: ITask>;\n}\n\nexport interface ITaskSequentializerWithRunningTask {\n\treadonly running: Promise;\n}\n\nexport interface ITaskSequentializerWithQueuedTask {\n\treadonly queued: IQueuedTask;\n}\n\n/**\n * @deprecated use `LimitedQueue` instead for an easier to use API\n */\nexport class TaskSequentializer {\n\n\tprivate _running?: IRunningTask;\n\tprivate _queued?: IQueuedTask;\n\n\tisRunning(taskId?: number): this is ITaskSequentializerWithRunningTask {\n\t\tif (typeof taskId === 'number') {\n\t\t\treturn this._running?.taskId === taskId;\n\t\t}\n\n\t\treturn !!this._running;\n\t}\n\n\tget running(): Promise | undefined {\n\t\treturn this._running?.promise;\n\t}\n\n\tcancelRunning(): void {\n\t\tthis._running?.cancel();\n\t}\n\n\trun(taskId: number, promise: Promise, onCancel?: () => void,): Promise {\n\t\tthis._running = { taskId, cancel: () => onCancel?.(), promise };\n\n\t\tpromise.then(() => this.doneRunning(taskId), () => this.doneRunning(taskId));\n\n\t\treturn promise;\n\t}\n\n\tprivate doneRunning(taskId: number): void {\n\t\tif (this._running && taskId === this._running.taskId) {\n\n\t\t\t// only set running to done if the promise finished that is associated with that taskId\n\t\t\tthis._running = undefined;\n\n\t\t\t// schedule the queued task now that we are free if we have any\n\t\t\tthis.runQueued();\n\t\t}\n\t}\n\n\tprivate runQueued(): void {\n\t\tif (this._queued) {\n\t\t\tconst queued = this._queued;\n\t\t\tthis._queued = undefined;\n\n\t\t\t// Run queued task and complete on the associated promise\n\t\t\tqueued.run().then(queued.promiseResolve, queued.promiseReject);\n\t\t}\n\t}\n\n\t/**\n\t * Note: the promise to schedule as next run MUST itself call `run`.\n\t * Otherwise, this sequentializer will report `false` for `isRunning`\n\t * even when this task is running. Missing this detail means that\n\t * suddenly multiple tasks will run in parallel.\n\t */\n\tqueue(run: ITask>): Promise {\n\n\t\t// this is our first queued task, so we create associated promise with it\n\t\t// so that we can return a promise that completes when the task has\n\t\t// completed.\n\t\tif (!this._queued) {\n\t\t\tconst { promise, resolve: promiseResolve, reject: promiseReject } = promiseWithResolvers();\n\t\t\tthis._queued = {\n\t\t\t\trun,\n\t\t\t\tpromise,\n\t\t\t\tpromiseResolve: promiseResolve!,\n\t\t\t\tpromiseReject: promiseReject!\n\t\t\t};\n\t\t}\n\n\t\t// we have a previous queued task, just overwrite it\n\t\telse {\n\t\t\tthis._queued.run = run;\n\t\t}\n\n\t\treturn this._queued.promise;\n\t}\n\n\thasQueued(): this is ITaskSequentializerWithQueuedTask {\n\t\treturn !!this._queued;\n\t}\n\n\tasync join(): Promise {\n\t\treturn this._queued?.promise ?? this._running?.promise;\n\t}\n}\n\n//#endregion\n\n//#region\n\n/**\n * The `IntervalCounter` allows to count the number\n * of calls to `increment()` over a duration of\n * `interval`. This utility can be used to conditionally\n * throttle a frequent task when a certain threshold\n * is reached.\n */\nexport class IntervalCounter {\n\n\tprivate lastIncrementTime = 0;\n\n\tprivate value = 0;\n\n\tconstructor(private readonly interval: number, private readonly nowFn = () => Date.now()) { }\n\n\tincrement(): number {\n\t\tconst now = this.nowFn();\n\n\t\t// We are outside of the range of `interval` and as such\n\t\t// start counting from 0 and remember the time\n\t\tif (now - this.lastIncrementTime > this.interval) {\n\t\t\tthis.lastIncrementTime = now;\n\t\t\tthis.value = 0;\n\t\t}\n\n\t\tthis.value++;\n\n\t\treturn this.value;\n\t}\n}\n\n//#endregion\n\n//#region\n\nexport type ValueCallback = (value: T | Promise) => void;\n\nconst enum DeferredOutcome {\n\tResolved,\n\tRejected\n}\n\n/**\n * Creates a promise whose resolution or rejection can be controlled imperatively.\n */\nexport class DeferredPromise {\n\n\tprivate completeCallback!: ValueCallback;\n\tprivate errorCallback!: (err: unknown) => void;\n\tprivate outcome?: { outcome: DeferredOutcome.Rejected; value: any } | { outcome: DeferredOutcome.Resolved; value: T };\n\n\tpublic get isRejected() {\n\t\treturn this.outcome?.outcome === DeferredOutcome.Rejected;\n\t}\n\n\tpublic get isResolved() {\n\t\treturn this.outcome?.outcome === DeferredOutcome.Resolved;\n\t}\n\n\tpublic get isSettled() {\n\t\treturn !!this.outcome;\n\t}\n\n\tpublic get value() {\n\t\treturn this.outcome?.outcome === DeferredOutcome.Resolved ? this.outcome?.value : undefined;\n\t}\n\n\tpublic readonly p: Promise;\n\n\tconstructor() {\n\t\tthis.p = new Promise((c, e) => {\n\t\t\tthis.completeCallback = c;\n\t\t\tthis.errorCallback = e;\n\t\t});\n\t}\n\n\tpublic complete(value: T) {\n\t\treturn new Promise(resolve => {\n\t\t\tthis.completeCallback(value);\n\t\t\tthis.outcome = { outcome: DeferredOutcome.Resolved, value };\n\t\t\tresolve();\n\t\t});\n\t}\n\n\tpublic error(err: unknown) {\n\t\treturn new Promise(resolve => {\n\t\t\tthis.errorCallback(err);\n\t\t\tthis.outcome = { outcome: DeferredOutcome.Rejected, value: err };\n\t\t\tresolve();\n\t\t});\n\t}\n\n\tpublic cancel() {\n\t\treturn this.error(new CancellationError());\n\t}\n}\n\n//#endregion\n\n//#region Promises\n\nexport namespace Promises {\n\n\t/**\n\t * A drop-in replacement for `Promise.all` with the only difference\n\t * that the method awaits every promise to either fulfill or reject.\n\t *\n\t * Similar to `Promise.all`, only the first error will be returned\n\t * if any.\n\t */\n\texport async function settled(promises: Promise[]): Promise {\n\t\tlet firstError: Error | undefined = undefined;\n\n\t\tconst result = await Promise.all(promises.map(promise => promise.then(value => value, error => {\n\t\t\tif (!firstError) {\n\t\t\t\tfirstError = error;\n\t\t\t}\n\n\t\t\treturn undefined; // do not rethrow so that other promises can settle\n\t\t})));\n\n\t\tif (typeof firstError !== 'undefined') {\n\t\t\tthrow firstError;\n\t\t}\n\n\t\treturn result as unknown as T[]; // cast is needed and protected by the `throw` above\n\t}\n\n\t/**\n\t * A helper to create a new `Promise` with a body that is a promise\n\t * itself. By default, an error that raises from the async body will\n\t * end up as a unhandled rejection, so this utility properly awaits the\n\t * body and rejects the promise as a normal promise does without async\n\t * body.\n\t *\n\t * This method should only be used in rare cases where otherwise `async`\n\t * cannot be used (e.g. when callbacks are involved that require this).\n\t */\n\texport function withAsyncBody(bodyFn: (resolve: (value: T) => unknown, reject: (error: E) => unknown) => Promise): Promise {\n\t\t// eslint-disable-next-line no-async-promise-executor\n\t\treturn new Promise(async (resolve, reject) => {\n\t\t\ttry {\n\t\t\t\tawait bodyFn(resolve, reject);\n\t\t\t} catch (error) {\n\t\t\t\treject(error);\n\t\t\t}\n\t\t});\n\t}\n}\n\nexport class StatefulPromise {\n\tprivate _value: T | undefined = undefined;\n\tget value(): T | undefined { return this._value; }\n\n\tprivate _error: unknown = undefined;\n\tget error(): unknown { return this._error; }\n\n\tprivate _isResolved = false;\n\tget isResolved() { return this._isResolved; }\n\n\tpublic readonly promise: Promise;\n\n\tconstructor(promise: Promise) {\n\t\tthis.promise = promise.then(\n\t\t\tvalue => {\n\t\t\t\tthis._value = value;\n\t\t\t\tthis._isResolved = true;\n\t\t\t\treturn value;\n\t\t\t},\n\t\t\terror => {\n\t\t\t\tthis._error = error;\n\t\t\t\tthis._isResolved = true;\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t);\n\t}\n\n\t/**\n\t * Returns the resolved value.\n\t * Throws if the promise is not resolved yet.\n\t */\n\tpublic requireValue(): T {\n\t\tif (!this._isResolved) {\n\t\t\tthrow new BugIndicatingError('Promise is not resolved yet');\n\t\t}\n\t\tif (this._error) {\n\t\t\tthrow this._error;\n\t\t}\n\t\treturn this._value!;\n\t}\n}\n\nexport class LazyStatefulPromise {\n\tprivate readonly _promise = new Lazy(() => new StatefulPromise(this._compute()));\n\n\tconstructor(\n\t\tprivate readonly _compute: () => Promise,\n\t) { }\n\n\t/**\n\t * Returns the resolved value.\n\t * Throws if the promise is not resolved yet.\n\t */\n\tpublic requireValue(): T {\n\t\treturn this._promise.value.requireValue();\n\t}\n\n\t/**\n\t * Returns the promise (and triggers a computation of the promise if not yet done so).\n\t */\n\tpublic getPromise(): Promise {\n\t\treturn this._promise.value.promise;\n\t}\n\n\t/**\n\t * Reads the current value without triggering a computation of the promise.\n\t */\n\tpublic get currentValue(): T | undefined {\n\t\treturn this._promise.rawValue?.value;\n\t}\n}\n\n//#endregion\n\n//#region\n\nconst enum AsyncIterableSourceState {\n\tInitial,\n\tDoneOK,\n\tDoneError,\n}\n\n/**\n * An object that allows to emit async values asynchronously or bring the iterable to an error state using `reject()`.\n * This emitter is valid only for the duration of the executor (until the promise returned by the executor settles).\n */\nexport interface AsyncIterableEmitter {\n\t/**\n\t * The value will be appended at the end.\n\t *\n\t * **NOTE** If `reject()` has already been called, this method has no effect.\n\t */\n\temitOne(value: T): void;\n\t/**\n\t * The values will be appended at the end.\n\t *\n\t * **NOTE** If `reject()` has already been called, this method has no effect.\n\t */\n\temitMany(values: T[]): void;\n\t/**\n\t * Writing an error will permanently invalidate this iterable.\n\t * The current users will receive an error thrown, as will all future users.\n\t *\n\t * **NOTE** If `reject()` have already been called, this method has no effect.\n\t */\n\treject(error: Error): void;\n}\n\n/**\n * An executor for the `AsyncIterableObject` that has access to an emitter.\n */\nexport interface AsyncIterableExecutor {\n\t/**\n\t * @param emitter An object that allows to emit async values valid only for the duration of the executor.\n\t */\n\t(emitter: AsyncIterableEmitter): void | Promise;\n}\n\n/**\n * A rich implementation for an `AsyncIterable`.\n */\nexport class AsyncIterableObject implements AsyncIterable {\n\n\tpublic static fromArray(items: T[]): AsyncIterableObject {\n\t\treturn new AsyncIterableObject((writer) => {\n\t\t\twriter.emitMany(items);\n\t\t});\n\t}\n\n\tpublic static fromPromise(promise: Promise): AsyncIterableObject {\n\t\treturn new AsyncIterableObject(async (emitter) => {\n\t\t\temitter.emitMany(await promise);\n\t\t});\n\t}\n\n\tpublic static fromPromises(promises: Promise[]): AsyncIterableObject {\n\t\treturn new AsyncIterableObject(async (emitter) => {\n\t\t\tawait Promise.all(promises.map(async (p) => emitter.emitOne(await p)));\n\t\t});\n\t}\n\n\tpublic static merge(iterables: AsyncIterable[]): AsyncIterableObject {\n\t\treturn new AsyncIterableObject(async (emitter) => {\n\t\t\tawait Promise.all(iterables.map(async (iterable) => {\n\t\t\t\tfor await (const item of iterable) {\n\t\t\t\t\temitter.emitOne(item);\n\t\t\t\t}\n\t\t\t}));\n\t\t});\n\t}\n\n\tpublic static EMPTY = AsyncIterableObject.fromArray([]);\n\n\tprivate _state: AsyncIterableSourceState;\n\tprivate _results: T[];\n\tprivate _error: Error | null;\n\tprivate readonly _onReturn?: () => void | Promise;\n\tprivate readonly _onStateChanged: Emitter;\n\n\tconstructor(executor: AsyncIterableExecutor, onReturn?: () => void | Promise) {\n\t\tthis._state = AsyncIterableSourceState.Initial;\n\t\tthis._results = [];\n\t\tthis._error = null;\n\t\tthis._onReturn = onReturn;\n\t\tthis._onStateChanged = new Emitter();\n\n\t\tqueueMicrotask(async () => {\n\t\t\tconst writer: AsyncIterableEmitter = {\n\t\t\t\temitOne: (item) => this.emitOne(item),\n\t\t\t\temitMany: (items) => this.emitMany(items),\n\t\t\t\treject: (error) => this.reject(error)\n\t\t\t};\n\t\t\ttry {\n\t\t\t\tawait Promise.resolve(executor(writer));\n\t\t\t\tthis.resolve();\n\t\t\t} catch (err) {\n\t\t\t\tthis.reject(err);\n\t\t\t} finally {\n\t\t\t\twriter.emitOne = undefined!;\n\t\t\t\twriter.emitMany = undefined!;\n\t\t\t\twriter.reject = undefined!;\n\t\t\t}\n\t\t});\n\t}\n\n\t[Symbol.asyncIterator](): AsyncIterator {\n\t\tlet i = 0;\n\t\treturn {\n\t\t\tnext: async () => {\n\t\t\t\tdo {\n\t\t\t\t\tif (this._state === AsyncIterableSourceState.DoneError) {\n\t\t\t\t\t\tthrow this._error;\n\t\t\t\t\t}\n\t\t\t\t\tif (i < this._results.length) {\n\t\t\t\t\t\treturn { done: false, value: this._results[i++] };\n\t\t\t\t\t}\n\t\t\t\t\tif (this._state === AsyncIterableSourceState.DoneOK) {\n\t\t\t\t\t\treturn { done: true, value: undefined };\n\t\t\t\t\t}\n\t\t\t\t\tawait Event.toPromise(this._onStateChanged.event);\n\t\t\t\t} while (true);\n\t\t\t},\n\t\t\treturn: async () => {\n\t\t\t\tthis._onReturn?.();\n\t\t\t\treturn { done: true, value: undefined };\n\t\t\t}\n\t\t};\n\t}\n\n\tpublic static map(iterable: AsyncIterable, mapFn: (item: T) => R): AsyncIterableObject {\n\t\treturn new AsyncIterableObject(async (emitter) => {\n\t\t\tfor await (const item of iterable) {\n\t\t\t\temitter.emitOne(mapFn(item));\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic map(mapFn: (item: T) => R): AsyncIterableObject {\n\t\treturn AsyncIterableObject.map(this, mapFn);\n\t}\n\n\tpublic static filter(iterable: AsyncIterable, filterFn: (item: T) => boolean): AsyncIterableObject {\n\t\treturn new AsyncIterableObject(async (emitter) => {\n\t\t\tfor await (const item of iterable) {\n\t\t\t\tif (filterFn(item)) {\n\t\t\t\t\temitter.emitOne(item);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic filter(filterFn: (item: T) => boolean): AsyncIterableObject {\n\t\treturn AsyncIterableObject.filter(this, filterFn);\n\t}\n\n\tpublic static coalesce(iterable: AsyncIterable): AsyncIterableObject {\n\t\treturn >AsyncIterableObject.filter(iterable, item => !!item);\n\t}\n\n\tpublic coalesce(): AsyncIterableObject> {\n\t\treturn AsyncIterableObject.coalesce(this) as AsyncIterableObject>;\n\t}\n\n\tpublic static async toPromise(iterable: AsyncIterable): Promise {\n\t\tconst result: T[] = [];\n\t\tfor await (const item of iterable) {\n\t\t\tresult.push(item);\n\t\t}\n\t\treturn result;\n\t}\n\n\tpublic toPromise(): Promise {\n\t\treturn AsyncIterableObject.toPromise(this);\n\t}\n\n\t/**\n\t * The value will be appended at the end.\n\t *\n\t * **NOTE** If `resolve()` or `reject()` have already been called, this method has no effect.\n\t */\n\tprivate emitOne(value: T): void {\n\t\tif (this._state !== AsyncIterableSourceState.Initial) {\n\t\t\treturn;\n\t\t}\n\t\t// it is important to add new values at the end,\n\t\t// as we may have iterators already running on the array\n\t\tthis._results.push(value);\n\t\tthis._onStateChanged.fire();\n\t}\n\n\t/**\n\t * The values will be appended at the end.\n\t *\n\t * **NOTE** If `resolve()` or `reject()` have already been called, this method has no effect.\n\t */\n\tprivate emitMany(values: T[]): void {\n\t\tif (this._state !== AsyncIterableSourceState.Initial) {\n\t\t\treturn;\n\t\t}\n\t\t// it is important to add new values at the end,\n\t\t// as we may have iterators already running on the array\n\t\tthis._results = this._results.concat(values);\n\t\tthis._onStateChanged.fire();\n\t}\n\n\t/**\n\t * Calling `resolve()` will mark the result array as complete.\n\t *\n\t * **NOTE** `resolve()` must be called, otherwise all consumers of this iterable will hang indefinitely, similar to a non-resolved promise.\n\t * **NOTE** If `resolve()` or `reject()` have already been called, this method has no effect.\n\t */\n\tprivate resolve(): void {\n\t\tif (this._state !== AsyncIterableSourceState.Initial) {\n\t\t\treturn;\n\t\t}\n\t\tthis._state = AsyncIterableSourceState.DoneOK;\n\t\tthis._onStateChanged.fire();\n\t}\n\n\t/**\n\t * Writing an error will permanently invalidate this iterable.\n\t * The current users will receive an error thrown, as will all future users.\n\t *\n\t * **NOTE** If `resolve()` or `reject()` have already been called, this method has no effect.\n\t */\n\tprivate reject(error: Error) {\n\t\tif (this._state !== AsyncIterableSourceState.Initial) {\n\t\t\treturn;\n\t\t}\n\t\tthis._state = AsyncIterableSourceState.DoneError;\n\t\tthis._error = error;\n\t\tthis._onStateChanged.fire();\n\t}\n}\n\nexport class CancelableAsyncIterableObject extends AsyncIterableObject {\n\tconstructor(\n\t\tprivate readonly _source: CancellationTokenSource,\n\t\texecutor: AsyncIterableExecutor\n\t) {\n\t\tsuper(executor);\n\t}\n\n\tcancel(): void {\n\t\tthis._source.cancel();\n\t}\n}\n\nexport function createCancelableAsyncIterable(callback: (token: CancellationToken) => AsyncIterable): CancelableAsyncIterableObject {\n\tconst source = new CancellationTokenSource();\n\tconst innerIterable = callback(source.token);\n\n\treturn new CancelableAsyncIterableObject(source, async (emitter) => {\n\t\tconst subscription = source.token.onCancellationRequested(() => {\n\t\t\tsubscription.dispose();\n\t\t\tsource.dispose();\n\t\t\temitter.reject(new CancellationError());\n\t\t});\n\t\ttry {\n\t\t\tfor await (const item of innerIterable) {\n\t\t\t\tif (source.token.isCancellationRequested) {\n\t\t\t\t\t// canceled in the meantime\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\temitter.emitOne(item);\n\t\t\t}\n\t\t\tsubscription.dispose();\n\t\t\tsource.dispose();\n\t\t} catch (err) {\n\t\t\tsubscription.dispose();\n\t\t\tsource.dispose();\n\t\t\temitter.reject(err);\n\t\t}\n\t});\n}\n\nexport class AsyncIterableSource {\n\n\tprivate readonly _deferred = new DeferredPromise();\n\tprivate readonly _asyncIterable: AsyncIterableObject;\n\n\tprivate _errorFn: (error: Error) => void;\n\tprivate _emitFn: (item: T) => void;\n\n\t/**\n\t *\n\t * @param onReturn A function that will be called when consuming the async iterable\n\t * has finished by the consumer, e.g the for-await-loop has be existed (break, return) early.\n\t * This is NOT called when resolving this source by its owner.\n\t */\n\tconstructor(onReturn?: () => Promise | void) {\n\t\tthis._asyncIterable = new AsyncIterableObject(emitter => {\n\n\t\t\tif (earlyError) {\n\t\t\t\temitter.reject(earlyError);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (earlyItems) {\n\t\t\t\temitter.emitMany(earlyItems);\n\t\t\t}\n\t\t\tthis._errorFn = (error: Error) => emitter.reject(error);\n\t\t\tthis._emitFn = (item: T) => emitter.emitOne(item);\n\t\t\treturn this._deferred.p;\n\t\t}, onReturn);\n\n\t\tlet earlyError: Error | undefined;\n\t\tlet earlyItems: T[] | undefined;\n\n\t\tthis._emitFn = (item: T) => {\n\t\t\tif (!earlyItems) {\n\t\t\t\tearlyItems = [];\n\t\t\t}\n\t\t\tearlyItems.push(item);\n\t\t};\n\t\tthis._errorFn = (error: Error) => {\n\t\t\tif (!earlyError) {\n\t\t\t\tearlyError = error;\n\t\t\t}\n\t\t};\n\t}\n\n\tget asyncIterable(): AsyncIterableObject {\n\t\treturn this._asyncIterable;\n\t}\n\n\tresolve(): void {\n\t\tthis._deferred.complete();\n\t}\n\n\treject(error: Error): void {\n\t\tthis._errorFn(error);\n\t\tthis._deferred.complete();\n\t}\n\n\temitOne(item: T): void {\n\t\tthis._emitFn(item);\n\t}\n}\n\n//#endregion\n", "/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\nimport { CharCode } from 'vs/base/common/charCode';\nimport { Constants } from 'vs/base/common/uint';\n\nexport function isFalsyOrWhitespace(str: string | undefined): boolean {\n\tif (!str || typeof str !== 'string') {\n\t\treturn true;\n\t}\n\treturn str.trim().length === 0;\n}\n\nconst _formatRegexp = /{(\\d+)}/g;\n\n/**\n * Helper to produce a string with a variable number of arguments. Insert variable segments\n * into the string using the {n} notation where N is the index of the argument following the string.\n * @param value string to which formatting is applied\n * @param args replacements for {n}-entries\n */\nexport function format(value: string, ...args: any[]): string {\n\tif (args.length === 0) {\n\t\treturn value;\n\t}\n\treturn value.replace(_formatRegexp, function (match, group) {\n\t\tconst idx = parseInt(group, 10);\n\t\treturn isNaN(idx) || idx < 0 || idx >= args.length ?\n\t\t\tmatch :\n\t\t\targs[idx];\n\t});\n}\n\nconst _format2Regexp = /{([^}]+)}/g;\n\n/**\n * Helper to create a string from a template and a string record.\n * Similar to `format` but with objects instead of positional arguments.\n */\nexport function format2(template: string, values: Record): string {\n\tif (Object.keys(values).length === 0) {\n\t\treturn template;\n\t}\n\treturn template.replace(_format2Regexp, (match, group) => (values[group] ?? match) as string);\n}\n\n/**\n * Encodes the given value so that it can be used as literal value in html attributes.\n *\n * In other words, computes `$val`, such that `attr` in `
` has the runtime value `value`.\n * This prevents XSS injection.\n */\nexport function htmlAttributeEncodeValue(value: string): string {\n\treturn value.replace(/[<>\"'&]/g, ch => {\n\t\tswitch (ch) {\n\t\t\tcase '<': return '<';\n\t\t\tcase '>': return '>';\n\t\t\tcase '\"': return '"';\n\t\t\tcase '\\'': return ''';\n\t\t\tcase '&': return '&';\n\t\t}\n\t\treturn ch;\n\t});\n}\n\n/**\n * Converts HTML characters inside the string to use entities instead. Makes the string safe from\n * being used e.g. in HTMLElement.innerHTML.\n */\nexport function escape(html: string): string {\n\treturn html.replace(/[<>&]/g, function (match) {\n\t\tswitch (match) {\n\t\t\tcase '<': return '<';\n\t\t\tcase '>': return '>';\n\t\t\tcase '&': return '&';\n\t\t\tdefault: return match;\n\t\t}\n\t});\n}\n\n/**\n * Escapes regular expression characters in a given string\n */\nexport function escapeRegExpCharacters(value: string): string {\n\treturn value.replace(/[\\\\\\{\\}\\*\\+\\?\\|\\^\\$\\.\\[\\]\\(\\)]/g, '\\\\$&');\n}\n\n/**\n * Counts how often `substr` occurs inside `value`.\n */\nexport function count(value: string, substr: string): number {\n\tlet result = 0;\n\tlet index = value.indexOf(substr);\n\twhile (index !== -1) {\n\t\tresult++;\n\t\tindex = value.indexOf(substr, index + substr.length);\n\t}\n\treturn result;\n}\n\nexport function truncate(value: string, maxLength: number, suffix = '\u2026'): string {\n\tif (value.length <= maxLength) {\n\t\treturn value;\n\t}\n\n\treturn `${value.substr(0, maxLength)}${suffix}`;\n}\n\nexport function truncateMiddle(value: string, maxLength: number, suffix = '\u2026'): string {\n\tif (value.length <= maxLength) {\n\t\treturn value;\n\t}\n\n\tconst prefixLength = Math.ceil(maxLength / 2) - suffix.length / 2;\n\tconst suffixLength = Math.floor(maxLength / 2) - suffix.length / 2;\n\n\treturn `${value.substr(0, prefixLength)}${suffix}${value.substr(value.length - suffixLength)}`;\n}\n\n/**\n * Removes all occurrences of needle from the beginning and end of haystack.\n * @param haystack string to trim\n * @param needle the thing to trim (default is a blank)\n */\nexport function trim(haystack: string, needle: string = ' '): string {\n\tconst trimmed = ltrim(haystack, needle);\n\treturn rtrim(trimmed, needle);\n}\n\n/**\n * Removes all occurrences of needle from the beginning of haystack.\n * @param haystack string to trim\n * @param needle the thing to trim\n */\nexport function ltrim(haystack: string, needle: string): string {\n\tif (!haystack || !needle) {\n\t\treturn haystack;\n\t}\n\n\tconst needleLen = needle.length;\n\tif (needleLen === 0 || haystack.length === 0) {\n\t\treturn haystack;\n\t}\n\n\tlet offset = 0;\n\n\twhile (haystack.indexOf(needle, offset) === offset) {\n\t\toffset = offset + needleLen;\n\t}\n\treturn haystack.substring(offset);\n}\n\n/**\n * Removes all occurrences of needle from the end of haystack.\n * @param haystack string to trim\n * @param needle the thing to trim\n */\nexport function rtrim(haystack: string, needle: string): string {\n\tif (!haystack || !needle) {\n\t\treturn haystack;\n\t}\n\n\tconst needleLen = needle.length,\n\t\thaystackLen = haystack.length;\n\n\tif (needleLen === 0 || haystackLen === 0) {\n\t\treturn haystack;\n\t}\n\n\tlet offset = haystackLen,\n\t\tidx = -1;\n\n\twhile (true) {\n\t\tidx = haystack.lastIndexOf(needle, offset - 1);\n\t\tif (idx === -1 || idx + needleLen !== offset) {\n\t\t\tbreak;\n\t\t}\n\t\tif (idx === 0) {\n\t\t\treturn '';\n\t\t}\n\t\toffset = idx;\n\t}\n\n\treturn haystack.substring(0, offset);\n}\n\nexport function convertSimple2RegExpPattern(pattern: string): string {\n\treturn pattern.replace(/[\\-\\\\\\{\\}\\+\\?\\|\\^\\$\\.\\,\\[\\]\\(\\)\\#\\s]/g, '\\\\$&').replace(/[\\*]/g, '.*');\n}\n\nexport function stripWildcards(pattern: string): string {\n\treturn pattern.replace(/\\*/g, '');\n}\n\nexport interface RegExpOptions {\n\tmatchCase?: boolean;\n\twholeWord?: boolean;\n\tmultiline?: boolean;\n\tglobal?: boolean;\n\tunicode?: boolean;\n}\n\nexport function createRegExp(searchString: string, isRegex: boolean, options: RegExpOptions = {}): RegExp {\n\tif (!searchString) {\n\t\tthrow new Error('Cannot create regex from empty string');\n\t}\n\tif (!isRegex) {\n\t\tsearchString = escapeRegExpCharacters(searchString);\n\t}\n\tif (options.wholeWord) {\n\t\tif (!/\\B/.test(searchString.charAt(0))) {\n\t\t\tsearchString = '\\\\b' + searchString;\n\t\t}\n\t\tif (!/\\B/.test(searchString.charAt(searchString.length - 1))) {\n\t\t\tsearchString = searchString + '\\\\b';\n\t\t}\n\t}\n\tlet modifiers = '';\n\tif (options.global) {\n\t\tmodifiers += 'g';\n\t}\n\tif (!options.matchCase) {\n\t\tmodifiers += 'i';\n\t}\n\tif (options.multiline) {\n\t\tmodifiers += 'm';\n\t}\n\tif (options.unicode) {\n\t\tmodifiers += 'u';\n\t}\n\n\treturn new RegExp(searchString, modifiers);\n}\n\nexport function regExpLeadsToEndlessLoop(regexp: RegExp): boolean {\n\t// Exit early if it's one of these special cases which are meant to match\n\t// against an empty string\n\tif (regexp.source === '^' || regexp.source === '^$' || regexp.source === '$' || regexp.source === '^\\\\s*$') {\n\t\treturn false;\n\t}\n\n\t// We check against an empty string. If the regular expression doesn't advance\n\t// (e.g. ends in an endless loop) it will match an empty string.\n\tconst match = regexp.exec('');\n\treturn !!(match && regexp.lastIndex === 0);\n}\n\nexport function splitLines(str: string): string[] {\n\treturn str.split(/\\r\\n|\\r|\\n/);\n}\n\nexport function splitLinesIncludeSeparators(str: string): string[] {\n\tconst linesWithSeparators: string[] = [];\n\tconst splitLinesAndSeparators = str.split(/(\\r\\n|\\r|\\n)/);\n\tfor (let i = 0; i < Math.ceil(splitLinesAndSeparators.length / 2); i++) {\n\t\tlinesWithSeparators.push(splitLinesAndSeparators[2 * i] + (splitLinesAndSeparators[2 * i + 1] ?? ''));\n\t}\n\treturn linesWithSeparators;\n}\n\n/**\n * Returns first index of the string that is not whitespace.\n * If string is empty or contains only whitespaces, returns -1\n */\nexport function firstNonWhitespaceIndex(str: string): number {\n\tfor (let i = 0, len = str.length; i < len; i++) {\n\t\tconst chCode = str.charCodeAt(i);\n\t\tif (chCode !== CharCode.Space && chCode !== CharCode.Tab) {\n\t\t\treturn i;\n\t\t}\n\t}\n\treturn -1;\n}\n\n/**\n * Returns the leading whitespace of the string.\n * If the string contains only whitespaces, returns entire string\n */\nexport function getLeadingWhitespace(str: string, start: number = 0, end: number = str.length): string {\n\tfor (let i = start; i < end; i++) {\n\t\tconst chCode = str.charCodeAt(i);\n\t\tif (chCode !== CharCode.Space && chCode !== CharCode.Tab) {\n\t\t\treturn str.substring(start, i);\n\t\t}\n\t}\n\treturn str.substring(start, end);\n}\n\n/**\n * Returns last index of the string that is not whitespace.\n * If string is empty or contains only whitespaces, returns -1\n */\nexport function lastNonWhitespaceIndex(str: string, startIndex: number = str.length - 1): number {\n\tfor (let i = startIndex; i >= 0; i--) {\n\t\tconst chCode = str.charCodeAt(i);\n\t\tif (chCode !== CharCode.Space && chCode !== CharCode.Tab) {\n\t\t\treturn i;\n\t\t}\n\t}\n\treturn -1;\n}\n\n/**\n * Function that works identically to String.prototype.replace, except, the\n * replace function is allowed to be async and return a Promise.\n */\nexport function replaceAsync(str: string, search: RegExp, replacer: (match: string, ...args: any[]) => Promise): Promise {\n\tconst parts: (string | Promise)[] = [];\n\n\tlet last = 0;\n\tfor (const match of str.matchAll(search)) {\n\t\tparts.push(str.slice(last, match.index));\n\t\tif (match.index === undefined) {\n\t\t\tthrow new Error('match.index should be defined');\n\t\t}\n\n\t\tlast = match.index + match[0].length;\n\t\tparts.push(replacer(match[0], ...match.slice(1), match.index, str, match.groups));\n\t}\n\n\tparts.push(str.slice(last));\n\n\treturn Promise.all(parts).then(p => p.join(''));\n}\n\nexport function compare(a: string, b: string): number {\n\tif (a < b) {\n\t\treturn -1;\n\t} else if (a > b) {\n\t\treturn 1;\n\t} else {\n\t\treturn 0;\n\t}\n}\n\nexport function compareSubstring(a: string, b: string, aStart: number = 0, aEnd: number = a.length, bStart: number = 0, bEnd: number = b.length): number {\n\tfor (; aStart < aEnd && bStart < bEnd; aStart++, bStart++) {\n\t\tconst codeA = a.charCodeAt(aStart);\n\t\tconst codeB = b.charCodeAt(bStart);\n\t\tif (codeA < codeB) {\n\t\t\treturn -1;\n\t\t} else if (codeA > codeB) {\n\t\t\treturn 1;\n\t\t}\n\t}\n\tconst aLen = aEnd - aStart;\n\tconst bLen = bEnd - bStart;\n\tif (aLen < bLen) {\n\t\treturn -1;\n\t} else if (aLen > bLen) {\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n\nexport function compareIgnoreCase(a: string, b: string): number {\n\treturn compareSubstringIgnoreCase(a, b, 0, a.length, 0, b.length);\n}\n\nexport function compareSubstringIgnoreCase(a: string, b: string, aStart: number = 0, aEnd: number = a.length, bStart: number = 0, bEnd: number = b.length): number {\n\n\tfor (; aStart < aEnd && bStart < bEnd; aStart++, bStart++) {\n\n\t\tlet codeA = a.charCodeAt(aStart);\n\t\tlet codeB = b.charCodeAt(bStart);\n\n\t\tif (codeA === codeB) {\n\t\t\t// equal\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (codeA >= 128 || codeB >= 128) {\n\t\t\t// not ASCII letters -> fallback to lower-casing strings\n\t\t\treturn compareSubstring(a.toLowerCase(), b.toLowerCase(), aStart, aEnd, bStart, bEnd);\n\t\t}\n\n\t\t// mapper lower-case ascii letter onto upper-case varinats\n\t\t// [97-122] (lower ascii) --> [65-90] (upper ascii)\n\t\tif (isLowerAsciiLetter(codeA)) {\n\t\t\tcodeA -= 32;\n\t\t}\n\t\tif (isLowerAsciiLetter(codeB)) {\n\t\t\tcodeB -= 32;\n\t\t}\n\n\t\t// compare both code points\n\t\tconst diff = codeA - codeB;\n\t\tif (diff === 0) {\n\t\t\tcontinue;\n\t\t}\n\n\t\treturn diff;\n\t}\n\n\tconst aLen = aEnd - aStart;\n\tconst bLen = bEnd - bStart;\n\n\tif (aLen < bLen) {\n\t\treturn -1;\n\t} else if (aLen > bLen) {\n\t\treturn 1;\n\t}\n\n\treturn 0;\n}\n\nexport function isAsciiDigit(code: number): boolean {\n\treturn code >= CharCode.Digit0 && code <= CharCode.Digit9;\n}\n\nexport function isLowerAsciiLetter(code: number): boolean {\n\treturn code >= CharCode.a && code <= CharCode.z;\n}\n\nexport function isUpperAsciiLetter(code: number): boolean {\n\treturn code >= CharCode.A && code <= CharCode.Z;\n}\n\nexport function equalsIgnoreCase(a: string, b: string): boolean {\n\treturn a.length === b.length && compareSubstringIgnoreCase(a, b) === 0;\n}\n\nexport function startsWithIgnoreCase(str: string, candidate: string): boolean {\n\tconst candidateLength = candidate.length;\n\tif (candidate.length > str.length) {\n\t\treturn false;\n\t}\n\n\treturn compareSubstringIgnoreCase(str, candidate, 0, candidateLength) === 0;\n}\n\n/**\n * @returns the length of the common prefix of the two strings.\n */\nexport function commonPrefixLength(a: string, b: string): number {\n\n\tconst len = Math.min(a.length, b.length);\n\tlet i: number;\n\n\tfor (i = 0; i < len; i++) {\n\t\tif (a.charCodeAt(i) !== b.charCodeAt(i)) {\n\t\t\treturn i;\n\t\t}\n\t}\n\n\treturn len;\n}\n\n/**\n * @returns the length of the common suffix of the two strings.\n */\nexport function commonSuffixLength(a: string, b: string): number {\n\n\tconst len = Math.min(a.length, b.length);\n\tlet i: number;\n\n\tconst aLastIndex = a.length - 1;\n\tconst bLastIndex = b.length - 1;\n\n\tfor (i = 0; i < len; i++) {\n\t\tif (a.charCodeAt(aLastIndex - i) !== b.charCodeAt(bLastIndex - i)) {\n\t\t\treturn i;\n\t\t}\n\t}\n\n\treturn len;\n}\n\n/**\n * See http://en.wikipedia.org/wiki/Surrogate_pair\n */\nexport function isHighSurrogate(charCode: number): boolean {\n\treturn (0xD800 <= charCode && charCode <= 0xDBFF);\n}\n\n/**\n * See http://en.wikipedia.org/wiki/Surrogate_pair\n */\nexport function isLowSurrogate(charCode: number): boolean {\n\treturn (0xDC00 <= charCode && charCode <= 0xDFFF);\n}\n\n/**\n * See http://en.wikipedia.org/wiki/Surrogate_pair\n */\nexport function computeCodePoint(highSurrogate: number, lowSurrogate: number): number {\n\treturn ((highSurrogate - 0xD800) << 10) + (lowSurrogate - 0xDC00) + 0x10000;\n}\n\n/**\n * get the code point that begins at offset `offset`\n */\nexport function getNextCodePoint(str: string, len: number, offset: number): number {\n\tconst charCode = str.charCodeAt(offset);\n\tif (isHighSurrogate(charCode) && offset + 1 < len) {\n\t\tconst nextCharCode = str.charCodeAt(offset + 1);\n\t\tif (isLowSurrogate(nextCharCode)) {\n\t\t\treturn computeCodePoint(charCode, nextCharCode);\n\t\t}\n\t}\n\treturn charCode;\n}\n\n/**\n * get the code point that ends right before offset `offset`\n */\nfunction getPrevCodePoint(str: string, offset: number): number {\n\tconst charCode = str.charCodeAt(offset - 1);\n\tif (isLowSurrogate(charCode) && offset > 1) {\n\t\tconst prevCharCode = str.charCodeAt(offset - 2);\n\t\tif (isHighSurrogate(prevCharCode)) {\n\t\t\treturn computeCodePoint(prevCharCode, charCode);\n\t\t}\n\t}\n\treturn charCode;\n}\n\nexport class CodePointIterator {\n\n\tprivate readonly _str: string;\n\tprivate readonly _len: number;\n\tprivate _offset: number;\n\n\tpublic get offset(): number {\n\t\treturn this._offset;\n\t}\n\n\tconstructor(str: string, offset: number = 0) {\n\t\tthis._str = str;\n\t\tthis._len = str.length;\n\t\tthis._offset = offset;\n\t}\n\n\tpublic setOffset(offset: number): void {\n\t\tthis._offset = offset;\n\t}\n\n\tpublic prevCodePoint(): number {\n\t\tconst codePoint = getPrevCodePoint(this._str, this._offset);\n\t\tthis._offset -= (codePoint >= Constants.UNICODE_SUPPLEMENTARY_PLANE_BEGIN ? 2 : 1);\n\t\treturn codePoint;\n\t}\n\n\tpublic nextCodePoint(): number {\n\t\tconst codePoint = getNextCodePoint(this._str, this._len, this._offset);\n\t\tthis._offset += (codePoint >= Constants.UNICODE_SUPPLEMENTARY_PLANE_BEGIN ? 2 : 1);\n\t\treturn codePoint;\n\t}\n\n\tpublic eol(): boolean {\n\t\treturn (this._offset >= this._len);\n\t}\n}\n\nexport const noBreakWhitespace = '\\xa0';\n", "/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\nimport * as strings from 'vs/base/common/strings';\n\n/**\n * Return a hash value for an object.\n */\nexport function hash(obj: any): number {\n\treturn doHash(obj, 0);\n}\n\nexport function doHash(obj: any, hashVal: number): number {\n\tswitch (typeof obj) {\n\t\tcase 'object':\n\t\t\tif (obj === null) {\n\t\t\t\treturn numberHash(349, hashVal);\n\t\t\t} else if (Array.isArray(obj)) {\n\t\t\t\treturn arrayHash(obj, hashVal);\n\t\t\t}\n\t\t\treturn objectHash(obj, hashVal);\n\t\tcase 'string':\n\t\t\treturn stringHash(obj, hashVal);\n\t\tcase 'boolean':\n\t\t\treturn booleanHash(obj, hashVal);\n\t\tcase 'number':\n\t\t\treturn numberHash(obj, hashVal);\n\t\tcase 'undefined':\n\t\t\treturn numberHash(937, hashVal);\n\t\tdefault:\n\t\t\treturn numberHash(617, hashVal);\n\t}\n}\n\nexport function numberHash(val: number, initialHashVal: number): number {\n\treturn (((initialHashVal << 5) - initialHashVal) + val) | 0; // hashVal * 31 + ch, keep as int32\n}\n\nfunction booleanHash(b: boolean, initialHashVal: number): number {\n\treturn numberHash(b ? 433 : 863, initialHashVal);\n}\n\nexport function stringHash(s: string, hashVal: number) {\n\thashVal = numberHash(149417, hashVal);\n\tfor (let i = 0, length = s.length; i < length; i++) {\n\t\thashVal = numberHash(s.charCodeAt(i), hashVal);\n\t}\n\treturn hashVal;\n}\n\nfunction arrayHash(arr: any[], initialHashVal: number): number {\n\tinitialHashVal = numberHash(104579, initialHashVal);\n\treturn arr.reduce((hashVal, item) => doHash(item, hashVal), initialHashVal);\n}\n\nfunction objectHash(obj: any, initialHashVal: number): number {\n\tinitialHashVal = numberHash(181387, initialHashVal);\n\treturn Object.keys(obj).sort().reduce((hashVal, key) => {\n\t\thashVal = stringHash(key, hashVal);\n\t\treturn doHash(obj[key], hashVal);\n\t}, initialHashVal);\n}\n\nexport class Hasher {\n\n\tprivate _value = 0;\n\n\tget value(): number {\n\t\treturn this._value;\n\t}\n\n\thash(obj: any): number {\n\t\tthis._value = doHash(obj, this._value);\n\t\treturn this._value;\n\t}\n}\n\nconst enum SHA1Constant {\n\tBLOCK_SIZE = 64, // 512 / 8\n\tUNICODE_REPLACEMENT = 0xFFFD,\n}\n\nfunction leftRotate(value: number, bits: number, totalBits: number = 32): number {\n\t// delta + bits = totalBits\n\tconst delta = totalBits - bits;\n\n\t// All ones, expect `delta` zeros aligned to the right\n\tconst mask = ~((1 << delta) - 1);\n\n\t// Join (value left-shifted `bits` bits) with (masked value right-shifted `delta` bits)\n\treturn ((value << bits) | ((mask & value) >>> delta)) >>> 0;\n}\n\nfunction fill(dest: Uint8Array, index: number = 0, count: number = dest.byteLength, value: number = 0): void {\n\tfor (let i = 0; i < count; i++) {\n\t\tdest[index + i] = value;\n\t}\n}\n\nfunction leftPad(value: string, length: number, char: string = '0'): string {\n\twhile (value.length < length) {\n\t\tvalue = char + value;\n\t}\n\treturn value;\n}\n\nexport function toHexString(buffer: ArrayBuffer): string;\nexport function toHexString(value: number, bitsize?: number): string;\nexport function toHexString(bufferOrValue: ArrayBuffer | number, bitsize: number = 32): string {\n\tif (bufferOrValue instanceof ArrayBuffer) {\n\t\treturn Array.from(new Uint8Array(bufferOrValue)).map(b => b.toString(16).padStart(2, '0')).join('');\n\t}\n\n\treturn leftPad((bufferOrValue >>> 0).toString(16), bitsize / 4);\n}\n\n/**\n * A SHA1 implementation that works with strings and does not allocate.\n */\nexport class StringSHA1 {\n\tprivate static _bigBlock32 = new DataView(new ArrayBuffer(320)); // 80 * 4 = 320\n\n\tprivate _h0 = 0x67452301;\n\tprivate _h1 = 0xEFCDAB89;\n\tprivate _h2 = 0x98BADCFE;\n\tprivate _h3 = 0x10325476;\n\tprivate _h4 = 0xC3D2E1F0;\n\n\tprivate readonly _buff: Uint8Array;\n\tprivate readonly _buffDV: DataView;\n\tprivate _buffLen: number;\n\tprivate _totalLen: number;\n\tprivate _leftoverHighSurrogate: number;\n\tprivate _finished: boolean;\n\n\tconstructor() {\n\t\tthis._buff = new Uint8Array(SHA1Constant.BLOCK_SIZE + 3 /* to fit any utf-8 */);\n\t\tthis._buffDV = new DataView(this._buff.buffer);\n\t\tthis._buffLen = 0;\n\t\tthis._totalLen = 0;\n\t\tthis._leftoverHighSurrogate = 0;\n\t\tthis._finished = false;\n\t}\n\n\tpublic update(str: string): void {\n\t\tconst strLen = str.length;\n\t\tif (strLen === 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst buff = this._buff;\n\t\tlet buffLen = this._buffLen;\n\t\tlet leftoverHighSurrogate = this._leftoverHighSurrogate;\n\t\tlet charCode: number;\n\t\tlet offset: number;\n\n\t\tif (leftoverHighSurrogate !== 0) {\n\t\t\tcharCode = leftoverHighSurrogate;\n\t\t\toffset = -1;\n\t\t\tleftoverHighSurrogate = 0;\n\t\t} else {\n\t\t\tcharCode = str.charCodeAt(0);\n\t\t\toffset = 0;\n\t\t}\n\n\t\twhile (true) {\n\t\t\tlet codePoint = charCode;\n\t\t\tif (strings.isHighSurrogate(charCode)) {\n\t\t\t\tif (offset + 1 < strLen) {\n\t\t\t\t\tconst nextCharCode = str.charCodeAt(offset + 1);\n\t\t\t\t\tif (strings.isLowSurrogate(nextCharCode)) {\n\t\t\t\t\t\toffset++;\n\t\t\t\t\t\tcodePoint = strings.computeCodePoint(charCode, nextCharCode);\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// illegal => unicode replacement character\n\t\t\t\t\t\tcodePoint = SHA1Constant.UNICODE_REPLACEMENT;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// last character is a surrogate pair\n\t\t\t\t\tleftoverHighSurrogate = charCode;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} else if (strings.isLowSurrogate(charCode)) {\n\t\t\t\t// illegal => unicode replacement character\n\t\t\t\tcodePoint = SHA1Constant.UNICODE_REPLACEMENT;\n\t\t\t}\n\n\t\t\tbuffLen = this._push(buff, buffLen, codePoint);\n\t\t\toffset++;\n\t\t\tif (offset < strLen) {\n\t\t\t\tcharCode = str.charCodeAt(offset);\n\t\t\t} else {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tthis._buffLen = buffLen;\n\t\tthis._leftoverHighSurrogate = leftoverHighSurrogate;\n\t}\n\n\tprivate _push(buff: Uint8Array, buffLen: number, codePoint: number): number {\n\t\tif (codePoint < 0x0080) {\n\t\t\tbuff[buffLen++] = codePoint;\n\t\t} else if (codePoint < 0x0800) {\n\t\t\tbuff[buffLen++] = 0b11000000 | ((codePoint & 0b00000000000000000000011111000000) >>> 6);\n\t\t\tbuff[buffLen++] = 0b10000000 | ((codePoint & 0b00000000000000000000000000111111) >>> 0);\n\t\t} else if (codePoint < 0x10000) {\n\t\t\tbuff[buffLen++] = 0b11100000 | ((codePoint & 0b00000000000000001111000000000000) >>> 12);\n\t\t\tbuff[buffLen++] = 0b10000000 | ((codePoint & 0b00000000000000000000111111000000) >>> 6);\n\t\t\tbuff[buffLen++] = 0b10000000 | ((codePoint & 0b00000000000000000000000000111111) >>> 0);\n\t\t} else {\n\t\t\tbuff[buffLen++] = 0b11110000 | ((codePoint & 0b00000000000111000000000000000000) >>> 18);\n\t\t\tbuff[buffLen++] = 0b10000000 | ((codePoint & 0b00000000000000111111000000000000) >>> 12);\n\t\t\tbuff[buffLen++] = 0b10000000 | ((codePoint & 0b00000000000000000000111111000000) >>> 6);\n\t\t\tbuff[buffLen++] = 0b10000000 | ((codePoint & 0b00000000000000000000000000111111) >>> 0);\n\t\t}\n\n\t\tif (buffLen >= SHA1Constant.BLOCK_SIZE) {\n\t\t\tthis._step();\n\t\t\tbuffLen -= SHA1Constant.BLOCK_SIZE;\n\t\t\tthis._totalLen += SHA1Constant.BLOCK_SIZE;\n\t\t\t// take last 3 in case of UTF8 overflow\n\t\t\tbuff[0] = buff[SHA1Constant.BLOCK_SIZE + 0];\n\t\t\tbuff[1] = buff[SHA1Constant.BLOCK_SIZE + 1];\n\t\t\tbuff[2] = buff[SHA1Constant.BLOCK_SIZE + 2];\n\t\t}\n\n\t\treturn buffLen;\n\t}\n\n\tpublic digest(): string {\n\t\tif (!this._finished) {\n\t\t\tthis._finished = true;\n\t\t\tif (this._leftoverHighSurrogate) {\n\t\t\t\t// illegal => unicode replacement character\n\t\t\t\tthis._leftoverHighSurrogate = 0;\n\t\t\t\tthis._buffLen = this._push(this._buff, this._buffLen, SHA1Constant.UNICODE_REPLACEMENT);\n\t\t\t}\n\t\t\tthis._totalLen += this._buffLen;\n\t\t\tthis._wrapUp();\n\t\t}\n\n\t\treturn toHexString(this._h0) + toHexString(this._h1) + toHexString(this._h2) + toHexString(this._h3) + toHexString(this._h4);\n\t}\n\n\tprivate _wrapUp(): void {\n\t\tthis._buff[this._buffLen++] = 0x80;\n\t\tfill(this._buff, this._buffLen);\n\n\t\tif (this._buffLen > 56) {\n\t\t\tthis._step();\n\t\t\tfill(this._buff);\n\t\t}\n\n\t\t// this will fit because the mantissa can cover up to 52 bits\n\t\tconst ml = 8 * this._totalLen;\n\n\t\tthis._buffDV.setUint32(56, Math.floor(ml / 4294967296), false);\n\t\tthis._buffDV.setUint32(60, ml % 4294967296, false);\n\n\t\tthis._step();\n\t}\n\n\tprivate _step(): void {\n\t\tconst bigBlock32 = StringSHA1._bigBlock32;\n\t\tconst data = this._buffDV;\n\n\t\tfor (let j = 0; j < 64 /* 16*4 */; j += 4) {\n\t\t\tbigBlock32.setUint32(j, data.getUint32(j, false), false);\n\t\t}\n\n\t\tfor (let j = 64; j < 320 /* 80*4 */; j += 4) {\n\t\t\tbigBlock32.setUint32(j, leftRotate((bigBlock32.getUint32(j - 12, false) ^ bigBlock32.getUint32(j - 32, false) ^ bigBlock32.getUint32(j - 56, false) ^ bigBlock32.getUint32(j - 64, false)), 1), false);\n\t\t}\n\n\t\tlet a = this._h0;\n\t\tlet b = this._h1;\n\t\tlet c = this._h2;\n\t\tlet d = this._h3;\n\t\tlet e = this._h4;\n\n\t\tlet f: number, k: number;\n\t\tlet temp: number;\n\n\t\tfor (let j = 0; j < 80; j++) {\n\t\t\tif (j < 20) {\n\t\t\t\tf = (b & c) | ((~b) & d);\n\t\t\t\tk = 0x5A827999;\n\t\t\t} else if (j < 40) {\n\t\t\t\tf = b ^ c ^ d;\n\t\t\t\tk = 0x6ED9EBA1;\n\t\t\t} else if (j < 60) {\n\t\t\t\tf = (b & c) | (b & d) | (c & d);\n\t\t\t\tk = 0x8F1BBCDC;\n\t\t\t} else {\n\t\t\t\tf = b ^ c ^ d;\n\t\t\t\tk = 0xCA62C1D6;\n\t\t\t}\n\n\t\t\ttemp = (leftRotate(a, 5) + f + e + k + bigBlock32.getUint32(j * 4, false)) & 0xffffffff;\n\t\t\te = d;\n\t\t\td = c;\n\t\t\tc = leftRotate(b, 30);\n\t\t\tb = a;\n\t\t\ta = temp;\n\t\t}\n\n\t\tthis._h0 = (this._h0 + a) & 0xffffffff;\n\t\tthis._h1 = (this._h1 + b) & 0xffffffff;\n\t\tthis._h2 = (this._h2 + c) & 0xffffffff;\n\t\tthis._h3 = (this._h3 + d) & 0xffffffff;\n\t\tthis._h4 = (this._h4 + e) & 0xffffffff;\n\t}\n}\n", "/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\nimport * as browser from 'vs/base/browser/browser';\nimport { BrowserFeatures } from 'vs/base/browser/canIUse';\nimport { IKeyboardEvent, StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';\nimport { IMouseEvent, StandardMouseEvent } from 'vs/base/browser/mouseEvent';\nimport { AbstractIdleValue, IntervalTimer, TimeoutTimer, _runWhenIdle, IdleDeadline } from 'vs/base/common/async';\nimport { onUnexpectedError } from 'vs/base/common/errors';\nimport * as event from 'vs/base/common/event';\nimport { KeyCode } from 'vs/base/common/keyCodes';\nimport { Disposable, DisposableStore, IDisposable, toDisposable } from 'vs/base/common/lifecycle';\nimport * as platform from 'vs/base/common/platform';\nimport { hash } from 'vs/base/common/hash';\nimport { CodeWindow, ensureCodeWindow, mainWindow } from 'vs/base/browser/window';\nimport { isPointWithinTriangle } from 'vs/base/common/numbers';\n\nexport interface IRegisteredCodeWindow {\n\treadonly window: CodeWindow;\n\treadonly disposables: DisposableStore;\n}\n\n//# region Multi-Window Support Utilities\n\nexport const {\n\tregisterWindow,\n\tgetWindow,\n\tgetDocument,\n\tgetWindows,\n\tgetWindowsCount,\n\tgetWindowId,\n\tgetWindowById,\n\thasWindow,\n\tonDidRegisterWindow,\n\tonWillUnregisterWindow,\n\tonDidUnregisterWindow\n} = (function () {\n\tconst windows = new Map();\n\n\tensureCodeWindow(mainWindow, 1);\n\tconst mainWindowRegistration = { window: mainWindow, disposables: new DisposableStore() };\n\twindows.set(mainWindow.vscodeWindowId, mainWindowRegistration);\n\n\tconst onDidRegisterWindow = new event.Emitter();\n\tconst onDidUnregisterWindow = new event.Emitter();\n\tconst onWillUnregisterWindow = new event.Emitter();\n\n\tfunction getWindowById(windowId: number): IRegisteredCodeWindow | undefined;\n\tfunction getWindowById(windowId: number | undefined, fallbackToMain: true): IRegisteredCodeWindow;\n\tfunction getWindowById(windowId: number | undefined, fallbackToMain?: boolean): IRegisteredCodeWindow | undefined {\n\t\tconst window = typeof windowId === 'number' ? windows.get(windowId) : undefined;\n\n\t\treturn window ?? (fallbackToMain ? mainWindowRegistration : undefined);\n\t}\n\n\treturn {\n\t\tonDidRegisterWindow: onDidRegisterWindow.event,\n\t\tonWillUnregisterWindow: onWillUnregisterWindow.event,\n\t\tonDidUnregisterWindow: onDidUnregisterWindow.event,\n\t\tregisterWindow(window: CodeWindow): IDisposable {\n\t\t\tif (windows.has(window.vscodeWindowId)) {\n\t\t\t\treturn Disposable.None;\n\t\t\t}\n\n\t\t\tconst disposables = new DisposableStore();\n\n\t\t\tconst registeredWindow = {\n\t\t\t\twindow,\n\t\t\t\tdisposables: disposables.add(new DisposableStore())\n\t\t\t};\n\t\t\twindows.set(window.vscodeWindowId, registeredWindow);\n\n\t\t\tdisposables.add(toDisposable(() => {\n\t\t\t\twindows.delete(window.vscodeWindowId);\n\t\t\t\tonDidUnregisterWindow.fire(window);\n\t\t\t}));\n\n\t\t\tdisposables.add(addDisposableListener(window, EventType.BEFORE_UNLOAD, () => {\n\t\t\t\tonWillUnregisterWindow.fire(window);\n\t\t\t}));\n\n\t\t\tonDidRegisterWindow.fire(registeredWindow);\n\n\t\t\treturn disposables;\n\t\t},\n\t\tgetWindows(): Iterable {\n\t\t\treturn windows.values();\n\t\t},\n\t\tgetWindowsCount(): number {\n\t\t\treturn windows.size;\n\t\t},\n\t\tgetWindowId(targetWindow: Window): number {\n\t\t\treturn (targetWindow as CodeWindow).vscodeWindowId;\n\t\t},\n\t\thasWindow(windowId: number): boolean {\n\t\t\treturn windows.has(windowId);\n\t\t},\n\t\tgetWindowById,\n\t\tgetWindow(e: Node | UIEvent | undefined | null): CodeWindow {\n\t\t\tconst candidateNode = e as Node | undefined | null;\n\t\t\tif (candidateNode?.ownerDocument?.defaultView) {\n\t\t\t\treturn candidateNode.ownerDocument.defaultView.window as CodeWindow;\n\t\t\t}\n\n\t\t\tconst candidateEvent = e as UIEvent | undefined | null;\n\t\t\tif (candidateEvent?.view) {\n\t\t\t\treturn candidateEvent.view.window as CodeWindow;\n\t\t\t}\n\n\t\t\treturn mainWindow;\n\t\t},\n\t\tgetDocument(e: Node | UIEvent | undefined | null): Document {\n\t\t\tconst candidateNode = e as Node | undefined | null;\n\t\t\treturn getWindow(candidateNode).document;\n\t\t}\n\t};\n})();\n\n//#endregion\n\nexport function clearNode(node: HTMLElement): void {\n\twhile (node.firstChild) {\n\t\tnode.firstChild.remove();\n\t}\n}\n\n\nexport function clearNodeRecursively(domNode: ChildNode) {\n\twhile (domNode.firstChild) {\n\t\tconst element = domNode.firstChild;\n\t\telement.remove();\n\t\tclearNodeRecursively(element);\n\t}\n}\n\n\nclass DomListener implements IDisposable {\n\n\tprivate _handler: (e: any) => void;\n\tprivate _node: EventTarget;\n\tprivate readonly _type: string;\n\tprivate readonly _options: boolean | AddEventListenerOptions;\n\n\tconstructor(node: EventTarget, type: string, handler: (e: any) => void, options?: boolean | AddEventListenerOptions) {\n\t\tthis._node = node;\n\t\tthis._type = type;\n\t\tthis._handler = handler;\n\t\tthis._options = (options || false);\n\t\tthis._node.addEventListener(this._type, this._handler, this._options);\n\t}\n\n\tdispose(): void {\n\t\tif (!this._handler) {\n\t\t\t// Already disposed\n\t\t\treturn;\n\t\t}\n\n\t\tthis._node.removeEventListener(this._type, this._handler, this._options);\n\n\t\t// Prevent leakers from holding on to the dom or handler func\n\t\tthis._node = null!;\n\t\tthis._handler = null!;\n\t}\n}\n\nexport function addDisposableListener(node: EventTarget, type: K, handler: (event: GlobalEventHandlersEventMap[K]) => void, useCapture?: boolean): IDisposable;\nexport function addDisposableListener(node: EventTarget, type: string, handler: (event: any) => void, useCapture?: boolean): IDisposable;\nexport function addDisposableListener(node: EventTarget, type: string, handler: (event: any) => void, options: AddEventListenerOptions): IDisposable;\nexport function addDisposableListener(node: EventTarget, type: string, handler: (event: any) => void, useCaptureOrOptions?: boolean | AddEventListenerOptions): IDisposable {\n\treturn new DomListener(node, type, handler, useCaptureOrOptions);\n}\n\nexport interface IAddStandardDisposableListenerSignature {\n\t(node: HTMLElement, type: 'click', handler: (event: IMouseEvent) => void, useCapture?: boolean): IDisposable;\n\t(node: HTMLElement, type: 'mousedown', handler: (event: IMouseEvent) => void, useCapture?: boolean): IDisposable;\n\t(node: HTMLElement, type: 'keydown', handler: (event: IKeyboardEvent) => void, useCapture?: boolean): IDisposable;\n\t(node: HTMLElement, type: 'keypress', handler: (event: IKeyboardEvent) => void, useCapture?: boolean): IDisposable;\n\t(node: HTMLElement, type: 'keyup', handler: (event: IKeyboardEvent) => void, useCapture?: boolean): IDisposable;\n\t(node: HTMLElement, type: 'pointerdown', handler: (event: PointerEvent) => void, useCapture?: boolean): IDisposable;\n\t(node: HTMLElement, type: 'pointermove', handler: (event: PointerEvent) => void, useCapture?: boolean): IDisposable;\n\t(node: HTMLElement, type: 'pointerup', handler: (event: PointerEvent) => void, useCapture?: boolean): IDisposable;\n\t(node: HTMLElement, type: string, handler: (event: any) => void, useCapture?: boolean): IDisposable;\n}\nfunction _wrapAsStandardMouseEvent(targetWindow: Window, handler: (e: IMouseEvent) => void): (e: MouseEvent) => void {\n\treturn function (e: MouseEvent) {\n\t\treturn handler(new StandardMouseEvent(targetWindow, e));\n\t};\n}\nfunction _wrapAsStandardKeyboardEvent(handler: (e: IKeyboardEvent) => void): (e: KeyboardEvent) => void {\n\treturn function (e: KeyboardEvent) {\n\t\treturn handler(new StandardKeyboardEvent(e));\n\t};\n}\nexport const addStandardDisposableListener: IAddStandardDisposableListenerSignature = function addStandardDisposableListener(node: HTMLElement, type: string, handler: (event: any) => void, useCapture?: boolean): IDisposable {\n\tlet wrapHandler = handler;\n\n\tif (type === 'click' || type === 'mousedown' || type === 'contextmenu') {\n\t\twrapHandler = _wrapAsStandardMouseEvent(getWindow(node), handler);\n\t} else if (type === 'keydown' || type === 'keypress' || type === 'keyup') {\n\t\twrapHandler = _wrapAsStandardKeyboardEvent(handler);\n\t}\n\n\treturn addDisposableListener(node, type, wrapHandler, useCapture);\n};\n\nexport const addStandardDisposableGenericMouseDownListener = function addStandardDisposableListener(node: HTMLElement, handler: (event: any) => void, useCapture?: boolean): IDisposable {\n\tconst wrapHandler = _wrapAsStandardMouseEvent(getWindow(node), handler);\n\n\treturn addDisposableGenericMouseDownListener(node, wrapHandler, useCapture);\n};\n\nexport const addStandardDisposableGenericMouseUpListener = function addStandardDisposableListener(node: HTMLElement, handler: (event: any) => void, useCapture?: boolean): IDisposable {\n\tconst wrapHandler = _wrapAsStandardMouseEvent(getWindow(node), handler);\n\n\treturn addDisposableGenericMouseUpListener(node, wrapHandler, useCapture);\n};\nexport function addDisposableGenericMouseDownListener(node: EventTarget, handler: (event: any) => void, useCapture?: boolean): IDisposable {\n\treturn addDisposableListener(node, platform.isIOS && BrowserFeatures.pointerEvents ? EventType.POINTER_DOWN : EventType.MOUSE_DOWN, handler, useCapture);\n}\n\nexport function addDisposableGenericMouseMoveListener(node: EventTarget, handler: (event: any) => void, useCapture?: boolean): IDisposable {\n\treturn addDisposableListener(node, platform.isIOS && BrowserFeatures.pointerEvents ? EventType.POINTER_MOVE : EventType.MOUSE_MOVE, handler, useCapture);\n}\n\nexport function addDisposableGenericMouseUpListener(node: EventTarget, handler: (event: any) => void, useCapture?: boolean): IDisposable {\n\treturn addDisposableListener(node, platform.isIOS && BrowserFeatures.pointerEvents ? EventType.POINTER_UP : EventType.MOUSE_UP, handler, useCapture);\n}\n\n/**\n * Execute the callback the next time the browser is idle, returning an\n * {@link IDisposable} that will cancel the callback when disposed. This wraps\n * [requestIdleCallback] so it will fallback to [setTimeout] if the environment\n * doesn't support it.\n *\n * @param targetWindow The window for which to run the idle callback\n * @param callback The callback to run when idle, this includes an\n * [IdleDeadline] that provides the time alloted for the idle callback by the\n * browser. Not respecting this deadline will result in a degraded user\n * experience.\n * @param timeout A timeout at which point to queue no longer wait for an idle\n * callback but queue it on the regular event loop (like setTimeout). Typically\n * this should not be used.\n *\n * [IdleDeadline]: https://developer.mozilla.org/en-US/docs/Web/API/IdleDeadline\n * [requestIdleCallback]: https://developer.mozilla.org/en-US/docs/Web/API/Window/requestIdleCallback\n * [setTimeout]: https://developer.mozilla.org/en-US/docs/Web/API/Window/setTimeout\n */\nexport function runWhenWindowIdle(targetWindow: Window | typeof globalThis, callback: (idle: IdleDeadline) => void, timeout?: number): IDisposable {\n\treturn _runWhenIdle(targetWindow, callback, timeout);\n}\n\n/**\n * An implementation of the \"idle-until-urgent\"-strategy as introduced\n * here: https://philipwalton.com/articles/idle-until-urgent/\n */\nexport class WindowIdleValue extends AbstractIdleValue {\n\tconstructor(targetWindow: Window | typeof globalThis, executor: () => T) {\n\t\tsuper(targetWindow, executor);\n\t}\n}\n\n/**\n * Schedule a callback to be run at the next animation frame.\n * This allows multiple parties to register callbacks that should run at the next animation frame.\n * If currently in an animation frame, `runner` will be executed immediately.\n * @return token that can be used to cancel the scheduled runner (only if `runner` was not executed immediately).\n */\nexport let runAtThisOrScheduleAtNextAnimationFrame: (targetWindow: Window, runner: () => void, priority?: number) => IDisposable;\n/**\n * Schedule a callback to be run at the next animation frame.\n * This allows multiple parties to register callbacks that should run at the next animation frame.\n * If currently in an animation frame, `runner` will be executed at the next animation frame.\n * @return token that can be used to cancel the scheduled runner.\n */\nexport let scheduleAtNextAnimationFrame: (targetWindow: Window, runner: () => void, priority?: number) => IDisposable;\n\nexport function disposableWindowInterval(targetWindow: Window, handler: () => void | boolean /* stop interval */ | Promise, interval: number, iterations?: number): IDisposable {\n\tlet iteration = 0;\n\tconst timer = targetWindow.setInterval(() => {\n\t\titeration++;\n\t\tif ((typeof iterations === 'number' && iteration >= iterations) || handler() === true) {\n\t\t\tdisposable.dispose();\n\t\t}\n\t}, interval);\n\tconst disposable = toDisposable(() => {\n\t\ttargetWindow.clearInterval(timer);\n\t});\n\treturn disposable;\n}\n\nexport class WindowIntervalTimer extends IntervalTimer {\n\n\tprivate readonly defaultTarget?: Window & typeof globalThis;\n\n\t/**\n\t *\n\t * @param node The optional node from which the target window is determined\n\t */\n\tconstructor(node?: Node) {\n\t\tsuper();\n\t\tthis.defaultTarget = node && getWindow(node);\n\t}\n\n\toverride cancelAndSet(runner: () => void, interval: number, targetWindow?: Window & typeof globalThis): void {\n\t\treturn super.cancelAndSet(runner, interval, targetWindow ?? this.defaultTarget);\n\t}\n}\n\nclass AnimationFrameQueueItem implements IDisposable {\n\n\tprivate _runner: () => void;\n\tpublic priority: number;\n\tprivate _canceled: boolean;\n\n\tconstructor(runner: () => void, priority: number = 0) {\n\t\tthis._runner = runner;\n\t\tthis.priority = priority;\n\t\tthis._canceled = false;\n\t}\n\n\tdispose(): void {\n\t\tthis._canceled = true;\n\t}\n\n\texecute(): void {\n\t\tif (this._canceled) {\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\tthis._runner();\n\t\t} catch (e) {\n\t\t\tonUnexpectedError(e);\n\t\t}\n\t}\n\n\t// Sort by priority (largest to lowest)\n\tstatic sort(a: AnimationFrameQueueItem, b: AnimationFrameQueueItem): number {\n\t\treturn b.priority - a.priority;\n\t}\n}\n\n(function () {\n\t/**\n\t * The runners scheduled at the next animation frame\n\t */\n\tconst NEXT_QUEUE = new Map();\n\t/**\n\t * The runners scheduled at the current animation frame\n\t */\n\tconst CURRENT_QUEUE = new Map();\n\t/**\n\t * A flag to keep track if the native requestAnimationFrame was already called\n\t */\n\tconst animFrameRequested = new Map();\n\t/**\n\t * A flag to indicate if currently handling a native requestAnimationFrame callback\n\t */\n\tconst inAnimationFrameRunner = new Map();\n\n\tconst animationFrameRunner = (targetWindowId: number) => {\n\t\tanimFrameRequested.set(targetWindowId, false);\n\n\t\tconst currentQueue = NEXT_QUEUE.get(targetWindowId) ?? [];\n\t\tCURRENT_QUEUE.set(targetWindowId, currentQueue);\n\t\tNEXT_QUEUE.set(targetWindowId, []);\n\n\t\tinAnimationFrameRunner.set(targetWindowId, true);\n\t\twhile (currentQueue.length > 0) {\n\t\t\tcurrentQueue.sort(AnimationFrameQueueItem.sort);\n\t\t\tconst top = currentQueue.shift()!;\n\t\t\ttop.execute();\n\t\t}\n\t\tinAnimationFrameRunner.set(targetWindowId, false);\n\t};\n\n\tscheduleAtNextAnimationFrame = (targetWindow: Window, runner: () => void, priority: number = 0) => {\n\t\tconst targetWindowId = getWindowId(targetWindow);\n\t\tconst item = new AnimationFrameQueueItem(runner, priority);\n\n\t\tlet nextQueue = NEXT_QUEUE.get(targetWindowId);\n\t\tif (!nextQueue) {\n\t\t\tnextQueue = [];\n\t\t\tNEXT_QUEUE.set(targetWindowId, nextQueue);\n\t\t}\n\t\tnextQueue.push(item);\n\n\t\tif (!animFrameRequested.get(targetWindowId)) {\n\t\t\tanimFrameRequested.set(targetWindowId, true);\n\t\t\ttargetWindow.requestAnimationFrame(() => animationFrameRunner(targetWindowId));\n\t\t}\n\n\t\treturn item;\n\t};\n\n\trunAtThisOrScheduleAtNextAnimationFrame = (targetWindow: Window, runner: () => void, priority?: number) => {\n\t\tconst targetWindowId = getWindowId(targetWindow);\n\t\tif (inAnimationFrameRunner.get(targetWindowId)) {\n\t\t\tconst item = new AnimationFrameQueueItem(runner, priority);\n\t\t\tlet currentQueue = CURRENT_QUEUE.get(targetWindowId);\n\t\t\tif (!currentQueue) {\n\t\t\t\tcurrentQueue = [];\n\t\t\t\tCURRENT_QUEUE.set(targetWindowId, currentQueue);\n\t\t\t}\n\t\t\tcurrentQueue.push(item);\n\t\t\treturn item;\n\t\t} else {\n\t\t\treturn scheduleAtNextAnimationFrame(targetWindow, runner, priority);\n\t\t}\n\t};\n})();\n\nexport function measure(targetWindow: Window, callback: () => void): IDisposable {\n\treturn scheduleAtNextAnimationFrame(targetWindow, callback, 10000 /* must be early */);\n}\n\nexport function modify(targetWindow: Window, callback: () => void): IDisposable {\n\treturn scheduleAtNextAnimationFrame(targetWindow, callback, -10000 /* must be late */);\n}\n\n/**\n * Add a throttled listener. `handler` is fired at most every 8.33333ms or with the next animation frame (if browser supports it).\n */\nexport interface IEventMerger {\n\t(lastEvent: R | null, currentEvent: E): R;\n}\n\nconst MINIMUM_TIME_MS = 8;\nconst DEFAULT_EVENT_MERGER: IEventMerger = function (lastEvent: Event | null, currentEvent: Event) {\n\treturn currentEvent;\n};\n\nclass TimeoutThrottledDomListener extends Disposable {\n\n\tconstructor(node: any, type: string, handler: (event: R) => void, eventMerger: IEventMerger = DEFAULT_EVENT_MERGER, minimumTimeMs: number = MINIMUM_TIME_MS) {\n\t\tsuper();\n\n\t\tlet lastEvent: R | null = null;\n\t\tlet lastHandlerTime = 0;\n\t\tconst timeout = this._register(new TimeoutTimer());\n\n\t\tconst invokeHandler = () => {\n\t\t\tlastHandlerTime = (new Date()).getTime();\n\t\t\thandler(lastEvent);\n\t\t\tlastEvent = null;\n\t\t};\n\n\t\tthis._register(addDisposableListener(node, type, (e) => {\n\n\t\t\tlastEvent = eventMerger(lastEvent, e);\n\t\t\tconst elapsedTime = (new Date()).getTime() - lastHandlerTime;\n\n\t\t\tif (elapsedTime >= minimumTimeMs) {\n\t\t\t\ttimeout.cancel();\n\t\t\t\tinvokeHandler();\n\t\t\t} else {\n\t\t\t\ttimeout.setIfNotSet(invokeHandler, minimumTimeMs - elapsedTime);\n\t\t\t}\n\t\t}));\n\t}\n}\n\nexport function addDisposableThrottledListener(node: any, type: string, handler: (event: R) => void, eventMerger?: IEventMerger, minimumTimeMs?: number): IDisposable {\n\treturn new TimeoutThrottledDomListener(node, type, handler, eventMerger, minimumTimeMs);\n}\n\nexport function getComputedStyle(el: HTMLElement): CSSStyleDeclaration {\n\treturn getWindow(el).getComputedStyle(el, null);\n}\n\nexport function getClientArea(element: HTMLElement, fallback?: HTMLElement): Dimension {\n\tconst elWindow = getWindow(element);\n\tconst elDocument = elWindow.document;\n\n\t// Try with DOM clientWidth / clientHeight\n\tif (element !== elDocument.body) {\n\t\treturn new Dimension(element.clientWidth, element.clientHeight);\n\t}\n\n\t// If visual view port exits and it's on mobile, it should be used instead of window innerWidth / innerHeight, or document.body.clientWidth / document.body.clientHeight\n\tif (platform.isIOS && elWindow?.visualViewport) {\n\t\treturn new Dimension(elWindow.visualViewport.width, elWindow.visualViewport.height);\n\t}\n\n\t// Try innerWidth / innerHeight\n\tif (elWindow?.innerWidth && elWindow.innerHeight) {\n\t\treturn new Dimension(elWindow.innerWidth, elWindow.innerHeight);\n\t}\n\n\t// Try with document.body.clientWidth / document.body.clientHeight\n\tif (elDocument.body && elDocument.body.clientWidth && elDocument.body.clientHeight) {\n\t\treturn new Dimension(elDocument.body.clientWidth, elDocument.body.clientHeight);\n\t}\n\n\t// Try with document.documentElement.clientWidth / document.documentElement.clientHeight\n\tif (elDocument.documentElement && elDocument.documentElement.clientWidth && elDocument.documentElement.clientHeight) {\n\t\treturn new Dimension(elDocument.documentElement.clientWidth, elDocument.documentElement.clientHeight);\n\t}\n\n\tif (fallback) {\n\t\treturn getClientArea(fallback);\n\t}\n\n\tthrow new Error('Unable to figure out browser width and height');\n}\n\nclass SizeUtils {\n\t// Adapted from WinJS\n\t// Converts a CSS positioning string for the specified element to pixels.\n\tprivate static convertToPixels(element: HTMLElement, value: string): number {\n\t\treturn parseFloat(value) || 0;\n\t}\n\n\tprivate static getDimension(element: HTMLElement, cssPropertyName: string, jsPropertyName: string): number {\n\t\tconst computedStyle = getComputedStyle(element);\n\t\tconst value = computedStyle ? computedStyle.getPropertyValue(cssPropertyName) : '0';\n\t\treturn SizeUtils.convertToPixels(element, value);\n\t}\n\n\tstatic getBorderLeftWidth(element: HTMLElement): number {\n\t\treturn SizeUtils.getDimension(element, 'border-left-width', 'borderLeftWidth');\n\t}\n\tstatic getBorderRightWidth(element: HTMLElement): number {\n\t\treturn SizeUtils.getDimension(element, 'border-right-width', 'borderRightWidth');\n\t}\n\tstatic getBorderTopWidth(element: HTMLElement): number {\n\t\treturn SizeUtils.getDimension(element, 'border-top-width', 'borderTopWidth');\n\t}\n\tstatic getBorderBottomWidth(element: HTMLElement): number {\n\t\treturn SizeUtils.getDimension(element, 'border-bottom-width', 'borderBottomWidth');\n\t}\n\n\tstatic getPaddingLeft(element: HTMLElement): number {\n\t\treturn SizeUtils.getDimension(element, 'padding-left', 'paddingLeft');\n\t}\n\tstatic getPaddingRight(element: HTMLElement): number {\n\t\treturn SizeUtils.getDimension(element, 'padding-right', 'paddingRight');\n\t}\n\tstatic getPaddingTop(element: HTMLElement): number {\n\t\treturn SizeUtils.getDimension(element, 'padding-top', 'paddingTop');\n\t}\n\tstatic getPaddingBottom(element: HTMLElement): number {\n\t\treturn SizeUtils.getDimension(element, 'padding-bottom', 'paddingBottom');\n\t}\n\n\tstatic getMarginLeft(element: HTMLElement): number {\n\t\treturn SizeUtils.getDimension(element, 'margin-left', 'marginLeft');\n\t}\n\tstatic getMarginTop(element: HTMLElement): number {\n\t\treturn SizeUtils.getDimension(element, 'margin-top', 'marginTop');\n\t}\n\tstatic getMarginRight(element: HTMLElement): number {\n\t\treturn SizeUtils.getDimension(element, 'margin-right', 'marginRight');\n\t}\n\tstatic getMarginBottom(element: HTMLElement): number {\n\t\treturn SizeUtils.getDimension(element, 'margin-bottom', 'marginBottom');\n\t}\n}\n\n// ----------------------------------------------------------------------------------------\n// Position & Dimension\n\nexport interface IDimension {\n\treadonly width: number;\n\treadonly height: number;\n}\n\nexport class Dimension implements IDimension {\n\n\tstatic readonly None = new Dimension(0, 0);\n\n\tconstructor(\n\t\treadonly width: number,\n\t\treadonly height: number,\n\t) { }\n\n\twith(width: number = this.width, height: number = this.height): Dimension {\n\t\tif (width !== this.width || height !== this.height) {\n\t\t\treturn new Dimension(width, height);\n\t\t} else {\n\t\t\treturn this;\n\t\t}\n\t}\n\n\tstatic is(obj: unknown): obj is IDimension {\n\t\treturn typeof obj === 'object' && typeof (obj).height === 'number' && typeof (obj).width === 'number';\n\t}\n\n\tstatic lift(obj: IDimension): Dimension {\n\t\tif (obj instanceof Dimension) {\n\t\t\treturn obj;\n\t\t} else {\n\t\t\treturn new Dimension(obj.width, obj.height);\n\t\t}\n\t}\n\n\tstatic equals(a: Dimension | undefined, b: Dimension | undefined): boolean {\n\t\tif (a === b) {\n\t\t\treturn true;\n\t\t}\n\t\tif (!a || !b) {\n\t\t\treturn false;\n\t\t}\n\t\treturn a.width === b.width && a.height === b.height;\n\t}\n}\n\nexport interface IDomPosition {\n\treadonly left: number;\n\treadonly top: number;\n}\n\nexport function getTopLeftOffset(element: HTMLElement): IDomPosition {\n\t// Adapted from WinJS.Utilities.getPosition\n\t// and added borders to the mix\n\n\tlet offsetParent = element.offsetParent;\n\tlet top = element.offsetTop;\n\tlet left = element.offsetLeft;\n\n\twhile (\n\t\t(element = element.parentNode) !== null\n\t\t&& element !== element.ownerDocument.body\n\t\t&& element !== element.ownerDocument.documentElement\n\t) {\n\t\ttop -= element.scrollTop;\n\t\tconst c = isShadowRoot(element) ? null : getComputedStyle(element);\n\t\tif (c) {\n\t\t\tleft -= c.direction !== 'rtl' ? element.scrollLeft : -element.scrollLeft;\n\t\t}\n\n\t\tif (element === offsetParent) {\n\t\t\tleft += SizeUtils.getBorderLeftWidth(element);\n\t\t\ttop += SizeUtils.getBorderTopWidth(element);\n\t\t\ttop += element.offsetTop;\n\t\t\tleft += element.offsetLeft;\n\t\t\toffsetParent = element.offsetParent;\n\t\t}\n\t}\n\n\treturn {\n\t\tleft: left,\n\t\ttop: top\n\t};\n}\n\nexport interface IDomNodePagePosition {\n\tleft: number;\n\ttop: number;\n\twidth: number;\n\theight: number;\n}\n\nexport function size(element: HTMLElement, width: number | null, height: number | null): void {\n\tif (typeof width === 'number') {\n\t\telement.style.width = `${width}px`;\n\t}\n\n\tif (typeof height === 'number') {\n\t\telement.style.height = `${height}px`;\n\t}\n}\n\nexport function position(element: HTMLElement, top: number, right?: number, bottom?: number, left?: number, position: string = 'absolute'): void {\n\tif (typeof top === 'number') {\n\t\telement.style.top = `${top}px`;\n\t}\n\n\tif (typeof right === 'number') {\n\t\telement.style.right = `${right}px`;\n\t}\n\n\tif (typeof bottom === 'number') {\n\t\telement.style.bottom = `${bottom}px`;\n\t}\n\n\tif (typeof left === 'number') {\n\t\telement.style.left = `${left}px`;\n\t}\n\n\telement.style.position = position;\n}\n\n/**\n * Returns the position of a dom node relative to the entire page.\n */\nexport function getDomNodePagePosition(domNode: HTMLElement): IDomNodePagePosition {\n\tconst bb = domNode.getBoundingClientRect();\n\tconst window = getWindow(domNode);\n\treturn {\n\t\tleft: bb.left + window.scrollX,\n\t\ttop: bb.top + window.scrollY,\n\t\twidth: bb.width,\n\t\theight: bb.height\n\t};\n}\n\n/**\n * Returns the effective zoom on a given element before window zoom level is applied\n */\nexport function getDomNodeZoomLevel(domNode: HTMLElement): number {\n\tlet testElement: HTMLElement | null = domNode;\n\tlet zoom = 1.0;\n\tdo {\n\t\tconst elementZoomLevel = (getComputedStyle(testElement) as any).zoom;\n\t\tif (elementZoomLevel !== null && elementZoomLevel !== undefined && elementZoomLevel !== '1') {\n\t\t\tzoom *= elementZoomLevel;\n\t\t}\n\n\t\ttestElement = testElement.parentElement;\n\t} while (testElement !== null && testElement !== testElement.ownerDocument.documentElement);\n\n\treturn zoom;\n}\n\n\n// Adapted from WinJS\n// Gets the width of the element, including margins.\nexport function getTotalWidth(element: HTMLElement): number {\n\tconst margin = SizeUtils.getMarginLeft(element) + SizeUtils.getMarginRight(element);\n\treturn element.offsetWidth + margin;\n}\n\nexport function getContentWidth(element: HTMLElement): number {\n\tconst border = SizeUtils.getBorderLeftWidth(element) + SizeUtils.getBorderRightWidth(element);\n\tconst padding = SizeUtils.getPaddingLeft(element) + SizeUtils.getPaddingRight(element);\n\treturn element.offsetWidth - border - padding;\n}\n\nexport function getTotalScrollWidth(element: HTMLElement): number {\n\tconst margin = SizeUtils.getMarginLeft(element) + SizeUtils.getMarginRight(element);\n\treturn element.scrollWidth + margin;\n}\n\n// Adapted from WinJS\n// Gets the height of the content of the specified element. The content height does not include borders or padding.\nexport function getContentHeight(element: HTMLElement): number {\n\tconst border = SizeUtils.getBorderTopWidth(element) + SizeUtils.getBorderBottomWidth(element);\n\tconst padding = SizeUtils.getPaddingTop(element) + SizeUtils.getPaddingBottom(element);\n\treturn element.offsetHeight - border - padding;\n}\n\n// Adapted from WinJS\n// Gets the height of the element, including its margins.\nexport function getTotalHeight(element: HTMLElement): number {\n\tconst margin = SizeUtils.getMarginTop(element) + SizeUtils.getMarginBottom(element);\n\treturn element.offsetHeight + margin;\n}\n\n// Gets the left coordinate of the specified element relative to the specified parent.\nfunction getRelativeLeft(element: HTMLElement, parent: HTMLElement): number {\n\tif (element === null) {\n\t\treturn 0;\n\t}\n\n\tconst elementPosition = getTopLeftOffset(element);\n\tconst parentPosition = getTopLeftOffset(parent);\n\treturn elementPosition.left - parentPosition.left;\n}\n\nexport function getLargestChildWidth(parent: HTMLElement, children: HTMLElement[]): number {\n\tconst childWidths = children.map((child) => {\n\t\treturn Math.max(getTotalScrollWidth(child), getTotalWidth(child)) + getRelativeLeft(child, parent) || 0;\n\t});\n\tconst maxWidth = Math.max(...childWidths);\n\treturn maxWidth;\n}\n\n// ----------------------------------------------------------------------------------------\n\nexport function isAncestor(testChild: Node | null, testAncestor: Node | null): boolean {\n\treturn Boolean(testAncestor?.contains(testChild));\n}\n\nconst parentFlowToDataKey = 'parentFlowToElementId';\n\n/**\n * Set an explicit parent to use for nodes that are not part of the\n * regular dom structure.\n */\nexport function setParentFlowTo(fromChildElement: HTMLElement, toParentElement: Element): void {\n\tfromChildElement.dataset[parentFlowToDataKey] = toParentElement.id;\n}\n\nfunction getParentFlowToElement(node: HTMLElement): HTMLElement | null {\n\tconst flowToParentId = node.dataset[parentFlowToDataKey];\n\tif (typeof flowToParentId === 'string') {\n\t\treturn node.ownerDocument.getElementById(flowToParentId);\n\t}\n\treturn null;\n}\n\n/**\n * Check if `testAncestor` is an ancestor of `testChild`, observing the explicit\n * parents set by `setParentFlowTo`.\n */\nexport function isAncestorUsingFlowTo(testChild: Node, testAncestor: Node): boolean {\n\tlet node: Node | null = testChild;\n\twhile (node) {\n\t\tif (node === testAncestor) {\n\t\t\treturn true;\n\t\t}\n\n\t\tif (isHTMLElement(node)) {\n\t\t\tconst flowToParentElement = getParentFlowToElement(node);\n\t\t\tif (flowToParentElement) {\n\t\t\t\tnode = flowToParentElement;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tnode = node.parentNode;\n\t}\n\n\treturn false;\n}\n\nexport function findParentWithClass(node: HTMLElement, clazz: string, stopAtClazzOrNode?: string | HTMLElement): HTMLElement | null {\n\twhile (node && node.nodeType === node.ELEMENT_NODE) {\n\t\tif (node.classList.contains(clazz)) {\n\t\t\treturn node;\n\t\t}\n\n\t\tif (stopAtClazzOrNode) {\n\t\t\tif (typeof stopAtClazzOrNode === 'string') {\n\t\t\t\tif (node.classList.contains(stopAtClazzOrNode)) {\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (node === stopAtClazzOrNode) {\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tnode = node.parentNode;\n\t}\n\n\treturn null;\n}\n\nexport function hasParentWithClass(node: HTMLElement, clazz: string, stopAtClazzOrNode?: string | HTMLElement): boolean {\n\treturn !!findParentWithClass(node, clazz, stopAtClazzOrNode);\n}\n\nexport function isShadowRoot(node: Node): node is ShadowRoot {\n\treturn (\n\t\tnode && !!(node).host && !!(node).mode\n\t);\n}\n\nexport function isInShadowDOM(domNode: Node): boolean {\n\treturn !!getShadowRoot(domNode);\n}\n\nexport function getShadowRoot(domNode: Node): ShadowRoot | null {\n\twhile (domNode.parentNode) {\n\t\tif (domNode === domNode.ownerDocument?.body) {\n\t\t\t// reached the body\n\t\t\treturn null;\n\t\t}\n\t\tdomNode = domNode.parentNode;\n\t}\n\treturn isShadowRoot(domNode) ? domNode : null;\n}\n\n/**\n * Returns the active element across all child windows\n * based on document focus. Falls back to the main\n * window if no window has focus.\n */\nexport function getActiveElement(): Element | null {\n\tlet result = getActiveDocument().activeElement;\n\n\twhile (result?.shadowRoot) {\n\t\tresult = result.shadowRoot.activeElement;\n\t}\n\n\treturn result;\n}\n\n/**\n * Returns true if the focused window active element matches\n * the provided element. Falls back to the main window if no\n * window has focus.\n */\nexport function isActiveElement(element: Element): boolean {\n\treturn getActiveElement() === element;\n}\n\n/**\n * Returns true if the focused window active element is contained in\n * `ancestor`. Falls back to the main window if no window has focus.\n */\nexport function isAncestorOfActiveElement(ancestor: Element): boolean {\n\treturn isAncestor(getActiveElement(), ancestor);\n}\n\n/**\n * Returns whether the element is in the active `document`. The active\n * document has focus or will be the main windows document.\n */\nexport function isActiveDocument(element: Element): boolean {\n\treturn element.ownerDocument === getActiveDocument();\n}\n\n/**\n * Returns the active document across main and child windows.\n * Prefers the window with focus, otherwise falls back to\n * the main windows document.\n */\nexport function getActiveDocument(): Document {\n\tif (getWindowsCount() <= 1) {\n\t\treturn mainWindow.document;\n\t}\n\n\tconst documents = Array.from(getWindows()).map(({ window }) => window.document);\n\treturn documents.find(doc => doc.hasFocus()) ?? mainWindow.document;\n}\n\n/**\n * Returns the active window across main and child windows.\n * Prefers the window with focus, otherwise falls back to\n * the main window.\n */\nexport function getActiveWindow(): CodeWindow {\n\tconst document = getActiveDocument();\n\treturn (document.defaultView?.window ?? mainWindow) as CodeWindow;\n}\n\nconst globalStylesheets = new Map>();\n\nexport function isGlobalStylesheet(node: Node): boolean {\n\treturn globalStylesheets.has(node as HTMLStyleElement);\n}\n\n/**\n * A version of createStyleSheet which has a unified API to initialize/set the style content.\n */\nexport function createStyleSheet2(): WrappedStyleElement {\n\treturn new WrappedStyleElement();\n}\n\nclass WrappedStyleElement {\n\tprivate _currentCssStyle = '';\n\tprivate _styleSheet: HTMLStyleElement | undefined = undefined;\n\n\tpublic setStyle(cssStyle: string): void {\n\t\tif (cssStyle === this._currentCssStyle) {\n\t\t\treturn;\n\t\t}\n\t\tthis._currentCssStyle = cssStyle;\n\n\t\tif (!this._styleSheet) {\n\t\t\tthis._styleSheet = createStyleSheet(mainWindow.document.head, (s) => s.innerText = cssStyle);\n\t\t} else {\n\t\t\tthis._styleSheet.innerText = cssStyle;\n\t\t}\n\t}\n\n\tpublic dispose(): void {\n\t\tif (this._styleSheet) {\n\t\t\tthis._styleSheet.remove();\n\t\t\tthis._styleSheet = undefined;\n\t\t}\n\t}\n}\n\nexport function createStyleSheet(container: HTMLElement = mainWindow.document.head, beforeAppend?: (style: HTMLStyleElement) => void, disposableStore?: DisposableStore): HTMLStyleElement {\n\tconst style = document.createElement('style');\n\tstyle.type = 'text/css';\n\tstyle.media = 'screen';\n\tbeforeAppend?.(style);\n\tcontainer.appendChild(style);\n\n\tif (disposableStore) {\n\t\tdisposableStore.add(toDisposable(() => style.remove()));\n\t}\n\n\t// With as container, the stylesheet becomes global and is tracked\n\t// to support auxiliary windows to clone the stylesheet.\n\tif (container === mainWindow.document.head) {\n\t\tconst globalStylesheetClones = new Set();\n\t\tglobalStylesheets.set(style, globalStylesheetClones);\n\n\t\tfor (const { window: targetWindow, disposables } of getWindows()) {\n\t\t\tif (targetWindow === mainWindow) {\n\t\t\t\tcontinue; // main window is already tracked\n\t\t\t}\n\n\t\t\tconst cloneDisposable = disposables.add(cloneGlobalStyleSheet(style, globalStylesheetClones, targetWindow));\n\t\t\tdisposableStore?.add(cloneDisposable);\n\t\t}\n\t}\n\n\treturn style;\n}\n\nexport function cloneGlobalStylesheets(targetWindow: Window): IDisposable {\n\tconst disposables = new DisposableStore();\n\n\tfor (const [globalStylesheet, clonedGlobalStylesheets] of globalStylesheets) {\n\t\tdisposables.add(cloneGlobalStyleSheet(globalStylesheet, clonedGlobalStylesheets, targetWindow));\n\t}\n\n\treturn disposables;\n}\n\nfunction cloneGlobalStyleSheet(globalStylesheet: HTMLStyleElement, globalStylesheetClones: Set, targetWindow: Window): IDisposable {\n\tconst disposables = new DisposableStore();\n\n\tconst clone = globalStylesheet.cloneNode(true) as HTMLStyleElement;\n\ttargetWindow.document.head.appendChild(clone);\n\tdisposables.add(toDisposable(() => clone.remove()));\n\n\tfor (const rule of getDynamicStyleSheetRules(globalStylesheet)) {\n\t\tclone.sheet?.insertRule(rule.cssText, clone.sheet?.cssRules.length);\n\t}\n\n\tdisposables.add(sharedMutationObserver.observe(globalStylesheet, disposables, { childList: true })(() => {\n\t\tclone.textContent = globalStylesheet.textContent;\n\t}));\n\n\tglobalStylesheetClones.add(clone);\n\tdisposables.add(toDisposable(() => globalStylesheetClones.delete(clone)));\n\n\treturn disposables;\n}\n\ninterface IMutationObserver {\n\tusers: number;\n\treadonly observer: MutationObserver;\n\treadonly onDidMutate: event.Event;\n}\n\nexport const sharedMutationObserver = new class {\n\n\treadonly mutationObservers = new Map>();\n\n\tobserve(target: Node, disposables: DisposableStore, options?: MutationObserverInit): event.Event {\n\t\tlet mutationObserversPerTarget = this.mutationObservers.get(target);\n\t\tif (!mutationObserversPerTarget) {\n\t\t\tmutationObserversPerTarget = new Map();\n\t\t\tthis.mutationObservers.set(target, mutationObserversPerTarget);\n\t\t}\n\n\t\tconst optionsHash = hash(options);\n\t\tlet mutationObserverPerOptions = mutationObserversPerTarget.get(optionsHash);\n\t\tif (!mutationObserverPerOptions) {\n\t\t\tconst onDidMutate = new event.Emitter();\n\t\t\tconst observer = new MutationObserver(mutations => onDidMutate.fire(mutations));\n\t\t\tobserver.observe(target, options);\n\n\t\t\tconst resolvedMutationObserverPerOptions = mutationObserverPerOptions = {\n\t\t\t\tusers: 1,\n\t\t\t\tobserver,\n\t\t\t\tonDidMutate: onDidMutate.event\n\t\t\t};\n\n\t\t\tdisposables.add(toDisposable(() => {\n\t\t\t\tresolvedMutationObserverPerOptions.users -= 1;\n\n\t\t\t\tif (resolvedMutationObserverPerOptions.users === 0) {\n\t\t\t\t\tonDidMutate.dispose();\n\t\t\t\t\tobserver.disconnect();\n\n\t\t\t\t\tmutationObserversPerTarget?.delete(optionsHash);\n\t\t\t\t\tif (mutationObserversPerTarget?.size === 0) {\n\t\t\t\t\t\tthis.mutationObservers.delete(target);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}));\n\n\t\t\tmutationObserversPerTarget.set(optionsHash, mutationObserverPerOptions);\n\t\t} else {\n\t\t\tmutationObserverPerOptions.users += 1;\n\t\t}\n\n\t\treturn mutationObserverPerOptions.onDidMutate;\n\t}\n};\n\nexport function createMetaElement(container: HTMLElement = mainWindow.document.head): HTMLMetaElement {\n\treturn createHeadElement('meta', container) as HTMLMetaElement;\n}\n\nexport function createLinkElement(container: HTMLElement = mainWindow.document.head): HTMLLinkElement {\n\treturn createHeadElement('link', container) as HTMLLinkElement;\n}\n\nfunction createHeadElement(tagName: string, container: HTMLElement = mainWindow.document.head): HTMLElement {\n\tconst element = document.createElement(tagName);\n\tcontainer.appendChild(element);\n\treturn element;\n}\n\nlet _sharedStyleSheet: HTMLStyleElement | null = null;\nfunction getSharedStyleSheet(): HTMLStyleElement {\n\tif (!_sharedStyleSheet) {\n\t\t_sharedStyleSheet = createStyleSheet();\n\t}\n\treturn _sharedStyleSheet;\n}\n\nfunction getDynamicStyleSheetRules(style: HTMLStyleElement) {\n\tif (style?.sheet?.rules) {\n\t\t// Chrome, IE\n\t\treturn style.sheet.rules;\n\t}\n\tif (style?.sheet?.cssRules) {\n\t\t// FF\n\t\treturn style.sheet.cssRules;\n\t}\n\treturn [];\n}\n\nexport function createCSSRule(selector: string, cssText: string, style = getSharedStyleSheet()): void {\n\tif (!style || !cssText) {\n\t\treturn;\n\t}\n\n\tstyle.sheet?.insertRule(`${selector} {${cssText}}`, 0);\n\n\t// Apply rule also to all cloned global stylesheets\n\tfor (const clonedGlobalStylesheet of globalStylesheets.get(style) ?? []) {\n\t\tcreateCSSRule(selector, cssText, clonedGlobalStylesheet);\n\t}\n}\n\nexport function removeCSSRulesContainingSelector(ruleName: string, style = getSharedStyleSheet()): void {\n\tif (!style) {\n\t\treturn;\n\t}\n\n\tconst rules = getDynamicStyleSheetRules(style);\n\tconst toDelete: number[] = [];\n\tfor (let i = 0; i < rules.length; i++) {\n\t\tconst rule = rules[i];\n\t\tif (isCSSStyleRule(rule) && rule.selectorText.indexOf(ruleName) !== -1) {\n\t\t\ttoDelete.push(i);\n\t\t}\n\t}\n\n\tfor (let i = toDelete.length - 1; i >= 0; i--) {\n\t\tstyle.sheet?.deleteRule(toDelete[i]);\n\t}\n\n\t// Remove rules also from all cloned global stylesheets\n\tfor (const clonedGlobalStylesheet of globalStylesheets.get(style) ?? []) {\n\t\tremoveCSSRulesContainingSelector(ruleName, clonedGlobalStylesheet);\n\t}\n}\n\nfunction isCSSStyleRule(rule: CSSRule): rule is CSSStyleRule {\n\treturn typeof (rule as CSSStyleRule).selectorText === 'string';\n}\n\nexport function isHTMLElement(e: unknown): e is HTMLElement {\n\t// eslint-disable-next-line no-restricted-syntax\n\treturn e instanceof HTMLElement || e instanceof getWindow(e as Node).HTMLElement;\n}\n\nexport function isHTMLAnchorElement(e: unknown): e is HTMLAnchorElement {\n\t// eslint-disable-next-line no-restricted-syntax\n\treturn e instanceof HTMLAnchorElement || e instanceof getWindow(e as Node).HTMLAnchorElement;\n}\n\nexport function isHTMLSpanElement(e: unknown): e is HTMLSpanElement {\n\t// eslint-disable-next-line no-restricted-syntax\n\treturn e instanceof HTMLSpanElement || e instanceof getWindow(e as Node).HTMLSpanElement;\n}\n\nexport function isHTMLTextAreaElement(e: unknown): e is HTMLTextAreaElement {\n\t// eslint-disable-next-line no-restricted-syntax\n\treturn e instanceof HTMLTextAreaElement || e instanceof getWindow(e as Node).HTMLTextAreaElement;\n}\n\nexport function isHTMLInputElement(e: unknown): e is HTMLInputElement {\n\t// eslint-disable-next-line no-restricted-syntax\n\treturn e instanceof HTMLInputElement || e instanceof getWindow(e as Node).HTMLInputElement;\n}\n\nexport function isHTMLButtonElement(e: unknown): e is HTMLButtonElement {\n\t// eslint-disable-next-line no-restricted-syntax\n\treturn e instanceof HTMLButtonElement || e instanceof getWindow(e as Node).HTMLButtonElement;\n}\n\nexport function isHTMLDivElement(e: unknown): e is HTMLDivElement {\n\t// eslint-disable-next-line no-restricted-syntax\n\treturn e instanceof HTMLDivElement || e instanceof getWindow(e as Node).HTMLDivElement;\n}\n\nexport function isSVGElement(e: unknown): e is SVGElement {\n\t// eslint-disable-next-line no-restricted-syntax\n\treturn e instanceof SVGElement || e instanceof getWindow(e as Node).SVGElement;\n}\n\nexport function isMouseEvent(e: unknown): e is MouseEvent {\n\t// eslint-disable-next-line no-restricted-syntax\n\treturn e instanceof MouseEvent || e instanceof getWindow(e as UIEvent).MouseEvent;\n}\n\nexport function isKeyboardEvent(e: unknown): e is KeyboardEvent {\n\t// eslint-disable-next-line no-restricted-syntax\n\treturn e instanceof KeyboardEvent || e instanceof getWindow(e as UIEvent).KeyboardEvent;\n}\n\nexport function isPointerEvent(e: unknown): e is PointerEvent {\n\t// eslint-disable-next-line no-restricted-syntax\n\treturn e instanceof PointerEvent || e instanceof getWindow(e as UIEvent).PointerEvent;\n}\n\nexport function isDragEvent(e: unknown): e is DragEvent {\n\t// eslint-disable-next-line no-restricted-syntax\n\treturn e instanceof DragEvent || e instanceof getWindow(e as UIEvent).DragEvent;\n}\n\nexport const EventType = {\n\t// Mouse\n\tCLICK: 'click',\n\tAUXCLICK: 'auxclick',\n\tDBLCLICK: 'dblclick',\n\tMOUSE_UP: 'mouseup',\n\tMOUSE_DOWN: 'mousedown',\n\tMOUSE_OVER: 'mouseover',\n\tMOUSE_MOVE: 'mousemove',\n\tMOUSE_OUT: 'mouseout',\n\tMOUSE_ENTER: 'mouseenter',\n\tMOUSE_LEAVE: 'mouseleave',\n\tMOUSE_WHEEL: 'wheel',\n\tPOINTER_UP: 'pointerup',\n\tPOINTER_DOWN: 'pointerdown',\n\tPOINTER_MOVE: 'pointermove',\n\tPOINTER_LEAVE: 'pointerleave',\n\tCONTEXT_MENU: 'contextmenu',\n\tWHEEL: 'wheel',\n\t// Keyboard\n\tKEY_DOWN: 'keydown',\n\tKEY_PRESS: 'keypress',\n\tKEY_UP: 'keyup',\n\t// HTML Document\n\tLOAD: 'load',\n\tBEFORE_UNLOAD: 'beforeunload',\n\tUNLOAD: 'unload',\n\tPAGE_SHOW: 'pageshow',\n\tPAGE_HIDE: 'pagehide',\n\tPASTE: 'paste',\n\tABORT: 'abort',\n\tERROR: 'error',\n\tRESIZE: 'resize',\n\tSCROLL: 'scroll',\n\tFULLSCREEN_CHANGE: 'fullscreenchange',\n\tWK_FULLSCREEN_CHANGE: 'webkitfullscreenchange',\n\t// Form\n\tSELECT: 'select',\n\tCHANGE: 'change',\n\tSUBMIT: 'submit',\n\tRESET: 'reset',\n\tFOCUS: 'focus',\n\tFOCUS_IN: 'focusin',\n\tFOCUS_OUT: 'focusout',\n\tBLUR: 'blur',\n\tINPUT: 'input',\n\t// Local Storage\n\tSTORAGE: 'storage',\n\t// Drag\n\tDRAG_START: 'dragstart',\n\tDRAG: 'drag',\n\tDRAG_ENTER: 'dragenter',\n\tDRAG_LEAVE: 'dragleave',\n\tDRAG_OVER: 'dragover',\n\tDROP: 'drop',\n\tDRAG_END: 'dragend',\n\t// Animation\n\tANIMATION_START: browser.isWebKit ? 'webkitAnimationStart' : 'animationstart',\n\tANIMATION_END: browser.isWebKit ? 'webkitAnimationEnd' : 'animationend',\n\tANIMATION_ITERATION: browser.isWebKit ? 'webkitAnimationIteration' : 'animationiteration'\n} as const;\n\nexport interface EventLike {\n\tpreventDefault(): void;\n\tstopPropagation(): void;\n}\n\nexport function isEventLike(obj: unknown): obj is EventLike {\n\tconst candidate = obj as EventLike | undefined;\n\n\treturn !!(candidate && typeof candidate.preventDefault === 'function' && typeof candidate.stopPropagation === 'function');\n}\n\nexport const EventHelper = {\n\tstop: (e: T, cancelBubble?: boolean): T => {\n\t\te.preventDefault();\n\t\tif (cancelBubble) {\n\t\t\te.stopPropagation();\n\t\t}\n\t\treturn e;\n\t}\n};\n\nexport interface IFocusTracker extends Disposable {\n\treadonly onDidFocus: event.Event;\n\treadonly onDidBlur: event.Event;\n\trefreshState(): void;\n}\n\nexport function saveParentsScrollTop(node: Element): number[] {\n\tconst r: number[] = [];\n\tfor (let i = 0; node && node.nodeType === node.ELEMENT_NODE; i++) {\n\t\tr[i] = node.scrollTop;\n\t\tnode = node.parentNode;\n\t}\n\treturn r;\n}\n\nexport function restoreParentsScrollTop(node: Element, state: number[]): void {\n\tfor (let i = 0; node && node.nodeType === node.ELEMENT_NODE; i++) {\n\t\tif (node.scrollTop !== state[i]) {\n\t\t\tnode.scrollTop = state[i];\n\t\t}\n\t\tnode = node.parentNode;\n\t}\n}\n\nclass FocusTracker extends Disposable implements IFocusTracker {\n\n\tprivate readonly _onDidFocus = this._register(new event.Emitter());\n\treadonly onDidFocus = this._onDidFocus.event;\n\n\tprivate readonly _onDidBlur = this._register(new event.Emitter());\n\treadonly onDidBlur = this._onDidBlur.event;\n\n\tprivate _refreshStateHandler: () => void;\n\n\tprivate static hasFocusWithin(element: HTMLElement | Window): boolean {\n\t\tif (isHTMLElement(element)) {\n\t\t\tconst shadowRoot = getShadowRoot(element);\n\t\t\tconst activeElement = (shadowRoot ? shadowRoot.activeElement : element.ownerDocument.activeElement);\n\t\t\treturn isAncestor(activeElement, element);\n\t\t} else {\n\t\t\tconst window = element;\n\t\t\treturn isAncestor(window.document.activeElement, window.document);\n\t\t}\n\t}\n\n\tconstructor(element: HTMLElement | Window) {\n\t\tsuper();\n\t\tlet hasFocus = FocusTracker.hasFocusWithin(element);\n\t\tlet loosingFocus = false;\n\n\t\tconst onFocus = () => {\n\t\t\tloosingFocus = false;\n\t\t\tif (!hasFocus) {\n\t\t\t\thasFocus = true;\n\t\t\t\tthis._onDidFocus.fire();\n\t\t\t}\n\t\t};\n\n\t\tconst onBlur = () => {\n\t\t\tif (hasFocus) {\n\t\t\t\tloosingFocus = true;\n\t\t\t\t(isHTMLElement(element) ? getWindow(element) : element).setTimeout(() => {\n\t\t\t\t\tif (loosingFocus) {\n\t\t\t\t\t\tloosingFocus = false;\n\t\t\t\t\t\thasFocus = false;\n\t\t\t\t\t\tthis._onDidBlur.fire();\n\t\t\t\t\t}\n\t\t\t\t}, 0);\n\t\t\t}\n\t\t};\n\n\t\tthis._refreshStateHandler = () => {\n\t\t\tconst currentNodeHasFocus = FocusTracker.hasFocusWithin(element);\n\t\t\tif (currentNodeHasFocus !== hasFocus) {\n\t\t\t\tif (hasFocus) {\n\t\t\t\t\tonBlur();\n\t\t\t\t} else {\n\t\t\t\t\tonFocus();\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\tthis._register(addDisposableListener(element, EventType.FOCUS, onFocus, true));\n\t\tthis._register(addDisposableListener(element, EventType.BLUR, onBlur, true));\n\t\tif (isHTMLElement(element)) {\n\t\t\tthis._register(addDisposableListener(element, EventType.FOCUS_IN, () => this._refreshStateHandler()));\n\t\t\tthis._register(addDisposableListener(element, EventType.FOCUS_OUT, () => this._refreshStateHandler()));\n\t\t}\n\n\t}\n\n\trefreshState() {\n\t\tthis._refreshStateHandler();\n\t}\n}\n\n/**\n * Creates a new `IFocusTracker` instance that tracks focus changes on the given `element` and its descendants.\n *\n * @param element The `HTMLElement` or `Window` to track focus changes on.\n * @returns An `IFocusTracker` instance.\n */\nexport function trackFocus(element: HTMLElement | Window): IFocusTracker {\n\treturn new FocusTracker(element);\n}\n\nexport function after(sibling: HTMLElement, child: T): T {\n\tsibling.after(child);\n\treturn child;\n}\n\nexport function append(parent: HTMLElement, child: T): T;\nexport function append(parent: HTMLElement, ...children: (T | string)[]): void;\nexport function append(parent: HTMLElement, ...children: (T | string)[]): T | void {\n\tparent.append(...children);\n\tif (children.length === 1 && typeof children[0] !== 'string') {\n\t\treturn children[0];\n\t}\n}\n\nexport function prepend(parent: HTMLElement, child: T): T {\n\tparent.insertBefore(child, parent.firstChild);\n\treturn child;\n}\n\n/**\n * Removes all children from `parent` and appends `children`\n */\nexport function reset(parent: HTMLElement, ...children: Array): void {\n\tparent.innerText = '';\n\tappend(parent, ...children);\n}\n\nconst SELECTOR_REGEX = /([\\w\\-]+)?(#([\\w\\-]+))?((\\.([\\w\\-]+))*)/;\n\nexport enum Namespace {\n\tHTML = 'http://www.w3.org/1999/xhtml',\n\tSVG = 'http://www.w3.org/2000/svg'\n}\n\nfunction _$(namespace: Namespace, description: string, attrs?: { [key: string]: any }, ...children: Array): T {\n\tconst match = SELECTOR_REGEX.exec(description);\n\n\tif (!match) {\n\t\tthrow new Error('Bad use of emmet');\n\t}\n\n\tconst tagName = match[1] || 'div';\n\tlet result: T;\n\n\tif (namespace !== Namespace.HTML) {\n\t\tresult = document.createElementNS(namespace as string, tagName) as T;\n\t} else {\n\t\tresult = document.createElement(tagName) as unknown as T;\n\t}\n\n\tif (match[3]) {\n\t\tresult.id = match[3];\n\t}\n\tif (match[4]) {\n\t\tresult.className = match[4].replace(/\\./g, ' ').trim();\n\t}\n\n\tif (attrs) {\n\t\tObject.entries(attrs).forEach(([name, value]) => {\n\t\t\tif (typeof value === 'undefined') {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (/^on\\w+$/.test(name)) {\n\t\t\t\t(result)[name] = value;\n\t\t\t} else if (name === 'selected') {\n\t\t\t\tif (value) {\n\t\t\t\t\tresult.setAttribute(name, 'true');\n\t\t\t\t}\n\n\t\t\t} else {\n\t\t\t\tresult.setAttribute(name, value);\n\t\t\t}\n\t\t});\n\t}\n\n\tresult.append(...children);\n\n\treturn result as T;\n}\n\nexport function $(description: string, attrs?: { [key: string]: any }, ...children: Array): T {\n\treturn _$(Namespace.HTML, description, attrs, ...children);\n}\n\n$.SVG = function (description: string, attrs?: { [key: string]: any }, ...children: Array): T {\n\treturn _$(Namespace.SVG, description, attrs, ...children);\n};\n\nexport function join(nodes: Node[], separator: Node | string): Node[] {\n\tconst result: Node[] = [];\n\n\tnodes.forEach((node, index) => {\n\t\tif (index > 0) {\n\t\t\tif (separator instanceof Node) {\n\t\t\t\tresult.push(separator.cloneNode());\n\t\t\t} else {\n\t\t\t\tresult.push(document.createTextNode(separator));\n\t\t\t}\n\t\t}\n\n\t\tresult.push(node);\n\t});\n\n\treturn result;\n}\n\nexport function setVisibility(visible: boolean, ...elements: HTMLElement[]): void {\n\tif (visible) {\n\t\tshow(...elements);\n\t} else {\n\t\thide(...elements);\n\t}\n}\n\nexport function show(...elements: HTMLElement[]): void {\n\tfor (const element of elements) {\n\t\telement.style.display = '';\n\t\telement.removeAttribute('aria-hidden');\n\t}\n}\n\nexport function hide(...elements: HTMLElement[]): void {\n\tfor (const element of elements) {\n\t\telement.style.display = 'none';\n\t\telement.setAttribute('aria-hidden', 'true');\n\t}\n}\n\nfunction findParentWithAttribute(node: Node | null, attribute: string): HTMLElement | null {\n\twhile (node && node.nodeType === node.ELEMENT_NODE) {\n\t\tif (isHTMLElement(node) && node.hasAttribute(attribute)) {\n\t\t\treturn node;\n\t\t}\n\n\t\tnode = node.parentNode;\n\t}\n\n\treturn null;\n}\n\nexport function removeTabIndexAndUpdateFocus(node: HTMLElement): void {\n\tif (!node || !node.hasAttribute('tabIndex')) {\n\t\treturn;\n\t}\n\n\t// If we are the currently focused element and tabIndex is removed,\n\t// standard DOM behavior is to move focus to the element. We\n\t// typically never want that, rather put focus to the closest element\n\t// in the hierarchy of the parent DOM nodes.\n\tif (node.ownerDocument.activeElement === node) {\n\t\tconst parentFocusable = findParentWithAttribute(node.parentElement, 'tabIndex');\n\t\tparentFocusable?.focus();\n\t}\n\n\tnode.removeAttribute('tabindex');\n}\n\nexport function finalHandler(fn: (event: T) => any): (event: T) => any {\n\treturn e => {\n\t\te.preventDefault();\n\t\te.stopPropagation();\n\t\tfn(e);\n\t};\n}\n\nexport function domContentLoaded(targetWindow: Window): Promise {\n\treturn new Promise(resolve => {\n\t\tconst readyState = targetWindow.document.readyState;\n\t\tif (readyState === 'complete' || (targetWindow.document && targetWindow.document.body !== null)) {\n\t\t\tresolve(undefined);\n\t\t} else {\n\t\t\tconst listener = () => {\n\t\t\t\ttargetWindow.window.removeEventListener('DOMContentLoaded', listener, false);\n\t\t\t\tresolve();\n\t\t\t};\n\n\t\t\ttargetWindow.window.addEventListener('DOMContentLoaded', listener, false);\n\t\t}\n\t});\n}\n\n/**\n * Find a value usable for a dom node size such that the likelihood that it would be\n * displayed with constant screen pixels size is as high as possible.\n *\n * e.g. We would desire for the cursors to be 2px (CSS px) wide. Under a devicePixelRatio\n * of 1.25, the cursor will be 2.5 screen pixels wide. Depending on how the dom node aligns/\"snaps\"\n * with the screen pixels, it will sometimes be rendered with 2 screen pixels, and sometimes with 3 screen pixels.\n */\nexport function computeScreenAwareSize(window: Window, cssPx: number): number {\n\tconst screenPx = window.devicePixelRatio * cssPx;\n\treturn Math.max(1, Math.floor(screenPx)) / window.devicePixelRatio;\n}\n\n/**\n * Open safely a new window. This is the best way to do so, but you cannot tell\n * if the window was opened or if it was blocked by the browser's popup blocker.\n * If you want to tell if the browser blocked the new window, use {@link windowOpenWithSuccess}.\n *\n * See https://github.com/microsoft/monaco-editor/issues/601\n * To protect against malicious code in the linked site, particularly phishing attempts,\n * the window.opener should be set to null to prevent the linked site from having access\n * to change the location of the current page.\n * See https://mathiasbynens.github.io/rel-noopener/\n */\nexport function windowOpenNoOpener(url: string): void {\n\t// By using 'noopener' in the `windowFeatures` argument, the newly created window will\n\t// not be able to use `window.opener` to reach back to the current page.\n\t// See https://stackoverflow.com/a/46958731\n\t// See https://developer.mozilla.org/en-US/docs/Web/API/Window/open#noopener\n\t// However, this also doesn't allow us to realize if the browser blocked\n\t// the creation of the window.\n\tmainWindow.open(url, '_blank', 'noopener');\n}\n\n/**\n * Open a new window in a popup. This is the best way to do so, but you cannot tell\n * if the window was opened or if it was blocked by the browser's popup blocker.\n * If you want to tell if the browser blocked the new window, use {@link windowOpenWithSuccess}.\n *\n * Note: this does not set {@link window.opener} to null. This is to allow the opened popup to\n * be able to use {@link window.close} to close itself. Because of this, you should only use\n * this function on urls that you trust.\n *\n * In otherwords, you should almost always use {@link windowOpenNoOpener} instead of this function.\n */\nconst popupWidth = 780, popupHeight = 640;\nexport function windowOpenPopup(url: string): void {\n\tconst left = Math.floor(mainWindow.screenLeft + mainWindow.innerWidth / 2 - popupWidth / 2);\n\tconst top = Math.floor(mainWindow.screenTop + mainWindow.innerHeight / 2 - popupHeight / 2);\n\tmainWindow.open(\n\t\turl,\n\t\t'_blank',\n\t\t`width=${popupWidth},height=${popupHeight},top=${top},left=${left}`\n\t);\n}\n\n/**\n * Attempts to open a window and returns whether it succeeded. This technique is\n * not appropriate in certain contexts, like for example when the JS context is\n * executing inside a sandboxed iframe. If it is not necessary to know if the\n * browser blocked the new window, use {@link windowOpenNoOpener}.\n *\n * See https://github.com/microsoft/monaco-editor/issues/601\n * See https://github.com/microsoft/monaco-editor/issues/2474\n * See https://mathiasbynens.github.io/rel-noopener/\n *\n * @param url the url to open\n * @param noOpener whether or not to set the {@link window.opener} to null. You should leave the default\n * (true) unless you trust the url that is being opened.\n * @returns boolean indicating if the {@link window.open} call succeeded\n */\nexport function windowOpenWithSuccess(url: string, noOpener = true): boolean {\n\tconst newTab = mainWindow.open();\n\tif (newTab) {\n\t\tif (noOpener) {\n\t\t\t// see `windowOpenNoOpener` for details on why this is important\n\t\t\t(newTab as any).opener = null;\n\t\t}\n\t\tnewTab.location.href = url;\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nexport function animate(targetWindow: Window, fn: () => void): IDisposable {\n\tconst step = () => {\n\t\tfn();\n\t\tstepDisposable = scheduleAtNextAnimationFrame(targetWindow, step);\n\t};\n\n\tlet stepDisposable = scheduleAtNextAnimationFrame(targetWindow, step);\n\treturn toDisposable(() => stepDisposable.dispose());\n}\n\nexport function asCSSPropertyValue(value: string) {\n\treturn `'${value.replace(/'/g, '%27')}'`;\n}\n\nexport function asCssValueWithDefault(cssPropertyValue: string | undefined, dflt: string): string {\n\tif (cssPropertyValue !== undefined) {\n\t\tconst variableMatch = cssPropertyValue.match(/^\\s*var\\((.+)\\)$/);\n\t\tif (variableMatch) {\n\t\t\tconst varArguments = variableMatch[1].split(',', 2);\n\t\t\tif (varArguments.length === 2) {\n\t\t\t\tdflt = asCssValueWithDefault(varArguments[1].trim(), dflt);\n\t\t\t}\n\t\t\treturn `var(${varArguments[0]}, ${dflt})`;\n\t\t}\n\t\treturn cssPropertyValue;\n\t}\n\treturn dflt;\n}\n\nexport enum DetectedFullscreenMode {\n\n\t/**\n\t * The document is fullscreen, e.g. because an element\n\t * in the document requested to be fullscreen.\n\t */\n\tDOCUMENT = 1,\n\n\t/**\n\t * The browser is fullscreen, e.g. because the user enabled\n\t * native window fullscreen for it.\n\t */\n\tBROWSER\n}\n\nexport interface IDetectedFullscreen {\n\n\t/**\n\t * Figure out if the document is fullscreen or the browser.\n\t */\n\tmode: DetectedFullscreenMode;\n\n\t/**\n\t * Whether we know for sure that we are in fullscreen mode or\n\t * it is a guess.\n\t */\n\tguess: boolean;\n}\n\nexport function detectFullscreen(targetWindow: Window): IDetectedFullscreen | null {\n\n\t// Browser fullscreen: use DOM APIs to detect\n\tif (targetWindow.document.fullscreenElement || (targetWindow.document).webkitFullscreenElement || (targetWindow.document).webkitIsFullScreen) {\n\t\treturn { mode: DetectedFullscreenMode.DOCUMENT, guess: false };\n\t}\n\n\t// There is no standard way to figure out if the browser\n\t// is using native fullscreen. Via checking on screen\n\t// height and comparing that to window height, we can guess\n\t// it though.\n\n\tif (targetWindow.innerHeight === targetWindow.screen.height) {\n\t\t// if the height of the window matches the screen height, we can\n\t\t// safely assume that the browser is fullscreen because no browser\n\t\t// chrome is taking height away (e.g. like toolbars).\n\t\treturn { mode: DetectedFullscreenMode.BROWSER, guess: false };\n\t}\n\n\tif (platform.isMacintosh || platform.isLinux) {\n\t\t// macOS and Linux do not properly report `innerHeight`, only Windows does\n\t\tif (targetWindow.outerHeight === targetWindow.screen.height && targetWindow.outerWidth === targetWindow.screen.width) {\n\t\t\t// if the height of the browser matches the screen height, we can\n\t\t\t// only guess that we are in fullscreen. It is also possible that\n\t\t\t// the user has turned off taskbars in the OS and the browser is\n\t\t\t// simply able to span the entire size of the screen.\n\t\t\treturn { mode: DetectedFullscreenMode.BROWSER, guess: true };\n\t\t}\n\t}\n\n\t// Not in fullscreen\n\treturn null;\n}\n\n/**\n * Convert a Unicode string to a string in which each 16-bit unit occupies only one byte\n *\n * From https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/btoa\n */\nfunction toBinary(str: string): string {\n\tconst codeUnits = new Uint16Array(str.length);\n\tfor (let i = 0; i < codeUnits.length; i++) {\n\t\tcodeUnits[i] = str.charCodeAt(i);\n\t}\n\tlet binary = '';\n\tconst uint8array = new Uint8Array(codeUnits.buffer);\n\tfor (let i = 0; i < uint8array.length; i++) {\n\t\tbinary += String.fromCharCode(uint8array[i]);\n\t}\n\treturn binary;\n}\n\n/**\n * Version of the global `btoa` function that handles multi-byte characters instead\n * of throwing an exception.\n */\nexport function multibyteAwareBtoa(str: string): string {\n\treturn btoa(toBinary(str));\n}\n\ntype ModifierKey = 'alt' | 'ctrl' | 'shift' | 'meta';\n\nexport interface IModifierKeyStatus {\n\taltKey: boolean;\n\tshiftKey: boolean;\n\tctrlKey: boolean;\n\tmetaKey: boolean;\n\tlastKeyPressed?: ModifierKey;\n\tlastKeyReleased?: ModifierKey;\n\tevent?: KeyboardEvent;\n}\n\nexport class ModifierKeyEmitter extends event.Emitter {\n\n\tprivate readonly _subscriptions = new DisposableStore();\n\tprivate _keyStatus: IModifierKeyStatus;\n\tprivate static instance: ModifierKeyEmitter;\n\n\tprivate constructor() {\n\t\tsuper();\n\n\t\tthis._keyStatus = {\n\t\t\taltKey: false,\n\t\t\tshiftKey: false,\n\t\t\tctrlKey: false,\n\t\t\tmetaKey: false\n\t\t};\n\n\t\tthis._subscriptions.add(event.Event.runAndSubscribe(onDidRegisterWindow, ({ window, disposables }) => this.registerListeners(window, disposables), { window: mainWindow, disposables: this._subscriptions }));\n\t}\n\n\tprivate registerListeners(window: Window, disposables: DisposableStore): void {\n\t\tdisposables.add(addDisposableListener(window, 'keydown', e => {\n\t\t\tif (e.defaultPrevented) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst event = new StandardKeyboardEvent(e);\n\t\t\t// If Alt-key keydown event is repeated, ignore it #112347\n\t\t\t// Only known to be necessary for Alt-Key at the moment #115810\n\t\t\tif (event.keyCode === KeyCode.Alt && e.repeat) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (e.altKey && !this._keyStatus.altKey) {\n\t\t\t\tthis._keyStatus.lastKeyPressed = 'alt';\n\t\t\t} else if (e.ctrlKey && !this._keyStatus.ctrlKey) {\n\t\t\t\tthis._keyStatus.lastKeyPressed = 'ctrl';\n\t\t\t} else if (e.metaKey && !this._keyStatus.metaKey) {\n\t\t\t\tthis._keyStatus.lastKeyPressed = 'meta';\n\t\t\t} else if (e.shiftKey && !this._keyStatus.shiftKey) {\n\t\t\t\tthis._keyStatus.lastKeyPressed = 'shift';\n\t\t\t} else if (event.keyCode !== KeyCode.Alt) {\n\t\t\t\tthis._keyStatus.lastKeyPressed = undefined;\n\t\t\t} else {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthis._keyStatus.altKey = e.altKey;\n\t\t\tthis._keyStatus.ctrlKey = e.ctrlKey;\n\t\t\tthis._keyStatus.metaKey = e.metaKey;\n\t\t\tthis._keyStatus.shiftKey = e.shiftKey;\n\n\t\t\tif (this._keyStatus.lastKeyPressed) {\n\t\t\t\tthis._keyStatus.event = e;\n\t\t\t\tthis.fire(this._keyStatus);\n\t\t\t}\n\t\t}, true));\n\n\t\tdisposables.add(addDisposableListener(window, 'keyup', e => {\n\t\t\tif (e.defaultPrevented) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (!e.altKey && this._keyStatus.altKey) {\n\t\t\t\tthis._keyStatus.lastKeyReleased = 'alt';\n\t\t\t} else if (!e.ctrlKey && this._keyStatus.ctrlKey) {\n\t\t\t\tthis._keyStatus.lastKeyReleased = 'ctrl';\n\t\t\t} else if (!e.metaKey && this._keyStatus.metaKey) {\n\t\t\t\tthis._keyStatus.lastKeyReleased = 'meta';\n\t\t\t} else if (!e.shiftKey && this._keyStatus.shiftKey) {\n\t\t\t\tthis._keyStatus.lastKeyReleased = 'shift';\n\t\t\t} else {\n\t\t\t\tthis._keyStatus.lastKeyReleased = undefined;\n\t\t\t}\n\n\t\t\tif (this._keyStatus.lastKeyPressed !== this._keyStatus.lastKeyReleased) {\n\t\t\t\tthis._keyStatus.lastKeyPressed = undefined;\n\t\t\t}\n\n\t\t\tthis._keyStatus.altKey = e.altKey;\n\t\t\tthis._keyStatus.ctrlKey = e.ctrlKey;\n\t\t\tthis._keyStatus.metaKey = e.metaKey;\n\t\t\tthis._keyStatus.shiftKey = e.shiftKey;\n\n\t\t\tif (this._keyStatus.lastKeyReleased) {\n\t\t\t\tthis._keyStatus.event = e;\n\t\t\t\tthis.fire(this._keyStatus);\n\t\t\t}\n\t\t}, true));\n\n\t\tdisposables.add(addDisposableListener(window.document.body, 'mousedown', () => {\n\t\t\tthis._keyStatus.lastKeyPressed = undefined;\n\t\t}, true));\n\n\t\tdisposables.add(addDisposableListener(window.document.body, 'mouseup', () => {\n\t\t\tthis._keyStatus.lastKeyPressed = undefined;\n\t\t}, true));\n\n\t\tdisposables.add(addDisposableListener(window.document.body, 'mousemove', e => {\n\t\t\tif (e.buttons) {\n\t\t\t\tthis._keyStatus.lastKeyPressed = undefined;\n\t\t\t}\n\t\t}, true));\n\n\t\tdisposables.add(addDisposableListener(window, 'blur', () => {\n\t\t\tthis.resetKeyStatus();\n\t\t}));\n\t}\n\n\tget keyStatus(): IModifierKeyStatus {\n\t\treturn this._keyStatus;\n\t}\n\n\tget isModifierPressed(): boolean {\n\t\treturn this._keyStatus.altKey || this._keyStatus.ctrlKey || this._keyStatus.metaKey || this._keyStatus.shiftKey;\n\t}\n\n\t/**\n\t * Allows to explicitly reset the key status based on more knowledge (#109062)\n\t */\n\tresetKeyStatus(): void {\n\t\tthis.doResetKeyStatus();\n\t\tthis.fire(this._keyStatus);\n\t}\n\n\tprivate doResetKeyStatus(): void {\n\t\tthis._keyStatus = {\n\t\t\taltKey: false,\n\t\t\tshiftKey: false,\n\t\t\tctrlKey: false,\n\t\t\tmetaKey: false\n\t\t};\n\t}\n\n\tstatic getInstance() {\n\t\tif (!ModifierKeyEmitter.instance) {\n\t\t\tModifierKeyEmitter.instance = new ModifierKeyEmitter();\n\t\t}\n\n\t\treturn ModifierKeyEmitter.instance;\n\t}\n\n\toverride dispose() {\n\t\tsuper.dispose();\n\t\tthis._subscriptions.dispose();\n\t}\n}\n\nexport function getCookieValue(name: string): string | undefined {\n\tconst match = document.cookie.match('(^|[^;]+)\\\\s*' + name + '\\\\s*=\\\\s*([^;]+)'); // See https://stackoverflow.com/a/25490531\n\n\treturn match ? match.pop() : undefined;\n}\n\nexport interface IDragAndDropObserverCallbacks {\n\treadonly onDragEnter?: (e: DragEvent) => void;\n\treadonly onDragLeave?: (e: DragEvent) => void;\n\treadonly onDrop?: (e: DragEvent) => void;\n\treadonly onDragEnd?: (e: DragEvent) => void;\n\treadonly onDragStart?: (e: DragEvent) => void;\n\treadonly onDrag?: (e: DragEvent) => void;\n\treadonly onDragOver?: (e: DragEvent, dragDuration: number) => void;\n}\n\nexport class DragAndDropObserver extends Disposable {\n\n\t// A helper to fix issues with repeated DRAG_ENTER / DRAG_LEAVE\n\t// calls see https://github.com/microsoft/vscode/issues/14470\n\t// when the element has child elements where the events are fired\n\t// repeadedly.\n\tprivate counter: number = 0;\n\n\t// Allows to measure the duration of the drag operation.\n\tprivate dragStartTime = 0;\n\n\tconstructor(private readonly element: HTMLElement, private readonly callbacks: IDragAndDropObserverCallbacks) {\n\t\tsuper();\n\n\t\tthis.registerListeners();\n\t}\n\n\tprivate registerListeners(): void {\n\t\tif (this.callbacks.onDragStart) {\n\t\t\tthis._register(addDisposableListener(this.element, EventType.DRAG_START, (e: DragEvent) => {\n\t\t\t\tthis.callbacks.onDragStart?.(e);\n\t\t\t}));\n\t\t}\n\n\t\tif (this.callbacks.onDrag) {\n\t\t\tthis._register(addDisposableListener(this.element, EventType.DRAG, (e: DragEvent) => {\n\t\t\t\tthis.callbacks.onDrag?.(e);\n\t\t\t}));\n\t\t}\n\n\t\tthis._register(addDisposableListener(this.element, EventType.DRAG_ENTER, (e: DragEvent) => {\n\t\t\tthis.counter++;\n\t\t\tthis.dragStartTime = e.timeStamp;\n\n\t\t\tthis.callbacks.onDragEnter?.(e);\n\t\t}));\n\n\t\tthis._register(addDisposableListener(this.element, EventType.DRAG_OVER, (e: DragEvent) => {\n\t\t\te.preventDefault(); // needed so that the drop event fires (https://stackoverflow.com/questions/21339924/drop-event-not-firing-in-chrome)\n\n\t\t\tthis.callbacks.onDragOver?.(e, e.timeStamp - this.dragStartTime);\n\t\t}));\n\n\t\tthis._register(addDisposableListener(this.element, EventType.DRAG_LEAVE, (e: DragEvent) => {\n\t\t\tthis.counter--;\n\n\t\t\tif (this.counter === 0) {\n\t\t\t\tthis.dragStartTime = 0;\n\n\t\t\t\tthis.callbacks.onDragLeave?.(e);\n\t\t\t}\n\t\t}));\n\n\t\tthis._register(addDisposableListener(this.element, EventType.DRAG_END, (e: DragEvent) => {\n\t\t\tthis.counter = 0;\n\t\t\tthis.dragStartTime = 0;\n\n\t\t\tthis.callbacks.onDragEnd?.(e);\n\t\t}));\n\n\t\tthis._register(addDisposableListener(this.element, EventType.DROP, (e: DragEvent) => {\n\t\t\tthis.counter = 0;\n\t\t\tthis.dragStartTime = 0;\n\n\t\t\tthis.callbacks.onDrop?.(e);\n\t\t}));\n\t}\n}\n\ntype HTMLElementAttributeKeys = Partial<{ [K in keyof T]: T[K] extends Function ? never : T[K] extends object ? HTMLElementAttributeKeys : T[K] }>;\ntype ElementAttributes = HTMLElementAttributeKeys & Record;\ntype RemoveHTMLElement = T extends HTMLElement ? never : T;\ntype UnionToIntersection = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;\ntype ArrayToObj = UnionToIntersection>;\ntype HHTMLElementTagNameMap = HTMLElementTagNameMap & { '': HTMLDivElement };\n\ntype TagToElement = T extends `${infer TStart}#${string}`\n\t? TStart extends keyof HHTMLElementTagNameMap\n\t? HHTMLElementTagNameMap[TStart]\n\t: HTMLElement\n\t: T extends `${infer TStart}.${string}`\n\t? TStart extends keyof HHTMLElementTagNameMap\n\t? HHTMLElementTagNameMap[TStart]\n\t: HTMLElement\n\t: T extends keyof HTMLElementTagNameMap\n\t? HTMLElementTagNameMap[T]\n\t: HTMLElement;\n\ntype TagToElementAndId = TTag extends `${infer TTag}@${infer TId}`\n\t? { element: TagToElement; id: TId }\n\t: { element: TagToElement; id: 'root' };\n\ntype TagToRecord = TagToElementAndId extends { element: infer TElement; id: infer TId }\n\t? Record<(TId extends string ? TId : never) | 'root', TElement>\n\t: never;\n\ntype Child = HTMLElement | string | Record;\n\nconst H_REGEX = /(?[\\w\\-]+)?(?:#(?[\\w\\-]+))?(?(?:\\.(?:[\\w\\-]+))*)(?:@(?(?:[\\w\\_])+))?/;\n\n/**\n * A helper function to create nested dom nodes.\n *\n *\n * ```ts\n * const elements = h('div.code-view', [\n * \th('div.title@title'),\n * \th('div.container', [\n * \t\th('div.gutter@gutterDiv'),\n * \t\th('div@editor'),\n * \t]),\n * ]);\n * const editor = createEditor(elements.editor);\n * ```\n*/\nexport function h\n\t(tag: TTag):\n\tTagToRecord extends infer Y ? { [TKey in keyof Y]: Y[TKey] } : never;\n\nexport function h\n\t(tag: TTag, children: [...T]):\n\t(ArrayToObj & TagToRecord) extends infer Y ? { [TKey in keyof Y]: Y[TKey] } : never;\n\nexport function h\n\t(tag: TTag, attributes: Partial>>):\n\tTagToRecord extends infer Y ? { [TKey in keyof Y]: Y[TKey] } : never;\n\nexport function h\n\t(tag: TTag, attributes: Partial>>, children: [...T]):\n\t(ArrayToObj & TagToRecord) extends infer Y ? { [TKey in keyof Y]: Y[TKey] } : never;\n\nexport function h(tag: string, ...args: [] | [attributes: { $: string } & Partial> | Record, children?: any[]] | [children: any[]]): Record {\n\tlet attributes: { $?: string } & Partial>;\n\tlet children: (Record | HTMLElement)[] | undefined;\n\n\tif (Array.isArray(args[0])) {\n\t\tattributes = {};\n\t\tchildren = args[0];\n\t} else {\n\t\tattributes = args[0] as any || {};\n\t\tchildren = args[1];\n\t}\n\n\tconst match = H_REGEX.exec(tag);\n\n\tif (!match || !match.groups) {\n\t\tthrow new Error('Bad use of h');\n\t}\n\n\tconst tagName = match.groups['tag'] || 'div';\n\tconst el = document.createElement(tagName);\n\n\tif (match.groups['id']) {\n\t\tel.id = match.groups['id'];\n\t}\n\n\tconst classNames = [];\n\tif (match.groups['class']) {\n\t\tfor (const className of match.groups['class'].split('.')) {\n\t\t\tif (className !== '') {\n\t\t\t\tclassNames.push(className);\n\t\t\t}\n\t\t}\n\t}\n\tif (attributes.className !== undefined) {\n\t\tfor (const className of attributes.className.split('.')) {\n\t\t\tif (className !== '') {\n\t\t\t\tclassNames.push(className);\n\t\t\t}\n\t\t}\n\t}\n\tif (classNames.length > 0) {\n\t\tel.className = classNames.join(' ');\n\t}\n\n\tconst result: Record = {};\n\n\tif (match.groups['name']) {\n\t\tresult[match.groups['name']] = el;\n\t}\n\n\tif (children) {\n\t\tfor (const c of children) {\n\t\t\tif (isHTMLElement(c)) {\n\t\t\t\tel.appendChild(c);\n\t\t\t} else if (typeof c === 'string') {\n\t\t\t\tel.append(c);\n\t\t\t} else if ('root' in c) {\n\t\t\t\tObject.assign(result, c);\n\t\t\t\tel.appendChild(c.root);\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (const [key, value] of Object.entries(attributes)) {\n\t\tif (key === 'className') {\n\t\t\tcontinue;\n\t\t} else if (key === 'style') {\n\t\t\tfor (const [cssKey, cssValue] of Object.entries(value)) {\n\t\t\t\tel.style.setProperty(\n\t\t\t\t\tcamelCaseToHyphenCase(cssKey),\n\t\t\t\t\ttypeof cssValue === 'number' ? cssValue + 'px' : '' + cssValue\n\t\t\t\t);\n\t\t\t}\n\t\t} else if (key === 'tabIndex') {\n\t\t\tel.tabIndex = value;\n\t\t} else {\n\t\t\tel.setAttribute(camelCaseToHyphenCase(key), value.toString());\n\t\t}\n\t}\n\n\tresult['root'] = el;\n\n\treturn result;\n}\n\nexport function svgElem\n\t(tag: TTag):\n\tTagToRecord extends infer Y ? { [TKey in keyof Y]: Y[TKey] } : never;\n\nexport function svgElem\n\t(tag: TTag, children: [...T]):\n\t(ArrayToObj & TagToRecord) extends infer Y ? { [TKey in keyof Y]: Y[TKey] } : never;\n\nexport function svgElem\n\t(tag: TTag, attributes: Partial>>):\n\tTagToRecord extends infer Y ? { [TKey in keyof Y]: Y[TKey] } : never;\n\nexport function svgElem\n\t(tag: TTag, attributes: Partial>>, children: [...T]):\n\t(ArrayToObj & TagToRecord) extends infer Y ? { [TKey in keyof Y]: Y[TKey] } : never;\n\nexport function svgElem(tag: string, ...args: [] | [attributes: { $: string } & Partial> | Record, children?: any[]] | [children: any[]]): Record {\n\tlet attributes: { $?: string } & Partial>;\n\tlet children: (Record | HTMLElement)[] | undefined;\n\n\tif (Array.isArray(args[0])) {\n\t\tattributes = {};\n\t\tchildren = args[0];\n\t} else {\n\t\tattributes = args[0] as any || {};\n\t\tchildren = args[1];\n\t}\n\n\tconst match = H_REGEX.exec(tag);\n\n\tif (!match || !match.groups) {\n\t\tthrow new Error('Bad use of h');\n\t}\n\n\tconst tagName = match.groups['tag'] || 'div';\n\tconst el = document.createElementNS('http://www.w3.org/2000/svg', tagName) as any as HTMLElement;\n\n\tif (match.groups['id']) {\n\t\tel.id = match.groups['id'];\n\t}\n\n\tconst classNames = [];\n\tif (match.groups['class']) {\n\t\tfor (const className of match.groups['class'].split('.')) {\n\t\t\tif (className !== '') {\n\t\t\t\tclassNames.push(className);\n\t\t\t}\n\t\t}\n\t}\n\tif (attributes.className !== undefined) {\n\t\tfor (const className of attributes.className.split('.')) {\n\t\t\tif (className !== '') {\n\t\t\t\tclassNames.push(className);\n\t\t\t}\n\t\t}\n\t}\n\tif (classNames.length > 0) {\n\t\tel.className = classNames.join(' ');\n\t}\n\n\tconst result: Record = {};\n\n\tif (match.groups['name']) {\n\t\tresult[match.groups['name']] = el;\n\t}\n\n\tif (children) {\n\t\tfor (const c of children) {\n\t\t\tif (isHTMLElement(c)) {\n\t\t\t\tel.appendChild(c);\n\t\t\t} else if (typeof c === 'string') {\n\t\t\t\tel.append(c);\n\t\t\t} else if ('root' in c) {\n\t\t\t\tObject.assign(result, c);\n\t\t\t\tel.appendChild(c.root);\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (const [key, value] of Object.entries(attributes)) {\n\t\tif (key === 'className') {\n\t\t\tcontinue;\n\t\t} else if (key === 'style') {\n\t\t\tfor (const [cssKey, cssValue] of Object.entries(value)) {\n\t\t\t\tel.style.setProperty(\n\t\t\t\t\tcamelCaseToHyphenCase(cssKey),\n\t\t\t\t\ttypeof cssValue === 'number' ? cssValue + 'px' : '' + cssValue\n\t\t\t\t);\n\t\t\t}\n\t\t} else if (key === 'tabIndex') {\n\t\t\tel.tabIndex = value;\n\t\t} else {\n\t\t\tel.setAttribute(camelCaseToHyphenCase(key), value.toString());\n\t\t}\n\t}\n\n\tresult['root'] = el;\n\n\treturn result;\n}\n\nfunction camelCaseToHyphenCase(str: string) {\n\treturn str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();\n}\n\nexport function copyAttributes(from: Element, to: Element, filter?: string[]): void {\n\tfor (const { name, value } of from.attributes) {\n\t\tif (!filter || filter.includes(name)) {\n\t\t\tto.setAttribute(name, value);\n\t\t}\n\t}\n}\n\nfunction copyAttribute(from: Element, to: Element, name: string): void {\n\tconst value = from.getAttribute(name);\n\tif (value) {\n\t\tto.setAttribute(name, value);\n\t} else {\n\t\tto.removeAttribute(name);\n\t}\n}\n\nexport function trackAttributes(from: Element, to: Element, filter?: string[]): IDisposable {\n\tcopyAttributes(from, to, filter);\n\n\tconst disposables = new DisposableStore();\n\n\tdisposables.add(sharedMutationObserver.observe(from, disposables, { attributes: true, attributeFilter: filter })(mutations => {\n\t\tfor (const mutation of mutations) {\n\t\t\tif (mutation.type === 'attributes' && mutation.attributeName) {\n\t\t\t\tcopyAttribute(from, to, mutation.attributeName);\n\t\t\t}\n\t\t}\n\t}));\n\n\treturn disposables;\n}\n\n/**\n * Helper for calculating the \"safe triangle\" occluded by hovers to avoid early dismissal.\n * @see https://www.smashingmagazine.com/2023/08/better-context-menus-safe-triangles/ for example\n */\nexport class SafeTriangle {\n\t// 4 triangles, 2 points (x, y) stored for each\n\tprivate triangles: number[] = [];\n\n\tconstructor(\n\t\tprivate readonly originX: number,\n\t\tprivate readonly originY: number,\n\t\ttarget: HTMLElement\n\t) {\n\t\tconst { top, left, right, bottom } = target.getBoundingClientRect();\n\t\tconst t = this.triangles;\n\t\tlet i = 0;\n\n\t\tt[i++] = left;\n\t\tt[i++] = top;\n\t\tt[i++] = right;\n\t\tt[i++] = top;\n\n\t\tt[i++] = left;\n\t\tt[i++] = top;\n\t\tt[i++] = left;\n\t\tt[i++] = bottom;\n\n\t\tt[i++] = right;\n\t\tt[i++] = top;\n\t\tt[i++] = right;\n\t\tt[i++] = bottom;\n\n\t\tt[i++] = left;\n\t\tt[i++] = bottom;\n\t\tt[i++] = right;\n\t\tt[i++] = bottom;\n\t}\n\n\tpublic contains(x: number, y: number) {\n\t\tconst { triangles, originX, originY } = this;\n\t\tfor (let i = 0; i < 4; i++) {\n\t\t\tif (isPointWithinTriangle(x, y, originX, originY, triangles[2 * i], triangles[2 * i + 1], triangles[2 * i + 2], triangles[2 * i + 3])) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n}\n", "/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\nexport class FastDomNode {\n\n\tprivate _maxWidth: string = '';\n\tprivate _width: string = '';\n\tprivate _height: string = '';\n\tprivate _top: string = '';\n\tprivate _left: string = '';\n\tprivate _bottom: string = '';\n\tprivate _right: string = '';\n\tprivate _paddingTop: string = '';\n\tprivate _paddingLeft: string = '';\n\tprivate _paddingBottom: string = '';\n\tprivate _paddingRight: string = '';\n\tprivate _fontFamily: string = '';\n\tprivate _fontWeight: string = '';\n\tprivate _fontSize: string = '';\n\tprivate _fontStyle: string = '';\n\tprivate _fontFeatureSettings: string = '';\n\tprivate _fontVariationSettings: string = '';\n\tprivate _textDecoration: string = '';\n\tprivate _lineHeight: string = '';\n\tprivate _letterSpacing: string = '';\n\tprivate _className: string = '';\n\tprivate _display: string = '';\n\tprivate _position: string = '';\n\tprivate _visibility: string = '';\n\tprivate _color: string = '';\n\tprivate _backgroundColor: string = '';\n\tprivate _layerHint: boolean = false;\n\tprivate _contain: 'none' | 'strict' | 'content' | 'size' | 'layout' | 'style' | 'paint' = 'none';\n\tprivate _boxShadow: string = '';\n\n\tconstructor(\n\t\tpublic readonly domNode: T\n\t) { }\n\n\tpublic setMaxWidth(_maxWidth: number | string): void {\n\t\tconst maxWidth = numberAsPixels(_maxWidth);\n\t\tif (this._maxWidth === maxWidth) {\n\t\t\treturn;\n\t\t}\n\t\tthis._maxWidth = maxWidth;\n\t\tthis.domNode.style.maxWidth = this._maxWidth;\n\t}\n\n\tpublic setWidth(_width: number | string): void {\n\t\tconst width = numberAsPixels(_width);\n\t\tif (this._width === width) {\n\t\t\treturn;\n\t\t}\n\t\tthis._width = width;\n\t\tthis.domNode.style.width = this._width;\n\t}\n\n\tpublic setHeight(_height: number | string): void {\n\t\tconst height = numberAsPixels(_height);\n\t\tif (this._height === height) {\n\t\t\treturn;\n\t\t}\n\t\tthis._height = height;\n\t\tthis.domNode.style.height = this._height;\n\t}\n\n\tpublic setTop(_top: number | string): void {\n\t\tconst top = numberAsPixels(_top);\n\t\tif (this._top === top) {\n\t\t\treturn;\n\t\t}\n\t\tthis._top = top;\n\t\tthis.domNode.style.top = this._top;\n\t}\n\n\tpublic setLeft(_left: number | string): void {\n\t\tconst left = numberAsPixels(_left);\n\t\tif (this._left === left) {\n\t\t\treturn;\n\t\t}\n\t\tthis._left = left;\n\t\tthis.domNode.style.left = this._left;\n\t}\n\n\tpublic setBottom(_bottom: number | string): void {\n\t\tconst bottom = numberAsPixels(_bottom);\n\t\tif (this._bottom === bottom) {\n\t\t\treturn;\n\t\t}\n\t\tthis._bottom = bottom;\n\t\tthis.domNode.style.bottom = this._bottom;\n\t}\n\n\tpublic setRight(_right: number | string): void {\n\t\tconst right = numberAsPixels(_right);\n\t\tif (this._right === right) {\n\t\t\treturn;\n\t\t}\n\t\tthis._right = right;\n\t\tthis.domNode.style.right = this._right;\n\t}\n\n\tpublic setPaddingTop(_paddingTop: number | string): void {\n\t\tconst paddingTop = numberAsPixels(_paddingTop);\n\t\tif (this._paddingTop === paddingTop) {\n\t\t\treturn;\n\t\t}\n\t\tthis._paddingTop = paddingTop;\n\t\tthis.domNode.style.paddingTop = this._paddingTop;\n\t}\n\n\tpublic setPaddingLeft(_paddingLeft: number | string): void {\n\t\tconst paddingLeft = numberAsPixels(_paddingLeft);\n\t\tif (this._paddingLeft === paddingLeft) {\n\t\t\treturn;\n\t\t}\n\t\tthis._paddingLeft = paddingLeft;\n\t\tthis.domNode.style.paddingLeft = this._paddingLeft;\n\t}\n\n\tpublic setPaddingBottom(_paddingBottom: number | string): void {\n\t\tconst paddingBottom = numberAsPixels(_paddingBottom);\n\t\tif (this._paddingBottom === paddingBottom) {\n\t\t\treturn;\n\t\t}\n\t\tthis._paddingBottom = paddingBottom;\n\t\tthis.domNode.style.paddingBottom = this._paddingBottom;\n\t}\n\n\tpublic setPaddingRight(_paddingRight: number | string): void {\n\t\tconst paddingRight = numberAsPixels(_paddingRight);\n\t\tif (this._paddingRight === paddingRight) {\n\t\t\treturn;\n\t\t}\n\t\tthis._paddingRight = paddingRight;\n\t\tthis.domNode.style.paddingRight = this._paddingRight;\n\t}\n\n\tpublic setFontFamily(fontFamily: string): void {\n\t\tif (this._fontFamily === fontFamily) {\n\t\t\treturn;\n\t\t}\n\t\tthis._fontFamily = fontFamily;\n\t\tthis.domNode.style.fontFamily = this._fontFamily;\n\t}\n\n\tpublic setFontWeight(fontWeight: string): void {\n\t\tif (this._fontWeight === fontWeight) {\n\t\t\treturn;\n\t\t}\n\t\tthis._fontWeight = fontWeight;\n\t\tthis.domNode.style.fontWeight = this._fontWeight;\n\t}\n\n\tpublic setFontSize(_fontSize: number | string): void {\n\t\tconst fontSize = numberAsPixels(_fontSize);\n\t\tif (this._fontSize === fontSize) {\n\t\t\treturn;\n\t\t}\n\t\tthis._fontSize = fontSize;\n\t\tthis.domNode.style.fontSize = this._fontSize;\n\t}\n\n\tpublic setFontStyle(fontStyle: string): void {\n\t\tif (this._fontStyle === fontStyle) {\n\t\t\treturn;\n\t\t}\n\t\tthis._fontStyle = fontStyle;\n\t\tthis.domNode.style.fontStyle = this._fontStyle;\n\t}\n\n\tpublic setFontFeatureSettings(fontFeatureSettings: string): void {\n\t\tif (this._fontFeatureSettings === fontFeatureSettings) {\n\t\t\treturn;\n\t\t}\n\t\tthis._fontFeatureSettings = fontFeatureSettings;\n\t\tthis.domNode.style.fontFeatureSettings = this._fontFeatureSettings;\n\t}\n\n\tpublic setFontVariationSettings(fontVariationSettings: string): void {\n\t\tif (this._fontVariationSettings === fontVariationSettings) {\n\t\t\treturn;\n\t\t}\n\t\tthis._fontVariationSettings = fontVariationSettings;\n\t\tthis.domNode.style.fontVariationSettings = this._fontVariationSettings;\n\t}\n\n\tpublic setTextDecoration(textDecoration: string): void {\n\t\tif (this._textDecoration === textDecoration) {\n\t\t\treturn;\n\t\t}\n\t\tthis._textDecoration = textDecoration;\n\t\tthis.domNode.style.textDecoration = this._textDecoration;\n\t}\n\n\tpublic setLineHeight(_lineHeight: number | string): void {\n\t\tconst lineHeight = numberAsPixels(_lineHeight);\n\t\tif (this._lineHeight === lineHeight) {\n\t\t\treturn;\n\t\t}\n\t\tthis._lineHeight = lineHeight;\n\t\tthis.domNode.style.lineHeight = this._lineHeight;\n\t}\n\n\tpublic setLetterSpacing(_letterSpacing: number | string): void {\n\t\tconst letterSpacing = numberAsPixels(_letterSpacing);\n\t\tif (this._letterSpacing === letterSpacing) {\n\t\t\treturn;\n\t\t}\n\t\tthis._letterSpacing = letterSpacing;\n\t\tthis.domNode.style.letterSpacing = this._letterSpacing;\n\t}\n\n\tpublic setClassName(className: string): void {\n\t\tif (this._className === className) {\n\t\t\treturn;\n\t\t}\n\t\tthis._className = className;\n\t\tthis.domNode.className = this._className;\n\t}\n\n\tpublic toggleClassName(className: string, shouldHaveIt?: boolean): void {\n\t\tthis.domNode.classList.toggle(className, shouldHaveIt);\n\t\tthis._className = this.domNode.className;\n\t}\n\n\tpublic setDisplay(display: string): void {\n\t\tif (this._display === display) {\n\t\t\treturn;\n\t\t}\n\t\tthis._display = display;\n\t\tthis.domNode.style.display = this._display;\n\t}\n\n\tpublic setPosition(position: string): void {\n\t\tif (this._position === position) {\n\t\t\treturn;\n\t\t}\n\t\tthis._position = position;\n\t\tthis.domNode.style.position = this._position;\n\t}\n\n\tpublic setVisibility(visibility: string): void {\n\t\tif (this._visibility === visibility) {\n\t\t\treturn;\n\t\t}\n\t\tthis._visibility = visibility;\n\t\tthis.domNode.style.visibility = this._visibility;\n\t}\n\n\tpublic setColor(color: string): void {\n\t\tif (this._color === color) {\n\t\t\treturn;\n\t\t}\n\t\tthis._color = color;\n\t\tthis.domNode.style.color = this._color;\n\t}\n\n\tpublic setBackgroundColor(backgroundColor: string): void {\n\t\tif (this._backgroundColor === backgroundColor) {\n\t\t\treturn;\n\t\t}\n\t\tthis._backgroundColor = backgroundColor;\n\t\tthis.domNode.style.backgroundColor = this._backgroundColor;\n\t}\n\n\tpublic setLayerHinting(layerHint: boolean): void {\n\t\tif (this._layerHint === layerHint) {\n\t\t\treturn;\n\t\t}\n\t\tthis._layerHint = layerHint;\n\t\tthis.domNode.style.transform = this._layerHint ? 'translate3d(0px, 0px, 0px)' : '';\n\t}\n\n\tpublic setBoxShadow(boxShadow: string): void {\n\t\tif (this._boxShadow === boxShadow) {\n\t\t\treturn;\n\t\t}\n\t\tthis._boxShadow = boxShadow;\n\t\tthis.domNode.style.boxShadow = boxShadow;\n\t}\n\n\tpublic setContain(contain: 'none' | 'strict' | 'content' | 'size' | 'layout' | 'style' | 'paint'): void {\n\t\tif (this._contain === contain) {\n\t\t\treturn;\n\t\t}\n\t\tthis._contain = contain;\n\t\t(this.domNode.style).contain = this._contain;\n\t}\n\n\tpublic setAttribute(name: string, value: string): void {\n\t\tthis.domNode.setAttribute(name, value);\n\t}\n\n\tpublic removeAttribute(name: string): void {\n\t\tthis.domNode.removeAttribute(name);\n\t}\n\n\tpublic appendChild(child: FastDomNode): void {\n\t\tthis.domNode.appendChild(child.domNode);\n\t}\n\n\tpublic removeChild(child: FastDomNode): void {\n\t\tthis.domNode.removeChild(child.domNode);\n\t}\n}\n\nfunction numberAsPixels(value: number | string): string {\n\treturn (typeof value === 'number' ? `${value}px` : value);\n}\n\nexport function createFastDomNode(domNode: T): FastDomNode {\n\treturn new FastDomNode(domNode);\n}\n", "/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\nimport * as dom from 'vs/base/browser/dom';\nimport { DisposableStore, IDisposable, toDisposable } from 'vs/base/common/lifecycle';\n\nexport interface IPointerMoveCallback {\n\t(event: PointerEvent): void;\n}\n\nexport interface IOnStopCallback {\n\t(browserEvent?: PointerEvent | KeyboardEvent): void;\n}\n\nexport class GlobalPointerMoveMonitor implements IDisposable {\n\n\tprivate readonly _hooks = new DisposableStore();\n\tprivate _pointerMoveCallback: IPointerMoveCallback | null = null;\n\tprivate _onStopCallback: IOnStopCallback | null = null;\n\n\tpublic dispose(): void {\n\t\tthis.stopMonitoring(false);\n\t\tthis._hooks.dispose();\n\t}\n\n\tpublic stopMonitoring(invokeStopCallback: boolean, browserEvent?: PointerEvent | KeyboardEvent): void {\n\t\tif (!this.isMonitoring()) {\n\t\t\t// Not monitoring\n\t\t\treturn;\n\t\t}\n\n\t\t// Unhook\n\t\tthis._hooks.clear();\n\t\tthis._pointerMoveCallback = null;\n\t\tconst onStopCallback = this._onStopCallback;\n\t\tthis._onStopCallback = null;\n\n\t\tif (invokeStopCallback && onStopCallback) {\n\t\t\tonStopCallback(browserEvent);\n\t\t}\n\t}\n\n\tpublic isMonitoring(): boolean {\n\t\treturn !!this._pointerMoveCallback;\n\t}\n\n\tpublic startMonitoring(\n\t\tinitialElement: Element,\n\t\tpointerId: number,\n\t\tinitialButtons: number,\n\t\tpointerMoveCallback: IPointerMoveCallback,\n\t\tonStopCallback: IOnStopCallback\n\t): void {\n\t\tif (this.isMonitoring()) {\n\t\t\tthis.stopMonitoring(false);\n\t\t}\n\t\tthis._pointerMoveCallback = pointerMoveCallback;\n\t\tthis._onStopCallback = onStopCallback;\n\n\t\tlet eventSource: Element | Window = initialElement;\n\n\t\ttry {\n\t\t\tinitialElement.setPointerCapture(pointerId);\n\t\t\tthis._hooks.add(toDisposable(() => {\n\t\t\t\ttry {\n\t\t\t\t\tinitialElement.releasePointerCapture(pointerId);\n\t\t\t\t} catch (err) {\n\t\t\t\t\t// See https://github.com/microsoft/vscode/issues/161731\n\t\t\t\t\t//\n\t\t\t\t\t// `releasePointerCapture` sometimes fails when being invoked with the exception:\n\t\t\t\t\t// DOMException: Failed to execute 'releasePointerCapture' on 'Element':\n\t\t\t\t\t// No active pointer with the given id is found.\n\t\t\t\t\t//\n\t\t\t\t\t// There's no need to do anything in case of failure\n\t\t\t\t}\n\t\t\t}));\n\t\t} catch (err) {\n\t\t\t// See https://github.com/microsoft/vscode/issues/144584\n\t\t\t// See https://github.com/microsoft/vscode/issues/146947\n\t\t\t// `setPointerCapture` sometimes fails when being invoked\n\t\t\t// from a `mousedown` listener on macOS and Windows\n\t\t\t// and it always fails on Linux with the exception:\n\t\t\t// DOMException: Failed to execute 'setPointerCapture' on 'Element':\n\t\t\t// No active pointer with the given id is found.\n\t\t\t// In case of failure, we bind the listeners on the window\n\t\t\teventSource = dom.getWindow(initialElement);\n\t\t}\n\n\t\tthis._hooks.add(dom.addDisposableListener(\n\t\t\teventSource,\n\t\t\tdom.EventType.POINTER_MOVE,\n\t\t\t(e) => {\n\t\t\t\tif (e.buttons !== initialButtons) {\n\t\t\t\t\t// Buttons state has changed in the meantime\n\t\t\t\t\tthis.stopMonitoring(true);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\te.preventDefault();\n\t\t\t\tthis._pointerMoveCallback!(e);\n\t\t\t}\n\t\t));\n\n\t\tthis._hooks.add(dom.addDisposableListener(\n\t\t\teventSource,\n\t\t\tdom.EventType.POINTER_UP,\n\t\t\t(e: PointerEvent) => this.stopMonitoring(true)\n\t\t));\n\t}\n}\n", "/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\nfunction createDecorator(mapFn: (fn: Function, key: string) => Function): Function {\n\treturn (target: any, key: string, descriptor: any) => {\n\t\tlet fnKey: string | null = null;\n\t\tlet fn: Function | null = null;\n\n\t\tif (typeof descriptor.value === 'function') {\n\t\t\tfnKey = 'value';\n\t\t\tfn = descriptor.value;\n\t\t} else if (typeof descriptor.get === 'function') {\n\t\t\tfnKey = 'get';\n\t\t\tfn = descriptor.get;\n\t\t}\n\n\t\tif (!fn) {\n\t\t\tthrow new Error('not supported');\n\t\t}\n\n\t\tdescriptor[fnKey!] = mapFn(fn, key);\n\t};\n}\n\nexport function memoize(_target: any, key: string, descriptor: any) {\n\tlet fnKey: string | null = null;\n\tlet fn: Function | null = null;\n\n\tif (typeof descriptor.value === 'function') {\n\t\tfnKey = 'value';\n\t\tfn = descriptor.value;\n\n\t\tif (fn!.length !== 0) {\n\t\t\tconsole.warn('Memoize should only be used in functions with zero parameters');\n\t\t}\n\t} else if (typeof descriptor.get === 'function') {\n\t\tfnKey = 'get';\n\t\tfn = descriptor.get;\n\t}\n\n\tif (!fn) {\n\t\tthrow new Error('not supported');\n\t}\n\n\tconst memoizeKey = `$memoize$${key}`;\n\tdescriptor[fnKey!] = function (...args: any[]) {\n\t\tif (!this.hasOwnProperty(memoizeKey)) {\n\t\t\tObject.defineProperty(this, memoizeKey, {\n\t\t\t\tconfigurable: false,\n\t\t\t\tenumerable: false,\n\t\t\t\twritable: false,\n\t\t\t\tvalue: fn.apply(this, args)\n\t\t\t});\n\t\t}\n\n\t\treturn this[memoizeKey];\n\t};\n}\n\nexport interface IDebounceReducer {\n\t(previousValue: T, ...args: any[]): T;\n}\n\nexport function debounce(delay: number, reducer?: IDebounceReducer, initialValueProvider?: () => T): Function {\n\treturn createDecorator((fn, key) => {\n\t\tconst timerKey = `$debounce$${key}`;\n\t\tconst resultKey = `$debounce$result$${key}`;\n\n\t\treturn function (this: any, ...args: any[]) {\n\t\t\tif (!this[resultKey]) {\n\t\t\t\tthis[resultKey] = initialValueProvider ? initialValueProvider() : undefined;\n\t\t\t}\n\n\t\t\tclearTimeout(this[timerKey]);\n\n\t\t\tif (reducer) {\n\t\t\t\tthis[resultKey] = reducer(this[resultKey], ...args);\n\t\t\t\targs = [this[resultKey]];\n\t\t\t}\n\n\t\t\tthis[timerKey] = setTimeout(() => {\n\t\t\t\tfn.apply(this, args);\n\t\t\t\tthis[resultKey] = initialValueProvider ? initialValueProvider() : undefined;\n\t\t\t}, delay);\n\t\t};\n\t});\n}\n\nexport function throttle(delay: number, reducer?: IDebounceReducer, initialValueProvider?: () => T): Function {\n\treturn createDecorator((fn, key) => {\n\t\tconst timerKey = `$throttle$timer$${key}`;\n\t\tconst resultKey = `$throttle$result$${key}`;\n\t\tconst lastRunKey = `$throttle$lastRun$${key}`;\n\t\tconst pendingKey = `$throttle$pending$${key}`;\n\n\t\treturn function (this: any, ...args: any[]) {\n\t\t\tif (!this[resultKey]) {\n\t\t\t\tthis[resultKey] = initialValueProvider ? initialValueProvider() : undefined;\n\t\t\t}\n\t\t\tif (this[lastRunKey] === null || this[lastRunKey] === undefined) {\n\t\t\t\tthis[lastRunKey] = -Number.MAX_VALUE;\n\t\t\t}\n\n\t\t\tif (reducer) {\n\t\t\t\tthis[resultKey] = reducer(this[resultKey], ...args);\n\t\t\t}\n\n\t\t\tif (this[pendingKey]) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst nextTime = this[lastRunKey] + delay;\n\t\t\tif (nextTime <= Date.now()) {\n\t\t\t\tthis[lastRunKey] = Date.now();\n\t\t\t\tfn.apply(this, [this[resultKey]]);\n\t\t\t\tthis[resultKey] = initialValueProvider ? initialValueProvider() : undefined;\n\t\t\t} else {\n\t\t\t\tthis[pendingKey] = true;\n\t\t\t\tthis[timerKey] = setTimeout(() => {\n\t\t\t\t\tthis[pendingKey] = false;\n\t\t\t\t\tthis[lastRunKey] = Date.now();\n\t\t\t\t\tfn.apply(this, [this[resultKey]]);\n\t\t\t\t\tthis[resultKey] = initialValueProvider ? initialValueProvider() : undefined;\n\t\t\t\t}, nextTime - Date.now());\n\t\t\t}\n\t\t};\n\t});\n}\n", "/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\nimport * as DomUtils from 'vs/base/browser/dom';\nimport { mainWindow } from 'vs/base/browser/window';\nimport * as arrays from 'vs/base/common/arrays';\nimport { memoize } from 'vs/base/common/decorators';\nimport { Event as EventUtils } from 'vs/base/common/event';\nimport { Disposable, IDisposable, markAsSingleton, toDisposable } from 'vs/base/common/lifecycle';\nimport { LinkedList } from 'vs/base/common/linkedList';\n\nexport namespace EventType {\n\texport const Tap = '-xterm-gesturetap';\n\texport const Change = '-xterm-gesturechange';\n\texport const Start = '-xterm-gesturestart';\n\texport const End = '-xterm-gesturesend';\n\texport const Contextmenu = '-xterm-gesturecontextmenu';\n}\n\ninterface TouchData {\n\tid: number;\n\tinitialTarget: EventTarget;\n\tinitialTimeStamp: number;\n\tinitialPageX: number;\n\tinitialPageY: number;\n\trollingTimestamps: number[];\n\trollingPageX: number[];\n\trollingPageY: number[];\n}\n\nexport interface GestureEvent extends MouseEvent {\n\tinitialTarget: EventTarget | undefined;\n\ttranslationX: number;\n\ttranslationY: number;\n\tpageX: number;\n\tpageY: number;\n\ttapCount: number;\n}\n\ninterface Touch {\n\tidentifier: number;\n\tscreenX: number;\n\tscreenY: number;\n\tclientX: number;\n\tclientY: number;\n\tpageX: number;\n\tpageY: number;\n\tradiusX: number;\n\tradiusY: number;\n\trotationAngle: number;\n\tforce: number;\n\ttarget: Element;\n}\n\ninterface TouchList {\n\t[i: number]: Touch;\n\tlength: number;\n\titem(index: number): Touch;\n\tidentifiedTouch(id: number): Touch;\n}\n\ninterface TouchEvent extends Event {\n\ttouches: TouchList;\n\ttargetTouches: TouchList;\n\tchangedTouches: TouchList;\n}\n\nexport class Gesture extends Disposable {\n\n\tprivate static readonly SCROLL_FRICTION = -0.005;\n\tprivate static INSTANCE: Gesture;\n\tprivate static readonly HOLD_DELAY = 700;\n\n\tprivate dispatched = false;\n\tprivate readonly targets = new LinkedList();\n\tprivate readonly ignoreTargets = new LinkedList();\n\tprivate handle: IDisposable | null;\n\n\tprivate readonly activeTouches: { [id: number]: TouchData };\n\n\tprivate _lastSetTapCountTime: number;\n\n\tprivate static readonly CLEAR_TAP_COUNT_TIME = 400; // ms\n\n\n\tprivate constructor() {\n\t\tsuper();\n\n\t\tthis.activeTouches = {};\n\t\tthis.handle = null;\n\t\tthis._lastSetTapCountTime = 0;\n\n\t\tthis._register(EventUtils.runAndSubscribe(DomUtils.onDidRegisterWindow, ({ window, disposables }) => {\n\t\t\tdisposables.add(DomUtils.addDisposableListener(window.document, 'touchstart', (e: TouchEvent) => this.onTouchStart(e), { passive: false }));\n\t\t\tdisposables.add(DomUtils.addDisposableListener(window.document, 'touchend', (e: TouchEvent) => this.onTouchEnd(window, e)));\n\t\t\tdisposables.add(DomUtils.addDisposableListener(window.document, 'touchmove', (e: TouchEvent) => this.onTouchMove(e), { passive: false }));\n\t\t}, { window: mainWindow, disposables: this._store }));\n\t}\n\n\tpublic static addTarget(element: HTMLElement): IDisposable {\n\t\tif (!Gesture.isTouchDevice()) {\n\t\t\treturn Disposable.None;\n\t\t}\n\t\tif (!Gesture.INSTANCE) {\n\t\t\tGesture.INSTANCE = markAsSingleton(new Gesture());\n\t\t}\n\n\t\tconst remove = Gesture.INSTANCE.targets.push(element);\n\t\treturn toDisposable(remove);\n\t}\n\n\tpublic static ignoreTarget(element: HTMLElement): IDisposable {\n\t\tif (!Gesture.isTouchDevice()) {\n\t\t\treturn Disposable.None;\n\t\t}\n\t\tif (!Gesture.INSTANCE) {\n\t\t\tGesture.INSTANCE = markAsSingleton(new Gesture());\n\t\t}\n\n\t\tconst remove = Gesture.INSTANCE.ignoreTargets.push(element);\n\t\treturn toDisposable(remove);\n\t}\n\n\t@memoize\n\tstatic isTouchDevice(): boolean {\n\t\t// `'ontouchstart' in window` always evaluates to true with typescript's modern typings. This causes `window` to be\n\t\t// `never` later in `window.navigator`. That's why we need the explicit `window as Window` cast\n\t\treturn 'ontouchstart' in mainWindow || navigator.maxTouchPoints > 0;\n\t}\n\n\tpublic override dispose(): void {\n\t\tif (this.handle) {\n\t\t\tthis.handle.dispose();\n\t\t\tthis.handle = null;\n\t\t}\n\n\t\tsuper.dispose();\n\t}\n\n\tprivate onTouchStart(e: TouchEvent): void {\n\t\tconst timestamp = Date.now(); // use Date.now() because on FF e.timeStamp is not epoch based.\n\n\t\tif (this.handle) {\n\t\t\tthis.handle.dispose();\n\t\t\tthis.handle = null;\n\t\t}\n\n\t\tfor (let i = 0, len = e.targetTouches.length; i < len; i++) {\n\t\t\tconst touch = e.targetTouches.item(i);\n\n\t\t\tthis.activeTouches[touch.identifier] = {\n\t\t\t\tid: touch.identifier,\n\t\t\t\tinitialTarget: touch.target,\n\t\t\t\tinitialTimeStamp: timestamp,\n\t\t\t\tinitialPageX: touch.pageX,\n\t\t\t\tinitialPageY: touch.pageY,\n\t\t\t\trollingTimestamps: [timestamp],\n\t\t\t\trollingPageX: [touch.pageX],\n\t\t\t\trollingPageY: [touch.pageY]\n\t\t\t};\n\n\t\t\tconst evt = this.newGestureEvent(EventType.Start, touch.target);\n\t\t\tevt.pageX = touch.pageX;\n\t\t\tevt.pageY = touch.pageY;\n\t\t\tthis.dispatchEvent(evt);\n\t\t}\n\n\t\tif (this.dispatched) {\n\t\t\te.preventDefault();\n\t\t\te.stopPropagation();\n\t\t\tthis.dispatched = false;\n\t\t}\n\t}\n\n\tprivate onTouchEnd(targetWindow: Window, e: TouchEvent): void {\n\t\tconst timestamp = Date.now(); // use Date.now() because on FF e.timeStamp is not epoch based.\n\n\t\tconst activeTouchCount = Object.keys(this.activeTouches).length;\n\n\t\tfor (let i = 0, len = e.changedTouches.length; i < len; i++) {\n\n\t\t\tconst touch = e.changedTouches.item(i);\n\n\t\t\tif (!this.activeTouches.hasOwnProperty(String(touch.identifier))) {\n\t\t\t\tconsole.warn('move of an UNKNOWN touch', touch);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst data = this.activeTouches[touch.identifier],\n\t\t\t\tholdTime = Date.now() - data.initialTimeStamp;\n\n\t\t\tif (holdTime < Gesture.HOLD_DELAY\n\t\t\t\t&& Math.abs(data.initialPageX - arrays.tail(data.rollingPageX)!) < 30\n\t\t\t\t&& Math.abs(data.initialPageY - arrays.tail(data.rollingPageY)!) < 30) {\n\n\t\t\t\tconst evt = this.newGestureEvent(EventType.Tap, data.initialTarget);\n\t\t\t\tevt.pageX = arrays.tail(data.rollingPageX)!;\n\t\t\t\tevt.pageY = arrays.tail(data.rollingPageY)!;\n\t\t\t\tthis.dispatchEvent(evt);\n\n\t\t\t} else if (holdTime >= Gesture.HOLD_DELAY\n\t\t\t\t&& Math.abs(data.initialPageX - arrays.tail(data.rollingPageX)!) < 30\n\t\t\t\t&& Math.abs(data.initialPageY - arrays.tail(data.rollingPageY)!) < 30) {\n\n\t\t\t\tconst evt = this.newGestureEvent(EventType.Contextmenu, data.initialTarget);\n\t\t\t\tevt.pageX = arrays.tail(data.rollingPageX)!;\n\t\t\t\tevt.pageY = arrays.tail(data.rollingPageY)!;\n\t\t\t\tthis.dispatchEvent(evt);\n\n\t\t\t} else if (activeTouchCount === 1) {\n\t\t\t\tconst finalX = arrays.tail(data.rollingPageX)!;\n\t\t\t\tconst finalY = arrays.tail(data.rollingPageY)!;\n\n\t\t\t\tconst deltaT = arrays.tail(data.rollingTimestamps)! - data.rollingTimestamps[0];\n\t\t\t\tconst deltaX = finalX - data.rollingPageX[0];\n\t\t\t\tconst deltaY = finalY - data.rollingPageY[0];\n\n\t\t\t\t// We need to get all the dispatch targets on the start of the inertia event\n\t\t\t\tconst dispatchTo = [...this.targets].filter(t => data.initialTarget instanceof Node && t.contains(data.initialTarget));\n\t\t\t\tthis.inertia(targetWindow, dispatchTo, timestamp,\t// time now\n\t\t\t\t\tMath.abs(deltaX) / deltaT,\t\t\t\t\t\t// speed\n\t\t\t\t\tdeltaX > 0 ? 1 : -1,\t\t\t\t\t\t\t// x direction\n\t\t\t\t\tfinalX,\t\t\t\t\t\t\t\t\t\t\t// x now\n\t\t\t\t\tMath.abs(deltaY) / deltaT, \t\t\t\t\t// y speed\n\t\t\t\t\tdeltaY > 0 ? 1 : -1,\t\t\t\t\t\t\t// y direction\n\t\t\t\t\tfinalY\t\t\t\t\t\t\t\t\t\t\t// y now\n\t\t\t\t);\n\t\t\t}\n\n\n\t\t\tthis.dispatchEvent(this.newGestureEvent(EventType.End, data.initialTarget));\n\t\t\t// forget about this touch\n\t\t\tdelete this.activeTouches[touch.identifier];\n\t\t}\n\n\t\tif (this.dispatched) {\n\t\t\te.preventDefault();\n\t\t\te.stopPropagation();\n\t\t\tthis.dispatched = false;\n\t\t}\n\t}\n\n\tprivate newGestureEvent(type: string, initialTarget?: EventTarget): GestureEvent {\n\t\tconst event = document.createEvent('CustomEvent') as unknown as GestureEvent;\n\t\tevent.initEvent(type, false, true);\n\t\tevent.initialTarget = initialTarget;\n\t\tevent.tapCount = 0;\n\t\treturn event;\n\t}\n\n\tprivate dispatchEvent(event: GestureEvent): void {\n\t\tif (event.type === EventType.Tap) {\n\t\t\tconst currentTime = (new Date()).getTime();\n\t\t\tlet setTapCount = 0;\n\t\t\tif (currentTime - this._lastSetTapCountTime > Gesture.CLEAR_TAP_COUNT_TIME) {\n\t\t\t\tsetTapCount = 1;\n\t\t\t} else {\n\t\t\t\tsetTapCount = 2;\n\t\t\t}\n\n\t\t\tthis._lastSetTapCountTime = currentTime;\n\t\t\tevent.tapCount = setTapCount;\n\t\t} else if (event.type === EventType.Change || event.type === EventType.Contextmenu) {\n\t\t\t// tap is canceled by scrolling or context menu\n\t\t\tthis._lastSetTapCountTime = 0;\n\t\t}\n\n\t\tif (event.initialTarget instanceof Node) {\n\t\t\tfor (const ignoreTarget of this.ignoreTargets) {\n\t\t\t\tif (ignoreTarget.contains(event.initialTarget)) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst targets: [number, HTMLElement][] = [];\n\t\t\tfor (const target of this.targets) {\n\t\t\t\tif (target.contains(event.initialTarget)) {\n\t\t\t\t\tlet depth = 0;\n\t\t\t\t\tlet now: Node | null = event.initialTarget;\n\t\t\t\t\twhile (now && now !== target) {\n\t\t\t\t\t\tdepth++;\n\t\t\t\t\t\tnow = now.parentElement;\n\t\t\t\t\t}\n\t\t\t\t\ttargets.push([depth, target]);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ttargets.sort((a, b) => a[0] - b[0]);\n\n\t\t\tfor (const [_, target] of targets) {\n\t\t\t\ttarget.dispatchEvent(event);\n\t\t\t\tthis.dispatched = true;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate inertia(targetWindow: Window, dispatchTo: readonly EventTarget[], t1: number, vX: number, dirX: number, x: number, vY: number, dirY: number, y: number): void {\n\t\tthis.handle = DomUtils.scheduleAtNextAnimationFrame(targetWindow, () => {\n\t\t\tconst now = Date.now();\n\n\t\t\t// velocity: old speed + accel_over_time\n\t\t\tconst deltaT = now - t1;\n\t\t\tlet delta_pos_x = 0, delta_pos_y = 0;\n\t\t\tlet stopped = true;\n\n\t\t\tvX += Gesture.SCROLL_FRICTION * deltaT;\n\t\t\tvY += Gesture.SCROLL_FRICTION * deltaT;\n\n\t\t\tif (vX > 0) {\n\t\t\t\tstopped = false;\n\t\t\t\tdelta_pos_x = dirX * vX * deltaT;\n\t\t\t}\n\n\t\t\tif (vY > 0) {\n\t\t\t\tstopped = false;\n\t\t\t\tdelta_pos_y = dirY * vY * deltaT;\n\t\t\t}\n\n\t\t\t// dispatch translation event\n\t\t\tconst evt = this.newGestureEvent(EventType.Change);\n\t\t\tevt.translationX = delta_pos_x;\n\t\t\tevt.translationY = delta_pos_y;\n\t\t\tdispatchTo.forEach(d => d.dispatchEvent(evt));\n\n\t\t\tif (!stopped) {\n\t\t\t\tthis.inertia(targetWindow, dispatchTo, now, vX, dirX, x + delta_pos_x, vY, dirY, y + delta_pos_y);\n\t\t\t}\n\t\t});\n\t}\n\n\tprivate onTouchMove(e: TouchEvent): void {\n\t\tconst timestamp = Date.now(); // use Date.now() because on FF e.timeStamp is not epoch based.\n\n\t\tfor (let i = 0, len = e.changedTouches.length; i < len; i++) {\n\n\t\t\tconst touch = e.changedTouches.item(i);\n\n\t\t\tif (!this.activeTouches.hasOwnProperty(String(touch.identifier))) {\n\t\t\t\tconsole.warn('end of an UNKNOWN touch', touch);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst data = this.activeTouches[touch.identifier];\n\n\t\t\tconst evt = this.newGestureEvent(EventType.Change, data.initialTarget);\n\t\t\tevt.translationX = touch.pageX - arrays.tail(data.rollingPageX)!;\n\t\t\tevt.translationY = touch.pageY - arrays.tail(data.rollingPageY)!;\n\t\t\tevt.pageX = touch.pageX;\n\t\t\tevt.pageY = touch.pageY;\n\t\t\tthis.dispatchEvent(evt);\n\n\t\t\t// only keep a few data points, to average the final speed\n\t\t\tif (data.rollingPageX.length > 3) {\n\t\t\t\tdata.rollingPageX.shift();\n\t\t\t\tdata.rollingPageY.shift();\n\t\t\t\tdata.rollingTimestamps.shift();\n\t\t\t}\n\n\t\t\tdata.rollingPageX.push(touch.pageX);\n\t\t\tdata.rollingPageY.push(touch.pageY);\n\t\t\tdata.rollingTimestamps.push(timestamp);\n\t\t}\n\n\t\tif (this.dispatched) {\n\t\t\te.preventDefault();\n\t\t\te.stopPropagation();\n\t\t\tthis.dispatched = false;\n\t\t}\n\t}\n}\n", "/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\nimport * as dom from 'vs/base/browser/dom';\nimport { IKeyboardEvent, StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';\nimport { IMouseEvent, StandardMouseEvent } from 'vs/base/browser/mouseEvent';\nimport { Gesture } from 'vs/base/browser/touch';\nimport { Disposable, IDisposable } from 'vs/base/common/lifecycle';\n\nexport abstract class Widget extends Disposable {\n\n\tprotected onclick(domNode: HTMLElement, listener: (e: IMouseEvent) => void): void {\n\t\tthis._register(dom.addDisposableListener(domNode, dom.EventType.CLICK, (e: MouseEvent) => listener(new StandardMouseEvent(dom.getWindow(domNode), e))));\n\t}\n\n\tprotected onmousedown(domNode: HTMLElement, listener: (e: IMouseEvent) => void): void {\n\t\tthis._register(dom.addDisposableListener(domNode, dom.EventType.MOUSE_DOWN, (e: MouseEvent) => listener(new StandardMouseEvent(dom.getWindow(domNode), e))));\n\t}\n\n\tprotected onmouseover(domNode: HTMLElement, listener: (e: IMouseEvent) => void): void {\n\t\tthis._register(dom.addDisposableListener(domNode, dom.EventType.MOUSE_OVER, (e: MouseEvent) => listener(new StandardMouseEvent(dom.getWindow(domNode), e))));\n\t}\n\n\tprotected onmouseleave(domNode: HTMLElement, listener: (e: IMouseEvent) => void): void {\n\t\tthis._register(dom.addDisposableListener(domNode, dom.EventType.MOUSE_LEAVE, (e: MouseEvent) => listener(new StandardMouseEvent(dom.getWindow(domNode), e))));\n\t}\n\n\tprotected onkeydown(domNode: HTMLElement, listener: (e: IKeyboardEvent) => void): void {\n\t\tthis._register(dom.addDisposableListener(domNode, dom.EventType.KEY_DOWN, (e: KeyboardEvent) => listener(new StandardKeyboardEvent(e))));\n\t}\n\n\tprotected onkeyup(domNode: HTMLElement, listener: (e: IKeyboardEvent) => void): void {\n\t\tthis._register(dom.addDisposableListener(domNode, dom.EventType.KEY_UP, (e: KeyboardEvent) => listener(new StandardKeyboardEvent(e))));\n\t}\n\n\tprotected oninput(domNode: HTMLElement, listener: (e: Event) => void): void {\n\t\tthis._register(dom.addDisposableListener(domNode, dom.EventType.INPUT, listener));\n\t}\n\n\tprotected onblur(domNode: HTMLElement, listener: (e: Event) => void): void {\n\t\tthis._register(dom.addDisposableListener(domNode, dom.EventType.BLUR, listener));\n\t}\n\n\tprotected onfocus(domNode: HTMLElement, listener: (e: Event) => void): void {\n\t\tthis._register(dom.addDisposableListener(domNode, dom.EventType.FOCUS, listener));\n\t}\n\n\tprotected onchange(domNode: HTMLElement, listener: (e: Event) => void): void {\n\t\tthis._register(dom.addDisposableListener(domNode, dom.EventType.CHANGE, listener));\n\t}\n\n\tprotected ignoreGesture(domNode: HTMLElement): IDisposable {\n\t\treturn Gesture.ignoreTarget(domNode);\n\t}\n}\n", "/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\nimport { GlobalPointerMoveMonitor } from 'vs/base/browser/globalPointerMoveMonitor';\nimport { Widget } from 'vs/base/browser/ui/widget';\nimport { TimeoutTimer } from 'vs/base/common/async';\nimport * as dom from 'vs/base/browser/dom';\n\n/**\n * The arrow image size.\n */\nexport const ARROW_IMG_SIZE = 11;\n\nexport interface ScrollbarArrowOptions {\n\tonActivate: () => void;\n\tclassName: string;\n\t// icon: ThemeIcon;\n\n\tbgWidth: number;\n\tbgHeight: number;\n\n\ttop?: number;\n\tleft?: number;\n\tbottom?: number;\n\tright?: number;\n}\n\nexport class ScrollbarArrow extends Widget {\n\n\tprivate _onActivate: () => void;\n\tpublic bgDomNode: HTMLElement;\n\tpublic domNode: HTMLElement;\n\tprivate _pointerdownRepeatTimer: dom.WindowIntervalTimer;\n\tprivate _pointerdownScheduleRepeatTimer: TimeoutTimer;\n\tprivate _pointerMoveMonitor: GlobalPointerMoveMonitor;\n\n\tconstructor(opts: ScrollbarArrowOptions) {\n\t\tsuper();\n\t\tthis._onActivate = opts.onActivate;\n\n\t\tthis.bgDomNode = document.createElement('div');\n\t\tthis.bgDomNode.className = 'arrow-background';\n\t\tthis.bgDomNode.style.position = 'absolute';\n\t\tthis.bgDomNode.style.width = opts.bgWidth + 'px';\n\t\tthis.bgDomNode.style.height = opts.bgHeight + 'px';\n\t\tif (typeof opts.top !== 'undefined') {\n\t\t\tthis.bgDomNode.style.top = '0px';\n\t\t}\n\t\tif (typeof opts.left !== 'undefined') {\n\t\t\tthis.bgDomNode.style.left = '0px';\n\t\t}\n\t\tif (typeof opts.bottom !== 'undefined') {\n\t\t\tthis.bgDomNode.style.bottom = '0px';\n\t\t}\n\t\tif (typeof opts.right !== 'undefined') {\n\t\t\tthis.bgDomNode.style.right = '0px';\n\t\t}\n\n\t\tthis.domNode = document.createElement('div');\n\t\tthis.domNode.className = opts.className;\n\t\t// this.domNode.classList.add(...ThemeIcon.asClassNameArray(opts.icon));\n\n\t\tthis.domNode.style.position = 'absolute';\n\t\tthis.domNode.style.width = ARROW_IMG_SIZE + 'px';\n\t\tthis.domNode.style.height = ARROW_IMG_SIZE + 'px';\n\t\tif (typeof opts.top !== 'undefined') {\n\t\t\tthis.domNode.style.top = opts.top + 'px';\n\t\t}\n\t\tif (typeof opts.left !== 'undefined') {\n\t\t\tthis.domNode.style.left = opts.left + 'px';\n\t\t}\n\t\tif (typeof opts.bottom !== 'undefined') {\n\t\t\tthis.domNode.style.bottom = opts.bottom + 'px';\n\t\t}\n\t\tif (typeof opts.right !== 'undefined') {\n\t\t\tthis.domNode.style.right = opts.right + 'px';\n\t\t}\n\n\t\tthis._pointerMoveMonitor = this._register(new GlobalPointerMoveMonitor());\n\t\tthis._register(dom.addStandardDisposableListener(this.bgDomNode, dom.EventType.POINTER_DOWN, (e) => this._arrowPointerDown(e)));\n\t\tthis._register(dom.addStandardDisposableListener(this.domNode, dom.EventType.POINTER_DOWN, (e) => this._arrowPointerDown(e)));\n\n\t\tthis._pointerdownRepeatTimer = this._register(new dom.WindowIntervalTimer());\n\t\tthis._pointerdownScheduleRepeatTimer = this._register(new TimeoutTimer());\n\t}\n\n\tprivate _arrowPointerDown(e: PointerEvent): void {\n\t\tif (!e.target || !(e.target instanceof Element)) {\n\t\t\treturn;\n\t\t}\n\t\tconst scheduleRepeater = () => {\n\t\t\tthis._pointerdownRepeatTimer.cancelAndSet(() => this._onActivate(), 1000 / 24, dom.getWindow(e));\n\t\t};\n\n\t\tthis._onActivate();\n\t\tthis._pointerdownRepeatTimer.cancel();\n\t\tthis._pointerdownScheduleRepeatTimer.cancelAndSet(scheduleRepeater, 200);\n\n\t\tthis._pointerMoveMonitor.startMonitoring(\n\t\t\te.target,\n\t\t\te.pointerId,\n\t\t\te.buttons,\n\t\t\t(pointerMoveData) => { /* Intentional empty */ },\n\t\t\t() => {\n\t\t\t\tthis._pointerdownRepeatTimer.cancel();\n\t\t\t\tthis._pointerdownScheduleRepeatTimer.cancel();\n\t\t\t}\n\t\t);\n\n\t\te.preventDefault();\n\t}\n}\n", "/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\nimport { Emitter, Event } from 'vs/base/common/event';\nimport { Disposable, IDisposable } from 'vs/base/common/lifecycle';\n\nexport const enum ScrollbarVisibility {\n\tAuto = 1,\n\tHidden = 2,\n\tVisible = 3\n}\n\nexport interface ScrollEvent {\n\tinSmoothScrolling: boolean;\n\n\toldWidth: number;\n\toldScrollWidth: number;\n\toldScrollLeft: number;\n\n\twidth: number;\n\tscrollWidth: number;\n\tscrollLeft: number;\n\n\toldHeight: number;\n\toldScrollHeight: number;\n\toldScrollTop: number;\n\n\theight: number;\n\tscrollHeight: number;\n\tscrollTop: number;\n\n\twidthChanged: boolean;\n\tscrollWidthChanged: boolean;\n\tscrollLeftChanged: boolean;\n\n\theightChanged: boolean;\n\tscrollHeightChanged: boolean;\n\tscrollTopChanged: boolean;\n}\n\nexport class ScrollState implements IScrollDimensions, IScrollPosition {\n\t_scrollStateBrand: void = undefined;\n\n\tpublic readonly rawScrollLeft: number;\n\tpublic readonly rawScrollTop: number;\n\n\tpublic readonly width: number;\n\tpublic readonly scrollWidth: number;\n\tpublic readonly scrollLeft: number;\n\tpublic readonly height: number;\n\tpublic readonly scrollHeight: number;\n\tpublic readonly scrollTop: number;\n\n\tconstructor(\n\t\tprivate readonly _forceIntegerValues: boolean,\n\t\twidth: number,\n\t\tscrollWidth: number,\n\t\tscrollLeft: number,\n\t\theight: number,\n\t\tscrollHeight: number,\n\t\tscrollTop: number\n\t) {\n\t\tif (this._forceIntegerValues) {\n\t\t\twidth = width | 0;\n\t\t\tscrollWidth = scrollWidth | 0;\n\t\t\tscrollLeft = scrollLeft | 0;\n\t\t\theight = height | 0;\n\t\t\tscrollHeight = scrollHeight | 0;\n\t\t\tscrollTop = scrollTop | 0;\n\t\t}\n\n\t\tthis.rawScrollLeft = scrollLeft; // before validation\n\t\tthis.rawScrollTop = scrollTop; // before validation\n\n\t\tif (width < 0) {\n\t\t\twidth = 0;\n\t\t}\n\t\tif (scrollLeft + width > scrollWidth) {\n\t\t\tscrollLeft = scrollWidth - width;\n\t\t}\n\t\tif (scrollLeft < 0) {\n\t\t\tscrollLeft = 0;\n\t\t}\n\n\t\tif (height < 0) {\n\t\t\theight = 0;\n\t\t}\n\t\tif (scrollTop + height > scrollHeight) {\n\t\t\tscrollTop = scrollHeight - height;\n\t\t}\n\t\tif (scrollTop < 0) {\n\t\t\tscrollTop = 0;\n\t\t}\n\n\t\tthis.width = width;\n\t\tthis.scrollWidth = scrollWidth;\n\t\tthis.scrollLeft = scrollLeft;\n\t\tthis.height = height;\n\t\tthis.scrollHeight = scrollHeight;\n\t\tthis.scrollTop = scrollTop;\n\t}\n\n\tpublic equals(other: ScrollState): boolean {\n\t\treturn (\n\t\t\tthis.rawScrollLeft === other.rawScrollLeft\n\t\t\t&& this.rawScrollTop === other.rawScrollTop\n\t\t\t&& this.width === other.width\n\t\t\t&& this.scrollWidth === other.scrollWidth\n\t\t\t&& this.scrollLeft === other.scrollLeft\n\t\t\t&& this.height === other.height\n\t\t\t&& this.scrollHeight === other.scrollHeight\n\t\t\t&& this.scrollTop === other.scrollTop\n\t\t);\n\t}\n\n\tpublic withScrollDimensions(update: INewScrollDimensions, useRawScrollPositions: boolean): ScrollState {\n\t\treturn new ScrollState(\n\t\t\tthis._forceIntegerValues,\n\t\t\t(typeof update.width !== 'undefined' ? update.width : this.width),\n\t\t\t(typeof update.scrollWidth !== 'undefined' ? update.scrollWidth : this.scrollWidth),\n\t\t\tuseRawScrollPositions ? this.rawScrollLeft : this.scrollLeft,\n\t\t\t(typeof update.height !== 'undefined' ? update.height : this.height),\n\t\t\t(typeof update.scrollHeight !== 'undefined' ? update.scrollHeight : this.scrollHeight),\n\t\t\tuseRawScrollPositions ? this.rawScrollTop : this.scrollTop\n\t\t);\n\t}\n\n\tpublic withScrollPosition(update: INewScrollPosition): ScrollState {\n\t\treturn new ScrollState(\n\t\t\tthis._forceIntegerValues,\n\t\t\tthis.width,\n\t\t\tthis.scrollWidth,\n\t\t\t(typeof update.scrollLeft !== 'undefined' ? update.scrollLeft : this.rawScrollLeft),\n\t\t\tthis.height,\n\t\t\tthis.scrollHeight,\n\t\t\t(typeof update.scrollTop !== 'undefined' ? update.scrollTop : this.rawScrollTop)\n\t\t);\n\t}\n\n\tpublic createScrollEvent(previous: ScrollState, inSmoothScrolling: boolean): ScrollEvent {\n\t\tconst widthChanged = (this.width !== previous.width);\n\t\tconst scrollWidthChanged = (this.scrollWidth !== previous.scrollWidth);\n\t\tconst scrollLeftChanged = (this.scrollLeft !== previous.scrollLeft);\n\n\t\tconst heightChanged = (this.height !== previous.height);\n\t\tconst scrollHeightChanged = (this.scrollHeight !== previous.scrollHeight);\n\t\tconst scrollTopChanged = (this.scrollTop !== previous.scrollTop);\n\n\t\treturn {\n\t\t\tinSmoothScrolling: inSmoothScrolling,\n\t\t\toldWidth: previous.width,\n\t\t\toldScrollWidth: previous.scrollWidth,\n\t\t\toldScrollLeft: previous.scrollLeft,\n\n\t\t\twidth: this.width,\n\t\t\tscrollWidth: this.scrollWidth,\n\t\t\tscrollLeft: this.scrollLeft,\n\n\t\t\toldHeight: previous.height,\n\t\t\toldScrollHeight: previous.scrollHeight,\n\t\t\toldScrollTop: previous.scrollTop,\n\n\t\t\theight: this.height,\n\t\t\tscrollHeight: this.scrollHeight,\n\t\t\tscrollTop: this.scrollTop,\n\n\t\t\twidthChanged: widthChanged,\n\t\t\tscrollWidthChanged: scrollWidthChanged,\n\t\t\tscrollLeftChanged: scrollLeftChanged,\n\n\t\t\theightChanged: heightChanged,\n\t\t\tscrollHeightChanged: scrollHeightChanged,\n\t\t\tscrollTopChanged: scrollTopChanged,\n\t\t};\n\t}\n\n}\n\nexport interface IScrollDimensions {\n\treadonly width: number;\n\treadonly scrollWidth: number;\n\treadonly height: number;\n\treadonly scrollHeight: number;\n}\nexport interface INewScrollDimensions {\n\twidth?: number;\n\tscrollWidth?: number;\n\theight?: number;\n\tscrollHeight?: number;\n}\n\nexport interface IScrollPosition {\n\treadonly scrollLeft: number;\n\treadonly scrollTop: number;\n}\nexport interface ISmoothScrollPosition {\n\treadonly scrollLeft: number;\n\treadonly scrollTop: number;\n\n\treadonly width: number;\n\treadonly height: number;\n}\nexport interface INewScrollPosition {\n\tscrollLeft?: number;\n\tscrollTop?: number;\n}\n\nexport interface IScrollableOptions {\n\t/**\n\t * Define if the scroll values should always be integers.\n\t */\n\tforceIntegerValues: boolean;\n\t/**\n\t * Set the duration (ms) used for smooth scroll animations.\n\t */\n\tsmoothScrollDuration: number;\n\t/**\n\t * A function to schedule an update at the next frame (used for smooth scroll animations).\n\t */\n\tscheduleAtNextAnimationFrame: (callback: () => void) => IDisposable;\n}\n\nexport class Scrollable extends Disposable {\n\n\t_scrollableBrand: void = undefined;\n\n\tprivate _smoothScrollDuration: number;\n\tprivate readonly _scheduleAtNextAnimationFrame: (callback: () => void) => IDisposable;\n\tprivate _state: ScrollState;\n\tprivate _smoothScrolling: SmoothScrollingOperation | null;\n\n\tprivate _onScroll = this._register(new Emitter());\n\tpublic readonly onScroll: Event = this._onScroll.event;\n\n\tconstructor(options: IScrollableOptions) {\n\t\tsuper();\n\n\t\tthis._smoothScrollDuration = options.smoothScrollDuration;\n\t\tthis._scheduleAtNextAnimationFrame = options.scheduleAtNextAnimationFrame;\n\t\tthis._state = new ScrollState(options.forceIntegerValues, 0, 0, 0, 0, 0, 0);\n\t\tthis._smoothScrolling = null;\n\t}\n\n\tpublic override dispose(): void {\n\t\tif (this._smoothScrolling) {\n\t\t\tthis._smoothScrolling.dispose();\n\t\t\tthis._smoothScrolling = null;\n\t\t}\n\t\tsuper.dispose();\n\t}\n\n\tpublic setSmoothScrollDuration(smoothScrollDuration: number): void {\n\t\tthis._smoothScrollDuration = smoothScrollDuration;\n\t}\n\n\tpublic validateScrollPosition(scrollPosition: INewScrollPosition): IScrollPosition {\n\t\treturn this._state.withScrollPosition(scrollPosition);\n\t}\n\n\tpublic getScrollDimensions(): IScrollDimensions {\n\t\treturn this._state;\n\t}\n\n\tpublic setScrollDimensions(dimensions: INewScrollDimensions, useRawScrollPositions: boolean): void {\n\t\tconst newState = this._state.withScrollDimensions(dimensions, useRawScrollPositions);\n\t\tthis._setState(newState, Boolean(this._smoothScrolling));\n\n\t\t// Validate outstanding animated scroll position target\n\t\tthis._smoothScrolling?.acceptScrollDimensions(this._state);\n\t}\n\n\t/**\n\t * Returns the final scroll position that the instance will have once the smooth scroll animation concludes.\n\t * If no scroll animation is occurring, it will return the current scroll position instead.\n\t */\n\tpublic getFutureScrollPosition(): IScrollPosition {\n\t\tif (this._smoothScrolling) {\n\t\t\treturn this._smoothScrolling.to;\n\t\t}\n\t\treturn this._state;\n\t}\n\n\t/**\n\t * Returns the current scroll position.\n\t * Note: This result might be an intermediate scroll position, as there might be an ongoing smooth scroll animation.\n\t */\n\tpublic getCurrentScrollPosition(): IScrollPosition {\n\t\treturn this._state;\n\t}\n\n\tpublic setScrollPositionNow(update: INewScrollPosition): void {\n\t\t// no smooth scrolling requested\n\t\tconst newState = this._state.withScrollPosition(update);\n\n\t\t// Terminate any outstanding smooth scrolling\n\t\tif (this._smoothScrolling) {\n\t\t\tthis._smoothScrolling.dispose();\n\t\t\tthis._smoothScrolling = null;\n\t\t}\n\n\t\tthis._setState(newState, false);\n\t}\n\n\tpublic setScrollPositionSmooth(update: INewScrollPosition, reuseAnimation?: boolean): void {\n\t\tif (this._smoothScrollDuration === 0) {\n\t\t\t// Smooth scrolling not supported.\n\t\t\treturn this.setScrollPositionNow(update);\n\t\t}\n\n\t\tif (this._smoothScrolling) {\n\t\t\t// Combine our pending scrollLeft/scrollTop with incoming scrollLeft/scrollTop\n\t\t\tupdate = {\n\t\t\t\tscrollLeft: (typeof update.scrollLeft === 'undefined' ? this._smoothScrolling.to.scrollLeft : update.scrollLeft),\n\t\t\t\tscrollTop: (typeof update.scrollTop === 'undefined' ? this._smoothScrolling.to.scrollTop : update.scrollTop)\n\t\t\t};\n\n\t\t\t// Validate `update`\n\t\t\tconst validTarget = this._state.withScrollPosition(update);\n\n\t\t\tif (this._smoothScrolling.to.scrollLeft === validTarget.scrollLeft && this._smoothScrolling.to.scrollTop === validTarget.scrollTop) {\n\t\t\t\t// No need to interrupt or extend the current animation since we're going to the same place\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tlet newSmoothScrolling: SmoothScrollingOperation;\n\t\t\tif (reuseAnimation) {\n\t\t\t\tnewSmoothScrolling = new SmoothScrollingOperation(this._smoothScrolling.from, validTarget, this._smoothScrolling.startTime, this._smoothScrolling.duration);\n\t\t\t} else {\n\t\t\t\tnewSmoothScrolling = this._smoothScrolling.combine(this._state, validTarget, this._smoothScrollDuration);\n\t\t\t}\n\t\t\tthis._smoothScrolling.dispose();\n\t\t\tthis._smoothScrolling = newSmoothScrolling;\n\t\t} else {\n\t\t\t// Validate `update`\n\t\t\tconst validTarget = this._state.withScrollPosition(update);\n\n\t\t\tthis._smoothScrolling = SmoothScrollingOperation.start(this._state, validTarget, this._smoothScrollDuration);\n\t\t}\n\n\t\t// Begin smooth scrolling animation\n\t\tthis._smoothScrolling.animationFrameDisposable = this._scheduleAtNextAnimationFrame(() => {\n\t\t\tif (!this._smoothScrolling) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis._smoothScrolling.animationFrameDisposable = null;\n\t\t\tthis._performSmoothScrolling();\n\t\t});\n\t}\n\n\tpublic hasPendingScrollAnimation(): boolean {\n\t\treturn Boolean(this._smoothScrolling);\n\t}\n\n\tprivate _performSmoothScrolling(): void {\n\t\tif (!this._smoothScrolling) {\n\t\t\treturn;\n\t\t}\n\t\tconst update = this._smoothScrolling.tick();\n\t\tconst newState = this._state.withScrollPosition(update);\n\n\t\tthis._setState(newState, true);\n\n\t\tif (!this._smoothScrolling) {\n\t\t\t// Looks like someone canceled the smooth scrolling\n\t\t\t// from the scroll event handler\n\t\t\treturn;\n\t\t}\n\n\t\tif (update.isDone) {\n\t\t\tthis._smoothScrolling.dispose();\n\t\t\tthis._smoothScrolling = null;\n\t\t\treturn;\n\t\t}\n\n\t\t// Continue smooth scrolling animation\n\t\tthis._smoothScrolling.animationFrameDisposable = this._scheduleAtNextAnimationFrame(() => {\n\t\t\tif (!this._smoothScrolling) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis._smoothScrolling.animationFrameDisposable = null;\n\t\t\tthis._performSmoothScrolling();\n\t\t});\n\t}\n\n\tprivate _setState(newState: ScrollState, inSmoothScrolling: boolean): void {\n\t\tconst oldState = this._state;\n\t\tif (oldState.equals(newState)) {\n\t\t\t// no change\n\t\t\treturn;\n\t\t}\n\t\tthis._state = newState;\n\t\tthis._onScroll.fire(this._state.createScrollEvent(oldState, inSmoothScrolling));\n\t}\n}\n\nexport class SmoothScrollingUpdate {\n\n\tpublic readonly scrollLeft: number;\n\tpublic readonly scrollTop: number;\n\tpublic readonly isDone: boolean;\n\n\tconstructor(scrollLeft: number, scrollTop: number, isDone: boolean) {\n\t\tthis.scrollLeft = scrollLeft;\n\t\tthis.scrollTop = scrollTop;\n\t\tthis.isDone = isDone;\n\t}\n\n}\n\ninterface IAnimation {\n\t(completion: number): number;\n}\n\nfunction createEaseOutCubic(from: number, to: number): IAnimation {\n\tconst delta = to - from;\n\treturn function (completion: number): number {\n\t\treturn from + delta * easeOutCubic(completion);\n\t};\n}\n\nfunction createComposed(a: IAnimation, b: IAnimation, cut: number): IAnimation {\n\treturn function (completion: number): number {\n\t\tif (completion < cut) {\n\t\t\treturn a(completion / cut);\n\t\t}\n\t\treturn b((completion - cut) / (1 - cut));\n\t};\n}\n\nexport class SmoothScrollingOperation {\n\n\tpublic readonly from: ISmoothScrollPosition;\n\tpublic to: ISmoothScrollPosition;\n\tpublic readonly duration: number;\n\tpublic readonly startTime: number;\n\tpublic animationFrameDisposable: IDisposable | null;\n\n\tprivate scrollLeft!: IAnimation;\n\tprivate scrollTop!: IAnimation;\n\n\tconstructor(from: ISmoothScrollPosition, to: ISmoothScrollPosition, startTime: number, duration: number) {\n\t\tthis.from = from;\n\t\tthis.to = to;\n\t\tthis.duration = duration;\n\t\tthis.startTime = startTime;\n\n\t\tthis.animationFrameDisposable = null;\n\n\t\tthis._initAnimations();\n\t}\n\n\tprivate _initAnimations(): void {\n\t\tthis.scrollLeft = this._initAnimation(this.from.scrollLeft, this.to.scrollLeft, this.to.width);\n\t\tthis.scrollTop = this._initAnimation(this.from.scrollTop, this.to.scrollTop, this.to.height);\n\t}\n\n\tprivate _initAnimation(from: number, to: number, viewportSize: number): IAnimation {\n\t\tconst delta = Math.abs(from - to);\n\t\tif (delta > 2.5 * viewportSize) {\n\t\t\tlet stop1: number, stop2: number;\n\t\t\tif (from < to) {\n\t\t\t\t// scroll to 75% of the viewportSize\n\t\t\t\tstop1 = from + 0.75 * viewportSize;\n\t\t\t\tstop2 = to - 0.75 * viewportSize;\n\t\t\t} else {\n\t\t\t\tstop1 = from - 0.75 * viewportSize;\n\t\t\t\tstop2 = to + 0.75 * viewportSize;\n\t\t\t}\n\t\t\treturn createComposed(createEaseOutCubic(from, stop1), createEaseOutCubic(stop2, to), 0.33);\n\t\t}\n\t\treturn createEaseOutCubic(from, to);\n\t}\n\n\tpublic dispose(): void {\n\t\tif (this.animationFrameDisposable !== null) {\n\t\t\tthis.animationFrameDisposable.dispose();\n\t\t\tthis.animationFrameDisposable = null;\n\t\t}\n\t}\n\n\tpublic acceptScrollDimensions(state: ScrollState): void {\n\t\tthis.to = state.withScrollPosition(this.to);\n\t\tthis._initAnimations();\n\t}\n\n\tpublic tick(): SmoothScrollingUpdate {\n\t\treturn this._tick(Date.now());\n\t}\n\n\tprotected _tick(now: number): SmoothScrollingUpdate {\n\t\tconst completion = (now - this.startTime) / this.duration;\n\n\t\tif (completion < 1) {\n\t\t\tconst newScrollLeft = this.scrollLeft(completion);\n\t\t\tconst newScrollTop = this.scrollTop(completion);\n\t\t\treturn new SmoothScrollingUpdate(newScrollLeft, newScrollTop, false);\n\t\t}\n\n\t\treturn new SmoothScrollingUpdate(this.to.scrollLeft, this.to.scrollTop, true);\n\t}\n\n\tpublic combine(from: ISmoothScrollPosition, to: ISmoothScrollPosition, duration: number): SmoothScrollingOperation {\n\t\treturn SmoothScrollingOperation.start(from, to, duration);\n\t}\n\n\tpublic static start(from: ISmoothScrollPosition, to: ISmoothScrollPosition, duration: number): SmoothScrollingOperation {\n\t\t// +10 / -10 : pretend the animation already started for a quicker response to a scroll request\n\t\tduration = duration + 10;\n\t\tconst startTime = Date.now() - 10;\n\n\t\treturn new SmoothScrollingOperation(from, to, startTime, duration);\n\t}\n}\n\nfunction easeInCubic(t: number) {\n\treturn Math.pow(t, 3);\n}\n\nfunction easeOutCubic(t: number) {\n\treturn 1 - easeInCubic(1 - t);\n}\n", "/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\nimport { FastDomNode } from 'vs/base/browser/fastDomNode';\nimport { TimeoutTimer } from 'vs/base/common/async';\nimport { Disposable } from 'vs/base/common/lifecycle';\nimport { ScrollbarVisibility } from 'vs/base/common/scrollable';\n\nexport class ScrollbarVisibilityController extends Disposable {\n\tprivate _visibility: ScrollbarVisibility;\n\tprivate _visibleClassName: string;\n\tprivate _invisibleClassName: string;\n\tprivate _domNode: FastDomNode | null;\n\tprivate _rawShouldBeVisible: boolean;\n\tprivate _shouldBeVisible: boolean;\n\tprivate _isNeeded: boolean;\n\tprivate _isVisible: boolean;\n\tprivate _revealTimer: TimeoutTimer;\n\n\tconstructor(visibility: ScrollbarVisibility, visibleClassName: string, invisibleClassName: string) {\n\t\tsuper();\n\t\tthis._visibility = visibility;\n\t\tthis._visibleClassName = visibleClassName;\n\t\tthis._invisibleClassName = invisibleClassName;\n\t\tthis._domNode = null;\n\t\tthis._isVisible = false;\n\t\tthis._isNeeded = false;\n\t\tthis._rawShouldBeVisible = false;\n\t\tthis._shouldBeVisible = false;\n\t\tthis._revealTimer = this._register(new TimeoutTimer());\n\t}\n\n\tpublic setVisibility(visibility: ScrollbarVisibility): void {\n\t\tif (this._visibility !== visibility) {\n\t\t\tthis._visibility = visibility;\n\t\t\tthis._updateShouldBeVisible();\n\t\t}\n\t}\n\n\t// ----------------- Hide / Reveal\n\n\tpublic setShouldBeVisible(rawShouldBeVisible: boolean): void {\n\t\tthis._rawShouldBeVisible = rawShouldBeVisible;\n\t\tthis._updateShouldBeVisible();\n\t}\n\n\tprivate _applyVisibilitySetting(): boolean {\n\t\tif (this._visibility === ScrollbarVisibility.Hidden) {\n\t\t\treturn false;\n\t\t}\n\t\tif (this._visibility === ScrollbarVisibility.Visible) {\n\t\t\treturn true;\n\t\t}\n\t\treturn this._rawShouldBeVisible;\n\t}\n\n\tprivate _updateShouldBeVisible(): void {\n\t\tconst shouldBeVisible = this._applyVisibilitySetting();\n\n\t\tif (this._shouldBeVisible !== shouldBeVisible) {\n\t\t\tthis._shouldBeVisible = shouldBeVisible;\n\t\t\tthis.ensureVisibility();\n\t\t}\n\t}\n\n\tpublic setIsNeeded(isNeeded: boolean): void {\n\t\tif (this._isNeeded !== isNeeded) {\n\t\t\tthis._isNeeded = isNeeded;\n\t\t\tthis.ensureVisibility();\n\t\t}\n\t}\n\n\tpublic setDomNode(domNode: FastDomNode): void {\n\t\tthis._domNode = domNode;\n\t\tthis._domNode.setClassName(this._invisibleClassName);\n\n\t\t// Now that the flags & the dom node are in a consistent state, ensure the Hidden/Visible configuration\n\t\tthis.setShouldBeVisible(false);\n\t}\n\n\tpublic ensureVisibility(): void {\n\n\t\tif (!this._isNeeded) {\n\t\t\t// Nothing to be rendered\n\t\t\tthis._hide(false);\n\t\t\treturn;\n\t\t}\n\n\t\tif (this._shouldBeVisible) {\n\t\t\tthis._reveal();\n\t\t} else {\n\t\t\tthis._hide(true);\n\t\t}\n\t}\n\n\tprivate _reveal(): void {\n\t\tif (this._isVisible) {\n\t\t\treturn;\n\t\t}\n\t\tthis._isVisible = true;\n\n\t\t// The CSS animation doesn't play otherwise\n\t\tthis._revealTimer.setIfNotSet(() => {\n\t\t\tthis._domNode?.setClassName(this._visibleClassName);\n\t\t}, 0);\n\t}\n\n\tprivate _hide(withFadeAway: boolean): void {\n\t\tthis._revealTimer.cancel();\n\t\tif (!this._isVisible) {\n\t\t\treturn;\n\t\t}\n\t\tthis._isVisible = false;\n\t\tthis._domNode?.setClassName(this._invisibleClassName + (withFadeAway ? ' fade' : ''));\n\t}\n}\n", "/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\nimport * as dom from 'vs/base/browser/dom';\nimport { createFastDomNode, FastDomNode } from 'vs/base/browser/fastDomNode';\nimport { GlobalPointerMoveMonitor } from 'vs/base/browser/globalPointerMoveMonitor';\nimport { StandardWheelEvent } from 'vs/base/browser/mouseEvent';\nimport { ScrollbarArrow, ScrollbarArrowOptions } from 'vs/base/browser/ui/scrollbar/scrollbarArrow';\nimport { ScrollbarState } from 'vs/base/browser/ui/scrollbar/scrollbarState';\nimport { ScrollbarVisibilityController } from 'vs/base/browser/ui/scrollbar/scrollbarVisibilityController';\nimport { Widget } from 'vs/base/browser/ui/widget';\nimport * as platform from 'vs/base/common/platform';\nimport { INewScrollPosition, Scrollable, ScrollbarVisibility } from 'vs/base/common/scrollable';\n\n/**\n * The orthogonal distance to the slider at which dragging \"resets\". This implements \"snapping\"\n */\nconst POINTER_DRAG_RESET_DISTANCE = 140;\n\nexport interface ISimplifiedPointerEvent {\n\tbuttons: number;\n\tpageX: number;\n\tpageY: number;\n}\n\nexport interface ScrollbarHost {\n\tonMouseWheel(mouseWheelEvent: StandardWheelEvent): void;\n\tonDragStart(): void;\n\tonDragEnd(): void;\n}\n\nexport interface AbstractScrollbarOptions {\n\tlazyRender: boolean;\n\thost: ScrollbarHost;\n\tscrollbarState: ScrollbarState;\n\tvisibility: ScrollbarVisibility;\n\textraScrollbarClassName: string;\n\tscrollable: Scrollable;\n\tscrollByPage: boolean;\n}\n\nexport abstract class AbstractScrollbar extends Widget {\n\n\tprotected _host: ScrollbarHost;\n\tprotected _scrollable: Scrollable;\n\tprotected _scrollByPage: boolean;\n\tprivate _lazyRender: boolean;\n\tprotected _scrollbarState: ScrollbarState;\n\tprotected _visibilityController: ScrollbarVisibilityController;\n\tprivate _pointerMoveMonitor: GlobalPointerMoveMonitor;\n\n\tpublic domNode: FastDomNode;\n\tpublic slider!: FastDomNode;\n\n\tprotected _shouldRender: boolean;\n\n\tconstructor(opts: AbstractScrollbarOptions) {\n\t\tsuper();\n\t\tthis._lazyRender = opts.lazyRender;\n\t\tthis._host = opts.host;\n\t\tthis._scrollable = opts.scrollable;\n\t\tthis._scrollByPage = opts.scrollByPage;\n\t\tthis._scrollbarState = opts.scrollbarState;\n\t\tthis._visibilityController = this._register(new ScrollbarVisibilityController(opts.visibility, 'visible scrollbar ' + opts.extraScrollbarClassName, 'invisible scrollbar ' + opts.extraScrollbarClassName));\n\t\tthis._visibilityController.setIsNeeded(this._scrollbarState.isNeeded());\n\t\tthis._pointerMoveMonitor = this._register(new GlobalPointerMoveMonitor());\n\t\tthis._shouldRender = true;\n\t\tthis.domNode = createFastDomNode(document.createElement('div'));\n\t\tthis.domNode.setAttribute('role', 'presentation');\n\t\tthis.domNode.setAttribute('aria-hidden', 'true');\n\n\t\tthis._visibilityController.setDomNode(this.domNode);\n\t\tthis.domNode.setPosition('absolute');\n\n\t\tthis._register(dom.addDisposableListener(this.domNode.domNode, dom.EventType.POINTER_DOWN, (e: PointerEvent) => this._domNodePointerDown(e)));\n\t}\n\n\t// ----------------- creation\n\n\t/**\n\t * Creates the dom node for an arrow & adds it to the container\n\t */\n\tprotected _createArrow(opts: ScrollbarArrowOptions): void {\n\t\tconst arrow = this._register(new ScrollbarArrow(opts));\n\t\tthis.domNode.domNode.appendChild(arrow.bgDomNode);\n\t\tthis.domNode.domNode.appendChild(arrow.domNode);\n\t}\n\n\t/**\n\t * Creates the slider dom node, adds it to the container & hooks up the events\n\t */\n\tprotected _createSlider(top: number, left: number, width: number | undefined, height: number | undefined): void {\n\t\tthis.slider = createFastDomNode(document.createElement('div'));\n\t\tthis.slider.setClassName('slider');\n\t\tthis.slider.setPosition('absolute');\n\t\tthis.slider.setTop(top);\n\t\tthis.slider.setLeft(left);\n\t\tif (typeof width === 'number') {\n\t\t\tthis.slider.setWidth(width);\n\t\t}\n\t\tif (typeof height === 'number') {\n\t\t\tthis.slider.setHeight(height);\n\t\t}\n\t\tthis.slider.setLayerHinting(true);\n\t\tthis.slider.setContain('strict');\n\n\t\tthis.domNode.domNode.appendChild(this.slider.domNode);\n\n\t\tthis._register(dom.addDisposableListener(\n\t\t\tthis.slider.domNode,\n\t\t\tdom.EventType.POINTER_DOWN,\n\t\t\t(e: PointerEvent) => {\n\t\t\t\tif (e.button === 0) {\n\t\t\t\t\te.preventDefault();\n\t\t\t\t\tthis._sliderPointerDown(e);\n\t\t\t\t}\n\t\t\t}\n\t\t));\n\n\t\tthis.onclick(this.slider.domNode, e => {\n\t\t\tif (e.leftButton) {\n\t\t\t\te.stopPropagation();\n\t\t\t}\n\t\t});\n\t}\n\n\t// ----------------- Update state\n\n\tprotected _onElementSize(visibleSize: number): boolean {\n\t\tif (this._scrollbarState.setVisibleSize(visibleSize)) {\n\t\t\tthis._visibilityController.setIsNeeded(this._scrollbarState.isNeeded());\n\t\t\tthis._shouldRender = true;\n\t\t\tif (!this._lazyRender) {\n\t\t\t\tthis.render();\n\t\t\t}\n\t\t}\n\t\treturn this._shouldRender;\n\t}\n\n\tprotected _onElementScrollSize(elementScrollSize: number): boolean {\n\t\tif (this._scrollbarState.setScrollSize(elementScrollSize)) {\n\t\t\tthis._visibilityController.setIsNeeded(this._scrollbarState.isNeeded());\n\t\t\tthis._shouldRender = true;\n\t\t\tif (!this._lazyRender) {\n\t\t\t\tthis.render();\n\t\t\t}\n\t\t}\n\t\treturn this._shouldRender;\n\t}\n\n\tprotected _onElementScrollPosition(elementScrollPosition: number): boolean {\n\t\tif (this._scrollbarState.setScrollPosition(elementScrollPosition)) {\n\t\t\tthis._visibilityController.setIsNeeded(this._scrollbarState.isNeeded());\n\t\t\tthis._shouldRender = true;\n\t\t\tif (!this._lazyRender) {\n\t\t\t\tthis.render();\n\t\t\t}\n\t\t}\n\t\treturn this._shouldRender;\n\t}\n\n\t// ----------------- rendering\n\n\tpublic beginReveal(): void {\n\t\tthis._visibilityController.setShouldBeVisible(true);\n\t}\n\n\tpublic beginHide(): void {\n\t\tthis._visibilityController.setShouldBeVisible(false);\n\t}\n\n\tpublic render(): void {\n\t\tif (!this._shouldRender) {\n\t\t\treturn;\n\t\t}\n\t\tthis._shouldRender = false;\n\n\t\tthis._renderDomNode(this._scrollbarState.getRectangleLargeSize(), this._scrollbarState.getRectangleSmallSize());\n\t\tthis._updateSlider(this._scrollbarState.getSliderSize(), this._scrollbarState.getArrowSize() + this._scrollbarState.getSliderPosition());\n\t}\n\t// ----------------- DOM events\n\n\tprivate _domNodePointerDown(e: PointerEvent): void {\n\t\tif (e.target !== this.domNode.domNode) {\n\t\t\treturn;\n\t\t}\n\t\tthis._onPointerDown(e);\n\t}\n\n\tpublic delegatePointerDown(e: PointerEvent): void {\n\t\tconst domTop = this.domNode.domNode.getClientRects()[0].top;\n\t\tconst sliderStart = domTop + this._scrollbarState.getSliderPosition();\n\t\tconst sliderStop = domTop + this._scrollbarState.getSliderPosition() + this._scrollbarState.getSliderSize();\n\t\tconst pointerPos = this._sliderPointerPosition(e);\n\t\tif (sliderStart <= pointerPos && pointerPos <= sliderStop) {\n\t\t\t// Act as if it was a pointer down on the slider\n\t\t\tif (e.button === 0) {\n\t\t\t\te.preventDefault();\n\t\t\t\tthis._sliderPointerDown(e);\n\t\t\t}\n\t\t} else {\n\t\t\t// Act as if it was a pointer down on the scrollbar\n\t\t\tthis._onPointerDown(e);\n\t\t}\n\t}\n\n\tprivate _onPointerDown(e: PointerEvent): void {\n\t\tlet offsetX: number;\n\t\tlet offsetY: number;\n\t\tif (e.target === this.domNode.domNode && typeof e.offsetX === 'number' && typeof e.offsetY === 'number') {\n\t\t\toffsetX = e.offsetX;\n\t\t\toffsetY = e.offsetY;\n\t\t} else {\n\t\t\tconst domNodePosition = dom.getDomNodePagePosition(this.domNode.domNode);\n\t\t\toffsetX = e.pageX - domNodePosition.left;\n\t\t\toffsetY = e.pageY - domNodePosition.top;\n\t\t}\n\n\t\tconst offset = this._pointerDownRelativePosition(offsetX, offsetY);\n\t\tthis._setDesiredScrollPositionNow(\n\t\t\tthis._scrollByPage\n\t\t\t\t? this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(offset)\n\t\t\t\t: this._scrollbarState.getDesiredScrollPositionFromOffset(offset)\n\t\t);\n\n\t\tif (e.button === 0) {\n\t\t\t// left button\n\t\t\te.preventDefault();\n\t\t\tthis._sliderPointerDown(e);\n\t\t}\n\t}\n\n\tprivate _sliderPointerDown(e: PointerEvent): void {\n\t\tif (!e.target || !(e.target instanceof Element)) {\n\t\t\treturn;\n\t\t}\n\t\tconst initialPointerPosition = this._sliderPointerPosition(e);\n\t\tconst initialPointerOrthogonalPosition = this._sliderOrthogonalPointerPosition(e);\n\t\tconst initialScrollbarState = this._scrollbarState.clone();\n\t\tthis.slider.toggleClassName('active', true);\n\n\t\tthis._pointerMoveMonitor.startMonitoring(\n\t\t\te.target,\n\t\t\te.pointerId,\n\t\t\te.buttons,\n\t\t\t(pointerMoveData: PointerEvent) => {\n\t\t\t\tconst pointerOrthogonalPosition = this._sliderOrthogonalPointerPosition(pointerMoveData);\n\t\t\t\tconst pointerOrthogonalDelta = Math.abs(pointerOrthogonalPosition - initialPointerOrthogonalPosition);\n\n\t\t\t\tif (platform.isWindows && pointerOrthogonalDelta > POINTER_DRAG_RESET_DISTANCE) {\n\t\t\t\t\t// The pointer has wondered away from the scrollbar => reset dragging\n\t\t\t\t\tthis._setDesiredScrollPositionNow(initialScrollbarState.getScrollPosition());\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst pointerPosition = this._sliderPointerPosition(pointerMoveData);\n\t\t\t\tconst pointerDelta = pointerPosition - initialPointerPosition;\n\t\t\t\tthis._setDesiredScrollPositionNow(initialScrollbarState.getDesiredScrollPositionFromDelta(pointerDelta));\n\t\t\t},\n\t\t\t() => {\n\t\t\t\tthis.slider.toggleClassName('active', false);\n\t\t\t\tthis._host.onDragEnd();\n\t\t\t}\n\t\t);\n\n\t\tthis._host.onDragStart();\n\t}\n\n\tprivate _setDesiredScrollPositionNow(_desiredScrollPosition: number): void {\n\n\t\tconst desiredScrollPosition: INewScrollPosition = {};\n\t\tthis.writeScrollPosition(desiredScrollPosition, _desiredScrollPosition);\n\n\t\tthis._scrollable.setScrollPositionNow(desiredScrollPosition);\n\t}\n\n\tpublic updateScrollbarSize(scrollbarSize: number): void {\n\t\tthis._updateScrollbarSize(scrollbarSize);\n\t\tthis._scrollbarState.setScrollbarSize(scrollbarSize);\n\t\tthis._shouldRender = true;\n\t\tif (!this._lazyRender) {\n\t\t\tthis.render();\n\t\t}\n\t}\n\n\tpublic isNeeded(): boolean {\n\t\treturn this._scrollbarState.isNeeded();\n\t}\n\n\t// ----------------- Overwrite these\n\n\tprotected abstract _renderDomNode(largeSize: number, smallSize: number): void;\n\tprotected abstract _updateSlider(sliderSize: number, sliderPosition: number): void;\n\n\tprotected abstract _pointerDownRelativePosition(offsetX: number, offsetY: number): number;\n\tprotected abstract _sliderPointerPosition(e: ISimplifiedPointerEvent): number;\n\tprotected abstract _sliderOrthogonalPointerPosition(e: ISimplifiedPointerEvent): number;\n\tprotected abstract _updateScrollbarSize(size: number): void;\n\n\tpublic abstract writeScrollPosition(target: INewScrollPosition, scrollPosition: number): void;\n}\n", "/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n/**\n * The minimal size of the slider (such that it can still be clickable) -- it is artificially enlarged.\n */\nconst MINIMUM_SLIDER_SIZE = 20;\n\nexport class ScrollbarState {\n\n\t/**\n\t * For the vertical scrollbar: the width.\n\t * For the horizontal scrollbar: the height.\n\t */\n\tprivate _scrollbarSize: number;\n\n\t/**\n\t * For the vertical scrollbar: the height of the pair horizontal scrollbar.\n\t * For the horizontal scrollbar: the width of the pair vertical scrollbar.\n\t */\n\tprivate _oppositeScrollbarSize: number;\n\n\t/**\n\t * For the vertical scrollbar: the height of the scrollbar's arrows.\n\t * For the horizontal scrollbar: the width of the scrollbar's arrows.\n\t */\n\tprivate readonly _arrowSize: number;\n\n\t// --- variables\n\t/**\n\t * For the vertical scrollbar: the viewport height.\n\t * For the horizontal scrollbar: the viewport width.\n\t */\n\tprivate _visibleSize: number;\n\n\t/**\n\t * For the vertical scrollbar: the scroll height.\n\t * For the horizontal scrollbar: the scroll width.\n\t */\n\tprivate _scrollSize: number;\n\n\t/**\n\t * For the vertical scrollbar: the scroll top.\n\t * For the horizontal scrollbar: the scroll left.\n\t */\n\tprivate _scrollPosition: number;\n\n\t// --- computed variables\n\n\t/**\n\t * `visibleSize` - `oppositeScrollbarSize`\n\t */\n\tprivate _computedAvailableSize: number;\n\t/**\n\t * (`scrollSize` > 0 && `scrollSize` > `visibleSize`)\n\t */\n\tprivate _computedIsNeeded: boolean;\n\n\tprivate _computedSliderSize: number;\n\tprivate _computedSliderRatio: number;\n\tprivate _computedSliderPosition: number;\n\n\tconstructor(arrowSize: number, scrollbarSize: number, oppositeScrollbarSize: number, visibleSize: number, scrollSize: number, scrollPosition: number) {\n\t\tthis._scrollbarSize = Math.round(scrollbarSize);\n\t\tthis._oppositeScrollbarSize = Math.round(oppositeScrollbarSize);\n\t\tthis._arrowSize = Math.round(arrowSize);\n\n\t\tthis._visibleSize = visibleSize;\n\t\tthis._scrollSize = scrollSize;\n\t\tthis._scrollPosition = scrollPosition;\n\n\t\tthis._computedAvailableSize = 0;\n\t\tthis._computedIsNeeded = false;\n\t\tthis._computedSliderSize = 0;\n\t\tthis._computedSliderRatio = 0;\n\t\tthis._computedSliderPosition = 0;\n\n\t\tthis._refreshComputedValues();\n\t}\n\n\tpublic clone(): ScrollbarState {\n\t\treturn new ScrollbarState(this._arrowSize, this._scrollbarSize, this._oppositeScrollbarSize, this._visibleSize, this._scrollSize, this._scrollPosition);\n\t}\n\n\tpublic setVisibleSize(visibleSize: number): boolean {\n\t\tconst iVisibleSize = Math.round(visibleSize);\n\t\tif (this._visibleSize !== iVisibleSize) {\n\t\t\tthis._visibleSize = iVisibleSize;\n\t\t\tthis._refreshComputedValues();\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic setScrollSize(scrollSize: number): boolean {\n\t\tconst iScrollSize = Math.round(scrollSize);\n\t\tif (this._scrollSize !== iScrollSize) {\n\t\t\tthis._scrollSize = iScrollSize;\n\t\t\tthis._refreshComputedValues();\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic setScrollPosition(scrollPosition: number): boolean {\n\t\tconst iScrollPosition = Math.round(scrollPosition);\n\t\tif (this._scrollPosition !== iScrollPosition) {\n\t\t\tthis._scrollPosition = iScrollPosition;\n\t\t\tthis._refreshComputedValues();\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic setScrollbarSize(scrollbarSize: number): void {\n\t\tthis._scrollbarSize = Math.round(scrollbarSize);\n\t}\n\n\tpublic setOppositeScrollbarSize(oppositeScrollbarSize: number): void {\n\t\tthis._oppositeScrollbarSize = Math.round(oppositeScrollbarSize);\n\t}\n\n\tprivate static _computeValues(oppositeScrollbarSize: number, arrowSize: number, visibleSize: number, scrollSize: number, scrollPosition: number) {\n\t\tconst computedAvailableSize = Math.max(0, visibleSize - oppositeScrollbarSize);\n\t\tconst computedRepresentableSize = Math.max(0, computedAvailableSize - 2 * arrowSize);\n\t\tconst computedIsNeeded = (scrollSize > 0 && scrollSize > visibleSize);\n\n\t\tif (!computedIsNeeded) {\n\t\t\t// There is no need for a slider\n\t\t\treturn {\n\t\t\t\tcomputedAvailableSize: Math.round(computedAvailableSize),\n\t\t\t\tcomputedIsNeeded: computedIsNeeded,\n\t\t\t\tcomputedSliderSize: Math.round(computedRepresentableSize),\n\t\t\t\tcomputedSliderRatio: 0,\n\t\t\t\tcomputedSliderPosition: 0,\n\t\t\t};\n\t\t}\n\n\t\t// We must artificially increase the size of the slider if needed, since the slider would be too small to grab with the mouse otherwise\n\t\tconst computedSliderSize = Math.round(Math.max(MINIMUM_SLIDER_SIZE, Math.floor(visibleSize * computedRepresentableSize / scrollSize)));\n\n\t\t// The slider can move from 0 to `computedRepresentableSize` - `computedSliderSize`\n\t\t// in the same way `scrollPosition` can move from 0 to `scrollSize` - `visibleSize`.\n\t\tconst computedSliderRatio = (computedRepresentableSize - computedSliderSize) / (scrollSize - visibleSize);\n\t\tconst computedSliderPosition = (scrollPosition * computedSliderRatio);\n\n\t\treturn {\n\t\t\tcomputedAvailableSize: Math.round(computedAvailableSize),\n\t\t\tcomputedIsNeeded: computedIsNeeded,\n\t\t\tcomputedSliderSize: Math.round(computedSliderSize),\n\t\t\tcomputedSliderRatio: computedSliderRatio,\n\t\t\tcomputedSliderPosition: Math.round(computedSliderPosition),\n\t\t};\n\t}\n\n\tprivate _refreshComputedValues(): void {\n\t\tconst r = ScrollbarState._computeValues(this._oppositeScrollbarSize, this._arrowSize, this._visibleSize, this._scrollSize, this._scrollPosition);\n\t\tthis._computedAvailableSize = r.computedAvailableSize;\n\t\tthis._computedIsNeeded = r.computedIsNeeded;\n\t\tthis._computedSliderSize = r.computedSliderSize;\n\t\tthis._computedSliderRatio = r.computedSliderRatio;\n\t\tthis._computedSliderPosition = r.computedSliderPosition;\n\t}\n\n\tpublic getArrowSize(): number {\n\t\treturn this._arrowSize;\n\t}\n\n\tpublic getScrollPosition(): number {\n\t\treturn this._scrollPosition;\n\t}\n\n\tpublic getRectangleLargeSize(): number {\n\t\treturn this._computedAvailableSize;\n\t}\n\n\tpublic getRectangleSmallSize(): number {\n\t\treturn this._scrollbarSize;\n\t}\n\n\tpublic isNeeded(): boolean {\n\t\treturn this._computedIsNeeded;\n\t}\n\n\tpublic getSliderSize(): number {\n\t\treturn this._computedSliderSize;\n\t}\n\n\tpublic getSliderPosition(): number {\n\t\treturn this._computedSliderPosition;\n\t}\n\n\t/**\n\t * Compute a desired `scrollPosition` such that `offset` ends up in the center of the slider.\n\t * `offset` is based on the same coordinate system as the `sliderPosition`.\n\t */\n\tpublic getDesiredScrollPositionFromOffset(offset: number): number {\n\t\tif (!this._computedIsNeeded) {\n\t\t\t// no need for a slider\n\t\t\treturn 0;\n\t\t}\n\n\t\tconst desiredSliderPosition = offset - this._arrowSize - this._computedSliderSize / 2;\n\t\treturn Math.round(desiredSliderPosition / this._computedSliderRatio);\n\t}\n\n\t/**\n\t * Compute a desired `scrollPosition` from if offset is before or after the slider position.\n\t * If offset is before slider, treat as a page up (or left). If after, page down (or right).\n\t * `offset` and `_computedSliderPosition` are based on the same coordinate system.\n\t * `_visibleSize` corresponds to a \"page\" of lines in the returned coordinate system.\n\t */\n\tpublic getDesiredScrollPositionFromOffsetPaged(offset: number): number {\n\t\tif (!this._computedIsNeeded) {\n\t\t\t// no need for a slider\n\t\t\treturn 0;\n\t\t}\n\n\t\tconst correctedOffset = offset - this._arrowSize; // compensate if has arrows\n\t\tlet desiredScrollPosition = this._scrollPosition;\n\t\tif (correctedOffset < this._computedSliderPosition) {\n\t\t\tdesiredScrollPosition -= this._visibleSize; // page up/left\n\t\t} else {\n\t\t\tdesiredScrollPosition += this._visibleSize; // page down/right\n\t\t}\n\t\treturn desiredScrollPosition;\n\t}\n\n\t/**\n\t * Compute a desired `scrollPosition` such that the slider moves by `delta`.\n\t */\n\tpublic getDesiredScrollPositionFromDelta(delta: number): number {\n\t\tif (!this._computedIsNeeded) {\n\t\t\t// no need for a slider\n\t\t\treturn 0;\n\t\t}\n\n\t\tconst desiredSliderPosition = this._computedSliderPosition + delta;\n\t\treturn Math.round(desiredSliderPosition / this._computedSliderRatio);\n\t}\n}\n", "/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\nimport { AbstractScrollbar, ISimplifiedPointerEvent, ScrollbarHost } from 'vs/base/browser/ui/scrollbar/abstractScrollbar';\nimport { ScrollableElementResolvedOptions } from 'vs/base/browser/ui/scrollbar/scrollableElementOptions';\nimport { ScrollbarState } from 'vs/base/browser/ui/scrollbar/scrollbarState';\nimport { INewScrollPosition, Scrollable, ScrollbarVisibility, ScrollEvent } from 'vs/base/common/scrollable';\n\n\n\n\nexport class HorizontalScrollbar extends AbstractScrollbar {\n\n\tconstructor(scrollable: Scrollable, options: ScrollableElementResolvedOptions, host: ScrollbarHost) {\n\t\tconst scrollDimensions = scrollable.getScrollDimensions();\n\t\tconst scrollPosition = scrollable.getCurrentScrollPosition();\n\t\tsuper({\n\t\t\tlazyRender: options.lazyRender,\n\t\t\thost: host,\n\t\t\tscrollbarState: new ScrollbarState(\n\t\t\t\t(options.horizontalHasArrows ? options.arrowSize : 0),\n\t\t\t\t(options.horizontal === ScrollbarVisibility.Hidden ? 0 : options.horizontalScrollbarSize),\n\t\t\t\t(options.vertical === ScrollbarVisibility.Hidden ? 0 : options.verticalScrollbarSize),\n\t\t\t\tscrollDimensions.width,\n\t\t\t\tscrollDimensions.scrollWidth,\n\t\t\t\tscrollPosition.scrollLeft\n\t\t\t),\n\t\t\tvisibility: options.horizontal,\n\t\t\textraScrollbarClassName: 'horizontal',\n\t\t\tscrollable: scrollable,\n\t\t\tscrollByPage: options.scrollByPage\n\t\t});\n\n\t\tif (options.horizontalHasArrows) {\n throw new Error('horizontalHasArrows is not supported in xterm.js');\n\t\t\t// const arrowDelta = (options.arrowSize - ARROW_IMG_SIZE) / 2;\n\t\t\t// const scrollbarDelta = (options.horizontalScrollbarSize - ARROW_IMG_SIZE) / 2;\n\n\t\t\t// this._createArrow({\n\t\t\t// \tclassName: 'scra',\n\t\t\t// \ticon: Codicon.scrollbarButtonLeft,\n\t\t\t// \ttop: scrollbarDelta,\n\t\t\t// \tleft: arrowDelta,\n\t\t\t// \tbottom: undefined,\n\t\t\t// \tright: undefined,\n\t\t\t// \tbgWidth: options.arrowSize,\n\t\t\t// \tbgHeight: options.horizontalScrollbarSize,\n\t\t\t// \tonActivate: () => this._host.onMouseWheel(new StandardWheelEvent(null, 1, 0)),\n\t\t\t// });\n\n\t\t\t// this._createArrow({\n\t\t\t// \tclassName: 'scra',\n\t\t\t// \ticon: Codicon.scrollbarButtonRight,\n\t\t\t// \ttop: scrollbarDelta,\n\t\t\t// \tleft: undefined,\n\t\t\t// \tbottom: undefined,\n\t\t\t// \tright: arrowDelta,\n\t\t\t// \tbgWidth: options.arrowSize,\n\t\t\t// \tbgHeight: options.horizontalScrollbarSize,\n\t\t\t// \tonActivate: () => this._host.onMouseWheel(new StandardWheelEvent(null, -1, 0)),\n\t\t\t// });\n\t\t}\n\n\t\tthis._createSlider(Math.floor((options.horizontalScrollbarSize - options.horizontalSliderSize) / 2), 0, undefined, options.horizontalSliderSize);\n\t}\n\n\tprotected _updateSlider(sliderSize: number, sliderPosition: number): void {\n\t\tthis.slider.setWidth(sliderSize);\n\t\tthis.slider.setLeft(sliderPosition);\n\t}\n\n\tprotected _renderDomNode(largeSize: number, smallSize: number): void {\n\t\tthis.domNode.setWidth(largeSize);\n\t\tthis.domNode.setHeight(smallSize);\n\t\tthis.domNode.setLeft(0);\n\t\tthis.domNode.setBottom(0);\n\t}\n\n\tpublic onDidScroll(e: ScrollEvent): boolean {\n\t\tthis._shouldRender = this._onElementScrollSize(e.scrollWidth) || this._shouldRender;\n\t\tthis._shouldRender = this._onElementScrollPosition(e.scrollLeft) || this._shouldRender;\n\t\tthis._shouldRender = this._onElementSize(e.width) || this._shouldRender;\n\t\treturn this._shouldRender;\n\t}\n\n\tprotected _pointerDownRelativePosition(offsetX: number, offsetY: number): number {\n\t\treturn offsetX;\n\t}\n\n\tprotected _sliderPointerPosition(e: ISimplifiedPointerEvent): number {\n\t\treturn e.pageX;\n\t}\n\n\tprotected _sliderOrthogonalPointerPosition(e: ISimplifiedPointerEvent): number {\n\t\treturn e.pageY;\n\t}\n\n\tprotected _updateScrollbarSize(size: number): void {\n\t\tthis.slider.setHeight(size);\n\t}\n\n\tpublic writeScrollPosition(target: INewScrollPosition, scrollPosition: number): void {\n\t\ttarget.scrollLeft = scrollPosition;\n\t}\n\n\tpublic updateOptions(options: ScrollableElementResolvedOptions): void {\n\t\tthis.updateScrollbarSize(options.horizontal === ScrollbarVisibility.Hidden ? 0 : options.horizontalScrollbarSize);\n\t\tthis._scrollbarState.setOppositeScrollbarSize(options.vertical === ScrollbarVisibility.Hidden ? 0 : options.verticalScrollbarSize);\n\t\tthis._visibilityController.setVisibility(options.horizontal);\n\t\tthis._scrollByPage = options.scrollByPage;\n\t}\n}\n", "/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\nimport { AbstractScrollbar, ISimplifiedPointerEvent, ScrollbarHost } from 'vs/base/browser/ui/scrollbar/abstractScrollbar';\nimport { ScrollableElementResolvedOptions } from 'vs/base/browser/ui/scrollbar/scrollableElementOptions';\nimport { ScrollbarState } from 'vs/base/browser/ui/scrollbar/scrollbarState';\nimport { INewScrollPosition, Scrollable, ScrollbarVisibility, ScrollEvent } from 'vs/base/common/scrollable';\n\n\n\nexport class VerticalScrollbar extends AbstractScrollbar {\n\n\tconstructor(scrollable: Scrollable, options: ScrollableElementResolvedOptions, host: ScrollbarHost) {\n\t\tconst scrollDimensions = scrollable.getScrollDimensions();\n\t\tconst scrollPosition = scrollable.getCurrentScrollPosition();\n\t\tsuper({\n\t\t\tlazyRender: options.lazyRender,\n\t\t\thost: host,\n\t\t\tscrollbarState: new ScrollbarState(\n\t\t\t\t(options.verticalHasArrows ? options.arrowSize : 0),\n\t\t\t\t(options.vertical === ScrollbarVisibility.Hidden ? 0 : options.verticalScrollbarSize),\n\t\t\t\t// give priority to vertical scroll bar over horizontal and let it scroll all the way to the bottom\n\t\t\t\t0,\n\t\t\t\tscrollDimensions.height,\n\t\t\t\tscrollDimensions.scrollHeight,\n\t\t\t\tscrollPosition.scrollTop\n\t\t\t),\n\t\t\tvisibility: options.vertical,\n\t\t\textraScrollbarClassName: 'vertical',\n\t\t\tscrollable: scrollable,\n\t\t\tscrollByPage: options.scrollByPage\n\t\t});\n\n\t\tif (options.verticalHasArrows) {\n throw new Error('horizontalHasArrows is not supported in xterm.js');\n\t\t\t// const arrowDelta = (options.arrowSize - ARROW_IMG_SIZE) / 2;\n\t\t\t// const scrollbarDelta = (options.verticalScrollbarSize - ARROW_IMG_SIZE) / 2;\n\n\t\t\t// this._createArrow({\n\t\t\t// \tclassName: 'scra',\n\t\t\t// \ticon: Codicon.scrollbarButtonUp,\n\t\t\t// \ttop: arrowDelta,\n\t\t\t// \tleft: scrollbarDelta,\n\t\t\t// \tbottom: undefined,\n\t\t\t// \tright: undefined,\n\t\t\t// \tbgWidth: options.verticalScrollbarSize,\n\t\t\t// \tbgHeight: options.arrowSize,\n\t\t\t// \tonActivate: () => this._host.onMouseWheel(new StandardWheelEvent(null, 0, 1)),\n\t\t\t// });\n\n\t\t\t// this._createArrow({\n\t\t\t// \tclassName: 'scra',\n\t\t\t// \ticon: Codicon.scrollbarButtonDown,\n\t\t\t// \ttop: undefined,\n\t\t\t// \tleft: scrollbarDelta,\n\t\t\t// \tbottom: arrowDelta,\n\t\t\t// \tright: undefined,\n\t\t\t// \tbgWidth: options.verticalScrollbarSize,\n\t\t\t// \tbgHeight: options.arrowSize,\n\t\t\t// \tonActivate: () => this._host.onMouseWheel(new StandardWheelEvent(null, 0, -1)),\n\t\t\t// });\n\t\t}\n\n\t\tthis._createSlider(0, Math.floor((options.verticalScrollbarSize - options.verticalSliderSize) / 2), options.verticalSliderSize, undefined);\n\t}\n\n\tprotected _updateSlider(sliderSize: number, sliderPosition: number): void {\n\t\tthis.slider.setHeight(sliderSize);\n\t\tthis.slider.setTop(sliderPosition);\n\t}\n\n\tprotected _renderDomNode(largeSize: number, smallSize: number): void {\n\t\tthis.domNode.setWidth(smallSize);\n\t\tthis.domNode.setHeight(largeSize);\n\t\tthis.domNode.setRight(0);\n\t\tthis.domNode.setTop(0);\n\t}\n\n\tpublic onDidScroll(e: ScrollEvent): boolean {\n\t\tthis._shouldRender = this._onElementScrollSize(e.scrollHeight) || this._shouldRender;\n\t\tthis._shouldRender = this._onElementScrollPosition(e.scrollTop) || this._shouldRender;\n\t\tthis._shouldRender = this._onElementSize(e.height) || this._shouldRender;\n\t\treturn this._shouldRender;\n\t}\n\n\tprotected _pointerDownRelativePosition(offsetX: number, offsetY: number): number {\n\t\treturn offsetY;\n\t}\n\n\tprotected _sliderPointerPosition(e: ISimplifiedPointerEvent): number {\n\t\treturn e.pageY;\n\t}\n\n\tprotected _sliderOrthogonalPointerPosition(e: ISimplifiedPointerEvent): number {\n\t\treturn e.pageX;\n\t}\n\n\tprotected _updateScrollbarSize(size: number): void {\n\t\tthis.slider.setWidth(size);\n\t}\n\n\tpublic writeScrollPosition(target: INewScrollPosition, scrollPosition: number): void {\n\t\ttarget.scrollTop = scrollPosition;\n\t}\n\n\tpublic updateOptions(options: ScrollableElementResolvedOptions): void {\n\t\tthis.updateScrollbarSize(options.vertical === ScrollbarVisibility.Hidden ? 0 : options.verticalScrollbarSize);\n\t\t// give priority to vertical scroll bar over horizontal and let it scroll all the way to the bottom\n\t\tthis._scrollbarState.setOppositeScrollbarSize(0);\n\t\tthis._visibilityController.setVisibility(options.vertical);\n\t\tthis._scrollByPage = options.scrollByPage;\n\t}\n\n}\n", "/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\nimport { getZoomFactor, isChrome } from 'vs/base/browser/browser';\nimport * as dom from 'vs/base/browser/dom';\nimport { FastDomNode, createFastDomNode } from 'vs/base/browser/fastDomNode';\nimport { IMouseEvent, IMouseWheelEvent, StandardWheelEvent } from 'vs/base/browser/mouseEvent';\nimport { ScrollbarHost } from 'vs/base/browser/ui/scrollbar/abstractScrollbar';\nimport { HorizontalScrollbar } from 'vs/base/browser/ui/scrollbar/horizontalScrollbar';\nimport { ScrollableElementChangeOptions, ScrollableElementCreationOptions, ScrollableElementResolvedOptions } from 'vs/base/browser/ui/scrollbar/scrollableElementOptions';\nimport { VerticalScrollbar } from 'vs/base/browser/ui/scrollbar/verticalScrollbar';\nimport { Widget } from 'vs/base/browser/ui/widget';\nimport { TimeoutTimer } from 'vs/base/common/async';\nimport { Emitter, Event } from 'vs/base/common/event';\nimport { IDisposable, dispose } from 'vs/base/common/lifecycle';\nimport * as platform from 'vs/base/common/platform';\nimport { INewScrollDimensions, INewScrollPosition, IScrollDimensions, IScrollPosition, ScrollEvent, Scrollable, ScrollbarVisibility } from 'vs/base/common/scrollable';\n// import 'vs/css!./media/scrollbars';\n\nconst HIDE_TIMEOUT = 500;\nconst SCROLL_WHEEL_SENSITIVITY = 50;\nconst SCROLL_WHEEL_SMOOTH_SCROLL_ENABLED = true;\n\nexport interface IOverviewRulerLayoutInfo {\n\tparent: HTMLElement;\n\tinsertBefore: HTMLElement;\n}\n\nclass MouseWheelClassifierItem {\n\tpublic timestamp: number;\n\tpublic deltaX: number;\n\tpublic deltaY: number;\n\tpublic score: number;\n\n\tconstructor(timestamp: number, deltaX: number, deltaY: number) {\n\t\tthis.timestamp = timestamp;\n\t\tthis.deltaX = deltaX;\n\t\tthis.deltaY = deltaY;\n\t\tthis.score = 0;\n\t}\n}\n\nexport class MouseWheelClassifier {\n\n\tpublic static readonly INSTANCE = new MouseWheelClassifier();\n\n\tprivate readonly _capacity: number;\n\tprivate _memory: MouseWheelClassifierItem[];\n\tprivate _front: number;\n\tprivate _rear: number;\n\n\tconstructor() {\n\t\tthis._capacity = 5;\n\t\tthis._memory = [];\n\t\tthis._front = -1;\n\t\tthis._rear = -1;\n\t}\n\n\tpublic isPhysicalMouseWheel(): boolean {\n\t\tif (this._front === -1 && this._rear === -1) {\n\t\t\t// no elements\n\t\t\treturn false;\n\t\t}\n\n\t\t// 0.5 * last + 0.25 * 2nd last + 0.125 * 3rd last + ...\n\t\tlet remainingInfluence = 1;\n\t\tlet score = 0;\n\t\tlet iteration = 1;\n\n\t\tlet index = this._rear;\n\t\tdo {\n\t\t\tconst influence = (index === this._front ? remainingInfluence : Math.pow(2, -iteration));\n\t\t\tremainingInfluence -= influence;\n\t\t\tscore += this._memory[index].score * influence;\n\n\t\t\tif (index === this._front) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tindex = (this._capacity + index - 1) % this._capacity;\n\t\t\titeration++;\n\t\t} while (true);\n\n\t\treturn (score <= 0.5);\n\t}\n\n\tpublic acceptStandardWheelEvent(e: StandardWheelEvent): void {\n\t\tif (isChrome) {\n\t\t\tconst targetWindow = dom.getWindow(e.browserEvent);\n\t\t\tconst pageZoomFactor = getZoomFactor(targetWindow);\n\t\t\t// On Chrome, the incoming delta events are multiplied with the OS zoom factor.\n\t\t\t// The OS zoom factor can be reverse engineered by using the device pixel ratio and the configured zoom factor into account.\n\t\t\tthis.accept(Date.now(), e.deltaX * pageZoomFactor, e.deltaY * pageZoomFactor);\n\t\t} else {\n\t\t\tthis.accept(Date.now(), e.deltaX, e.deltaY);\n\t\t}\n\t}\n\n\tpublic accept(timestamp: number, deltaX: number, deltaY: number): void {\n\t\tlet previousItem = null;\n\t\tconst item = new MouseWheelClassifierItem(timestamp, deltaX, deltaY);\n\n\t\tif (this._front === -1 && this._rear === -1) {\n\t\t\tthis._memory[0] = item;\n\t\t\tthis._front = 0;\n\t\t\tthis._rear = 0;\n\t\t} else {\n\t\t\tpreviousItem = this._memory[this._rear];\n\n\t\t\tthis._rear = (this._rear + 1) % this._capacity;\n\t\t\tif (this._rear === this._front) {\n\t\t\t\t// Drop oldest\n\t\t\t\tthis._front = (this._front + 1) % this._capacity;\n\t\t\t}\n\t\t\tthis._memory[this._rear] = item;\n\t\t}\n\n\t\titem.score = this._computeScore(item, previousItem);\n\t}\n\n\t/**\n\t * A score between 0 and 1 for `item`.\n\t * - a score towards 0 indicates that the source appears to be a physical mouse wheel\n\t * - a score towards 1 indicates that the source appears to be a touchpad or magic mouse, etc.\n\t */\n\tprivate _computeScore(item: MouseWheelClassifierItem, previousItem: MouseWheelClassifierItem | null): number {\n\n\t\tif (Math.abs(item.deltaX) > 0 && Math.abs(item.deltaY) > 0) {\n\t\t\t// both axes exercised => definitely not a physical mouse wheel\n\t\t\treturn 1;\n\t\t}\n\n\t\tlet score: number = 0.5;\n\n\t\tif (!this._isAlmostInt(item.deltaX) || !this._isAlmostInt(item.deltaY)) {\n\t\t\t// non-integer deltas => indicator that this is not a physical mouse wheel\n\t\t\tscore += 0.25;\n\t\t}\n\n\t\t// Non-accelerating scroll => indicator that this is a physical mouse wheel\n\t\t// These can be identified by seeing whether they are the module of one another.\n\t\tif (previousItem) {\n\t\t\tconst absDeltaX = Math.abs(item.deltaX);\n\t\t\tconst absDeltaY = Math.abs(item.deltaY);\n\n\t\t\tconst absPreviousDeltaX = Math.abs(previousItem.deltaX);\n\t\t\tconst absPreviousDeltaY = Math.abs(previousItem.deltaY);\n\n\t\t\t// Min 1 to avoid division by zero, module 1 will still be 0.\n\t\t\tconst minDeltaX = Math.max(Math.min(absDeltaX, absPreviousDeltaX), 1);\n\t\t\tconst minDeltaY = Math.max(Math.min(absDeltaY, absPreviousDeltaY), 1);\n\n\t\t\tconst maxDeltaX = Math.max(absDeltaX, absPreviousDeltaX);\n\t\t\tconst maxDeltaY = Math.max(absDeltaY, absPreviousDeltaY);\n\n\t\t\tconst isSameModulo = (maxDeltaX % minDeltaX === 0 && maxDeltaY % minDeltaY === 0);\n\t\t\tif (isSameModulo) {\n\t\t\t\tscore -= 0.5;\n\t\t\t}\n\t\t}\n\n\t\treturn Math.min(Math.max(score, 0), 1);\n\t}\n\n\tprivate _isAlmostInt(value: number): boolean {\n\t\tconst delta = Math.abs(Math.round(value) - value);\n\t\treturn (delta < 0.01);\n\t}\n}\n\nexport abstract class AbstractScrollableElement extends Widget {\n\n\tprivate readonly _options: ScrollableElementResolvedOptions;\n\tprotected readonly _scrollable: Scrollable;\n\tprivate readonly _verticalScrollbar: VerticalScrollbar;\n\tprivate readonly _horizontalScrollbar: HorizontalScrollbar;\n\tprivate readonly _domNode: HTMLElement;\n\n\tprivate readonly _leftShadowDomNode: FastDomNode | null;\n\tprivate readonly _topShadowDomNode: FastDomNode | null;\n\tprivate readonly _topLeftShadowDomNode: FastDomNode | null;\n\n\tprivate readonly _listenOnDomNode: HTMLElement;\n\n\tprivate _mouseWheelToDispose: IDisposable[];\n\n\tprivate _isDragging: boolean;\n\tprivate _mouseIsOver: boolean;\n\n\tprivate readonly _hideTimeout: TimeoutTimer;\n\tprivate _shouldRender: boolean;\n\n\tprivate _revealOnScroll: boolean;\n\n\tprivate readonly _onScroll = this._register(new Emitter());\n\tpublic readonly onScroll: Event = this._onScroll.event;\n\n\tprivate readonly _onWillScroll = this._register(new Emitter());\n\tpublic readonly onWillScroll: Event = this._onWillScroll.event;\n\n\tpublic get options(): Readonly {\n\t\treturn this._options;\n\t}\n\n\tprotected constructor(element: HTMLElement, options: ScrollableElementCreationOptions, scrollable: Scrollable) {\n\t\tsuper();\n\t\t// HACK: xterm.js currnetly requires overflow to allow decorations to escape the container\n\t\t// element.style.overflow = 'hidden';\n\t\tthis._options = resolveOptions(options);\n\t\tthis._scrollable = scrollable;\n\n\t\tthis._register(this._scrollable.onScroll((e) => {\n\t\t\tthis._onWillScroll.fire(e);\n\t\t\tthis._onDidScroll(e);\n\t\t\tthis._onScroll.fire(e);\n\t\t}));\n\n\t\tconst scrollbarHost: ScrollbarHost = {\n\t\t\tonMouseWheel: (mouseWheelEvent: StandardWheelEvent) => this._onMouseWheel(mouseWheelEvent),\n\t\t\tonDragStart: () => this._onDragStart(),\n\t\t\tonDragEnd: () => this._onDragEnd(),\n\t\t};\n\t\tthis._verticalScrollbar = this._register(new VerticalScrollbar(this._scrollable, this._options, scrollbarHost));\n\t\tthis._horizontalScrollbar = this._register(new HorizontalScrollbar(this._scrollable, this._options, scrollbarHost));\n\n\t\tthis._domNode = document.createElement('div');\n\t\tthis._domNode.className = 'xterm-scrollable-element ' + this._options.className;\n\t\tthis._domNode.setAttribute('role', 'presentation');\n\t\tthis._domNode.style.position = 'relative';\n\t\t// HACK: xterm.js currnetly requires overflow to allow decorations to escape the container\n\t\t// this._domNode.style.overflow = 'hidden';\n\t\tthis._domNode.appendChild(element);\n\t\tthis._domNode.appendChild(this._horizontalScrollbar.domNode.domNode);\n\t\tthis._domNode.appendChild(this._verticalScrollbar.domNode.domNode);\n\n\t\tif (this._options.useShadows) {\n\t\t\tthis._leftShadowDomNode = createFastDomNode(document.createElement('div'));\n\t\t\tthis._leftShadowDomNode.setClassName('shadow');\n\t\t\tthis._domNode.appendChild(this._leftShadowDomNode.domNode);\n\n\t\t\tthis._topShadowDomNode = createFastDomNode(document.createElement('div'));\n\t\t\tthis._topShadowDomNode.setClassName('shadow');\n\t\t\tthis._domNode.appendChild(this._topShadowDomNode.domNode);\n\n\t\t\tthis._topLeftShadowDomNode = createFastDomNode(document.createElement('div'));\n\t\t\tthis._topLeftShadowDomNode.setClassName('shadow');\n\t\t\tthis._domNode.appendChild(this._topLeftShadowDomNode.domNode);\n\t\t} else {\n\t\t\tthis._leftShadowDomNode = null;\n\t\t\tthis._topShadowDomNode = null;\n\t\t\tthis._topLeftShadowDomNode = null;\n\t\t}\n\n\t\tthis._listenOnDomNode = this._options.listenOnDomNode || this._domNode;\n\n\t\tthis._mouseWheelToDispose = [];\n\t\tthis._setListeningToMouseWheel(this._options.handleMouseWheel);\n\n\t\tthis.onmouseover(this._listenOnDomNode, (e) => this._onMouseOver(e));\n\t\tthis.onmouseleave(this._listenOnDomNode, (e) => this._onMouseLeave(e));\n\n\t\tthis._hideTimeout = this._register(new TimeoutTimer());\n\t\tthis._isDragging = false;\n\t\tthis._mouseIsOver = false;\n\n\t\tthis._shouldRender = true;\n\n\t\tthis._revealOnScroll = true;\n\t}\n\n\tpublic override dispose(): void {\n\t\tthis._mouseWheelToDispose = dispose(this._mouseWheelToDispose);\n\t\tsuper.dispose();\n\t}\n\n\t/**\n\t * Get the generated 'scrollable' dom node\n\t */\n\tpublic getDomNode(): HTMLElement {\n\t\treturn this._domNode;\n\t}\n\n\tpublic getOverviewRulerLayoutInfo(): IOverviewRulerLayoutInfo {\n\t\treturn {\n\t\t\tparent: this._domNode,\n\t\t\tinsertBefore: this._verticalScrollbar.domNode.domNode,\n\t\t};\n\t}\n\n\t/**\n\t * Delegate a pointer down event to the vertical scrollbar.\n\t * This is to help with clicking somewhere else and having the scrollbar react.\n\t */\n\tpublic delegateVerticalScrollbarPointerDown(browserEvent: PointerEvent): void {\n\t\tthis._verticalScrollbar.delegatePointerDown(browserEvent);\n\t}\n\n\tpublic getScrollDimensions(): IScrollDimensions {\n\t\treturn this._scrollable.getScrollDimensions();\n\t}\n\n\tpublic setScrollDimensions(dimensions: INewScrollDimensions): void {\n\t\tthis._scrollable.setScrollDimensions(dimensions, false);\n\t}\n\n\t/**\n\t * Update the class name of the scrollable element.\n\t */\n\tpublic updateClassName(newClassName: string): void {\n\t\tthis._options.className = newClassName;\n\t\t// Defaults are different on Macs\n\t\tif (platform.isMacintosh) {\n\t\t\tthis._options.className += ' mac';\n\t\t}\n\t\tthis._domNode.className = 'xterm-scrollable-element ' + this._options.className;\n\t}\n\n\t/**\n\t * Update configuration options for the scrollbar.\n\t */\n\tpublic updateOptions(newOptions: ScrollableElementChangeOptions): void {\n\t\tif (typeof newOptions.handleMouseWheel !== 'undefined') {\n\t\t\tthis._options.handleMouseWheel = newOptions.handleMouseWheel;\n\t\t\tthis._setListeningToMouseWheel(this._options.handleMouseWheel);\n\t\t}\n\t\tif (typeof newOptions.mouseWheelScrollSensitivity !== 'undefined') {\n\t\t\tthis._options.mouseWheelScrollSensitivity = newOptions.mouseWheelScrollSensitivity;\n\t\t}\n\t\tif (typeof newOptions.fastScrollSensitivity !== 'undefined') {\n\t\t\tthis._options.fastScrollSensitivity = newOptions.fastScrollSensitivity;\n\t\t}\n\t\tif (typeof newOptions.scrollPredominantAxis !== 'undefined') {\n\t\t\tthis._options.scrollPredominantAxis = newOptions.scrollPredominantAxis;\n\t\t}\n\t\tif (typeof newOptions.horizontal !== 'undefined') {\n\t\t\tthis._options.horizontal = newOptions.horizontal;\n\t\t}\n\t\tif (typeof newOptions.vertical !== 'undefined') {\n\t\t\tthis._options.vertical = newOptions.vertical;\n\t\t}\n\t\tif (typeof newOptions.horizontalScrollbarSize !== 'undefined') {\n\t\t\tthis._options.horizontalScrollbarSize = newOptions.horizontalScrollbarSize;\n\t\t}\n\t\tif (typeof newOptions.verticalScrollbarSize !== 'undefined') {\n\t\t\tthis._options.verticalScrollbarSize = newOptions.verticalScrollbarSize;\n\t\t}\n\t\tif (typeof newOptions.scrollByPage !== 'undefined') {\n\t\t\tthis._options.scrollByPage = newOptions.scrollByPage;\n\t\t}\n\t\tthis._horizontalScrollbar.updateOptions(this._options);\n\t\tthis._verticalScrollbar.updateOptions(this._options);\n\n\t\tif (!this._options.lazyRender) {\n\t\t\tthis._render();\n\t\t}\n\t}\n\n\tpublic setRevealOnScroll(value: boolean) {\n\t\tthis._revealOnScroll = value;\n\t}\n\n\tpublic delegateScrollFromMouseWheelEvent(browserEvent: IMouseWheelEvent) {\n\t\tthis._onMouseWheel(new StandardWheelEvent(browserEvent));\n\t}\n\n\t// -------------------- mouse wheel scrolling --------------------\n\n\tprivate _setListeningToMouseWheel(shouldListen: boolean): void {\n\t\tconst isListening = (this._mouseWheelToDispose.length > 0);\n\n\t\tif (isListening === shouldListen) {\n\t\t\t// No change\n\t\t\treturn;\n\t\t}\n\n\t\t// Stop listening (if necessary)\n\t\tthis._mouseWheelToDispose = dispose(this._mouseWheelToDispose);\n\n\t\t// Start listening (if necessary)\n\t\tif (shouldListen) {\n\t\t\tconst onMouseWheel = (browserEvent: IMouseWheelEvent) => {\n\t\t\t\tthis._onMouseWheel(new StandardWheelEvent(browserEvent));\n\t\t\t};\n\n\t\t\tthis._mouseWheelToDispose.push(dom.addDisposableListener(this._listenOnDomNode, dom.EventType.MOUSE_WHEEL, onMouseWheel, { passive: false }));\n\t\t}\n\t}\n\n\tprivate _onMouseWheel(e: StandardWheelEvent): void {\n\t\tif (e.browserEvent?.defaultPrevented) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst classifier = MouseWheelClassifier.INSTANCE;\n\t\tif (SCROLL_WHEEL_SMOOTH_SCROLL_ENABLED) {\n\t\t\tclassifier.acceptStandardWheelEvent(e);\n\t\t}\n\n\t\t// useful for creating unit tests:\n\t\t// console.log(`${Date.now()}, ${e.deltaY}, ${e.deltaX}`);\n\n\t\tlet didScroll = false;\n\n\t\tif (e.deltaY || e.deltaX) {\n\t\t\tlet deltaY = e.deltaY * this._options.mouseWheelScrollSensitivity;\n\t\t\tlet deltaX = e.deltaX * this._options.mouseWheelScrollSensitivity;\n\n\t\t\tif (this._options.scrollPredominantAxis) {\n\t\t\t\tif (this._options.scrollYToX && deltaX + deltaY === 0) {\n\t\t\t\t\t// when configured to map Y to X and we both see\n\t\t\t\t\t// no dominant axis and X and Y are competing with\n\t\t\t\t\t// identical values into opposite directions, we\n\t\t\t\t\t// ignore the delta as we cannot make a decision then\n\t\t\t\t\tdeltaX = deltaY = 0;\n\t\t\t\t} else if (Math.abs(deltaY) >= Math.abs(deltaX)) {\n\t\t\t\t\tdeltaX = 0;\n\t\t\t\t} else {\n\t\t\t\t\tdeltaY = 0;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (this._options.flipAxes) {\n\t\t\t\t[deltaY, deltaX] = [deltaX, deltaY];\n\t\t\t}\n\n\t\t\t// Convert vertical scrolling to horizontal if shift is held, this\n\t\t\t// is handled at a higher level on Mac\n\t\t\tconst shiftConvert = !platform.isMacintosh && e.browserEvent && e.browserEvent.shiftKey;\n\t\t\tif ((this._options.scrollYToX || shiftConvert) && !deltaX) {\n\t\t\t\tdeltaX = deltaY;\n\t\t\t\tdeltaY = 0;\n\t\t\t}\n\n\t\t\tif (e.browserEvent && e.browserEvent.altKey) {\n\t\t\t\t// fastScrolling\n\t\t\t\tdeltaX = deltaX * this._options.fastScrollSensitivity;\n\t\t\t\tdeltaY = deltaY * this._options.fastScrollSensitivity;\n\t\t\t}\n\n\t\t\tconst futureScrollPosition = this._scrollable.getFutureScrollPosition();\n\n\t\t\tlet desiredScrollPosition: INewScrollPosition = {};\n\t\t\tif (deltaY) {\n\t\t\t\tconst deltaScrollTop = SCROLL_WHEEL_SENSITIVITY * deltaY;\n\t\t\t\t// Here we convert values such as -0.3 to -1 or 0.3 to 1, otherwise low speed scrolling will never scroll\n\t\t\t\tconst desiredScrollTop = futureScrollPosition.scrollTop - (deltaScrollTop < 0 ? Math.floor(deltaScrollTop) : Math.ceil(deltaScrollTop));\n\t\t\t\tthis._verticalScrollbar.writeScrollPosition(desiredScrollPosition, desiredScrollTop);\n\t\t\t}\n\t\t\tif (deltaX) {\n\t\t\t\tconst deltaScrollLeft = SCROLL_WHEEL_SENSITIVITY * deltaX;\n\t\t\t\t// Here we convert values such as -0.3 to -1 or 0.3 to 1, otherwise low speed scrolling will never scroll\n\t\t\t\tconst desiredScrollLeft = futureScrollPosition.scrollLeft - (deltaScrollLeft < 0 ? Math.floor(deltaScrollLeft) : Math.ceil(deltaScrollLeft));\n\t\t\t\tthis._horizontalScrollbar.writeScrollPosition(desiredScrollPosition, desiredScrollLeft);\n\t\t\t}\n\n\t\t\t// Check that we are scrolling towards a location which is valid\n\t\t\tdesiredScrollPosition = this._scrollable.validateScrollPosition(desiredScrollPosition);\n\n\t\t\tif (futureScrollPosition.scrollLeft !== desiredScrollPosition.scrollLeft || futureScrollPosition.scrollTop !== desiredScrollPosition.scrollTop) {\n\n\t\t\t\tconst canPerformSmoothScroll = (\n\t\t\t\t\tSCROLL_WHEEL_SMOOTH_SCROLL_ENABLED\n\t\t\t\t\t&& this._options.mouseWheelSmoothScroll\n\t\t\t\t\t&& classifier.isPhysicalMouseWheel()\n\t\t\t\t);\n\n\t\t\t\tif (canPerformSmoothScroll) {\n\t\t\t\t\tthis._scrollable.setScrollPositionSmooth(desiredScrollPosition);\n\t\t\t\t} else {\n\t\t\t\t\tthis._scrollable.setScrollPositionNow(desiredScrollPosition);\n\t\t\t\t}\n\n\t\t\t\tdidScroll = true;\n\t\t\t}\n\t\t}\n\n\t\tlet consumeMouseWheel = didScroll;\n\t\tif (!consumeMouseWheel && this._options.alwaysConsumeMouseWheel) {\n\t\t\tconsumeMouseWheel = true;\n\t\t}\n\t\tif (!consumeMouseWheel && this._options.consumeMouseWheelIfScrollbarIsNeeded && (this._verticalScrollbar.isNeeded() || this._horizontalScrollbar.isNeeded())) {\n\t\t\tconsumeMouseWheel = true;\n\t\t}\n\n\t\tif (consumeMouseWheel) {\n\t\t\te.preventDefault();\n\t\t\te.stopPropagation();\n\t\t}\n\t}\n\n\tprivate _onDidScroll(e: ScrollEvent): void {\n\t\tthis._shouldRender = this._horizontalScrollbar.onDidScroll(e) || this._shouldRender;\n\t\tthis._shouldRender = this._verticalScrollbar.onDidScroll(e) || this._shouldRender;\n\n\t\tif (this._options.useShadows) {\n\t\t\tthis._shouldRender = true;\n\t\t}\n\n\t\tif (this._revealOnScroll) {\n\t\t\tthis._reveal();\n\t\t}\n\n\t\tif (!this._options.lazyRender) {\n\t\t\tthis._render();\n\t\t}\n\t}\n\n\t/**\n\t * Render / mutate the DOM now.\n\t * Should be used together with the ctor option `lazyRender`.\n\t */\n\tpublic renderNow(): void {\n\t\tif (!this._options.lazyRender) {\n\t\t\tthrow new Error('Please use `lazyRender` together with `renderNow`!');\n\t\t}\n\n\t\tthis._render();\n\t}\n\n\tprivate _render(): void {\n\t\tif (!this._shouldRender) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis._shouldRender = false;\n\n\t\tthis._horizontalScrollbar.render();\n\t\tthis._verticalScrollbar.render();\n\n\t\tif (this._options.useShadows) {\n\t\t\tconst scrollState = this._scrollable.getCurrentScrollPosition();\n\t\t\tconst enableTop = scrollState.scrollTop > 0;\n\t\t\tconst enableLeft = scrollState.scrollLeft > 0;\n\n\t\t\tconst leftClassName = (enableLeft ? ' left' : '');\n\t\t\tconst topClassName = (enableTop ? ' top' : '');\n\t\t\tconst topLeftClassName = (enableLeft || enableTop ? ' top-left-corner' : '');\n\t\t\tthis._leftShadowDomNode!.setClassName(`shadow${leftClassName}`);\n\t\t\tthis._topShadowDomNode!.setClassName(`shadow${topClassName}`);\n\t\t\tthis._topLeftShadowDomNode!.setClassName(`shadow${topLeftClassName}${topClassName}${leftClassName}`);\n\t\t}\n\t}\n\n\t// -------------------- fade in / fade out --------------------\n\n\tprivate _onDragStart(): void {\n\t\tthis._isDragging = true;\n\t\tthis._reveal();\n\t}\n\n\tprivate _onDragEnd(): void {\n\t\tthis._isDragging = false;\n\t\tthis._hide();\n\t}\n\n\tprivate _onMouseLeave(e: IMouseEvent): void {\n\t\tthis._mouseIsOver = false;\n\t\tthis._hide();\n\t}\n\n\tprivate _onMouseOver(e: IMouseEvent): void {\n\t\tthis._mouseIsOver = true;\n\t\tthis._reveal();\n\t}\n\n\tprivate _reveal(): void {\n\t\tthis._verticalScrollbar.beginReveal();\n\t\tthis._horizontalScrollbar.beginReveal();\n\t\tthis._scheduleHide();\n\t}\n\n\tprivate _hide(): void {\n\t\tif (!this._mouseIsOver && !this._isDragging) {\n\t\t\tthis._verticalScrollbar.beginHide();\n\t\t\tthis._horizontalScrollbar.beginHide();\n\t\t}\n\t}\n\n\tprivate _scheduleHide(): void {\n\t\tif (!this._mouseIsOver && !this._isDragging) {\n\t\t\tthis._hideTimeout.cancelAndSet(() => this._hide(), HIDE_TIMEOUT);\n\t\t}\n\t}\n}\n\nexport class ScrollableElement extends AbstractScrollableElement {\n\n\tconstructor(element: HTMLElement, options: ScrollableElementCreationOptions) {\n\t\toptions = options || {};\n\t\toptions.mouseWheelSmoothScroll = false;\n\t\tconst scrollable = new Scrollable({\n\t\t\tforceIntegerValues: true,\n\t\t\tsmoothScrollDuration: 0,\n\t\t\tscheduleAtNextAnimationFrame: (callback) => dom.scheduleAtNextAnimationFrame(dom.getWindow(element), callback)\n\t\t});\n\t\tsuper(element, options, scrollable);\n\t\tthis._register(scrollable);\n\t}\n\n\tpublic setScrollPosition(update: INewScrollPosition): void {\n\t\tthis._scrollable.setScrollPositionNow(update);\n\t}\n\n\tpublic getScrollPosition(): IScrollPosition {\n\t\treturn this._scrollable.getCurrentScrollPosition();\n\t}\n}\n\nexport class SmoothScrollableElement extends AbstractScrollableElement {\n\n\tconstructor(element: HTMLElement, options: ScrollableElementCreationOptions, scrollable: Scrollable) {\n\t\tsuper(element, options, scrollable);\n\t}\n\n\tpublic setScrollPosition(update: INewScrollPosition & { reuseAnimation?: boolean }): void {\n\t\tif (update.reuseAnimation) {\n\t\t\tthis._scrollable.setScrollPositionSmooth(update, update.reuseAnimation);\n\t\t} else {\n\t\t\tthis._scrollable.setScrollPositionNow(update);\n\t\t}\n\t}\n\n\tpublic getScrollPosition(): IScrollPosition {\n\t\treturn this._scrollable.getCurrentScrollPosition();\n\t}\n\n}\n\nexport class DomScrollableElement extends AbstractScrollableElement {\n\n\tprivate _element: HTMLElement;\n\n\tconstructor(element: HTMLElement, options: ScrollableElementCreationOptions) {\n\t\toptions = options || {};\n\t\toptions.mouseWheelSmoothScroll = false;\n\t\tconst scrollable = new Scrollable({\n\t\t\tforceIntegerValues: false, // See https://github.com/microsoft/vscode/issues/139877\n\t\t\tsmoothScrollDuration: 0,\n\t\t\tscheduleAtNextAnimationFrame: (callback) => dom.scheduleAtNextAnimationFrame(dom.getWindow(element), callback)\n\t\t});\n\t\tsuper(element, options, scrollable);\n\t\tthis._register(scrollable);\n\t\tthis._element = element;\n\t\tthis._register(this.onScroll((e) => {\n\t\t\tif (e.scrollTopChanged) {\n\t\t\t\tthis._element.scrollTop = e.scrollTop;\n\t\t\t}\n\t\t\tif (e.scrollLeftChanged) {\n\t\t\t\tthis._element.scrollLeft = e.scrollLeft;\n\t\t\t}\n\t\t}));\n\t\tthis.scanDomNode();\n\t}\n\n\tpublic setScrollPosition(update: INewScrollPosition): void {\n\t\tthis._scrollable.setScrollPositionNow(update);\n\t}\n\n\tpublic getScrollPosition(): IScrollPosition {\n\t\treturn this._scrollable.getCurrentScrollPosition();\n\t}\n\n\tpublic scanDomNode(): void {\n\t\t// width, scrollLeft, scrollWidth, height, scrollTop, scrollHeight\n\t\tthis.setScrollDimensions({\n\t\t\twidth: this._element.clientWidth,\n\t\t\tscrollWidth: this._element.scrollWidth,\n\t\t\theight: this._element.clientHeight,\n\t\t\tscrollHeight: this._element.scrollHeight\n\t\t});\n\t\tthis.setScrollPosition({\n\t\t\tscrollLeft: this._element.scrollLeft,\n\t\t\tscrollTop: this._element.scrollTop,\n\t\t});\n\t}\n}\n\nfunction resolveOptions(opts: ScrollableElementCreationOptions): ScrollableElementResolvedOptions {\n\tconst result: ScrollableElementResolvedOptions = {\n\t\tlazyRender: (typeof opts.lazyRender !== 'undefined' ? opts.lazyRender : false),\n\t\tclassName: (typeof opts.className !== 'undefined' ? opts.className : ''),\n\t\tuseShadows: (typeof opts.useShadows !== 'undefined' ? opts.useShadows : true),\n\t\thandleMouseWheel: (typeof opts.handleMouseWheel !== 'undefined' ? opts.handleMouseWheel : true),\n\t\tflipAxes: (typeof opts.flipAxes !== 'undefined' ? opts.flipAxes : false),\n\t\tconsumeMouseWheelIfScrollbarIsNeeded: (typeof opts.consumeMouseWheelIfScrollbarIsNeeded !== 'undefined' ? opts.consumeMouseWheelIfScrollbarIsNeeded : false),\n\t\talwaysConsumeMouseWheel: (typeof opts.alwaysConsumeMouseWheel !== 'undefined' ? opts.alwaysConsumeMouseWheel : false),\n\t\tscrollYToX: (typeof opts.scrollYToX !== 'undefined' ? opts.scrollYToX : false),\n\t\tmouseWheelScrollSensitivity: (typeof opts.mouseWheelScrollSensitivity !== 'undefined' ? opts.mouseWheelScrollSensitivity : 1),\n\t\tfastScrollSensitivity: (typeof opts.fastScrollSensitivity !== 'undefined' ? opts.fastScrollSensitivity : 5),\n\t\tscrollPredominantAxis: (typeof opts.scrollPredominantAxis !== 'undefined' ? opts.scrollPredominantAxis : true),\n\t\tmouseWheelSmoothScroll: (typeof opts.mouseWheelSmoothScroll !== 'undefined' ? opts.mouseWheelSmoothScroll : true),\n\t\tarrowSize: (typeof opts.arrowSize !== 'undefined' ? opts.arrowSize : 11),\n\n\t\tlistenOnDomNode: (typeof opts.listenOnDomNode !== 'undefined' ? opts.listenOnDomNode : null),\n\n\t\thorizontal: (typeof opts.horizontal !== 'undefined' ? opts.horizontal : ScrollbarVisibility.Auto),\n\t\thorizontalScrollbarSize: (typeof opts.horizontalScrollbarSize !== 'undefined' ? opts.horizontalScrollbarSize : 10),\n\t\thorizontalSliderSize: (typeof opts.horizontalSliderSize !== 'undefined' ? opts.horizontalSliderSize : 0),\n\t\thorizontalHasArrows: (typeof opts.horizontalHasArrows !== 'undefined' ? opts.horizontalHasArrows : false),\n\n\t\tvertical: (typeof opts.vertical !== 'undefined' ? opts.vertical : ScrollbarVisibility.Auto),\n\t\tverticalScrollbarSize: (typeof opts.verticalScrollbarSize !== 'undefined' ? opts.verticalScrollbarSize : 10),\n\t\tverticalHasArrows: (typeof opts.verticalHasArrows !== 'undefined' ? opts.verticalHasArrows : false),\n\t\tverticalSliderSize: (typeof opts.verticalSliderSize !== 'undefined' ? opts.verticalSliderSize : 0),\n\n\t\tscrollByPage: (typeof opts.scrollByPage !== 'undefined' ? opts.scrollByPage : false)\n\t};\n\n\tresult.horizontalSliderSize = (typeof opts.horizontalSliderSize !== 'undefined' ? opts.horizontalSliderSize : result.horizontalScrollbarSize);\n\tresult.verticalSliderSize = (typeof opts.verticalSliderSize !== 'undefined' ? opts.verticalSliderSize : result.verticalScrollbarSize);\n\n\t// Defaults are different on Macs\n\tif (platform.isMacintosh) {\n\t\tresult.className += ' mac';\n\t}\n\n\treturn result;\n}\n", "/**\n * Copyright (c) 2024 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { ICoreBrowserService, IRenderService, IThemeService } from 'browser/services/Services';\nimport { ViewportConstants } from 'browser/shared/Constants';\nimport { Disposable, toDisposable } from 'vs/base/common/lifecycle';\nimport { IBufferService, ICoreMouseService, IOptionsService } from 'common/services/Services';\nimport { CoreMouseEventType } from 'common/Types';\nimport { scheduleAtNextAnimationFrame } from 'vs/base/browser/dom';\nimport { SmoothScrollableElement } from 'vs/base/browser/ui/scrollbar/scrollableElement';\nimport type { ScrollableElementChangeOptions } from 'vs/base/browser/ui/scrollbar/scrollableElementOptions';\nimport { Emitter, Event } from 'vs/base/common/event';\nimport { Scrollable, ScrollbarVisibility, type ScrollEvent } from 'vs/base/common/scrollable';\n\nexport class Viewport extends Disposable {\n\n protected _onRequestScrollLines = this._register(new Emitter());\n public readonly onRequestScrollLines = this._onRequestScrollLines.event;\n\n private _scrollableElement: SmoothScrollableElement;\n private _styleElement: HTMLStyleElement;\n\n private _queuedAnimationFrame?: number;\n private _latestYDisp?: number;\n private _isSyncing: boolean = false;\n private _isHandlingScroll: boolean = false;\n private _suppressOnScrollHandler: boolean = false;\n\n constructor(\n element: HTMLElement,\n screenElement: HTMLElement,\n @IBufferService private readonly _bufferService: IBufferService,\n @ICoreBrowserService coreBrowserService: ICoreBrowserService,\n @ICoreMouseService coreMouseService: ICoreMouseService,\n @IThemeService themeService: IThemeService,\n @IOptionsService private readonly _optionsService: IOptionsService,\n @IRenderService private readonly _renderService: IRenderService\n ) {\n super();\n\n const scrollable = this._register(new Scrollable({\n forceIntegerValues: false,\n smoothScrollDuration: this._optionsService.rawOptions.smoothScrollDuration,\n // This is used over `IRenderService.addRefreshCallback` since it can be canceled\n scheduleAtNextAnimationFrame: cb => scheduleAtNextAnimationFrame(coreBrowserService.window, cb)\n }));\n this._register(this._optionsService.onSpecificOptionChange('smoothScrollDuration', () => {\n scrollable.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration);\n }));\n\n this._scrollableElement = this._register(new SmoothScrollableElement(screenElement, {\n vertical: ScrollbarVisibility.Auto,\n horizontal: ScrollbarVisibility.Hidden,\n useShadows: false,\n mouseWheelSmoothScroll: true,\n ...this._getChangeOptions()\n }, scrollable));\n this._register(this._optionsService.onMultipleOptionChange([\n 'scrollSensitivity',\n 'fastScrollSensitivity',\n 'overviewRuler'\n ], () => this._scrollableElement.updateOptions(this._getChangeOptions())));\n // Don't handle mouse wheel if wheel events are supported by the current mouse prototcol\n this._register(coreMouseService.onProtocolChange(type => {\n this._scrollableElement.updateOptions({\n handleMouseWheel: !(type & CoreMouseEventType.WHEEL)\n });\n }));\n\n this._scrollableElement.setScrollDimensions({ height: 0, scrollHeight: 0 });\n this._register(Event.runAndSubscribe(themeService.onChangeColors, () => {\n this._scrollableElement.getDomNode().style.backgroundColor = themeService.colors.background.css;\n }));\n element.appendChild(this._scrollableElement.getDomNode());\n this._register(toDisposable(() => this._scrollableElement.getDomNode().remove()));\n\n this._styleElement = coreBrowserService.mainDocument.createElement('style');\n screenElement.appendChild(this._styleElement);\n this._register(toDisposable(() => this._styleElement.remove()));\n this._register(Event.runAndSubscribe(themeService.onChangeColors, () => {\n this._styleElement.textContent = [\n `.xterm .xterm-scrollable-element > .scrollbar > .slider {`,\n ` background: ${themeService.colors.scrollbarSliderBackground.css};`,\n `}`,\n `.xterm .xterm-scrollable-element > .scrollbar > .slider:hover {`,\n ` background: ${themeService.colors.scrollbarSliderHoverBackground.css};`,\n `}`,\n `.xterm .xterm-scrollable-element > .scrollbar > .slider.active {`,\n ` background: ${themeService.colors.scrollbarSliderActiveBackground.css};`,\n `}`\n ].join('\\n');\n }));\n\n this._register(this._bufferService.onResize(() => this.queueSync()));\n this._register(this._bufferService.buffers.onBufferActivate(() => {\n // Reset _latestYDisp when switching buffers to prevent stale scroll position\n // from alt buffer contaminating normal buffer scroll position\n this._latestYDisp = undefined;\n this.queueSync();\n }));\n this._register(this._bufferService.onScroll(() => this._sync()));\n\n this._register(this._scrollableElement.onScroll(e => this._handleScroll(e)));\n }\n\n public scrollLines(disp: number): void {\n const pos = this._scrollableElement.getScrollPosition();\n this._scrollableElement.setScrollPosition({\n reuseAnimation: true,\n scrollTop: pos.scrollTop + disp * this._renderService.dimensions.css.cell.height\n });\n }\n\n public scrollToLine(line: number, disableSmoothScroll?: boolean): void {\n if (disableSmoothScroll) {\n this._latestYDisp = line;\n }\n this._scrollableElement.setScrollPosition({\n reuseAnimation: !disableSmoothScroll,\n scrollTop: line * this._renderService.dimensions.css.cell.height\n });\n }\n\n private _getChangeOptions(): ScrollableElementChangeOptions {\n return {\n mouseWheelScrollSensitivity: this._optionsService.rawOptions.scrollSensitivity,\n fastScrollSensitivity: this._optionsService.rawOptions.fastScrollSensitivity,\n verticalScrollbarSize: this._optionsService.rawOptions.overviewRuler?.width || ViewportConstants.DEFAULT_SCROLL_BAR_WIDTH\n };\n }\n\n public queueSync(ydisp?: number): void {\n // Update state\n if (ydisp !== undefined) {\n this._latestYDisp = ydisp;\n }\n\n // Don't queue more than one callback\n if (this._queuedAnimationFrame !== undefined) {\n return;\n }\n this._queuedAnimationFrame = this._renderService.addRefreshCallback(() => {\n this._queuedAnimationFrame = undefined;\n this._sync(this._latestYDisp);\n });\n }\n\n private _sync(ydisp: number = this._bufferService.buffer.ydisp): void {\n if (!this._renderService || this._isSyncing) {\n return;\n }\n this._isSyncing = true;\n\n // Ignore any onScroll event that happens as a result of dimensions changing as this should\n // never cause a scrollLines call, only setScrollPosition can do that.\n this._suppressOnScrollHandler = true;\n this._scrollableElement.setScrollDimensions({\n height: this._renderService.dimensions.css.canvas.height,\n scrollHeight: this._renderService.dimensions.css.cell.height * this._bufferService.buffer.lines.length\n });\n this._suppressOnScrollHandler = false;\n\n // If ydisp has been changed by some other component (input/buffer), then stop animating smooth\n // scroll and scroll there immediately.\n if (ydisp !== this._latestYDisp) {\n this._scrollableElement.setScrollPosition({\n scrollTop: ydisp * this._renderService.dimensions.css.cell.height\n });\n }\n\n this._isSyncing = false;\n }\n\n private _handleScroll(e: ScrollEvent): void {\n if (!this._renderService) {\n return;\n }\n if (this._isHandlingScroll || this._suppressOnScrollHandler) {\n return;\n }\n this._isHandlingScroll = true;\n const newRow = Math.round(e.scrollTop / this._renderService.dimensions.css.cell.height);\n const diff = newRow - this._bufferService.buffer.ydisp;\n if (diff !== 0) {\n this._latestYDisp = newRow;\n this._onRequestScrollLines.fire(diff);\n }\n this._isHandlingScroll = false;\n }\n}\n", "/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\nimport { ICoreBrowserService, IRenderService } from 'browser/services/Services';\nimport { Disposable, toDisposable } from 'vs/base/common/lifecycle';\nimport { IBufferService, IDecorationService, IInternalDecoration } from 'common/services/Services';\n\nexport class BufferDecorationRenderer extends Disposable {\n private readonly _container: HTMLElement;\n private readonly _decorationElements: Map = new Map();\n\n private _animationFrame: number | undefined;\n private _altBufferIsActive: boolean = false;\n private _dimensionsChanged: boolean = false;\n\n constructor(\n private readonly _screenElement: HTMLElement,\n @IBufferService private readonly _bufferService: IBufferService,\n @ICoreBrowserService private readonly _coreBrowserService: ICoreBrowserService,\n @IDecorationService private readonly _decorationService: IDecorationService,\n @IRenderService private readonly _renderService: IRenderService\n ) {\n super();\n\n this._container = document.createElement('div');\n this._container.classList.add('xterm-decoration-container');\n this._screenElement.appendChild(this._container);\n\n this._register(this._renderService.onRenderedViewportChange(() => this._doRefreshDecorations()));\n this._register(this._renderService.onDimensionsChange(() => {\n this._dimensionsChanged = true;\n this._queueRefresh();\n }));\n this._register(this._coreBrowserService.onDprChange(() => this._queueRefresh()));\n this._register(this._bufferService.buffers.onBufferActivate(() => {\n this._altBufferIsActive = this._bufferService.buffer === this._bufferService.buffers.alt;\n }));\n this._register(this._decorationService.onDecorationRegistered(() => this._queueRefresh()));\n this._register(this._decorationService.onDecorationRemoved(decoration => this._removeDecoration(decoration)));\n this._register(toDisposable(() => {\n this._container.remove();\n this._decorationElements.clear();\n }));\n }\n\n private _queueRefresh(): void {\n if (this._animationFrame !== undefined) {\n return;\n }\n this._animationFrame = this._renderService.addRefreshCallback(() => {\n this._doRefreshDecorations();\n this._animationFrame = undefined;\n });\n }\n\n private _doRefreshDecorations(): void {\n for (const decoration of this._decorationService.decorations) {\n this._renderDecoration(decoration);\n }\n this._dimensionsChanged = false;\n }\n\n private _renderDecoration(decoration: IInternalDecoration): void {\n this._refreshStyle(decoration);\n if (this._dimensionsChanged) {\n this._refreshXPosition(decoration);\n }\n }\n\n private _createElement(decoration: IInternalDecoration): HTMLElement {\n const element = this._coreBrowserService.mainDocument.createElement('div');\n element.classList.add('xterm-decoration');\n element.classList.toggle('xterm-decoration-top-layer', decoration?.options?.layer === 'top');\n element.style.width = `${Math.round((decoration.options.width || 1) * this._renderService.dimensions.css.cell.width)}px`;\n element.style.height = `${(decoration.options.height || 1) * this._renderService.dimensions.css.cell.height}px`;\n element.style.top = `${(decoration.marker.line - this._bufferService.buffers.active.ydisp) * this._renderService.dimensions.css.cell.height}px`;\n element.style.lineHeight = `${this._renderService.dimensions.css.cell.height}px`;\n\n const x = decoration.options.x ?? 0;\n if (x && x > this._bufferService.cols) {\n // exceeded the container width, so hide\n element.style.display = 'none';\n }\n this._refreshXPosition(decoration, element);\n\n return element;\n }\n\n private _refreshStyle(decoration: IInternalDecoration): void {\n const line = decoration.marker.line - this._bufferService.buffers.active.ydisp;\n if (line < 0 || line >= this._bufferService.rows) {\n // outside of viewport\n if (decoration.element) {\n decoration.element.style.display = 'none';\n decoration.onRenderEmitter.fire(decoration.element);\n }\n } else {\n let element = this._decorationElements.get(decoration);\n if (!element) {\n element = this._createElement(decoration);\n decoration.element = element;\n this._decorationElements.set(decoration, element);\n this._container.appendChild(element);\n decoration.onDispose(() => {\n this._decorationElements.delete(decoration);\n element!.remove();\n });\n }\n element.style.display = this._altBufferIsActive ? 'none' : 'block';\n if (!this._altBufferIsActive) {\n element.style.width = `${Math.round((decoration.options.width || 1) * this._renderService.dimensions.css.cell.width)}px`;\n element.style.height = `${(decoration.options.height || 1) * this._renderService.dimensions.css.cell.height}px`;\n element.style.top = `${line * this._renderService.dimensions.css.cell.height}px`;\n element.style.lineHeight = `${this._renderService.dimensions.css.cell.height}px`;\n }\n decoration.onRenderEmitter.fire(element);\n }\n }\n\n private _refreshXPosition(decoration: IInternalDecoration, element: HTMLElement | undefined = decoration.element): void {\n if (!element) {\n return;\n }\n const x = decoration.options.x ?? 0;\n if ((decoration.options.anchor || 'left') === 'right') {\n element.style.right = x ? `${x * this._renderService.dimensions.css.cell.width}px` : '';\n } else {\n element.style.left = x ? `${x * this._renderService.dimensions.css.cell.width}px` : '';\n }\n }\n\n private _removeDecoration(decoration: IInternalDecoration): void {\n this._decorationElements.get(decoration)?.remove();\n this._decorationElements.delete(decoration);\n decoration.dispose();\n }\n}\n", "/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\nimport { IInternalDecoration } from 'common/services/Services';\n\nexport interface IColorZoneStore {\n readonly zones: IColorZone[];\n clear(): void;\n addDecoration(decoration: IInternalDecoration): void;\n /**\n * Sets the amount of padding in lines that will be added between zones, if new lines intersect\n * the padding they will be merged into the same zone.\n */\n setPadding(padding: { [position: string]: number }): void;\n}\n\nexport interface IColorZone {\n /** Color in a format supported by canvas' fillStyle. */\n color: string;\n position: 'full' | 'left' | 'center' | 'right' | undefined;\n startBufferLine: number;\n endBufferLine: number;\n}\n\ninterface IMinimalDecorationForColorZone {\n marker: Pick;\n options: Pick;\n}\n\nexport class ColorZoneStore implements IColorZoneStore {\n private _zones: IColorZone[] = [];\n\n // The zone pool is used to keep zone objects from being freed between clearing the color zone\n // store and fetching the zones. This helps reduce GC pressure since the color zones are\n // accumulated on potentially every scroll event.\n private _zonePool: IColorZone[] = [];\n private _zonePoolIndex = 0;\n\n private _linePadding: { [position: string]: number } = {\n full: 0,\n left: 0,\n center: 0,\n right: 0\n };\n\n public get zones(): IColorZone[] {\n // Trim the zone pool to free unused memory\n this._zonePool.length = Math.min(this._zonePool.length, this._zones.length);\n return this._zones;\n }\n\n public clear(): void {\n this._zones.length = 0;\n this._zonePoolIndex = 0;\n }\n\n public addDecoration(decoration: IMinimalDecorationForColorZone): void {\n if (!decoration.options.overviewRulerOptions) {\n return;\n }\n for (const z of this._zones) {\n if (z.color === decoration.options.overviewRulerOptions.color &&\n z.position === decoration.options.overviewRulerOptions.position) {\n if (this._lineIntersectsZone(z, decoration.marker.line)) {\n return;\n }\n if (this._lineAdjacentToZone(z, decoration.marker.line, decoration.options.overviewRulerOptions.position)) {\n this._addLineToZone(z, decoration.marker.line);\n return;\n }\n }\n }\n // Create using zone pool if possible\n if (this._zonePoolIndex < this._zonePool.length) {\n this._zonePool[this._zonePoolIndex].color = decoration.options.overviewRulerOptions.color;\n this._zonePool[this._zonePoolIndex].position = decoration.options.overviewRulerOptions.position;\n this._zonePool[this._zonePoolIndex].startBufferLine = decoration.marker.line;\n this._zonePool[this._zonePoolIndex].endBufferLine = decoration.marker.line;\n this._zones.push(this._zonePool[this._zonePoolIndex++]);\n return;\n }\n // Create\n this._zones.push({\n color: decoration.options.overviewRulerOptions.color,\n position: decoration.options.overviewRulerOptions.position,\n startBufferLine: decoration.marker.line,\n endBufferLine: decoration.marker.line\n });\n this._zonePool.push(this._zones[this._zones.length - 1]);\n this._zonePoolIndex++;\n }\n\n public setPadding(padding: { [position: string]: number }): void {\n this._linePadding = padding;\n }\n\n private _lineIntersectsZone(zone: IColorZone, line: number): boolean {\n return (\n line >= zone.startBufferLine &&\n line <= zone.endBufferLine\n );\n }\n\n private _lineAdjacentToZone(zone: IColorZone, line: number, position: IColorZone['position']): boolean {\n return (\n (line >= zone.startBufferLine - this._linePadding[position || 'full']) &&\n (line <= zone.endBufferLine + this._linePadding[position || 'full'])\n );\n }\n\n private _addLineToZone(zone: IColorZone, line: number): void {\n zone.startBufferLine = Math.min(zone.startBufferLine, line);\n zone.endBufferLine = Math.max(zone.endBufferLine, line);\n }\n}\n", "/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\nimport { ColorZoneStore, IColorZone, IColorZoneStore } from 'browser/decorations/ColorZoneStore';\nimport { ICoreBrowserService, IRenderService, IThemeService } from 'browser/services/Services';\nimport { Disposable, toDisposable } from 'vs/base/common/lifecycle';\nimport { IBufferService, IDecorationService, IOptionsService } from 'common/services/Services';\n\nconst enum Constants {\n OVERVIEW_RULER_BORDER_WIDTH = 1\n}\n\n// Helper objects to avoid excessive calculation and garbage collection during rendering. These are\n// static values for each render and can be accessed using the decoration position as the key.\nconst drawHeight = {\n full: 0,\n left: 0,\n center: 0,\n right: 0\n};\nconst drawWidth = {\n full: 0,\n left: 0,\n center: 0,\n right: 0\n};\nconst drawX = {\n full: 0,\n left: 0,\n center: 0,\n right: 0\n};\n\nexport class OverviewRulerRenderer extends Disposable {\n private readonly _canvas: HTMLCanvasElement;\n private readonly _ctx: CanvasRenderingContext2D;\n private readonly _colorZoneStore: IColorZoneStore = new ColorZoneStore();\n private get _width(): number {\n return this._optionsService.options.overviewRuler?.width || 0;\n }\n private _animationFrame: number | undefined;\n\n private _shouldUpdateDimensions: boolean | undefined = true;\n private _shouldUpdateAnchor: boolean | undefined = true;\n private _lastKnownBufferLength: number = 0;\n\n private _containerHeight: number | undefined;\n\n constructor(\n private readonly _viewportElement: HTMLElement,\n private readonly _screenElement: HTMLElement,\n @IBufferService private readonly _bufferService: IBufferService,\n @IDecorationService private readonly _decorationService: IDecorationService,\n @IRenderService private readonly _renderService: IRenderService,\n @IOptionsService private readonly _optionsService: IOptionsService,\n @IThemeService private readonly _themeService: IThemeService,\n @ICoreBrowserService private readonly _coreBrowserService: ICoreBrowserService\n ) {\n super();\n this._canvas = this._coreBrowserService.mainDocument.createElement('canvas');\n this._canvas.classList.add('xterm-decoration-overview-ruler');\n this._refreshCanvasDimensions();\n this._viewportElement.parentElement?.insertBefore(this._canvas, this._viewportElement);\n this._register(toDisposable(() => this._canvas?.remove()));\n\n const ctx = this._canvas.getContext('2d');\n if (!ctx) {\n throw new Error('Ctx cannot be null');\n } else {\n this._ctx = ctx;\n }\n\n this._register(this._decorationService.onDecorationRegistered(() => this._queueRefresh(undefined, true)));\n this._register(this._decorationService.onDecorationRemoved(() => this._queueRefresh(undefined, true)));\n\n this._register(this._renderService.onRenderedViewportChange(() => this._queueRefresh()));\n this._register(this._bufferService.buffers.onBufferActivate(() => {\n this._canvas!.style.display = this._bufferService.buffer === this._bufferService.buffers.alt ? 'none' : 'block';\n }));\n this._register(this._bufferService.onScroll(() => {\n if (this._lastKnownBufferLength !== this._bufferService.buffers.normal.lines.length) {\n this._refreshDrawHeightConstants();\n this._refreshColorZonePadding();\n }\n }));\n\n // Container height changed\n this._register(this._renderService.onRender((): void => {\n if (!this._containerHeight || this._containerHeight !== this._screenElement.clientHeight) {\n this._queueRefresh(true);\n this._containerHeight = this._screenElement.clientHeight;\n }\n }));\n\n this._register(this._coreBrowserService.onDprChange(() => this._queueRefresh(true)));\n this._register(this._optionsService.onSpecificOptionChange('overviewRuler', () => this._queueRefresh(true)));\n this._register(this._themeService.onChangeColors(() => this._queueRefresh()));\n this._queueRefresh(true);\n }\n\n private _refreshDrawConstants(): void {\n // width\n const outerWidth = Math.floor((this._canvas.width - Constants.OVERVIEW_RULER_BORDER_WIDTH) / 3);\n const innerWidth = Math.ceil((this._canvas.width - Constants.OVERVIEW_RULER_BORDER_WIDTH) / 3);\n drawWidth.full = this._canvas.width;\n drawWidth.left = outerWidth;\n drawWidth.center = innerWidth;\n drawWidth.right = outerWidth;\n // height\n this._refreshDrawHeightConstants();\n // x\n drawX.full = Constants.OVERVIEW_RULER_BORDER_WIDTH;\n drawX.left = Constants.OVERVIEW_RULER_BORDER_WIDTH;\n drawX.center = Constants.OVERVIEW_RULER_BORDER_WIDTH + drawWidth.left;\n drawX.right = Constants.OVERVIEW_RULER_BORDER_WIDTH + drawWidth.left + drawWidth.center;\n }\n\n private _refreshDrawHeightConstants(): void {\n drawHeight.full = Math.round(2 * this._coreBrowserService.dpr);\n // Calculate actual pixels per line\n const pixelsPerLine = this._canvas.height / this._bufferService.buffer.lines.length;\n // Clamp actual pixels within a range\n const nonFullHeight = Math.round(Math.max(Math.min(pixelsPerLine, 12), 6) * this._coreBrowserService.dpr);\n drawHeight.left = nonFullHeight;\n drawHeight.center = nonFullHeight;\n drawHeight.right = nonFullHeight;\n }\n\n private _refreshColorZonePadding(): void {\n this._colorZoneStore.setPadding({\n full: Math.floor(this._bufferService.buffers.active.lines.length / (this._canvas.height - 1) * drawHeight.full),\n left: Math.floor(this._bufferService.buffers.active.lines.length / (this._canvas.height - 1) * drawHeight.left),\n center: Math.floor(this._bufferService.buffers.active.lines.length / (this._canvas.height - 1) * drawHeight.center),\n right: Math.floor(this._bufferService.buffers.active.lines.length / (this._canvas.height - 1) * drawHeight.right)\n });\n this._lastKnownBufferLength = this._bufferService.buffers.normal.lines.length;\n }\n\n private _refreshCanvasDimensions(): void {\n this._canvas.style.width = `${this._width}px`;\n this._canvas.width = Math.round(this._width * this._coreBrowserService.dpr);\n this._canvas.style.height = `${this._screenElement.clientHeight}px`;\n this._canvas.height = Math.round(this._screenElement.clientHeight * this._coreBrowserService.dpr);\n this._refreshDrawConstants();\n this._refreshColorZonePadding();\n }\n\n private _refreshDecorations(): void {\n if (this._shouldUpdateDimensions) {\n this._refreshCanvasDimensions();\n }\n this._ctx.clearRect(0, 0, this._canvas.width, this._canvas.height);\n this._colorZoneStore.clear();\n for (const decoration of this._decorationService.decorations) {\n this._colorZoneStore.addDecoration(decoration);\n }\n this._ctx.lineWidth = 1;\n this._renderRulerOutline();\n const zones = this._colorZoneStore.zones;\n for (const zone of zones) {\n if (zone.position !== 'full') {\n this._renderColorZone(zone);\n }\n }\n for (const zone of zones) {\n if (zone.position === 'full') {\n this._renderColorZone(zone);\n }\n }\n this._shouldUpdateDimensions = false;\n this._shouldUpdateAnchor = false;\n }\n\n private _renderRulerOutline(): void {\n this._ctx.fillStyle = this._themeService.colors.overviewRulerBorder.css;\n this._ctx.fillRect(0, 0, Constants.OVERVIEW_RULER_BORDER_WIDTH, this._canvas.height);\n if (this._optionsService.rawOptions.overviewRuler.showTopBorder) {\n this._ctx.fillRect(Constants.OVERVIEW_RULER_BORDER_WIDTH, 0, this._canvas.width - Constants.OVERVIEW_RULER_BORDER_WIDTH, Constants.OVERVIEW_RULER_BORDER_WIDTH);\n }\n if (this._optionsService.rawOptions.overviewRuler.showBottomBorder) {\n this._ctx.fillRect(Constants.OVERVIEW_RULER_BORDER_WIDTH, this._canvas.height - Constants.OVERVIEW_RULER_BORDER_WIDTH, this._canvas.width - Constants.OVERVIEW_RULER_BORDER_WIDTH, this._canvas.height);\n }\n }\n\n private _renderColorZone(zone: IColorZone): void {\n this._ctx.fillStyle = zone.color;\n this._ctx.fillRect(\n /* x */ drawX[zone.position || 'full'],\n /* y */ Math.round(\n (this._canvas.height - 1) * // -1 to ensure at least 2px are allowed for decoration on last line\n (zone.startBufferLine / this._bufferService.buffers.active.lines.length) - drawHeight[zone.position || 'full'] / 2\n ),\n /* w */ drawWidth[zone.position || 'full'],\n /* h */ Math.round(\n (this._canvas.height - 1) * // -1 to ensure at least 2px are allowed for decoration on last line\n ((zone.endBufferLine - zone.startBufferLine) / this._bufferService.buffers.active.lines.length) + drawHeight[zone.position || 'full']\n )\n );\n }\n\n private _queueRefresh(updateCanvasDimensions?: boolean, updateAnchor?: boolean): void {\n this._shouldUpdateDimensions = updateCanvasDimensions || this._shouldUpdateDimensions;\n this._shouldUpdateAnchor = updateAnchor || this._shouldUpdateAnchor;\n if (this._animationFrame !== undefined) {\n return;\n }\n this._animationFrame = this._coreBrowserService.window.requestAnimationFrame(() => {\n this._refreshDecorations();\n this._animationFrame = undefined;\n });\n }\n}\n", "/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\n/**\n * C0 control codes\n * See = https://en.wikipedia.org/wiki/C0_and_C1_control_codes\n */\nexport namespace C0 {\n /** Null (Caret = ^@, C = \\0) */\n export const NUL = '\\x00';\n /** Start of Heading (Caret = ^A) */\n export const SOH = '\\x01';\n /** Start of Text (Caret = ^B) */\n export const STX = '\\x02';\n /** End of Text (Caret = ^C) */\n export const ETX = '\\x03';\n /** End of Transmission (Caret = ^D) */\n export const EOT = '\\x04';\n /** Enquiry (Caret = ^E) */\n export const ENQ = '\\x05';\n /** Acknowledge (Caret = ^F) */\n export const ACK = '\\x06';\n /** Bell (Caret = ^G, C = \\a) */\n export const BEL = '\\x07';\n /** Backspace (Caret = ^H, C = \\b) */\n export const BS = '\\x08';\n /** Character Tabulation, Horizontal Tabulation (Caret = ^I, C = \\t) */\n export const HT = '\\x09';\n /** Line Feed (Caret = ^J, C = \\n) */\n export const LF = '\\x0a';\n /** Line Tabulation, Vertical Tabulation (Caret = ^K, C = \\v) */\n export const VT = '\\x0b';\n /** Form Feed (Caret = ^L, C = \\f) */\n export const FF = '\\x0c';\n /** Carriage Return (Caret = ^M, C = \\r) */\n export const CR = '\\x0d';\n /** Shift Out (Caret = ^N) */\n export const SO = '\\x0e';\n /** Shift In (Caret = ^O) */\n export const SI = '\\x0f';\n /** Data Link Escape (Caret = ^P) */\n export const DLE = '\\x10';\n /** Device Control One (XON) (Caret = ^Q) */\n export const DC1 = '\\x11';\n /** Device Control Two (Caret = ^R) */\n export const DC2 = '\\x12';\n /** Device Control Three (XOFF) (Caret = ^S) */\n export const DC3 = '\\x13';\n /** Device Control Four (Caret = ^T) */\n export const DC4 = '\\x14';\n /** Negative Acknowledge (Caret = ^U) */\n export const NAK = '\\x15';\n /** Synchronous Idle (Caret = ^V) */\n export const SYN = '\\x16';\n /** End of Transmission Block (Caret = ^W) */\n export const ETB = '\\x17';\n /** Cancel (Caret = ^X) */\n export const CAN = '\\x18';\n /** End of Medium (Caret = ^Y) */\n export const EM = '\\x19';\n /** Substitute (Caret = ^Z) */\n export const SUB = '\\x1a';\n /** Escape (Caret = ^[, C = \\e) */\n export const ESC = '\\x1b';\n /** File Separator (Caret = ^\\) */\n export const FS = '\\x1c';\n /** Group Separator (Caret = ^]) */\n export const GS = '\\x1d';\n /** Record Separator (Caret = ^^) */\n export const RS = '\\x1e';\n /** Unit Separator (Caret = ^_) */\n export const US = '\\x1f';\n /** Space */\n export const SP = '\\x20';\n /** Delete (Caret = ^?) */\n export const DEL = '\\x7f';\n}\n\n/**\n * C1 control codes\n * See = https://en.wikipedia.org/wiki/C0_and_C1_control_codes\n */\nexport namespace C1 {\n /** padding character */\n export const PAD = '\\x80';\n /** High Octet Preset */\n export const HOP = '\\x81';\n /** Break Permitted Here */\n export const BPH = '\\x82';\n /** No Break Here */\n export const NBH = '\\x83';\n /** Index */\n export const IND = '\\x84';\n /** Next Line */\n export const NEL = '\\x85';\n /** Start of Selected Area */\n export const SSA = '\\x86';\n /** End of Selected Area */\n export const ESA = '\\x87';\n /** Horizontal Tabulation Set */\n export const HTS = '\\x88';\n /** Horizontal Tabulation With Justification */\n export const HTJ = '\\x89';\n /** Vertical Tabulation Set */\n export const VTS = '\\x8a';\n /** Partial Line Down */\n export const PLD = '\\x8b';\n /** Partial Line Up */\n export const PLU = '\\x8c';\n /** Reverse Index */\n export const RI = '\\x8d';\n /** Single-Shift 2 */\n export const SS2 = '\\x8e';\n /** Single-Shift 3 */\n export const SS3 = '\\x8f';\n /** Device Control String */\n export const DCS = '\\x90';\n /** Private Use 1 */\n export const PU1 = '\\x91';\n /** Private Use 2 */\n export const PU2 = '\\x92';\n /** Set Transmit State */\n export const STS = '\\x93';\n /** Destructive backspace, intended to eliminate ambiguity about meaning of BS. */\n export const CCH = '\\x94';\n /** Message Waiting */\n export const MW = '\\x95';\n /** Start of Protected Area */\n export const SPA = '\\x96';\n /** End of Protected Area */\n export const EPA = '\\x97';\n /** Start of String */\n export const SOS = '\\x98';\n /** Single Graphic Character Introducer */\n export const SGCI = '\\x99';\n /** Single Character Introducer */\n export const SCI = '\\x9a';\n /** Control Sequence Introducer */\n export const CSI = '\\x9b';\n /** String Terminator */\n export const ST = '\\x9c';\n /** Operating System Command */\n export const OSC = '\\x9d';\n /** Privacy Message */\n export const PM = '\\x9e';\n /** Application Program Command */\n export const APC = '\\x9f';\n}\nexport namespace C1_ESCAPED {\n export const ST = `${C0.ESC}\\\\`;\n}\n", "/**\n * Copyright (c) 2016 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IRenderService } from 'browser/services/Services';\nimport { IBufferService, ICoreService, IOptionsService } from 'common/services/Services';\nimport { C0 } from 'common/data/EscapeSequences';\n\ninterface IPosition {\n start: number;\n end: number;\n}\n\n/**\n * Encapsulates the logic for handling compositionstart, compositionupdate and compositionend\n * events, displaying the in-progress composition to the UI and forwarding the final composition\n * to the handler.\n */\nexport class CompositionHelper {\n /**\n * Whether input composition is currently happening, eg. via a mobile keyboard, speech input or\n * IME. This variable determines whether the compositionText should be displayed on the UI.\n */\n private _isComposing: boolean;\n public get isComposing(): boolean { return this._isComposing; }\n\n /**\n * The position within the input textarea's value of the current composition.\n */\n private _compositionPosition: IPosition;\n\n /**\n * Whether a composition is in the process of being sent, setting this to false will cancel any\n * in-progress composition.\n */\n private _isSendingComposition: boolean;\n\n /**\n * Data already sent due to keydown event.\n */\n private _dataAlreadySent: string;\n\n constructor(\n private readonly _textarea: HTMLTextAreaElement,\n private readonly _compositionView: HTMLElement,\n @IBufferService private readonly _bufferService: IBufferService,\n @IOptionsService private readonly _optionsService: IOptionsService,\n @ICoreService private readonly _coreService: ICoreService,\n @IRenderService private readonly _renderService: IRenderService\n ) {\n this._isComposing = false;\n this._isSendingComposition = false;\n this._compositionPosition = { start: 0, end: 0 };\n this._dataAlreadySent = '';\n }\n\n /**\n * Handles the compositionstart event, activating the composition view.\n */\n public compositionstart(): void {\n this._isComposing = true;\n this._compositionPosition.start = this._textarea.value.length;\n this._compositionView.textContent = '';\n this._dataAlreadySent = '';\n this._compositionView.classList.add('active');\n }\n\n /**\n * Handles the compositionupdate event, updating the composition view.\n * @param ev The event.\n */\n public compositionupdate(ev: Pick): void {\n this._compositionView.textContent = ev.data;\n this.updateCompositionElements();\n setTimeout(() => {\n this._compositionPosition.end = this._textarea.value.length;\n }, 0);\n }\n\n /**\n * Handles the compositionend event, hiding the composition view and sending the composition to\n * the handler.\n */\n public compositionend(): void {\n this._finalizeComposition(true);\n }\n\n /**\n * Handles the keydown event, routing any necessary events to the CompositionHelper functions.\n * @param ev The keydown event.\n * @returns Whether the Terminal should continue processing the keydown event.\n */\n public keydown(ev: KeyboardEvent): boolean {\n if (this._isComposing || this._isSendingComposition) {\n if (ev.keyCode === 20 || ev.keyCode === 229) {\n // 20 is CapsLock, 229 is Enter\n // Continue composing if the keyCode is the \"composition character\"\n return false;\n }\n if (ev.keyCode === 16 || ev.keyCode === 17 || ev.keyCode === 18) {\n // Continue composing if the keyCode is a modifier key\n return false;\n }\n // Finish composition immediately. This is mainly here for the case where enter is\n // pressed and the handler needs to be triggered before the command is executed.\n this._finalizeComposition(false);\n }\n\n if (ev.keyCode === 229) {\n // If the \"composition character\" is used but gets to this point it means a non-composition\n // character (eg. numbers and punctuation) was pressed when the IME was active.\n this._handleAnyTextareaChanges();\n return false;\n }\n\n return true;\n }\n\n /**\n * Finalizes the composition, resuming regular input actions. This is called when a composition\n * is ending.\n * @param waitForPropagation Whether to wait for events to propagate before sending\n * the input. This should be false if a non-composition keystroke is entered before the\n * compositionend event is triggered, such as enter, so that the composition is sent before\n * the command is executed.\n */\n private _finalizeComposition(waitForPropagation: boolean): void {\n this._compositionView.classList.remove('active');\n this._isComposing = false;\n\n if (!waitForPropagation) {\n // Cancel any delayed composition send requests and send the input immediately.\n this._isSendingComposition = false;\n const input = this._textarea.value.substring(this._compositionPosition.start, this._compositionPosition.end);\n this._coreService.triggerDataEvent(input, true);\n } else {\n // Make a deep copy of the composition position here as a new compositionstart event may\n // fire before the setTimeout executes.\n const currentCompositionPosition = {\n start: this._compositionPosition.start,\n end: this._compositionPosition.end\n };\n\n // Since composition* events happen before the changes take place in the textarea on most\n // browsers, use a setTimeout with 0ms time to allow the native compositionend event to\n // complete. This ensures the correct character is retrieved.\n // This solution was used because:\n // - The compositionend event's data property is unreliable, at least on Chromium\n // - The last compositionupdate event's data property does not always accurately describe\n // the character, a counter example being Korean where an ending consonsant can move to\n // the following character if the following input is a vowel.\n this._isSendingComposition = true;\n setTimeout(() => {\n // Ensure that the input has not already been sent\n if (this._isSendingComposition) {\n this._isSendingComposition = false;\n let input;\n // Add length of data already sent due to keydown event,\n // otherwise input characters can be duplicated. (Issue #3191)\n currentCompositionPosition.start += this._dataAlreadySent.length;\n if (this._isComposing) {\n // Use the start position of the new composition to get the string\n // if a new composition has started.\n input = this._textarea.value.substring(currentCompositionPosition.start, this._compositionPosition.start);\n } else {\n // Don't use the end position here in order to pick up any characters after the\n // composition has finished, for example when typing a non-composition character\n // (eg. 2) after a composition character.\n input = this._textarea.value.substring(currentCompositionPosition.start);\n }\n if (input.length > 0) {\n this._coreService.triggerDataEvent(input, true);\n }\n }\n }, 0);\n }\n }\n\n /**\n * Apply any changes made to the textarea after the current event chain is allowed to complete.\n * This should be called when not currently composing but a keydown event with the \"composition\n * character\" (229) is triggered, in order to allow non-composition text to be entered when an\n * IME is active.\n */\n private _handleAnyTextareaChanges(): void {\n const oldValue = this._textarea.value;\n setTimeout(() => {\n // Ignore if a composition has started since the timeout\n if (!this._isComposing) {\n const newValue = this._textarea.value;\n\n const diff = newValue.replace(oldValue, '');\n\n this._dataAlreadySent = diff;\n\n if (newValue.length > oldValue.length) {\n this._coreService.triggerDataEvent(diff, true);\n } else if (newValue.length < oldValue.length) {\n this._coreService.triggerDataEvent(`${C0.DEL}`, true);\n } else if ((newValue.length === oldValue.length) && (newValue !== oldValue)) {\n this._coreService.triggerDataEvent(newValue, true);\n }\n\n }\n }, 0);\n }\n\n /**\n * Positions the composition view on top of the cursor and the textarea just below it (so the\n * IME helper dialog is positioned correctly).\n * @param dontRecurse Whether to use setTimeout to recursively trigger another update, this is\n * necessary as the IME events across browsers are not consistently triggered.\n */\n public updateCompositionElements(dontRecurse?: boolean): void {\n if (!this._isComposing) {\n return;\n }\n\n if (this._bufferService.buffer.isCursorInViewport) {\n const cursorX = Math.min(this._bufferService.buffer.x, this._bufferService.cols - 1);\n\n const cellHeight = this._renderService.dimensions.css.cell.height;\n const cursorTop = this._bufferService.buffer.y * this._renderService.dimensions.css.cell.height;\n const cursorLeft = cursorX * this._renderService.dimensions.css.cell.width;\n\n this._compositionView.style.left = cursorLeft + 'px';\n this._compositionView.style.top = cursorTop + 'px';\n this._compositionView.style.height = cellHeight + 'px';\n this._compositionView.style.lineHeight = cellHeight + 'px';\n this._compositionView.style.fontFamily = this._optionsService.rawOptions.fontFamily;\n this._compositionView.style.fontSize = this._optionsService.rawOptions.fontSize + 'px';\n // Sync the textarea to the exact position of the composition view so the IME knows where the\n // text is.\n const compositionViewBounds = this._compositionView.getBoundingClientRect();\n this._textarea.style.left = cursorLeft + 'px';\n this._textarea.style.top = cursorTop + 'px';\n // Ensure the text area is at least 1x1, otherwise certain IMEs may break\n this._textarea.style.width = Math.max(compositionViewBounds.width, 1) + 'px';\n this._textarea.style.height = Math.max(compositionViewBounds.height, 1) + 'px';\n this._textarea.style.lineHeight = compositionViewBounds.height + 'px';\n }\n\n if (!dontRecurse) {\n setTimeout(() => this.updateCompositionElements(true), 0);\n }\n }\n}\n", "/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IColor, IColorRGB } from 'common/Types';\n\nlet $r = 0;\nlet $g = 0;\nlet $b = 0;\nlet $a = 0;\n\nexport const NULL_COLOR: IColor = {\n css: '#00000000',\n rgba: 0\n};\n\n/**\n * Helper functions where the source type is \"channels\" (individual color channels as numbers).\n */\nexport namespace channels {\n export function toCss(r: number, g: number, b: number, a?: number): string {\n if (a !== undefined) {\n return `#${toPaddedHex(r)}${toPaddedHex(g)}${toPaddedHex(b)}${toPaddedHex(a)}`;\n }\n return `#${toPaddedHex(r)}${toPaddedHex(g)}${toPaddedHex(b)}`;\n }\n\n export function toRgba(r: number, g: number, b: number, a: number = 0xFF): number {\n // Note: The aggregated number is RGBA32 (BE), thus needs to be converted to ABGR32\n // on LE systems, before it can be used for direct 32-bit buffer writes.\n // >>> 0 forces an unsigned int\n return (r << 24 | g << 16 | b << 8 | a) >>> 0;\n }\n\n export function toColor(r: number, g: number, b: number, a?: number): IColor {\n return {\n css: channels.toCss(r, g, b, a),\n rgba: channels.toRgba(r, g, b, a)\n };\n }\n}\n\n/**\n * Helper functions where the source type is `IColor`.\n */\nexport namespace color {\n export function blend(bg: IColor, fg: IColor): IColor {\n $a = (fg.rgba & 0xFF) / 255;\n if ($a === 1) {\n return {\n css: fg.css,\n rgba: fg.rgba\n };\n }\n const fgR = (fg.rgba >> 24) & 0xFF;\n const fgG = (fg.rgba >> 16) & 0xFF;\n const fgB = (fg.rgba >> 8) & 0xFF;\n const bgR = (bg.rgba >> 24) & 0xFF;\n const bgG = (bg.rgba >> 16) & 0xFF;\n const bgB = (bg.rgba >> 8) & 0xFF;\n $r = bgR + Math.round((fgR - bgR) * $a);\n $g = bgG + Math.round((fgG - bgG) * $a);\n $b = bgB + Math.round((fgB - bgB) * $a);\n const css = channels.toCss($r, $g, $b);\n const rgba = channels.toRgba($r, $g, $b);\n return { css, rgba };\n }\n\n export function isOpaque(color: IColor): boolean {\n return (color.rgba & 0xFF) === 0xFF;\n }\n\n export function ensureContrastRatio(bg: IColor, fg: IColor, ratio: number): IColor | undefined {\n const result = rgba.ensureContrastRatio(bg.rgba, fg.rgba, ratio);\n if (!result) {\n return undefined;\n }\n return channels.toColor(\n (result >> 24 & 0xFF),\n (result >> 16 & 0xFF),\n (result >> 8 & 0xFF)\n );\n }\n\n export function opaque(color: IColor): IColor {\n const rgbaColor = (color.rgba | 0xFF) >>> 0;\n [$r, $g, $b] = rgba.toChannels(rgbaColor);\n return {\n css: channels.toCss($r, $g, $b),\n rgba: rgbaColor\n };\n }\n\n export function opacity(color: IColor, opacity: number): IColor {\n $a = Math.round(opacity * 0xFF);\n [$r, $g, $b] = rgba.toChannels(color.rgba);\n return {\n css: channels.toCss($r, $g, $b, $a),\n rgba: channels.toRgba($r, $g, $b, $a)\n };\n }\n\n export function multiplyOpacity(color: IColor, factor: number): IColor {\n $a = color.rgba & 0xFF;\n return opacity(color, ($a * factor) / 0xFF);\n }\n\n export function toColorRGB(color: IColor): IColorRGB {\n return [(color.rgba >> 24) & 0xFF, (color.rgba >> 16) & 0xFF, (color.rgba >> 8) & 0xFF];\n }\n}\n\n/**\n * Helper functions where the source type is \"css\" (string: '#rgb', '#rgba', '#rrggbb',\n * '#rrggbbaa').\n */\nexport namespace css {\n // Attempt to set get the shared canvas context\n let $ctx: CanvasRenderingContext2D | undefined;\n let $litmusColor: CanvasGradient | undefined;\n try {\n // This is guaranteed to run in the first window, so document should be correct\n const canvas = document.createElement('canvas');\n canvas.width = 1;\n canvas.height = 1;\n const ctx = canvas.getContext('2d', {\n willReadFrequently: true\n });\n if (ctx) {\n $ctx = ctx;\n $ctx.globalCompositeOperation = 'copy';\n $litmusColor = $ctx.createLinearGradient(0, 0, 1, 1);\n }\n }\n catch {\n // noop\n }\n\n /**\n * Converts a css string to an IColor, this should handle all valid CSS color strings and will\n * throw if it's invalid. The ideal format to use is `#rrggbb[aa]` as it's the fastest to parse.\n *\n * Only `#rgb[a]`, `#rrggbb[aa]`, `rgb()` and `rgba()` formats are supported when run in a Node\n * environment.\n */\n export function toColor(css: string): IColor {\n // Formats: #rgb[a] and #rrggbb[aa]\n if (css.match(/#[\\da-f]{3,8}/i)) {\n switch (css.length) {\n case 4: { // #rgb\n $r = parseInt(css.slice(1, 2).repeat(2), 16);\n $g = parseInt(css.slice(2, 3).repeat(2), 16);\n $b = parseInt(css.slice(3, 4).repeat(2), 16);\n return channels.toColor($r, $g, $b);\n }\n case 5: { // #rgba\n $r = parseInt(css.slice(1, 2).repeat(2), 16);\n $g = parseInt(css.slice(2, 3).repeat(2), 16);\n $b = parseInt(css.slice(3, 4).repeat(2), 16);\n $a = parseInt(css.slice(4, 5).repeat(2), 16);\n return channels.toColor($r, $g, $b, $a);\n }\n case 7: // #rrggbb\n return {\n css,\n rgba: (parseInt(css.slice(1), 16) << 8 | 0xFF) >>> 0\n };\n case 9: // #rrggbbaa\n return {\n css,\n rgba: parseInt(css.slice(1), 16) >>> 0\n };\n }\n }\n\n // Formats: rgb() or rgba()\n const rgbaMatch = css.match(/rgba?\\(\\s*(\\d{1,3})\\s*,\\s*(\\d{1,3})\\s*,\\s*(\\d{1,3})\\s*(,\\s*(0|1|\\d?\\.(\\d+))\\s*)?\\)/);\n if (rgbaMatch) {\n $r = parseInt(rgbaMatch[1]);\n $g = parseInt(rgbaMatch[2]);\n $b = parseInt(rgbaMatch[3]);\n $a = Math.round((rgbaMatch[5] === undefined ? 1 : parseFloat(rgbaMatch[5])) * 0xFF);\n return channels.toColor($r, $g, $b, $a);\n }\n\n // Validate the context is available for canvas-based color parsing\n if (!$ctx || !$litmusColor) {\n throw new Error('css.toColor: Unsupported css format');\n }\n\n // Validate the color using canvas fillStyle\n // See https://html.spec.whatwg.org/multipage/canvas.html#fill-and-stroke-styles\n $ctx.fillStyle = $litmusColor;\n $ctx.fillStyle = css;\n if (typeof $ctx.fillStyle !== 'string') {\n throw new Error('css.toColor: Unsupported css format');\n }\n\n $ctx.fillRect(0, 0, 1, 1);\n [$r, $g, $b, $a] = $ctx.getImageData(0, 0, 1, 1).data;\n\n // Validate the color is non-transparent as color hue gets lost when drawn to the canvas\n if ($a !== 0xFF) {\n throw new Error('css.toColor: Unsupported css format');\n }\n\n // Extract the color from the canvas' fillStyle property which exposes the color value in rgba()\n // format\n // See https://html.spec.whatwg.org/multipage/canvas.html#serialisation-of-a-color\n return {\n rgba: channels.toRgba($r, $g, $b, $a),\n css\n };\n }\n}\n\n/**\n * Helper functions where the source type is \"rgb\" (number: 0xrrggbb).\n */\nexport namespace rgb {\n /**\n * Gets the relative luminance of an RGB color, this is useful in determining the contrast ratio\n * between two colors.\n * @param rgb The color to use.\n * @see https://www.w3.org/TR/WCAG20/#relativeluminancedef\n */\n export function relativeLuminance(rgb: number): number {\n return relativeLuminance2(\n (rgb >> 16) & 0xFF,\n (rgb >> 8 ) & 0xFF,\n (rgb ) & 0xFF);\n }\n\n /**\n * Gets the relative luminance of an RGB color, this is useful in determining the contrast ratio\n * between two colors.\n * @param r The red channel (0x00 to 0xFF).\n * @param g The green channel (0x00 to 0xFF).\n * @param b The blue channel (0x00 to 0xFF).\n * @see https://www.w3.org/TR/WCAG20/#relativeluminancedef\n */\n export function relativeLuminance2(r: number, g: number, b: number): number {\n const rs = r / 255;\n const gs = g / 255;\n const bs = b / 255;\n const rr = rs <= 0.03928 ? rs / 12.92 : Math.pow((rs + 0.055) / 1.055, 2.4);\n const rg = gs <= 0.03928 ? gs / 12.92 : Math.pow((gs + 0.055) / 1.055, 2.4);\n const rb = bs <= 0.03928 ? bs / 12.92 : Math.pow((bs + 0.055) / 1.055, 2.4);\n return rr * 0.2126 + rg * 0.7152 + rb * 0.0722;\n }\n}\n\n/**\n * Helper functions where the source type is \"rgba\" (number: 0xrrggbbaa).\n */\nexport namespace rgba {\n export function blend(bg: number, fg: number): number {\n $a = (fg & 0xFF) / 0xFF;\n if ($a === 1) {\n return fg;\n }\n const fgR = (fg >> 24) & 0xFF;\n const fgG = (fg >> 16) & 0xFF;\n const fgB = (fg >> 8) & 0xFF;\n const bgR = (bg >> 24) & 0xFF;\n const bgG = (bg >> 16) & 0xFF;\n const bgB = (bg >> 8) & 0xFF;\n $r = bgR + Math.round((fgR - bgR) * $a);\n $g = bgG + Math.round((fgG - bgG) * $a);\n $b = bgB + Math.round((fgB - bgB) * $a);\n return channels.toRgba($r, $g, $b);\n }\n\n /**\n * Given a foreground color and a background color, either increase or reduce the luminance of the\n * foreground color until the specified contrast ratio is met. If pure white or black is hit\n * without the contrast ratio being met, go the other direction using the background color as the\n * foreground color and take either the first or second result depending on which has the higher\n * contrast ratio.\n *\n * `undefined` will be returned if the contrast ratio is already met.\n *\n * @param bgRgba The background color in rgba format.\n * @param fgRgba The foreground color in rgba format.\n * @param ratio The contrast ratio to achieve.\n */\n export function ensureContrastRatio(bgRgba: number, fgRgba: number, ratio: number): number | undefined {\n const bgL = rgb.relativeLuminance(bgRgba >> 8);\n const fgL = rgb.relativeLuminance(fgRgba >> 8);\n const cr = contrastRatio(bgL, fgL);\n if (cr < ratio) {\n if (fgL < bgL) {\n const resultA = reduceLuminance(bgRgba, fgRgba, ratio);\n const resultARatio = contrastRatio(bgL, rgb.relativeLuminance(resultA >> 8));\n if (resultARatio < ratio) {\n const resultB = increaseLuminance(bgRgba, fgRgba, ratio);\n const resultBRatio = contrastRatio(bgL, rgb.relativeLuminance(resultB >> 8));\n return resultARatio > resultBRatio ? resultA : resultB;\n }\n return resultA;\n }\n const resultA = increaseLuminance(bgRgba, fgRgba, ratio);\n const resultARatio = contrastRatio(bgL, rgb.relativeLuminance(resultA >> 8));\n if (resultARatio < ratio) {\n const resultB = reduceLuminance(bgRgba, fgRgba, ratio);\n const resultBRatio = contrastRatio(bgL, rgb.relativeLuminance(resultB >> 8));\n return resultARatio > resultBRatio ? resultA : resultB;\n }\n return resultA;\n }\n return undefined;\n }\n\n export function reduceLuminance(bgRgba: number, fgRgba: number, ratio: number): number {\n // This is a naive but fast approach to reducing luminance as converting to\n // HSL and back is expensive\n const bgR = (bgRgba >> 24) & 0xFF;\n const bgG = (bgRgba >> 16) & 0xFF;\n const bgB = (bgRgba >> 8) & 0xFF;\n let fgR = (fgRgba >> 24) & 0xFF;\n let fgG = (fgRgba >> 16) & 0xFF;\n let fgB = (fgRgba >> 8) & 0xFF;\n let cr = contrastRatio(rgb.relativeLuminance2(fgR, fgG, fgB), rgb.relativeLuminance2(bgR, bgG, bgB));\n while (cr < ratio && (fgR > 0 || fgG > 0 || fgB > 0)) {\n // Reduce by 10% until the ratio is hit\n fgR -= Math.max(0, Math.ceil(fgR * 0.1));\n fgG -= Math.max(0, Math.ceil(fgG * 0.1));\n fgB -= Math.max(0, Math.ceil(fgB * 0.1));\n cr = contrastRatio(rgb.relativeLuminance2(fgR, fgG, fgB), rgb.relativeLuminance2(bgR, bgG, bgB));\n }\n return (fgR << 24 | fgG << 16 | fgB << 8 | 0xFF) >>> 0;\n }\n\n export function increaseLuminance(bgRgba: number, fgRgba: number, ratio: number): number {\n // This is a naive but fast approach to increasing luminance as converting to\n // HSL and back is expensive\n const bgR = (bgRgba >> 24) & 0xFF;\n const bgG = (bgRgba >> 16) & 0xFF;\n const bgB = (bgRgba >> 8) & 0xFF;\n let fgR = (fgRgba >> 24) & 0xFF;\n let fgG = (fgRgba >> 16) & 0xFF;\n let fgB = (fgRgba >> 8) & 0xFF;\n let cr = contrastRatio(rgb.relativeLuminance2(fgR, fgG, fgB), rgb.relativeLuminance2(bgR, bgG, bgB));\n while (cr < ratio && (fgR < 0xFF || fgG < 0xFF || fgB < 0xFF)) {\n // Increase by 10% until the ratio is hit\n fgR = Math.min(0xFF, fgR + Math.ceil((255 - fgR) * 0.1));\n fgG = Math.min(0xFF, fgG + Math.ceil((255 - fgG) * 0.1));\n fgB = Math.min(0xFF, fgB + Math.ceil((255 - fgB) * 0.1));\n cr = contrastRatio(rgb.relativeLuminance2(fgR, fgG, fgB), rgb.relativeLuminance2(bgR, bgG, bgB));\n }\n return (fgR << 24 | fgG << 16 | fgB << 8 | 0xFF) >>> 0;\n }\n\n export function toChannels(value: number): [number, number, number, number] {\n return [(value >> 24) & 0xFF, (value >> 16) & 0xFF, (value >> 8) & 0xFF, value & 0xFF];\n }\n}\n\nexport function toPaddedHex(c: number): string {\n const s = c.toString(16);\n return s.length < 2 ? '0' + s : s;\n}\n\n/**\n * Gets the contrast ratio between two relative luminance values.\n * @param l1 The first relative luminance.\n * @param l2 The first relative luminance.\n * @see https://www.w3.org/TR/WCAG20/#contrast-ratiodef\n */\nexport function contrastRatio(l1: number, l2: number): number {\n if (l1 < l2) {\n return (l2 + 0.05) / (l1 + 0.05);\n }\n return (l1 + 0.05) / (l2 + 0.05);\n}\n", "/**\n * Copyright (c) 2018 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IBufferLine, ICellData, CharData } from 'common/Types';\nimport { ICharacterJoiner } from 'browser/Types';\nimport { AttributeData } from 'common/buffer/AttributeData';\nimport { WHITESPACE_CELL_CHAR, Content } from 'common/buffer/Constants';\nimport { CellData } from 'common/buffer/CellData';\nimport { IBufferService } from 'common/services/Services';\nimport { ICharacterJoinerService } from 'browser/services/Services';\n\nexport class JoinedCellData extends AttributeData implements ICellData {\n private _width: number;\n // .content carries no meaning for joined CellData, simply nullify it\n // thus we have to overload all other .content accessors\n public content: number = 0;\n public fg: number;\n public bg: number;\n public combinedData: string = '';\n\n constructor(firstCell: ICellData, chars: string, width: number) {\n super();\n this.fg = firstCell.fg;\n this.bg = firstCell.bg;\n this.combinedData = chars;\n this._width = width;\n }\n\n public isCombined(): number {\n // always mark joined cell data as combined\n return Content.IS_COMBINED_MASK;\n }\n\n public getWidth(): number {\n return this._width;\n }\n\n public getChars(): string {\n return this.combinedData;\n }\n\n public getCode(): number {\n // code always gets the highest possible fake codepoint (read as -1)\n // this is needed as code is used by caches as identifier\n return 0x1FFFFF;\n }\n\n public setFromCharData(value: CharData): void {\n throw new Error('not implemented');\n }\n\n public getAsCharData(): CharData {\n return [this.fg, this.getChars(), this.getWidth(), this.getCode()];\n }\n}\n\nexport class CharacterJoinerService implements ICharacterJoinerService {\n public serviceBrand: undefined;\n\n private _characterJoiners: ICharacterJoiner[] = [];\n private _nextCharacterJoinerId: number = 0;\n private _workCell: CellData = new CellData();\n\n constructor(\n @IBufferService private _bufferService: IBufferService\n ) { }\n\n public register(handler: (text: string) => [number, number][]): number {\n const joiner: ICharacterJoiner = {\n id: this._nextCharacterJoinerId++,\n handler\n };\n\n this._characterJoiners.push(joiner);\n return joiner.id;\n }\n\n public deregister(joinerId: number): boolean {\n for (let i = 0; i < this._characterJoiners.length; i++) {\n if (this._characterJoiners[i].id === joinerId) {\n this._characterJoiners.splice(i, 1);\n return true;\n }\n }\n\n return false;\n }\n\n public getJoinedCharacters(row: number): [number, number][] {\n if (this._characterJoiners.length === 0) {\n return [];\n }\n\n const line = this._bufferService.buffer.lines.get(row);\n if (!line || line.length === 0) {\n return [];\n }\n\n const ranges: [number, number][] = [];\n const lineStr = line.translateToString(true);\n\n // Because some cells can be represented by multiple javascript characters,\n // we track the cell and the string indexes separately. This allows us to\n // translate the string ranges we get from the joiners back into cell ranges\n // for use when rendering\n let rangeStartColumn = 0;\n let currentStringIndex = 0;\n let rangeStartStringIndex = 0;\n let rangeAttrFG = line.getFg(0);\n let rangeAttrBG = line.getBg(0);\n\n for (let x = 0; x < line.getTrimmedLength(); x++) {\n line.loadCell(x, this._workCell);\n\n if (this._workCell.getWidth() === 0) {\n // If this character is of width 0, skip it.\n continue;\n }\n\n // End of range\n if (this._workCell.fg !== rangeAttrFG || this._workCell.bg !== rangeAttrBG) {\n // If we ended up with a sequence of more than one character,\n // look for ranges to join.\n if (x - rangeStartColumn > 1) {\n const joinedRanges = this._getJoinedRanges(\n lineStr,\n rangeStartStringIndex,\n currentStringIndex,\n line,\n rangeStartColumn\n );\n for (let i = 0; i < joinedRanges.length; i++) {\n ranges.push(joinedRanges[i]);\n }\n }\n\n // Reset our markers for a new range.\n rangeStartColumn = x;\n rangeStartStringIndex = currentStringIndex;\n rangeAttrFG = this._workCell.fg;\n rangeAttrBG = this._workCell.bg;\n }\n\n currentStringIndex += this._workCell.getChars().length || WHITESPACE_CELL_CHAR.length;\n }\n\n // Process any trailing ranges.\n if (this._bufferService.cols - rangeStartColumn > 1) {\n const joinedRanges = this._getJoinedRanges(\n lineStr,\n rangeStartStringIndex,\n currentStringIndex,\n line,\n rangeStartColumn\n );\n for (let i = 0; i < joinedRanges.length; i++) {\n ranges.push(joinedRanges[i]);\n }\n }\n\n return ranges;\n }\n\n /**\n * Given a segment of a line of text, find all ranges of text that should be\n * joined in a single rendering unit. Ranges are internally converted to\n * column ranges, rather than string ranges.\n * @param line String representation of the full line of text\n * @param startIndex Start position of the range to search in the string (inclusive)\n * @param endIndex End position of the range to search in the string (exclusive)\n */\n private _getJoinedRanges(line: string, startIndex: number, endIndex: number, lineData: IBufferLine, startCol: number): [number, number][] {\n const text = line.substring(startIndex, endIndex);\n // At this point we already know that there is at least one joiner so\n // we can just pull its value and assign it directly rather than\n // merging it into an empty array, which incurs unnecessary writes.\n let allJoinedRanges: [number, number][] = [];\n try {\n allJoinedRanges = this._characterJoiners[0].handler(text);\n } catch (error) {\n console.error(error);\n }\n for (let i = 1; i < this._characterJoiners.length; i++) {\n // We merge any overlapping ranges across the different joiners\n try {\n const joinerRanges = this._characterJoiners[i].handler(text);\n for (let j = 0; j < joinerRanges.length; j++) {\n CharacterJoinerService._mergeRanges(allJoinedRanges, joinerRanges[j]);\n }\n } catch (error) {\n console.error(error);\n }\n }\n this._stringRangesToCellRanges(allJoinedRanges, lineData, startCol);\n return allJoinedRanges;\n }\n\n /**\n * Modifies the provided ranges in-place to adjust for variations between\n * string length and cell width so that the range represents a cell range,\n * rather than the string range the joiner provides.\n * @param ranges String ranges containing start (inclusive) and end (exclusive) index\n * @param line Cell data for the relevant line in the terminal\n * @param startCol Offset within the line to start from\n */\n private _stringRangesToCellRanges(ranges: [number, number][], line: IBufferLine, startCol: number): void {\n let currentRangeIndex = 0;\n let currentRangeStarted = false;\n let currentStringIndex = 0;\n let currentRange = ranges[currentRangeIndex];\n\n // If we got through all of the ranges, stop searching\n if (!currentRange) {\n return;\n }\n\n for (let x = startCol; x < this._bufferService.cols; x++) {\n const width = line.getWidth(x);\n const length = line.getString(x).length || WHITESPACE_CELL_CHAR.length;\n\n // We skip zero-width characters when creating the string to join the text\n // so we do the same here\n if (width === 0) {\n continue;\n }\n\n // Adjust the start of the range\n if (!currentRangeStarted && currentRange[0] <= currentStringIndex) {\n currentRange[0] = x;\n currentRangeStarted = true;\n }\n\n // Adjust the end of the range\n if (currentRange[1] <= currentStringIndex) {\n currentRange[1] = x;\n\n // We're finished with this range, so we move to the next one\n currentRange = ranges[++currentRangeIndex];\n\n // If there are no more ranges left, stop searching\n if (!currentRange) {\n break;\n }\n\n // Ranges can be on adjacent characters. Because the end index of the\n // ranges are exclusive, this means that the index for the start of a\n // range can be the same as the end index of the previous range. To\n // account for the start of the next range, we check here just in case.\n if (currentRange[0] <= currentStringIndex) {\n currentRange[0] = x;\n currentRangeStarted = true;\n } else {\n currentRangeStarted = false;\n }\n }\n\n // Adjust the string index based on the character length to line up with\n // the column adjustment\n currentStringIndex += length;\n }\n\n // If there is still a range left at the end, it must extend all the way to\n // the end of the line.\n if (currentRange) {\n currentRange[1] = this._bufferService.cols;\n }\n }\n\n /**\n * Merges the range defined by the provided start and end into the list of\n * existing ranges. The merge is done in place on the existing range for\n * performance and is also returned.\n * @param ranges Existing range list\n * @param newRange Tuple of two numbers representing the new range to merge in.\n * @returns The ranges input with the new range merged in place\n */\n private static _mergeRanges(ranges: [number, number][], newRange: [number, number]): [number, number][] {\n let inRange = false;\n for (let i = 0; i < ranges.length; i++) {\n const range = ranges[i];\n if (!inRange) {\n if (newRange[1] <= range[0]) {\n // Case 1: New range is before the search range\n ranges.splice(i, 0, newRange);\n return ranges;\n }\n\n if (newRange[1] <= range[1]) {\n // Case 2: New range is either wholly contained within the\n // search range or overlaps with the front of it\n range[0] = Math.min(newRange[0], range[0]);\n return ranges;\n }\n\n if (newRange[0] < range[1]) {\n // Case 3: New range either wholly contains the search range\n // or overlaps with the end of it\n range[0] = Math.min(newRange[0], range[0]);\n inRange = true;\n }\n\n // Case 4: New range starts after the search range\n continue;\n } else {\n if (newRange[1] <= range[0]) {\n // Case 5: New range extends from previous range but doesn't\n // reach the current one\n ranges[i - 1][1] = newRange[1];\n return ranges;\n }\n\n if (newRange[1] <= range[1]) {\n // Case 6: New range extends from prvious range into the\n // current range\n ranges[i - 1][1] = Math.max(newRange[1], range[1]);\n ranges.splice(i, 1);\n return ranges;\n }\n\n // Case 7: New range extends from previous range past the\n // end of the current range\n ranges.splice(i, 1);\n i--;\n }\n }\n\n if (inRange) {\n // Case 8: New range extends past the last existing range\n ranges[ranges.length - 1][1] = newRange[1];\n } else {\n // Case 9: New range starts after the last existing range\n ranges.push(newRange);\n }\n\n return ranges;\n }\n}\n", "/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IDimensions, IRenderDimensions } from 'browser/renderer/shared/Types';\n\nexport function throwIfFalsy(value: T | undefined | null): T {\n if (!value) {\n throw new Error('value must not be falsy');\n }\n return value;\n}\n\nexport function isPowerlineGlyph(codepoint: number): boolean {\n // Only return true for Powerline symbols which require\n // different padding and should be excluded from minimum contrast\n // ratio standards\n return 0xE0A4 <= codepoint && codepoint <= 0xE0D6;\n}\n\nexport function isRestrictedPowerlineGlyph(codepoint: number): boolean {\n return 0xE0B0 <= codepoint && codepoint <= 0xE0B7;\n}\n\nfunction isNerdFontGlyph(codepoint: number): boolean {\n return 0xE000 <= codepoint && codepoint <= 0xF8FF;\n}\n\nfunction isBoxOrBlockGlyph(codepoint: number): boolean {\n return 0x2500 <= codepoint && codepoint <= 0x259F;\n}\n\nexport function isEmoji(codepoint: number): boolean {\n return (\n codepoint >= 0x1F600 && codepoint <= 0x1F64F || // Emoticons\n codepoint >= 0x1F300 && codepoint <= 0x1F5FF || // Misc Symbols and Pictographs\n codepoint >= 0x1F680 && codepoint <= 0x1F6FF || // Transport and Map\n codepoint >= 0x2600 && codepoint <= 0x26FF || // Misc symbols\n codepoint >= 0x2700 && codepoint <= 0x27BF || // Dingbats\n codepoint >= 0xFE00 && codepoint <= 0xFE0F || // Variation Selectors\n codepoint >= 0x1F900 && codepoint <= 0x1F9FF || // Supplemental Symbols and Pictographs\n codepoint >= 0x1F1E6 && codepoint <= 0x1F1FF\n );\n}\n\nexport function allowRescaling(codepoint: number | undefined, width: number, glyphSizeX: number, deviceCellWidth: number): boolean {\n return (\n // Is single cell width\n width === 1 &&\n // Glyph exceeds cell bounds, add 50% to avoid hurting readability by rescaling glyphs that\n // barely overlap\n glyphSizeX > Math.ceil(deviceCellWidth * 1.5) &&\n // Never rescale ascii\n codepoint !== undefined && codepoint > 0xFF &&\n // Never rescale emoji\n !isEmoji(codepoint) &&\n // Never rescale powerline or nerd fonts\n !isPowerlineGlyph(codepoint) && !isNerdFontGlyph(codepoint)\n );\n}\n\nexport function treatGlyphAsBackgroundColor(codepoint: number): boolean {\n return isPowerlineGlyph(codepoint) || isBoxOrBlockGlyph(codepoint);\n}\n\nexport function createRenderDimensions(): IRenderDimensions {\n return {\n css: {\n canvas: createDimension(),\n cell: createDimension()\n },\n device: {\n canvas: createDimension(),\n cell: createDimension(),\n char: {\n width: 0,\n height: 0,\n left: 0,\n top: 0\n }\n }\n };\n}\n\nfunction createDimension(): IDimensions {\n return {\n width: 0,\n height: 0\n };\n}\n\nexport function computeNextVariantOffset(cellWidth: number, lineWidth: number, currentOffset: number = 0): number {\n return (cellWidth - (Math.round(lineWidth) * 2 - currentOffset)) % (Math.round(lineWidth) * 2);\n}\n", "/**\n * Copyright (c) 2018, 2023 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IBufferLine, ICellData, IColor } from 'common/Types';\nimport { INVERTED_DEFAULT_COLOR } from 'browser/renderer/shared/Constants';\nimport { WHITESPACE_CELL_CHAR, Attributes } from 'common/buffer/Constants';\nimport { CellData } from 'common/buffer/CellData';\nimport { ICoreService, IDecorationService, IOptionsService } from 'common/services/Services';\nimport { channels, color } from 'common/Color';\nimport { ICharacterJoinerService, ICoreBrowserService, IThemeService } from 'browser/services/Services';\nimport { JoinedCellData } from 'browser/services/CharacterJoinerService';\nimport { treatGlyphAsBackgroundColor } from 'browser/renderer/shared/RendererUtils';\nimport { AttributeData } from 'common/buffer/AttributeData';\nimport { WidthCache } from 'browser/renderer/dom/WidthCache';\nimport { IColorContrastCache } from 'browser/Types';\n\n\nexport const enum RowCss {\n BOLD_CLASS = 'xterm-bold',\n DIM_CLASS = 'xterm-dim',\n ITALIC_CLASS = 'xterm-italic',\n UNDERLINE_CLASS = 'xterm-underline',\n OVERLINE_CLASS = 'xterm-overline',\n STRIKETHROUGH_CLASS = 'xterm-strikethrough',\n CURSOR_CLASS = 'xterm-cursor',\n CURSOR_BLINK_CLASS = 'xterm-cursor-blink',\n CURSOR_STYLE_BLOCK_CLASS = 'xterm-cursor-block',\n CURSOR_STYLE_OUTLINE_CLASS = 'xterm-cursor-outline',\n CURSOR_STYLE_BAR_CLASS = 'xterm-cursor-bar',\n CURSOR_STYLE_UNDERLINE_CLASS = 'xterm-cursor-underline'\n}\n\n\nexport class DomRendererRowFactory {\n private _workCell: CellData = new CellData();\n\n private _selectionStart: [number, number] | undefined;\n private _selectionEnd: [number, number] | undefined;\n private _columnSelectMode: boolean = false;\n\n public defaultSpacing = 0;\n\n constructor(\n private readonly _document: Document,\n @ICharacterJoinerService private readonly _characterJoinerService: ICharacterJoinerService,\n @IOptionsService private readonly _optionsService: IOptionsService,\n @ICoreBrowserService private readonly _coreBrowserService: ICoreBrowserService,\n @ICoreService private readonly _coreService: ICoreService,\n @IDecorationService private readonly _decorationService: IDecorationService,\n @IThemeService private readonly _themeService: IThemeService\n ) {}\n\n public handleSelectionChanged(start: [number, number] | undefined, end: [number, number] | undefined, columnSelectMode: boolean): void {\n this._selectionStart = start;\n this._selectionEnd = end;\n this._columnSelectMode = columnSelectMode;\n }\n\n public createRow(\n lineData: IBufferLine,\n row: number,\n isCursorRow: boolean,\n cursorStyle: string | undefined,\n cursorInactiveStyle: string | undefined,\n cursorX: number,\n cursorBlink: boolean,\n cellWidth: number,\n widthCache: WidthCache,\n linkStart: number,\n linkEnd: number\n ): HTMLSpanElement[] {\n\n const elements: HTMLSpanElement[] = [];\n const joinedRanges = this._characterJoinerService.getJoinedCharacters(row);\n const colors = this._themeService.colors;\n\n let lineLength = lineData.getNoBgTrimmedLength();\n if (isCursorRow && lineLength < cursorX + 1) {\n lineLength = cursorX + 1;\n }\n\n let charElement: HTMLSpanElement | undefined;\n let cellAmount = 0;\n let text = '';\n let i = 0;\n let oldBg = 0;\n let oldFg = 0;\n let oldExt = 0;\n let oldLinkHover: number | boolean = false;\n let oldSpacing = 0;\n let oldIsInSelection: boolean = false;\n let spacing = 0;\n let skipJoinedCheckUntilX = 0;\n const classes: string[] = [];\n\n const hasHover = linkStart !== -1 && linkEnd !== -1;\n\n for (let x = 0; x < lineLength; x++) {\n lineData.loadCell(x, this._workCell);\n let width = this._workCell.getWidth();\n\n // The character to the left is a wide character, drawing is owned by the char at x-1\n if (width === 0) {\n continue;\n }\n\n // If true, indicates that the current character(s) to draw were joined.\n let isJoined = false;\n\n // Indicates whether this cell is part of a joined range that should be ignored as it cannot\n // be rendered entirely, like the selection state differs across the range.\n let isValidJoinRange = (x >= skipJoinedCheckUntilX);\n\n let lastCharX = x;\n\n // Process any joined character ranges as needed. Because of how the\n // ranges are produced, we know that they are valid for the characters\n // and attributes of our input.\n let cell = this._workCell;\n if (joinedRanges.length > 0 && x === joinedRanges[0][0] && isValidJoinRange) {\n const range = joinedRanges.shift()!;\n // If the ligature's selection state is not consistent, don't join it. This helps the\n // selection render correctly regardless whether they should be joined.\n const firstSelectionState = this._isCellInSelection(range[0], row);\n for (i = range[0] + 1; i < range[1]; i++) {\n isValidJoinRange &&= (firstSelectionState === this._isCellInSelection(i, row));\n }\n // Similarly, if the cursor is in the ligature, don't join it.\n isValidJoinRange &&= !isCursorRow || cursorX < range[0] || cursorX >= range[1];\n if (!isValidJoinRange) {\n skipJoinedCheckUntilX = range[1];\n } else {\n isJoined = true;\n\n // We already know the exact start and end column of the joined range,\n // so we get the string and width representing it directly\n cell = new JoinedCellData(\n this._workCell,\n lineData.translateToString(true, range[0], range[1]),\n range[1] - range[0]\n );\n\n // Skip over the cells occupied by this range in the loop\n lastCharX = range[1] - 1;\n\n // Recalculate width\n width = cell.getWidth();\n }\n }\n\n const isInSelection = this._isCellInSelection(x, row);\n const isCursorCell = isCursorRow && x === cursorX;\n const isLinkHover = hasHover && x >= linkStart && x <= linkEnd;\n\n let isDecorated = false;\n this._decorationService.forEachDecorationAtCell(x, row, undefined, d => {\n isDecorated = true;\n });\n\n // get chars to render for this cell\n let chars = cell.getChars() || WHITESPACE_CELL_CHAR;\n if (chars === ' ' && (cell.isUnderline() || cell.isOverline())) {\n chars = '\\xa0';\n }\n\n // lookup char render width and calc spacing\n spacing = width * cellWidth - widthCache.get(chars, cell.isBold(), cell.isItalic());\n\n if (!charElement) {\n charElement = this._document.createElement('span');\n } else {\n /**\n * chars can only be merged on existing span if:\n * - existing span only contains mergeable chars (cellAmount != 0)\n * - bg did not change (or both are in selection)\n * - fg did not change (or both are in selection and selection fg is set)\n * - ext did not change\n * - underline from hover state did not change\n * - cell content renders to same letter-spacing\n * - cell is not cursor\n */\n if (\n cellAmount\n && (\n (isInSelection && oldIsInSelection)\n || (!isInSelection && !oldIsInSelection && cell.bg === oldBg)\n )\n && (\n (isInSelection && oldIsInSelection && colors.selectionForeground)\n || cell.fg === oldFg\n )\n && cell.extended.ext === oldExt\n && isLinkHover === oldLinkHover\n && spacing === oldSpacing\n && !isCursorCell\n && !isJoined\n && !isDecorated\n && isValidJoinRange\n ) {\n // no span alterations, thus only account chars skipping all code below\n if (cell.isInvisible()) {\n text += WHITESPACE_CELL_CHAR;\n } else {\n text += chars;\n }\n cellAmount++;\n continue;\n } else {\n /**\n * cannot merge:\n * - apply left-over text to old span\n * - create new span, reset state holders cellAmount & text\n */\n if (cellAmount) {\n charElement.textContent = text;\n }\n charElement = this._document.createElement('span');\n cellAmount = 0;\n text = '';\n }\n }\n // preserve conditions for next merger eval round\n oldBg = cell.bg;\n oldFg = cell.fg;\n oldExt = cell.extended.ext;\n oldLinkHover = isLinkHover;\n oldSpacing = spacing;\n oldIsInSelection = isInSelection;\n\n if (isJoined) {\n // The DOM renderer colors the background of the cursor but for ligatures all cells are\n // joined. The workaround here is to show a cursor around the whole ligature so it shows up,\n // the cursor looks the same when on any character of the ligature though\n if (cursorX >= x && cursorX <= lastCharX) {\n cursorX = x;\n }\n }\n\n if (!this._coreService.isCursorHidden && isCursorCell && this._coreService.isCursorInitialized) {\n classes.push(RowCss.CURSOR_CLASS);\n if (this._coreBrowserService.isFocused) {\n if (cursorBlink) {\n classes.push(RowCss.CURSOR_BLINK_CLASS);\n }\n classes.push(\n cursorStyle === 'bar'\n ? RowCss.CURSOR_STYLE_BAR_CLASS\n : cursorStyle === 'underline'\n ? RowCss.CURSOR_STYLE_UNDERLINE_CLASS\n : RowCss.CURSOR_STYLE_BLOCK_CLASS\n );\n } else {\n if (cursorInactiveStyle) {\n switch (cursorInactiveStyle) {\n case 'outline':\n classes.push(RowCss.CURSOR_STYLE_OUTLINE_CLASS);\n break;\n case 'block':\n classes.push(RowCss.CURSOR_STYLE_BLOCK_CLASS);\n break;\n case 'bar':\n classes.push(RowCss.CURSOR_STYLE_BAR_CLASS);\n break;\n case 'underline':\n classes.push(RowCss.CURSOR_STYLE_UNDERLINE_CLASS);\n break;\n default:\n break;\n }\n }\n }\n }\n\n if (cell.isBold()) {\n classes.push(RowCss.BOLD_CLASS);\n }\n\n if (cell.isItalic()) {\n classes.push(RowCss.ITALIC_CLASS);\n }\n\n if (cell.isDim()) {\n classes.push(RowCss.DIM_CLASS);\n }\n\n if (cell.isInvisible()) {\n text = WHITESPACE_CELL_CHAR;\n } else {\n text = cell.getChars() || WHITESPACE_CELL_CHAR;\n }\n\n if (cell.isUnderline()) {\n classes.push(`${RowCss.UNDERLINE_CLASS}-${cell.extended.underlineStyle}`);\n if (text === ' ') {\n text = '\\xa0'; // =  \n }\n if (!cell.isUnderlineColorDefault()) {\n if (cell.isUnderlineColorRGB()) {\n charElement.style.textDecorationColor = `rgb(${AttributeData.toColorRGB(cell.getUnderlineColor()).join(',')})`;\n } else {\n let fg = cell.getUnderlineColor();\n if (this._optionsService.rawOptions.drawBoldTextInBrightColors && cell.isBold() && fg < 8) {\n fg += 8;\n }\n charElement.style.textDecorationColor = colors.ansi[fg].css;\n }\n }\n }\n\n if (cell.isOverline()) {\n classes.push(RowCss.OVERLINE_CLASS);\n if (text === ' ') {\n text = '\\xa0'; // =  \n }\n }\n\n if (cell.isStrikethrough()) {\n classes.push(RowCss.STRIKETHROUGH_CLASS);\n }\n\n // apply link hover underline late, effectively overrides any previous text-decoration\n // settings\n if (isLinkHover) {\n charElement.style.textDecoration = 'underline';\n }\n\n let fg = cell.getFgColor();\n let fgColorMode = cell.getFgColorMode();\n let bg = cell.getBgColor();\n let bgColorMode = cell.getBgColorMode();\n const isInverse = !!cell.isInverse();\n if (isInverse) {\n const temp = fg;\n fg = bg;\n bg = temp;\n const temp2 = fgColorMode;\n fgColorMode = bgColorMode;\n bgColorMode = temp2;\n }\n\n // Apply any decoration foreground/background overrides, this must happen after inverse has\n // been applied\n let bgOverride: IColor | undefined;\n let fgOverride: IColor | undefined;\n let isTop = false;\n this._decorationService.forEachDecorationAtCell(x, row, undefined, d => {\n if (d.options.layer !== 'top' && isTop) {\n return;\n }\n if (d.backgroundColorRGB) {\n bgColorMode = Attributes.CM_RGB;\n bg = d.backgroundColorRGB.rgba >> 8 & 0xFFFFFF;\n bgOverride = d.backgroundColorRGB;\n }\n if (d.foregroundColorRGB) {\n fgColorMode = Attributes.CM_RGB;\n fg = d.foregroundColorRGB.rgba >> 8 & 0xFFFFFF;\n fgOverride = d.foregroundColorRGB;\n }\n isTop = d.options.layer === 'top';\n });\n\n // Apply selection\n if (!isTop && isInSelection) {\n // If in the selection, force the element to be above the selection to improve contrast and\n // support opaque selections. The applies background is not actually needed here as\n // selection is drawn in a seperate container, the main purpose of this to ensuring minimum\n // contrast ratio\n bgOverride = this._coreBrowserService.isFocused ? colors.selectionBackgroundOpaque : colors.selectionInactiveBackgroundOpaque;\n bg = bgOverride.rgba >> 8 & 0xFFFFFF;\n bgColorMode = Attributes.CM_RGB;\n // Since an opaque selection is being rendered, the selection pretends to be a decoration to\n // ensure text is drawn above the selection.\n isTop = true;\n // Apply selection foreground if applicable\n if (colors.selectionForeground) {\n fgColorMode = Attributes.CM_RGB;\n fg = colors.selectionForeground.rgba >> 8 & 0xFFFFFF;\n fgOverride = colors.selectionForeground;\n }\n }\n\n // If it's a top decoration, render above the selection\n if (isTop) {\n classes.push('xterm-decoration-top');\n }\n\n // Background\n let resolvedBg: IColor;\n switch (bgColorMode) {\n case Attributes.CM_P16:\n case Attributes.CM_P256:\n resolvedBg = colors.ansi[bg];\n classes.push(`xterm-bg-${bg}`);\n break;\n case Attributes.CM_RGB:\n resolvedBg = channels.toColor(bg >> 16, bg >> 8 & 0xFF, bg & 0xFF);\n this._addStyle(charElement, `background-color:#${padStart((bg >>> 0).toString(16), '0', 6)}`);\n break;\n case Attributes.CM_DEFAULT:\n default:\n if (isInverse) {\n resolvedBg = colors.foreground;\n classes.push(`xterm-bg-${INVERTED_DEFAULT_COLOR}`);\n } else {\n resolvedBg = colors.background;\n }\n }\n\n // If there is no background override by now it's the original color, so apply dim if needed\n if (!bgOverride) {\n if (cell.isDim()) {\n bgOverride = color.multiplyOpacity(resolvedBg, 0.5);\n }\n }\n\n // Foreground\n switch (fgColorMode) {\n case Attributes.CM_P16:\n case Attributes.CM_P256:\n if (cell.isBold() && fg < 8 && this._optionsService.rawOptions.drawBoldTextInBrightColors) {\n fg += 8;\n }\n if (!this._applyMinimumContrast(charElement, resolvedBg, colors.ansi[fg], cell, bgOverride, undefined)) {\n classes.push(`xterm-fg-${fg}`);\n }\n break;\n case Attributes.CM_RGB:\n const color = channels.toColor(\n (fg >> 16) & 0xFF,\n (fg >> 8) & 0xFF,\n (fg ) & 0xFF\n );\n if (!this._applyMinimumContrast(charElement, resolvedBg, color, cell, bgOverride, fgOverride)) {\n this._addStyle(charElement, `color:#${padStart(fg.toString(16), '0', 6)}`);\n }\n break;\n case Attributes.CM_DEFAULT:\n default:\n if (!this._applyMinimumContrast(charElement, resolvedBg, colors.foreground, cell, bgOverride, fgOverride)) {\n if (isInverse) {\n classes.push(`xterm-fg-${INVERTED_DEFAULT_COLOR}`);\n }\n }\n }\n\n // apply CSS classes\n // slightly faster than using classList by omitting\n // checks for doubled entries (code above should not have doublets)\n if (classes.length) {\n charElement.className = classes.join(' ');\n classes.length = 0;\n }\n\n // exclude conditions for cell merging - never merge these\n if (!isCursorCell && !isJoined && !isDecorated && isValidJoinRange) {\n cellAmount++;\n } else {\n charElement.textContent = text;\n }\n // apply letter-spacing rule\n if (spacing !== this.defaultSpacing) {\n charElement.style.letterSpacing = `${spacing}px`;\n }\n\n elements.push(charElement);\n x = lastCharX;\n }\n\n // postfix text of last merged span\n if (charElement && cellAmount) {\n charElement.textContent = text;\n }\n\n return elements;\n }\n\n private _applyMinimumContrast(element: HTMLElement, bg: IColor, fg: IColor, cell: ICellData, bgOverride: IColor | undefined, fgOverride: IColor | undefined): boolean {\n if (this._optionsService.rawOptions.minimumContrastRatio === 1 || treatGlyphAsBackgroundColor(cell.getCode())) {\n return false;\n }\n\n // Try get from cache first, only use the cache when there are no decoration overrides\n const cache = this._getContrastCache(cell);\n let adjustedColor: IColor | undefined | null = undefined;\n if (!bgOverride && !fgOverride) {\n adjustedColor = cache.getColor(bg.rgba, fg.rgba);\n }\n\n // Calculate and store in cache\n if (adjustedColor === undefined) {\n // Dim cells only require half the contrast, otherwise they wouldn't be distinguishable from\n // non-dim cells\n const ratio = this._optionsService.rawOptions.minimumContrastRatio / (cell.isDim() ? 2 : 1);\n adjustedColor = color.ensureContrastRatio(bgOverride || bg, fgOverride || fg, ratio);\n cache.setColor((bgOverride || bg).rgba, (fgOverride || fg).rgba, adjustedColor ?? null);\n }\n\n if (adjustedColor) {\n this._addStyle(element, `color:${adjustedColor.css}`);\n return true;\n }\n\n return false;\n }\n\n private _getContrastCache(cell: ICellData): IColorContrastCache {\n if (cell.isDim()) {\n return this._themeService.colors.halfContrastCache;\n }\n return this._themeService.colors.contrastCache;\n }\n\n private _addStyle(element: HTMLElement, style: string): void {\n element.setAttribute('style', `${element.getAttribute('style') || ''}${style};`);\n }\n\n private _isCellInSelection(x: number, y: number): boolean {\n const start = this._selectionStart;\n const end = this._selectionEnd;\n if (!start || !end) {\n return false;\n }\n if (this._columnSelectMode) {\n if (start[0] <= end[0]) {\n return x >= start[0] && y >= start[1] &&\n x < end[0] && y <= end[1];\n }\n return x < start[0] && y >= start[1] &&\n x >= end[0] && y <= end[1];\n }\n return (y > start[1] && y < end[1]) ||\n (start[1] === end[1] && y === start[1] && x >= start[0] && x < end[0]) ||\n (start[1] < end[1] && y === end[1] && x < end[0]) ||\n (start[1] < end[1] && y === start[1] && x >= start[0]);\n }\n}\n\nfunction padStart(text: string, padChar: string, length: number): string {\n while (text.length < length) {\n text = padChar + text;\n }\n return text;\n}\n", "/**\n * Copyright (c) 2023 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IDisposable } from 'common/Types';\nimport { FontWeight } from 'common/services/Services';\n\n\nexport const enum WidthCacheSettings {\n /** sentinel for unset values in flat cache */\n FLAT_UNSET = -9999,\n /** size of flat cache, size-1 equals highest codepoint handled by flat */\n FLAT_SIZE = 256,\n /** char repeat for measuring */\n REPEAT = 32\n}\n\n\nconst enum FontVariant {\n REGULAR = 0,\n BOLD = 1,\n ITALIC = 2,\n BOLD_ITALIC = 3\n}\n\n\nexport class WidthCache implements IDisposable {\n // flat cache for regular variant up to CacheSettings.FLAT_SIZE\n // NOTE: ~4x faster access than holey (serving >>80% of terminal content)\n // It has a small memory footprint (only 1MB for full BMP caching),\n // still the sweet spot is not reached before touching 32k different codepoints,\n // thus we store the remaining <<20% of terminal data in a holey structure.\n protected _flat = new Float32Array(WidthCacheSettings.FLAT_SIZE);\n\n // holey cache for bold, italic and bold&italic for any string\n // FIXME: can grow really big over time (~8.5 MB for full BMP caching),\n // so a shared API across terminals is needed\n protected _holey: Map | undefined;\n\n private _font = '';\n private _fontSize = 0;\n private _weight: FontWeight = 'normal';\n private _weightBold: FontWeight = 'bold';\n private _container: HTMLDivElement;\n private _measureElements: HTMLSpanElement[] = [];\n\n constructor(_document: Document, _helperContainer: HTMLElement) {\n this._container = _document.createElement('div');\n this._container.classList.add('xterm-width-cache-measure-container');\n this._container.setAttribute('aria-hidden', 'true');\n // SP should stack in spans\n this._container.style.whiteSpace = 'pre';\n // avoid undercuts in non-monospace fonts from kerning\n this._container.style.fontKerning = 'none';\n\n const regular = _document.createElement('span');\n regular.classList.add('xterm-char-measure-element');\n\n const bold = _document.createElement('span');\n bold.classList.add('xterm-char-measure-element');\n bold.style.fontWeight = 'bold';\n\n const italic = _document.createElement('span');\n italic.classList.add('xterm-char-measure-element');\n italic.style.fontStyle = 'italic';\n\n const boldItalic = _document.createElement('span');\n boldItalic.classList.add('xterm-char-measure-element');\n boldItalic.style.fontWeight = 'bold';\n boldItalic.style.fontStyle = 'italic';\n\n // NOTE: must be in order of FontVariant\n this._measureElements = [regular, bold, italic, boldItalic];\n this._container.appendChild(regular);\n this._container.appendChild(bold);\n this._container.appendChild(italic);\n this._container.appendChild(boldItalic);\n\n _helperContainer.appendChild(this._container);\n\n this.clear();\n }\n\n public dispose(): void {\n this._container.remove(); // remove elements from DOM\n this._measureElements.length = 0; // release element refs\n this._holey = undefined; // free cache memory via GC\n }\n\n /**\n * Clear the width cache.\n */\n public clear(): void {\n this._flat.fill(WidthCacheSettings.FLAT_UNSET);\n // .clear() has some overhead, re-assign instead (>3 times faster)\n this._holey = new Map();\n }\n\n /**\n * Set the font for measuring.\n * Must be called for any changes on font settings.\n * Also clears the cache.\n */\n public setFont(font: string, fontSize: number, weight: FontWeight, weightBold: FontWeight): void {\n // skip if nothing changed\n if (font === this._font\n && fontSize === this._fontSize\n && weight === this._weight\n && weightBold === this._weightBold\n ) {\n return;\n }\n\n this._font = font;\n this._fontSize = fontSize;\n this._weight = weight;\n this._weightBold = weightBold;\n\n this._container.style.fontFamily = this._font;\n this._container.style.fontSize = `${this._fontSize}px`;\n this._measureElements[FontVariant.REGULAR].style.fontWeight = `${weight}`;\n this._measureElements[FontVariant.BOLD].style.fontWeight = `${weightBold}`;\n this._measureElements[FontVariant.ITALIC].style.fontWeight = `${weight}`;\n this._measureElements[FontVariant.BOLD_ITALIC].style.fontWeight = `${weightBold}`;\n\n this.clear();\n }\n\n /**\n * Get the render width for cell content `c` with current font settings.\n * `variant` denotes the font variant to be used.\n */\n public get(c: string, bold: boolean | number, italic: boolean | number): number {\n let cp = 0;\n if (!bold && !italic && c.length === 1 && (cp = c.charCodeAt(0)) < WidthCacheSettings.FLAT_SIZE) {\n if (this._flat[cp] !== WidthCacheSettings.FLAT_UNSET) {\n return this._flat[cp];\n }\n const width = this._measure(c, 0);\n if (width > 0) {\n this._flat[cp] = width;\n }\n return width;\n }\n let key = c;\n if (bold) key += 'B';\n if (italic) key += 'I';\n let width = this._holey!.get(key);\n if (width === undefined) {\n let variant = 0;\n if (bold) variant |= FontVariant.BOLD;\n if (italic) variant |= FontVariant.ITALIC;\n width = this._measure(c, variant);\n if (width > 0) {\n this._holey!.set(key, width);\n }\n }\n return width;\n }\n\n protected _measure(c: string, variant: FontVariant): number {\n const el = this._measureElements[variant];\n el.textContent = c.repeat(WidthCacheSettings.REPEAT);\n return el.offsetWidth / WidthCacheSettings.REPEAT;\n }\n}\n", "/**\n * Copyright (c) 2022 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { ITerminal } from 'browser/Types';\nimport { ISelectionRenderModel } from 'browser/renderer/shared/Types';\nimport { Terminal } from '@xterm/xterm';\n\nclass SelectionRenderModel implements ISelectionRenderModel {\n public hasSelection!: boolean;\n public columnSelectMode!: boolean;\n public viewportStartRow!: number;\n public viewportEndRow!: number;\n public viewportCappedStartRow!: number;\n public viewportCappedEndRow!: number;\n public startCol!: number;\n public endCol!: number;\n public selectionStart: [number, number] | undefined;\n public selectionEnd: [number, number] | undefined;\n\n constructor() {\n this.clear();\n }\n\n public clear(): void {\n this.hasSelection = false;\n this.columnSelectMode = false;\n this.viewportStartRow = 0;\n this.viewportEndRow = 0;\n this.viewportCappedStartRow = 0;\n this.viewportCappedEndRow = 0;\n this.startCol = 0;\n this.endCol = 0;\n this.selectionStart = undefined;\n this.selectionEnd = undefined;\n }\n\n public update(terminal: ITerminal, start: [number, number] | undefined, end: [number, number] | undefined, columnSelectMode: boolean = false): void {\n this.selectionStart = start;\n this.selectionEnd = end;\n // Selection does not exist\n if (!start || !end || (start[0] === end[0] && start[1] === end[1])) {\n this.clear();\n return;\n }\n\n // Translate from buffer position to viewport position\n const viewportY = terminal.buffers.active.ydisp;\n const viewportStartRow = start[1] - viewportY;\n const viewportEndRow = end[1] - viewportY;\n const viewportCappedStartRow = Math.max(viewportStartRow, 0);\n const viewportCappedEndRow = Math.min(viewportEndRow, terminal.rows - 1);\n\n // No need to draw the selection\n if (viewportCappedStartRow >= terminal.rows || viewportCappedEndRow < 0) {\n this.clear();\n return;\n }\n\n this.hasSelection = true;\n this.columnSelectMode = columnSelectMode;\n this.viewportStartRow = viewportStartRow;\n this.viewportEndRow = viewportEndRow;\n this.viewportCappedStartRow = viewportCappedStartRow;\n this.viewportCappedEndRow = viewportCappedEndRow;\n this.startCol = start[0];\n this.endCol = end[0];\n }\n\n public isCellSelected(terminal: Terminal, x: number, y: number): boolean {\n if (!this.hasSelection) {\n return false;\n }\n y -= terminal.buffer.active.viewportY;\n if (this.columnSelectMode) {\n if (this.startCol <= this.endCol) {\n return x >= this.startCol && y >= this.viewportCappedStartRow &&\n x < this.endCol && y <= this.viewportCappedEndRow;\n }\n return x < this.startCol && y >= this.viewportCappedStartRow &&\n x >= this.endCol && y <= this.viewportCappedEndRow;\n }\n return (y > this.viewportStartRow && y < this.viewportEndRow) ||\n (this.viewportStartRow === this.viewportEndRow && y === this.viewportStartRow && x >= this.startCol && x < this.endCol) ||\n (this.viewportStartRow < this.viewportEndRow && y === this.viewportEndRow && x < this.endCol) ||\n (this.viewportStartRow < this.viewportEndRow && y === this.viewportStartRow && x >= this.startCol);\n }\n}\n\nexport function createSelectionRenderModel(): ISelectionRenderModel {\n return new SelectionRenderModel();\n}\n", "/**\n * Copyright (c) 2018 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { DomRendererRowFactory, RowCss } from 'browser/renderer/dom/DomRendererRowFactory';\nimport { WidthCache } from 'browser/renderer/dom/WidthCache';\nimport { INVERTED_DEFAULT_COLOR } from 'browser/renderer/shared/Constants';\nimport { createRenderDimensions } from 'browser/renderer/shared/RendererUtils';\nimport { createSelectionRenderModel } from 'browser/renderer/shared/SelectionRenderModel';\nimport { IRenderDimensions, IRenderer, IRequestRedrawEvent, ISelectionRenderModel } from 'browser/renderer/shared/Types';\nimport { ICharSizeService, ICoreBrowserService, IThemeService } from 'browser/services/Services';\nimport { ILinkifier2, ILinkifierEvent, ITerminal, ReadonlyColorSet } from 'browser/Types';\nimport { color } from 'common/Color';\nimport { Disposable, toDisposable } from 'vs/base/common/lifecycle';\nimport { IBufferService, ICoreService, IInstantiationService, IOptionsService } from 'common/services/Services';\nimport { Emitter } from 'vs/base/common/event';\n\n\nconst TERMINAL_CLASS_PREFIX = 'xterm-dom-renderer-owner-';\nconst ROW_CONTAINER_CLASS = 'xterm-rows';\nconst FG_CLASS_PREFIX = 'xterm-fg-';\nconst BG_CLASS_PREFIX = 'xterm-bg-';\nconst FOCUS_CLASS = 'xterm-focus';\nconst SELECTION_CLASS = 'xterm-selection';\n\nlet nextTerminalId = 1;\n\n/**\n * The standard renderer and fallback for when the webgl addon is slow. This is not meant to be\n * particularly fast and will even lack some features such as custom glyphs, hoever this is more\n * reliable as webgl may not work on some machines.\n */\nexport class DomRenderer extends Disposable implements IRenderer {\n private _rowFactory: DomRendererRowFactory;\n private _terminalClass: number = nextTerminalId++;\n\n private _themeStyleElement!: HTMLStyleElement;\n private _dimensionsStyleElement!: HTMLStyleElement;\n private _rowContainer: HTMLElement;\n private _rowElements: HTMLElement[] = [];\n private _selectionContainer: HTMLElement;\n private _widthCache: WidthCache;\n private _selectionRenderModel: ISelectionRenderModel = createSelectionRenderModel();\n\n public dimensions: IRenderDimensions;\n\n public readonly onRequestRedraw = this._register(new Emitter()).event;\n\n constructor(\n private readonly _terminal: ITerminal,\n private readonly _document: Document,\n private readonly _element: HTMLElement,\n private readonly _screenElement: HTMLElement,\n private readonly _viewportElement: HTMLElement,\n private readonly _helperContainer: HTMLElement,\n private readonly _linkifier2: ILinkifier2,\n @IInstantiationService instantiationService: IInstantiationService,\n @ICharSizeService private readonly _charSizeService: ICharSizeService,\n @IOptionsService private readonly _optionsService: IOptionsService,\n @IBufferService private readonly _bufferService: IBufferService,\n @ICoreService private readonly _coreService: ICoreService,\n @ICoreBrowserService private readonly _coreBrowserService: ICoreBrowserService,\n @IThemeService private readonly _themeService: IThemeService\n ) {\n super();\n this._rowContainer = this._document.createElement('div');\n this._rowContainer.classList.add(ROW_CONTAINER_CLASS);\n this._rowContainer.style.lineHeight = 'normal';\n this._rowContainer.setAttribute('aria-hidden', 'true');\n this._refreshRowElements(this._bufferService.cols, this._bufferService.rows);\n this._selectionContainer = this._document.createElement('div');\n this._selectionContainer.classList.add(SELECTION_CLASS);\n this._selectionContainer.setAttribute('aria-hidden', 'true');\n\n this.dimensions = createRenderDimensions();\n this._updateDimensions();\n this._register(this._optionsService.onOptionChange(() => this._handleOptionsChanged()));\n\n this._register(this._themeService.onChangeColors(e => this._injectCss(e)));\n this._injectCss(this._themeService.colors);\n\n this._rowFactory = instantiationService.createInstance(DomRendererRowFactory, document);\n\n this._element.classList.add(TERMINAL_CLASS_PREFIX + this._terminalClass);\n this._screenElement.appendChild(this._rowContainer);\n this._screenElement.appendChild(this._selectionContainer);\n\n this._register(this._linkifier2.onShowLinkUnderline(e => this._handleLinkHover(e)));\n this._register(this._linkifier2.onHideLinkUnderline(e => this._handleLinkLeave(e)));\n\n this._register(toDisposable(() => {\n this._element.classList.remove(TERMINAL_CLASS_PREFIX + this._terminalClass);\n\n // Outside influences such as React unmounts may manipulate the DOM before our disposal.\n // https://github.com/xtermjs/xterm.js/issues/2960\n this._rowContainer.remove();\n this._selectionContainer.remove();\n this._widthCache.dispose();\n this._themeStyleElement.remove();\n this._dimensionsStyleElement.remove();\n }));\n\n this._widthCache = new WidthCache(this._document, this._helperContainer);\n this._widthCache.setFont(\n this._optionsService.rawOptions.fontFamily,\n this._optionsService.rawOptions.fontSize,\n this._optionsService.rawOptions.fontWeight,\n this._optionsService.rawOptions.fontWeightBold\n );\n this._setDefaultSpacing();\n }\n\n private _updateDimensions(): void {\n const dpr = this._coreBrowserService.dpr;\n this.dimensions.device.char.width = this._charSizeService.width * dpr;\n this.dimensions.device.char.height = Math.ceil(this._charSizeService.height * dpr);\n this.dimensions.device.cell.width = this.dimensions.device.char.width + Math.round(this._optionsService.rawOptions.letterSpacing);\n this.dimensions.device.cell.height = Math.floor(this.dimensions.device.char.height * this._optionsService.rawOptions.lineHeight);\n this.dimensions.device.char.left = 0;\n this.dimensions.device.char.top = 0;\n this.dimensions.device.canvas.width = this.dimensions.device.cell.width * this._bufferService.cols;\n this.dimensions.device.canvas.height = this.dimensions.device.cell.height * this._bufferService.rows;\n this.dimensions.css.canvas.width = Math.round(this.dimensions.device.canvas.width / dpr);\n this.dimensions.css.canvas.height = Math.round(this.dimensions.device.canvas.height / dpr);\n this.dimensions.css.cell.width = this.dimensions.css.canvas.width / this._bufferService.cols;\n this.dimensions.css.cell.height = this.dimensions.css.canvas.height / this._bufferService.rows;\n\n for (const element of this._rowElements) {\n element.style.width = `${this.dimensions.css.canvas.width}px`;\n element.style.height = `${this.dimensions.css.cell.height}px`;\n element.style.lineHeight = `${this.dimensions.css.cell.height}px`;\n // Make sure rows don't overflow onto following row\n element.style.overflow = 'hidden';\n }\n\n if (!this._dimensionsStyleElement) {\n this._dimensionsStyleElement = this._document.createElement('style');\n this._screenElement.appendChild(this._dimensionsStyleElement);\n }\n\n const styles =\n `${this._terminalSelector} .${ROW_CONTAINER_CLASS} span {` +\n ` display: inline-block;` + // TODO: find workaround for inline-block (creates ~20% render penalty)\n ` height: 100%;` +\n ` vertical-align: top;` +\n `}`;\n\n this._dimensionsStyleElement.textContent = styles;\n\n this._selectionContainer.style.height = this._viewportElement.style.height;\n this._screenElement.style.width = `${this.dimensions.css.canvas.width}px`;\n this._screenElement.style.height = `${this.dimensions.css.canvas.height}px`;\n }\n\n private _injectCss(colors: ReadonlyColorSet): void {\n if (!this._themeStyleElement) {\n this._themeStyleElement = this._document.createElement('style');\n this._screenElement.appendChild(this._themeStyleElement);\n }\n\n // Base CSS\n let styles =\n `${this._terminalSelector} .${ROW_CONTAINER_CLASS} {` +\n // Disabling pointer events circumvents a browser behavior that prevents `click` events from\n // being delivered if the target element is replaced during the click. This happened due to\n // refresh() being called during the mousedown handler to start a selection.\n ` pointer-events: none;` +\n ` color: ${colors.foreground.css};` +\n ` font-family: ${this._optionsService.rawOptions.fontFamily};` +\n ` font-size: ${this._optionsService.rawOptions.fontSize}px;` +\n ` font-kerning: none;` +\n ` white-space: pre` +\n `}`;\n styles +=\n `${this._terminalSelector} .${ROW_CONTAINER_CLASS} .xterm-dim {` +\n ` color: ${color.multiplyOpacity(colors.foreground, 0.5).css};` +\n `}`;\n // Text styles\n styles +=\n `${this._terminalSelector} span:not(.${RowCss.BOLD_CLASS}) {` +\n ` font-weight: ${this._optionsService.rawOptions.fontWeight};` +\n `}` +\n `${this._terminalSelector} span.${RowCss.BOLD_CLASS} {` +\n ` font-weight: ${this._optionsService.rawOptions.fontWeightBold};` +\n `}` +\n `${this._terminalSelector} span.${RowCss.ITALIC_CLASS} {` +\n ` font-style: italic;` +\n `}`;\n // Blink animation\n const blinkAnimationUnderlineId = `blink_underline_${this._terminalClass}`;\n const blinkAnimationBarId = `blink_bar_${this._terminalClass}`;\n const blinkAnimationBlockId = `blink_block_${this._terminalClass}`;\n styles +=\n `@keyframes ${blinkAnimationUnderlineId} {` +\n ` 50% {` +\n ` border-bottom-style: hidden;` +\n ` }` +\n `}`;\n styles +=\n `@keyframes ${blinkAnimationBarId} {` +\n ` 50% {` +\n ` box-shadow: none;` +\n ` }` +\n `}`;\n styles +=\n `@keyframes ${blinkAnimationBlockId} {` +\n ` 0% {` +\n ` background-color: ${colors.cursor.css};` +\n ` color: ${colors.cursorAccent.css};` +\n ` }` +\n ` 50% {` +\n ` background-color: inherit;` +\n ` color: ${colors.cursor.css};` +\n ` }` +\n `}`;\n // Cursor\n styles +=\n `${this._terminalSelector} .${ROW_CONTAINER_CLASS}.${FOCUS_CLASS} .${RowCss.CURSOR_CLASS}.${RowCss.CURSOR_BLINK_CLASS}.${RowCss.CURSOR_STYLE_UNDERLINE_CLASS} {` +\n ` animation: ${blinkAnimationUnderlineId} 1s step-end infinite;` +\n `}` +\n `${this._terminalSelector} .${ROW_CONTAINER_CLASS}.${FOCUS_CLASS} .${RowCss.CURSOR_CLASS}.${RowCss.CURSOR_BLINK_CLASS}.${RowCss.CURSOR_STYLE_BAR_CLASS} {` +\n ` animation: ${blinkAnimationBarId} 1s step-end infinite;` +\n `}` +\n `${this._terminalSelector} .${ROW_CONTAINER_CLASS}.${FOCUS_CLASS} .${RowCss.CURSOR_CLASS}.${RowCss.CURSOR_BLINK_CLASS}.${RowCss.CURSOR_STYLE_BLOCK_CLASS} {` +\n ` animation: ${blinkAnimationBlockId} 1s step-end infinite;` +\n `}` +\n // !important helps fix an issue where the cursor will not render on top of the selection,\n // however it's very hard to fix this issue and retain the blink animation without the use of\n // !important. So this edge case fails when cursor blink is on.\n `${this._terminalSelector} .${ROW_CONTAINER_CLASS} .${RowCss.CURSOR_CLASS}.${RowCss.CURSOR_STYLE_BLOCK_CLASS} {` +\n ` background-color: ${colors.cursor.css};` +\n ` color: ${colors.cursorAccent.css};` +\n `}` +\n `${this._terminalSelector} .${ROW_CONTAINER_CLASS} .${RowCss.CURSOR_CLASS}.${RowCss.CURSOR_STYLE_BLOCK_CLASS}:not(.${RowCss.CURSOR_BLINK_CLASS}) {` +\n ` background-color: ${colors.cursor.css} !important;` +\n ` color: ${colors.cursorAccent.css} !important;` +\n `}` +\n `${this._terminalSelector} .${ROW_CONTAINER_CLASS} .${RowCss.CURSOR_CLASS}.${RowCss.CURSOR_STYLE_OUTLINE_CLASS} {` +\n ` outline: 1px solid ${colors.cursor.css};` +\n ` outline-offset: -1px;` +\n `}` +\n `${this._terminalSelector} .${ROW_CONTAINER_CLASS} .${RowCss.CURSOR_CLASS}.${RowCss.CURSOR_STYLE_BAR_CLASS} {` +\n ` box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${colors.cursor.css} inset;` +\n `}` +\n `${this._terminalSelector} .${ROW_CONTAINER_CLASS} .${RowCss.CURSOR_CLASS}.${RowCss.CURSOR_STYLE_UNDERLINE_CLASS} {` +\n ` border-bottom: 1px ${colors.cursor.css};` +\n ` border-bottom-style: solid;` +\n ` height: calc(100% - 1px);` +\n `}`;\n // Selection\n styles +=\n `${this._terminalSelector} .${SELECTION_CLASS} {` +\n ` position: absolute;` +\n ` top: 0;` +\n ` left: 0;` +\n ` z-index: 1;` +\n ` pointer-events: none;` +\n `}` +\n `${this._terminalSelector}.focus .${SELECTION_CLASS} div {` +\n ` position: absolute;` +\n ` background-color: ${colors.selectionBackgroundOpaque.css};` +\n `}` +\n `${this._terminalSelector} .${SELECTION_CLASS} div {` +\n ` position: absolute;` +\n ` background-color: ${colors.selectionInactiveBackgroundOpaque.css};` +\n `}`;\n // Colors\n for (const [i, c] of colors.ansi.entries()) {\n styles +=\n `${this._terminalSelector} .${FG_CLASS_PREFIX}${i} { color: ${c.css}; }` +\n `${this._terminalSelector} .${FG_CLASS_PREFIX}${i}.${RowCss.DIM_CLASS} { color: ${color.multiplyOpacity(c, 0.5).css}; }` +\n `${this._terminalSelector} .${BG_CLASS_PREFIX}${i} { background-color: ${c.css}; }`;\n }\n styles +=\n `${this._terminalSelector} .${FG_CLASS_PREFIX}${INVERTED_DEFAULT_COLOR} { color: ${color.opaque(colors.background).css}; }` +\n `${this._terminalSelector} .${FG_CLASS_PREFIX}${INVERTED_DEFAULT_COLOR}.${RowCss.DIM_CLASS} { color: ${color.multiplyOpacity(color.opaque(colors.background), 0.5).css}; }` +\n `${this._terminalSelector} .${BG_CLASS_PREFIX}${INVERTED_DEFAULT_COLOR} { background-color: ${colors.foreground.css}; }`;\n\n this._themeStyleElement.textContent = styles;\n }\n\n /**\n * default letter spacing\n * Due to rounding issues in dimensions dpr calc glyph might render\n * slightly too wide or too narrow. The method corrects the stacking offsets\n * by applying a default letter-spacing for all chars.\n * The value gets passed to the row factory to avoid setting this value again\n * (render speedup is roughly 10%).\n */\n private _setDefaultSpacing(): void {\n // measure same char as in CharSizeService to get the base deviation\n const spacing = this.dimensions.css.cell.width - this._widthCache.get('W', false, false);\n this._rowContainer.style.letterSpacing = `${spacing}px`;\n this._rowFactory.defaultSpacing = spacing;\n }\n\n public handleDevicePixelRatioChange(): void {\n this._updateDimensions();\n this._widthCache.clear();\n this._setDefaultSpacing();\n }\n\n private _refreshRowElements(cols: number, rows: number): void {\n // Add missing elements\n for (let i = this._rowElements.length; i <= rows; i++) {\n const row = this._document.createElement('div');\n this._rowContainer.appendChild(row);\n this._rowElements.push(row);\n }\n // Remove excess elements\n while (this._rowElements.length > rows) {\n this._rowContainer.removeChild(this._rowElements.pop()!);\n }\n }\n\n public handleResize(cols: number, rows: number): void {\n this._refreshRowElements(cols, rows);\n this._updateDimensions();\n this.handleSelectionChanged(this._selectionRenderModel.selectionStart, this._selectionRenderModel.selectionEnd, this._selectionRenderModel.columnSelectMode);\n }\n\n public handleCharSizeChanged(): void {\n this._updateDimensions();\n this._widthCache.clear();\n this._setDefaultSpacing();\n }\n\n public handleBlur(): void {\n this._rowContainer.classList.remove(FOCUS_CLASS);\n this.renderRows(0, this._bufferService.rows - 1);\n }\n\n public handleFocus(): void {\n this._rowContainer.classList.add(FOCUS_CLASS);\n this.renderRows(this._bufferService.buffer.y, this._bufferService.buffer.y);\n }\n\n public handleSelectionChanged(start: [number, number] | undefined, end: [number, number] | undefined, columnSelectMode: boolean): void {\n // Remove all selections\n this._selectionContainer.replaceChildren();\n this._rowFactory.handleSelectionChanged(start, end, columnSelectMode);\n this.renderRows(0, this._bufferService.rows - 1);\n\n // Selection does not exist\n if (!start || !end) {\n return;\n }\n\n this._selectionRenderModel.update(this._terminal, start, end, columnSelectMode);\n if (!this._selectionRenderModel.hasSelection) {\n return;\n }\n\n // Translate from buffer position to viewport position\n const viewportStartRow = this._selectionRenderModel.viewportStartRow;\n const viewportEndRow = this._selectionRenderModel.viewportEndRow;\n const viewportCappedStartRow = this._selectionRenderModel.viewportCappedStartRow;\n const viewportCappedEndRow = this._selectionRenderModel.viewportCappedEndRow;\n\n // Create the selections\n const documentFragment = this._document.createDocumentFragment();\n\n if (columnSelectMode) {\n const isXFlipped = start[0] > end[0];\n documentFragment.appendChild(\n this._createSelectionElement(viewportCappedStartRow, isXFlipped ? end[0] : start[0], isXFlipped ? start[0] : end[0], viewportCappedEndRow - viewportCappedStartRow + 1)\n );\n } else {\n // Draw first row\n const startCol = viewportStartRow === viewportCappedStartRow ? start[0] : 0;\n const endCol = viewportCappedStartRow === viewportEndRow ? end[0] : this._bufferService.cols;\n documentFragment.appendChild(this._createSelectionElement(viewportCappedStartRow, startCol, endCol));\n // Draw middle rows\n const middleRowsCount = viewportCappedEndRow - viewportCappedStartRow - 1;\n documentFragment.appendChild(this._createSelectionElement(viewportCappedStartRow + 1, 0, this._bufferService.cols, middleRowsCount));\n // Draw final row\n if (viewportCappedStartRow !== viewportCappedEndRow) {\n // Only draw viewportEndRow if it's not the same as viewporttartRow\n const endCol = viewportEndRow === viewportCappedEndRow ? end[0] : this._bufferService.cols;\n documentFragment.appendChild(this._createSelectionElement(viewportCappedEndRow, 0, endCol));\n }\n }\n this._selectionContainer.appendChild(documentFragment);\n }\n\n /**\n * Creates a selection element at the specified position.\n * @param row The row of the selection.\n * @param colStart The start column.\n * @param colEnd The end columns.\n */\n private _createSelectionElement(row: number, colStart: number, colEnd: number, rowCount: number = 1): HTMLElement {\n const element = this._document.createElement('div');\n const left = colStart * this.dimensions.css.cell.width;\n let width = this.dimensions.css.cell.width * (colEnd - colStart);\n if (left + width > this.dimensions.css.canvas.width) {\n width = this.dimensions.css.canvas.width - left;\n }\n\n element.style.height = `${rowCount * this.dimensions.css.cell.height}px`;\n element.style.top = `${row * this.dimensions.css.cell.height}px`;\n element.style.left = `${left}px`;\n element.style.width = `${width}px`;\n return element;\n }\n\n public handleCursorMove(): void {\n // No-op, the cursor is drawn when rows are drawn\n }\n\n private _handleOptionsChanged(): void {\n // Force a refresh\n this._updateDimensions();\n // Refresh CSS\n this._injectCss(this._themeService.colors);\n // update spacing cache\n this._widthCache.setFont(\n this._optionsService.rawOptions.fontFamily,\n this._optionsService.rawOptions.fontSize,\n this._optionsService.rawOptions.fontWeight,\n this._optionsService.rawOptions.fontWeightBold\n );\n this._setDefaultSpacing();\n }\n\n public clear(): void {\n for (const e of this._rowElements) {\n /**\n * NOTE: This used to be `e.innerText = '';` but that doesn't work when using `jsdom` and\n * `@testing-library/react`\n *\n * references:\n * - https://github.com/testing-library/react-testing-library/issues/1146\n * - https://github.com/jsdom/jsdom/issues/1245\n */\n e.replaceChildren();\n }\n }\n\n public renderRows(start: number, end: number): void {\n const buffer = this._bufferService.buffer;\n const cursorAbsoluteY = buffer.ybase + buffer.y;\n const cursorX = Math.min(buffer.x, this._bufferService.cols - 1);\n const cursorBlink = this._coreService.decPrivateModes.cursorBlink ?? this._optionsService.rawOptions.cursorBlink;\n const cursorStyle = this._coreService.decPrivateModes.cursorStyle ?? this._optionsService.rawOptions.cursorStyle;\n const cursorInactiveStyle = this._optionsService.rawOptions.cursorInactiveStyle;\n\n for (let y = start; y <= end; y++) {\n const row = y + buffer.ydisp;\n const rowElement = this._rowElements[y];\n const lineData = buffer.lines.get(row);\n if (!rowElement || !lineData) {\n break;\n }\n rowElement.replaceChildren(\n ...this._rowFactory.createRow(\n lineData,\n row,\n row === cursorAbsoluteY,\n cursorStyle,\n cursorInactiveStyle,\n cursorX,\n cursorBlink,\n this.dimensions.css.cell.width,\n this._widthCache,\n -1,\n -1\n )\n );\n }\n }\n\n private get _terminalSelector(): string {\n return `.${TERMINAL_CLASS_PREFIX}${this._terminalClass}`;\n }\n\n private _handleLinkHover(e: ILinkifierEvent): void {\n this._setCellUnderline(e.x1, e.x2, e.y1, e.y2, e.cols, true);\n }\n\n private _handleLinkLeave(e: ILinkifierEvent): void {\n this._setCellUnderline(e.x1, e.x2, e.y1, e.y2, e.cols, false);\n }\n\n private _setCellUnderline(x: number, x2: number, y: number, y2: number, cols: number, enabled: boolean): void {\n /**\n * NOTE: The linkifier may send out of viewport y-values if:\n * - negative y-value: the link started at a higher line\n * - y-value >= maxY: the link ends at a line below viewport\n *\n * For negative y-values we can simply adjust x = 0,\n * as higher up link start means, that everything from\n * (0,0) is a link under top-down-left-right char progression\n *\n * Additionally there might be a small chance of out-of-sync x|y-values\n * from a race condition of render updates vs. link event handler execution:\n * - (sync) resize: chances terminal buffer in sync, schedules render update async\n * - (async) link handler race condition: new buffer metrics, but still on old render state\n * - (async) render update: brings term metrics and render state back in sync\n */\n // clip coords into viewport\n if (y < 0) x = 0;\n if (y2 < 0) x2 = 0;\n const maxY = this._bufferService.rows - 1;\n y = Math.max(Math.min(y, maxY), 0);\n y2 = Math.max(Math.min(y2, maxY), 0);\n\n cols = Math.min(cols, this._bufferService.cols);\n const buffer = this._bufferService.buffer;\n const cursorAbsoluteY = buffer.ybase + buffer.y;\n const cursorX = Math.min(buffer.x, cols - 1);\n const cursorBlink = this._optionsService.rawOptions.cursorBlink;\n const cursorStyle = this._optionsService.rawOptions.cursorStyle;\n const cursorInactiveStyle = this._optionsService.rawOptions.cursorInactiveStyle;\n\n // refresh rows within link range\n for (let i = y; i <= y2; ++i) {\n const row = i + buffer.ydisp;\n const rowElement = this._rowElements[i];\n const bufferline = buffer.lines.get(row);\n if (!rowElement || !bufferline) {\n break;\n }\n rowElement.replaceChildren(\n ...this._rowFactory.createRow(\n bufferline,\n row,\n row === cursorAbsoluteY,\n cursorStyle,\n cursorInactiveStyle,\n cursorX,\n cursorBlink,\n this.dimensions.css.cell.width,\n this._widthCache,\n enabled ? (i === y ? x : 0) : -1,\n enabled ? ((i === y2 ? x2 : cols) - 1) : -1\n )\n );\n }\n }\n}\n", "/**\n * Copyright (c) 2016 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IOptionsService } from 'common/services/Services';\nimport { ICharSizeService } from 'browser/services/Services';\nimport { Disposable } from 'vs/base/common/lifecycle';\nimport { Emitter } from 'vs/base/common/event';\n\nexport class CharSizeService extends Disposable implements ICharSizeService {\n public serviceBrand: undefined;\n\n public width: number = 0;\n public height: number = 0;\n private _measureStrategy: IMeasureStrategy;\n\n public get hasValidSize(): boolean { return this.width > 0 && this.height > 0; }\n\n private readonly _onCharSizeChange = this._register(new Emitter());\n public readonly onCharSizeChange = this._onCharSizeChange.event;\n\n constructor(\n document: Document,\n parentElement: HTMLElement,\n @IOptionsService private readonly _optionsService: IOptionsService\n ) {\n super();\n try {\n this._measureStrategy = this._register(new TextMetricsMeasureStrategy(this._optionsService));\n } catch {\n this._measureStrategy = this._register(new DomMeasureStrategy(document, parentElement, this._optionsService));\n }\n this._register(this._optionsService.onMultipleOptionChange(['fontFamily', 'fontSize'], () => this.measure()));\n }\n\n public measure(): void {\n const result = this._measureStrategy.measure();\n if (result.width !== this.width || result.height !== this.height) {\n this.width = result.width;\n this.height = result.height;\n this._onCharSizeChange.fire();\n }\n }\n}\n\ninterface IMeasureStrategy {\n measure(): Readonly;\n}\n\ninterface IMeasureResult {\n width: number;\n height: number;\n}\n\nconst enum DomMeasureStrategyConstants {\n REPEAT = 32\n}\n\nabstract class BaseMeasureStategy extends Disposable implements IMeasureStrategy {\n protected _result: IMeasureResult = { width: 0, height: 0 };\n\n protected _validateAndSet(width: number | undefined, height: number | undefined): void {\n // If values are 0 then the element is likely currently display:none, in which case we should\n // retain the previous value.\n if (width !== undefined && width > 0 && height !== undefined && height > 0) {\n this._result.width = width;\n this._result.height = height;\n }\n }\n\n public abstract measure(): Readonly;\n}\n\nclass DomMeasureStrategy extends BaseMeasureStategy {\n private _measureElement: HTMLElement;\n\n constructor(\n private _document: Document,\n private _parentElement: HTMLElement,\n private _optionsService: IOptionsService\n ) {\n super();\n this._measureElement = this._document.createElement('span');\n this._measureElement.classList.add('xterm-char-measure-element');\n this._measureElement.textContent = 'W'.repeat(DomMeasureStrategyConstants.REPEAT);\n this._measureElement.setAttribute('aria-hidden', 'true');\n this._measureElement.style.whiteSpace = 'pre';\n this._measureElement.style.fontKerning = 'none';\n this._parentElement.appendChild(this._measureElement);\n }\n\n public measure(): Readonly {\n this._measureElement.style.fontFamily = this._optionsService.rawOptions.fontFamily;\n this._measureElement.style.fontSize = `${this._optionsService.rawOptions.fontSize}px`;\n\n // Note that this triggers a synchronous layout\n this._validateAndSet(Number(this._measureElement.offsetWidth) / DomMeasureStrategyConstants.REPEAT, Number(this._measureElement.offsetHeight));\n\n return this._result;\n }\n}\n\nclass TextMetricsMeasureStrategy extends BaseMeasureStategy {\n private _canvas: OffscreenCanvas;\n private _ctx: OffscreenCanvasRenderingContext2D;\n\n constructor(\n private _optionsService: IOptionsService\n ) {\n super();\n // This will throw if any required API is not supported\n this._canvas = new OffscreenCanvas(100, 100);\n this._ctx = this._canvas.getContext('2d')!;\n const a = this._ctx.measureText('W');\n if (!('width' in a && 'fontBoundingBoxAscent' in a && 'fontBoundingBoxDescent' in a)) {\n throw new Error('Required font metrics not supported');\n }\n }\n\n public measure(): Readonly {\n this._ctx.font = `${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`;\n const metrics = this._ctx.measureText('W');\n this._validateAndSet(metrics.width, metrics.fontBoundingBoxAscent + metrics.fontBoundingBoxDescent);\n return this._result;\n }\n}\n", "/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { ICoreBrowserService } from './Services';\nimport { Emitter, Event } from 'vs/base/common/event';\nimport { addDisposableListener } from 'vs/base/browser/dom';\nimport { Disposable, MutableDisposable, toDisposable } from 'vs/base/common/lifecycle';\n\nexport class CoreBrowserService extends Disposable implements ICoreBrowserService {\n public serviceBrand: undefined;\n\n private _isFocused = false;\n private _cachedIsFocused: boolean | undefined = undefined;\n private _screenDprMonitor = this._register(new ScreenDprMonitor(this._window));\n\n private readonly _onDprChange = this._register(new Emitter());\n public readonly onDprChange = this._onDprChange.event;\n private readonly _onWindowChange = this._register(new Emitter());\n public readonly onWindowChange = this._onWindowChange.event;\n\n constructor(\n private _textarea: HTMLTextAreaElement,\n private _window: Window & typeof globalThis,\n public readonly mainDocument: Document\n ) {\n super();\n\n // Monitor device pixel ratio\n this._register(this.onWindowChange(w => this._screenDprMonitor.setWindow(w)));\n this._register(Event.forward(this._screenDprMonitor.onDprChange, this._onDprChange));\n\n this._register(addDisposableListener(this._textarea, 'focus', () => this._isFocused = true));\n this._register(addDisposableListener(this._textarea, 'blur', () => this._isFocused = false));\n }\n\n public get window(): Window & typeof globalThis {\n return this._window;\n }\n\n public set window(value: Window & typeof globalThis) {\n if (this._window !== value) {\n this._window = value;\n this._onWindowChange.fire(this._window);\n }\n }\n\n public get dpr(): number {\n return this.window.devicePixelRatio;\n }\n\n public get isFocused(): boolean {\n if (this._cachedIsFocused === undefined) {\n this._cachedIsFocused = this._isFocused && this._textarea.ownerDocument.hasFocus();\n queueMicrotask(() => this._cachedIsFocused = undefined);\n }\n return this._cachedIsFocused;\n }\n}\n\n\n/**\n * The screen device pixel ratio monitor allows listening for when the\n * window.devicePixelRatio value changes. This is done not with polling but with\n * the use of window.matchMedia to watch media queries. When the event fires,\n * the listener will be reattached using a different media query to ensure that\n * any further changes will _register.\n *\n * The listener should fire on both window zoom changes and switching to a\n * monitor with a different DPI.\n */\nclass ScreenDprMonitor extends Disposable {\n private _currentDevicePixelRatio: number;\n private _outerListener: ((this: MediaQueryList, ev: MediaQueryListEvent) => any) | undefined;\n private _resolutionMediaMatchList: MediaQueryList | undefined;\n private _windowResizeListener = this._register(new MutableDisposable());\n\n private readonly _onDprChange = this._register(new Emitter());\n public readonly onDprChange = this._onDprChange.event;\n\n constructor(private _parentWindow: Window) {\n super();\n\n // Initialize listener and dpr value\n this._outerListener = () => this._setDprAndFireIfDiffers();\n this._currentDevicePixelRatio = this._parentWindow.devicePixelRatio;\n this._updateDpr();\n\n // Monitor active window resize\n this._setWindowResizeListener();\n\n // Setup additional disposables\n this._register(toDisposable(() => this.clearListener()));\n }\n\n\n public setWindow(parentWindow: Window): void {\n this._parentWindow = parentWindow;\n this._setWindowResizeListener();\n this._setDprAndFireIfDiffers();\n }\n\n private _setWindowResizeListener(): void {\n this._windowResizeListener.value = addDisposableListener(this._parentWindow, 'resize', () => this._setDprAndFireIfDiffers());\n }\n\n private _setDprAndFireIfDiffers(): void {\n if (this._parentWindow.devicePixelRatio !== this._currentDevicePixelRatio) {\n this._onDprChange.fire(this._parentWindow.devicePixelRatio);\n }\n this._updateDpr();\n }\n\n private _updateDpr(): void {\n if (!this._outerListener) {\n return;\n }\n\n // Clear listeners for old DPR\n this._resolutionMediaMatchList?.removeListener(this._outerListener);\n\n // Add listeners for new DPR\n this._currentDevicePixelRatio = this._parentWindow.devicePixelRatio;\n this._resolutionMediaMatchList = this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`);\n this._resolutionMediaMatchList.addListener(this._outerListener);\n }\n\n public clearListener(): void {\n if (!this._resolutionMediaMatchList || !this._outerListener) {\n return;\n }\n this._resolutionMediaMatchList.removeListener(this._outerListener);\n this._resolutionMediaMatchList = undefined;\n this._outerListener = undefined;\n }\n}\n", "import { ILinkProvider, ILinkProviderService } from 'browser/services/Services';\nimport { Disposable, toDisposable } from 'vs/base/common/lifecycle';\nimport { IDisposable } from 'common/Types';\n\nexport class LinkProviderService extends Disposable implements ILinkProviderService {\n declare public serviceBrand: undefined;\n\n public readonly linkProviders: ILinkProvider[] = [];\n\n constructor() {\n super();\n this._register(toDisposable(() => this.linkProviders.length = 0));\n }\n\n public registerLinkProvider(linkProvider: ILinkProvider): IDisposable {\n this.linkProviders.push(linkProvider);\n return {\n dispose: () => {\n // Remove the link provider from the list\n const providerIndex = this.linkProviders.indexOf(linkProvider);\n\n if (providerIndex !== -1) {\n this.linkProviders.splice(providerIndex, 1);\n }\n }\n };\n }\n}\n", "/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nexport function getCoordsRelativeToElement(window: Pick, event: {clientX: number, clientY: number}, element: HTMLElement): [number, number] {\n const rect = element.getBoundingClientRect();\n const elementStyle = window.getComputedStyle(element);\n const leftPadding = parseInt(elementStyle.getPropertyValue('padding-left'));\n const topPadding = parseInt(elementStyle.getPropertyValue('padding-top'));\n return [\n event.clientX - rect.left - leftPadding,\n event.clientY - rect.top - topPadding\n ];\n}\n\n/**\n * Gets coordinates within the terminal for a particular mouse event. The result\n * is returned as an array in the form [x, y] instead of an object as it's a\n * little faster and this function is used in some low level code.\n * @param window The window object the element belongs to.\n * @param event The mouse event.\n * @param element The terminal's container element.\n * @param colCount The number of columns in the terminal.\n * @param rowCount The number of rows n the terminal.\n * @param hasValidCharSize Whether there is a valid character size available.\n * @param cssCellWidth The cell width device pixel render dimensions.\n * @param cssCellHeight The cell height device pixel render dimensions.\n * @param isSelection Whether the request is for the selection or not. This will\n * apply an offset to the x value such that the left half of the cell will\n * select that cell and the right half will select the next cell.\n */\nexport function getCoords(window: Pick, event: Pick, element: HTMLElement, colCount: number, rowCount: number, hasValidCharSize: boolean, cssCellWidth: number, cssCellHeight: number, isSelection?: boolean): [number, number] | undefined {\n // Coordinates cannot be measured if there are no valid\n if (!hasValidCharSize) {\n return undefined;\n }\n\n const coords = getCoordsRelativeToElement(window, event, element);\n if (!coords) {\n return undefined;\n }\n\n coords[0] = Math.ceil((coords[0] + (isSelection ? cssCellWidth / 2 : 0)) / cssCellWidth);\n coords[1] = Math.ceil(coords[1] / cssCellHeight);\n\n // Ensure coordinates are within the terminal viewport. Note that selections\n // need an addition point of precision to cover the end point (as characters\n // cover half of one char and half of the next).\n coords[0] = Math.min(Math.max(coords[0], 1), colCount + (isSelection ? 1 : 0));\n coords[1] = Math.min(Math.max(coords[1], 1), rowCount);\n\n return coords;\n}\n", "/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { ICharSizeService, IRenderService, IMouseService } from './Services';\nimport { getCoords, getCoordsRelativeToElement } from 'browser/input/Mouse';\n\nexport class MouseService implements IMouseService {\n public serviceBrand: undefined;\n\n constructor(\n @IRenderService private readonly _renderService: IRenderService,\n @ICharSizeService private readonly _charSizeService: ICharSizeService\n ) {\n }\n\n public getCoords(event: {clientX: number, clientY: number}, element: HTMLElement, colCount: number, rowCount: number, isSelection?: boolean): [number, number] | undefined {\n return getCoords(\n window,\n event,\n element,\n colCount,\n rowCount,\n this._charSizeService.hasValidSize,\n this._renderService.dimensions.css.cell.width,\n this._renderService.dimensions.css.cell.height,\n isSelection\n );\n }\n\n public getMouseReportCoords(event: MouseEvent, element: HTMLElement): { col: number, row: number, x: number, y: number } | undefined {\n const coords = getCoordsRelativeToElement(window, event, element);\n if (!this._charSizeService.hasValidSize) {\n return undefined;\n }\n coords[0] = Math.min(Math.max(coords[0], 0), this._renderService.dimensions.css.canvas.width - 1);\n coords[1] = Math.min(Math.max(coords[1], 0), this._renderService.dimensions.css.canvas.height - 1);\n return {\n col: Math.floor(coords[0] / this._renderService.dimensions.css.cell.width),\n row: Math.floor(coords[1] / this._renderService.dimensions.css.cell.height),\n x: Math.floor(coords[0]),\n y: Math.floor(coords[1])\n };\n }\n}\n", "/**\n * Copyright (c) 2018 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IRenderDebouncerWithCallback } from 'browser/Types';\nimport { ICoreBrowserService } from 'browser/services/Services';\n\n/**\n * Debounces calls to render terminal rows using animation frames.\n */\nexport class RenderDebouncer implements IRenderDebouncerWithCallback {\n private _rowStart: number | undefined;\n private _rowEnd: number | undefined;\n private _rowCount: number | undefined;\n private _animationFrame: number | undefined;\n private _refreshCallbacks: FrameRequestCallback[] = [];\n\n constructor(\n private _renderCallback: (start: number, end: number) => void,\n private readonly _coreBrowserService: ICoreBrowserService\n ) {\n }\n\n public dispose(): void {\n if (this._animationFrame) {\n this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame);\n this._animationFrame = undefined;\n }\n }\n\n public addRefreshCallback(callback: FrameRequestCallback): number {\n this._refreshCallbacks.push(callback);\n if (!this._animationFrame) {\n this._animationFrame = this._coreBrowserService.window.requestAnimationFrame(() => this._innerRefresh());\n }\n return this._animationFrame;\n }\n\n public refresh(rowStart: number | undefined, rowEnd: number | undefined, rowCount: number): void {\n this._rowCount = rowCount;\n // Get the min/max row start/end for the arg values\n rowStart = rowStart !== undefined ? rowStart : 0;\n rowEnd = rowEnd !== undefined ? rowEnd : this._rowCount - 1;\n // Set the properties to the updated values\n this._rowStart = this._rowStart !== undefined ? Math.min(this._rowStart, rowStart) : rowStart;\n this._rowEnd = this._rowEnd !== undefined ? Math.max(this._rowEnd, rowEnd) : rowEnd;\n\n if (this._animationFrame) {\n return;\n }\n\n this._animationFrame = this._coreBrowserService.window.requestAnimationFrame(() => this._innerRefresh());\n }\n\n private _innerRefresh(): void {\n this._animationFrame = undefined;\n\n // Make sure values are set\n if (this._rowStart === undefined || this._rowEnd === undefined || this._rowCount === undefined) {\n this._runRefreshCallbacks();\n return;\n }\n\n // Clamp values\n const start = Math.max(this._rowStart, 0);\n const end = Math.min(this._rowEnd, this._rowCount - 1);\n\n // Reset debouncer (this happens before render callback as the render could trigger it again)\n this._rowStart = undefined;\n this._rowEnd = undefined;\n\n // Run render callback\n this._renderCallback(start, end);\n this._runRefreshCallbacks();\n }\n\n private _runRefreshCallbacks(): void {\n for (const callback of this._refreshCallbacks) {\n callback(0);\n }\n this._refreshCallbacks = [];\n }\n}\n", "/**\n * Copyright (c) 2016 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\ninterface INavigator {\n userAgent: string;\n language: string;\n platform: string;\n}\n\n// We're declaring a navigator global here as we expect it in all runtimes (node and browser), but\n// we want this module to live in common.\ndeclare const navigator: INavigator;\ndeclare const process: unknown;\n\nexport const isNode = (typeof process !== 'undefined' && 'title' in (process as any)) ? true : false;\nconst userAgent = (isNode) ? 'node' : navigator.userAgent;\nconst platform = (isNode) ? 'node' : navigator.platform;\n\nexport const isFirefox = userAgent.includes('Firefox');\nexport const isLegacyEdge = userAgent.includes('Edge');\nexport const isSafari = /^((?!chrome|android).)*safari/i.test(userAgent);\nexport function getSafariVersion(): number {\n if (!isSafari) {\n return 0;\n }\n const majorVersion = userAgent.match(/Version\\/(\\d+)/);\n if (majorVersion === null || majorVersion.length < 2) {\n return 0;\n }\n return parseInt(majorVersion[1]);\n}\n\n// Find the users platform. We use this to interpret the meta key\n// and ISO third level shifts.\n// http://stackoverflow.com/q/19877924/577598\nexport const isMac = ['Macintosh', 'MacIntel', 'MacPPC', 'Mac68K'].includes(platform);\nexport const isIpad = platform === 'iPad';\nexport const isIphone = platform === 'iPhone';\nexport const isWindows = ['Windows', 'Win16', 'Win32', 'WinCE'].includes(platform);\nexport const isLinux = platform.indexOf('Linux') >= 0;\n// Note that when this is true, isLinux will also be true.\nexport const isChromeOS = /\\bCrOS\\b/.test(userAgent);\n", "/**\n * Copyright (c) 2022 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { isNode } from 'common/Platform';\n\ninterface ITaskQueue {\n /**\n * Adds a task to the queue which will run in a future idle callback.\n * To avoid perceivable stalls on the mainthread, tasks with heavy workload\n * should split their work into smaller pieces and return `true` to get\n * called again until the work is done (on falsy return value).\n */\n enqueue(task: () => boolean | void): void;\n\n /**\n * Flushes the queue, running all remaining tasks synchronously.\n */\n flush(): void;\n\n /**\n * Clears any remaining tasks from the queue, these will not be run.\n */\n clear(): void;\n}\n\ninterface ITaskDeadline {\n timeRemaining(): number;\n}\ntype CallbackWithDeadline = (deadline: ITaskDeadline) => void;\n\nabstract class TaskQueue implements ITaskQueue {\n private _tasks: (() => boolean | void)[] = [];\n private _idleCallback?: number;\n private _i = 0;\n\n protected abstract _requestCallback(callback: CallbackWithDeadline): number;\n protected abstract _cancelCallback(identifier: number): void;\n\n public enqueue(task: () => boolean | void): void {\n this._tasks.push(task);\n this._start();\n }\n\n public flush(): void {\n while (this._i < this._tasks.length) {\n if (!this._tasks[this._i]()) {\n this._i++;\n }\n }\n this.clear();\n }\n\n public clear(): void {\n if (this._idleCallback) {\n this._cancelCallback(this._idleCallback);\n this._idleCallback = undefined;\n }\n this._i = 0;\n this._tasks.length = 0;\n }\n\n private _start(): void {\n if (!this._idleCallback) {\n this._idleCallback = this._requestCallback(this._process.bind(this));\n }\n }\n\n private _process(deadline: ITaskDeadline): void {\n this._idleCallback = undefined;\n let taskDuration = 0;\n let longestTask = 0;\n let lastDeadlineRemaining = deadline.timeRemaining();\n let deadlineRemaining = 0;\n while (this._i < this._tasks.length) {\n taskDuration = performance.now();\n if (!this._tasks[this._i]()) {\n this._i++;\n }\n // other than performance.now, performance.now might not be stable (changes on wall clock\n // changes), this is not an issue here as a clock change during a short running task is very\n // unlikely in case it still happened and leads to negative duration, simply assume 1 msec\n taskDuration = Math.max(1, performance.now() - taskDuration);\n longestTask = Math.max(taskDuration, longestTask);\n // Guess the following task will take a similar time to the longest task in this batch, allow\n // additional room to try avoid exceeding the deadline\n deadlineRemaining = deadline.timeRemaining();\n if (longestTask * 1.5 > deadlineRemaining) {\n // Warn when the time exceeding the deadline is over 20ms, if this happens in practice the\n // task should be split into sub-tasks to ensure the UI remains responsive.\n if (lastDeadlineRemaining - taskDuration < -20) {\n console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(lastDeadlineRemaining - taskDuration))}ms`);\n }\n this._start();\n return;\n }\n lastDeadlineRemaining = deadlineRemaining;\n }\n this.clear();\n }\n}\n\n/**\n * A queue of that runs tasks over several tasks via setTimeout, trying to maintain above 60 frames\n * per second. The tasks will run in the order they are enqueued, but they will run some time later,\n * and care should be taken to ensure they're non-urgent and will not introduce race conditions.\n */\nexport class PriorityTaskQueue extends TaskQueue {\n protected _requestCallback(callback: CallbackWithDeadline): number {\n return setTimeout(() => callback(this._createDeadline(16)));\n }\n\n protected _cancelCallback(identifier: number): void {\n clearTimeout(identifier);\n }\n\n private _createDeadline(duration: number): ITaskDeadline {\n const end = performance.now() + duration;\n return {\n timeRemaining: () => Math.max(0, end - performance.now())\n };\n }\n}\n\nclass IdleTaskQueueInternal extends TaskQueue {\n protected _requestCallback(callback: IdleRequestCallback): number {\n return requestIdleCallback(callback);\n }\n\n protected _cancelCallback(identifier: number): void {\n cancelIdleCallback(identifier);\n }\n}\n\n/**\n * A queue of that runs tasks over several idle callbacks, trying to respect the idle callback's\n * deadline given by the environment. The tasks will run in the order they are enqueued, but they\n * will run some time later, and care should be taken to ensure they're non-urgent and will not\n * introduce race conditions.\n *\n * This reverts to a {@link PriorityTaskQueue} if the environment does not support idle callbacks.\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport const IdleTaskQueue = (!isNode && 'requestIdleCallback' in window) ? IdleTaskQueueInternal : PriorityTaskQueue;\n\n/**\n * An object that tracks a single debounced task that will run on the next idle frame. When called\n * multiple times, only the last set task will run.\n */\nexport class DebouncedIdleTask {\n private _queue: ITaskQueue;\n\n constructor() {\n this._queue = new IdleTaskQueue();\n }\n\n public set(task: () => boolean | void): void {\n this._queue.clear();\n this._queue.enqueue(task);\n }\n\n public flush(): void {\n this._queue.flush();\n }\n}\n", "/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { RenderDebouncer } from 'browser/RenderDebouncer';\nimport { IRenderDebouncerWithCallback } from 'browser/Types';\nimport { IRenderDimensions, IRenderer } from 'browser/renderer/shared/Types';\nimport { ICharSizeService, ICoreBrowserService, IRenderService, IThemeService } from 'browser/services/Services';\nimport { Disposable, MutableDisposable, toDisposable } from 'vs/base/common/lifecycle';\nimport { DebouncedIdleTask } from 'common/TaskQueue';\nimport { IBufferService, ICoreService, IDecorationService, IOptionsService } from 'common/services/Services';\nimport { Emitter } from 'vs/base/common/event';\n\ninterface ISelectionState {\n start: [number, number] | undefined;\n end: [number, number] | undefined;\n columnSelectMode: boolean;\n}\n\nconst enum Constants {\n SYNCHRONIZED_OUTPUT_TIMEOUT_MS = 1000\n}\n\nexport class RenderService extends Disposable implements IRenderService {\n public serviceBrand: undefined;\n\n private _renderer: MutableDisposable = this._register(new MutableDisposable());\n private _renderDebouncer: IRenderDebouncerWithCallback;\n private _pausedResizeTask = new DebouncedIdleTask();\n private _observerDisposable = this._register(new MutableDisposable());\n\n private _isPaused: boolean = false;\n private _needsFullRefresh: boolean = false;\n private _isNextRenderRedrawOnly: boolean = true;\n private _needsSelectionRefresh: boolean = false;\n private _canvasWidth: number = 0;\n private _canvasHeight: number = 0;\n private _syncOutputHandler: SynchronizedOutputHandler;\n private _selectionState: ISelectionState = {\n start: undefined,\n end: undefined,\n columnSelectMode: false\n };\n\n private readonly _onDimensionsChange = this._register(new Emitter());\n public readonly onDimensionsChange = this._onDimensionsChange.event;\n private readonly _onRenderedViewportChange = this._register(new Emitter<{ start: number, end: number }>());\n public readonly onRenderedViewportChange = this._onRenderedViewportChange.event;\n private readonly _onRender = this._register(new Emitter<{ start: number, end: number }>());\n public readonly onRender = this._onRender.event;\n private readonly _onRefreshRequest = this._register(new Emitter<{ start: number, end: number }>());\n public readonly onRefreshRequest = this._onRefreshRequest.event;\n\n public get dimensions(): IRenderDimensions { return this._renderer.value!.dimensions; }\n\n constructor(\n private _rowCount: number,\n screenElement: HTMLElement,\n @IOptionsService private readonly _optionsService: IOptionsService,\n @ICharSizeService private readonly _charSizeService: ICharSizeService,\n @ICoreService private readonly _coreService: ICoreService,\n @IDecorationService decorationService: IDecorationService,\n @IBufferService bufferService: IBufferService,\n @ICoreBrowserService private readonly _coreBrowserService: ICoreBrowserService,\n @IThemeService themeService: IThemeService\n ) {\n super();\n\n this._renderDebouncer = new RenderDebouncer((start, end) => this._renderRows(start, end), this._coreBrowserService);\n this._register(this._renderDebouncer);\n\n this._syncOutputHandler = new SynchronizedOutputHandler(\n this._coreBrowserService,\n this._coreService,\n () => this._fullRefresh()\n );\n this._register(toDisposable(() => this._syncOutputHandler.dispose()));\n\n this._register(this._coreBrowserService.onDprChange(() => this.handleDevicePixelRatioChange()));\n\n this._register(bufferService.onResize(() => this._fullRefresh()));\n this._register(bufferService.buffers.onBufferActivate(() => this._renderer.value?.clear()));\n this._register(this._optionsService.onOptionChange(() => this._handleOptionsChanged()));\n this._register(this._charSizeService.onCharSizeChange(() => this.handleCharSizeChanged()));\n\n // Do a full refresh whenever any decoration is added or removed. This may not actually result\n // in changes but since decorations should be used sparingly or added/removed all in the same\n // frame this should have minimal performance impact.\n this._register(decorationService.onDecorationRegistered(() => this._fullRefresh()));\n this._register(decorationService.onDecorationRemoved(() => this._fullRefresh()));\n\n // Clear the renderer when the a change that could affect glyphs occurs\n this._register(this._optionsService.onMultipleOptionChange([\n 'customGlyphs',\n 'drawBoldTextInBrightColors',\n 'letterSpacing',\n 'lineHeight',\n 'fontFamily',\n 'fontSize',\n 'fontWeight',\n 'fontWeightBold',\n 'minimumContrastRatio',\n 'rescaleOverlappingGlyphs'\n ], () => {\n this.clear();\n this.handleResize(bufferService.cols, bufferService.rows);\n this._fullRefresh();\n }));\n\n // Refresh the cursor line when the cursor changes\n this._register(this._optionsService.onMultipleOptionChange([\n 'cursorBlink',\n 'cursorStyle'\n ], () => this.refreshRows(bufferService.buffer.y, bufferService.buffer.y, true)));\n\n this._register(themeService.onChangeColors(() => this._fullRefresh()));\n\n this._registerIntersectionObserver(this._coreBrowserService.window, screenElement);\n this._register(this._coreBrowserService.onWindowChange((w) => this._registerIntersectionObserver(w, screenElement)));\n }\n\n private _registerIntersectionObserver(w: Window & typeof globalThis, screenElement: HTMLElement): void {\n // Detect whether IntersectionObserver is detected and enable renderer pause\n // and resume based on terminal visibility if so\n if ('IntersectionObserver' in w) {\n const observer = new w.IntersectionObserver(e => this._handleIntersectionChange(e[e.length - 1]), { threshold: 0 });\n observer.observe(screenElement);\n this._observerDisposable.value = toDisposable(() => observer.disconnect());\n }\n }\n\n private _handleIntersectionChange(entry: IntersectionObserverEntry): void {\n this._isPaused = entry.isIntersecting === undefined ? (entry.intersectionRatio === 0) : !entry.isIntersecting;\n\n // Terminal was hidden on open\n if (!this._isPaused && !this._charSizeService.hasValidSize) {\n this._charSizeService.measure();\n }\n\n if (!this._isPaused && this._needsFullRefresh) {\n this._pausedResizeTask.flush();\n this.refreshRows(0, this._rowCount - 1);\n this._needsFullRefresh = false;\n }\n }\n\n public refreshRows(start: number, end: number, isRedrawOnly: boolean = false): void {\n if (this._isPaused) {\n this._needsFullRefresh = true;\n return;\n }\n\n if (this._coreService.decPrivateModes.synchronizedOutput) {\n this._syncOutputHandler.bufferRows(start, end);\n return;\n }\n\n const buffered = this._syncOutputHandler.flush();\n if (buffered) {\n start = Math.min(start, buffered.start);\n end = Math.max(end, buffered.end);\n }\n\n if (!isRedrawOnly) {\n this._isNextRenderRedrawOnly = false;\n }\n this._renderDebouncer.refresh(start, end, this._rowCount);\n }\n\n private _renderRows(start: number, end: number): void {\n if (!this._renderer.value) {\n return;\n }\n\n // Skip rendering if synchronized output mode is enabled. This check must happen here\n // (in addition to refreshRows) to handle renders that were queued before the mode was enabled.\n if (this._coreService.decPrivateModes.synchronizedOutput) {\n this._syncOutputHandler.bufferRows(start, end);\n return;\n }\n\n // Since this is debounced, a resize event could have happened between the time a refresh was\n // requested and when this triggers. Clamp the values of start and end to ensure they're valid\n // given the current viewport state.\n start = Math.min(start, this._rowCount - 1);\n end = Math.min(end, this._rowCount - 1);\n\n // Render\n this._renderer.value.renderRows(start, end);\n\n // Update selection if needed\n if (this._needsSelectionRefresh) {\n this._renderer.value.handleSelectionChanged(this._selectionState.start, this._selectionState.end, this._selectionState.columnSelectMode);\n this._needsSelectionRefresh = false;\n }\n\n // Fire render event only if it was not a redraw\n if (!this._isNextRenderRedrawOnly) {\n this._onRenderedViewportChange.fire({ start, end });\n }\n this._onRender.fire({ start, end });\n this._isNextRenderRedrawOnly = true;\n }\n\n public resize(cols: number, rows: number): void {\n this._rowCount = rows;\n this._fireOnCanvasResize();\n }\n\n private _handleOptionsChanged(): void {\n if (!this._renderer.value) {\n return;\n }\n this.refreshRows(0, this._rowCount - 1);\n this._fireOnCanvasResize();\n }\n\n private _fireOnCanvasResize(): void {\n if (!this._renderer.value) {\n return;\n }\n // Don't fire the event if the dimensions haven't changed\n if (this._renderer.value.dimensions.css.canvas.width === this._canvasWidth && this._renderer.value.dimensions.css.canvas.height === this._canvasHeight) {\n return;\n }\n this._onDimensionsChange.fire(this._renderer.value.dimensions);\n }\n\n public hasRenderer(): boolean {\n return !!this._renderer.value;\n }\n\n public setRenderer(renderer: IRenderer): void {\n this._renderer.value = renderer;\n // If the value was not set, the terminal is being disposed so ignore it\n if (this._renderer.value) {\n this._renderer.value.onRequestRedraw(e => this.refreshRows(e.start, e.end, true));\n\n // Force a refresh\n this._needsSelectionRefresh = true;\n this._fullRefresh();\n }\n }\n\n public addRefreshCallback(callback: FrameRequestCallback): number {\n return this._renderDebouncer.addRefreshCallback(callback);\n }\n\n private _fullRefresh(): void {\n if (this._isPaused) {\n this._needsFullRefresh = true;\n } else {\n this.refreshRows(0, this._rowCount - 1);\n }\n }\n\n public clearTextureAtlas(): void {\n if (!this._renderer.value) {\n return;\n }\n this._renderer.value.clearTextureAtlas?.();\n this._fullRefresh();\n }\n\n public handleDevicePixelRatioChange(): void {\n // Force char size measurement as DomMeasureStrategy(getBoundingClientRect) is not stable\n // when devicePixelRatio changes\n this._charSizeService.measure();\n\n if (!this._renderer.value) {\n return;\n }\n this._renderer.value.handleDevicePixelRatioChange();\n this.refreshRows(0, this._rowCount - 1);\n }\n\n public handleResize(cols: number, rows: number): void {\n if (!this._renderer.value) {\n return;\n }\n if (this._isPaused) {\n this._pausedResizeTask.set(() => this._renderer.value?.handleResize(cols, rows));\n } else {\n this._renderer.value.handleResize(cols, rows);\n }\n this._fullRefresh();\n }\n\n // TODO: Is this useful when we have onResize?\n public handleCharSizeChanged(): void {\n this._renderer.value?.handleCharSizeChanged();\n }\n\n public handleBlur(): void {\n this._renderer.value?.handleBlur();\n }\n\n public handleFocus(): void {\n this._renderer.value?.handleFocus();\n }\n\n public handleSelectionChanged(start: [number, number] | undefined, end: [number, number] | undefined, columnSelectMode: boolean): void {\n this._selectionState.start = start;\n this._selectionState.end = end;\n this._selectionState.columnSelectMode = columnSelectMode;\n this._renderer.value?.handleSelectionChanged(start, end, columnSelectMode);\n }\n\n public handleCursorMove(): void {\n this._renderer.value?.handleCursorMove();\n }\n\n public clear(): void {\n this._renderer.value?.clear();\n }\n}\n\n/**\n * Buffers row refresh requests during synchronized output mode (DEC mode 2026).\n * When the mode is disabled, the accumulated row range is flushed for rendering.\n * A safety timeout ensures rendering occurs even if the end sequence is not received.\n */\nclass SynchronizedOutputHandler {\n private _start: number = 0;\n private _end: number = 0;\n private _timeout: number | undefined;\n private _isBuffering: boolean = false;\n\n constructor(\n private readonly _coreBrowserService: ICoreBrowserService,\n private readonly _coreService: ICoreService,\n private readonly _onTimeout: () => void\n ) {}\n\n public bufferRows(start: number, end: number): void {\n if (!this._isBuffering) {\n this._start = start;\n this._end = end;\n this._isBuffering = true;\n } else {\n this._start = Math.min(this._start, start);\n this._end = Math.max(this._end, end);\n }\n\n if (this._timeout === undefined) {\n this._timeout = this._coreBrowserService.window.setTimeout(() => {\n this._timeout = undefined;\n this._coreService.decPrivateModes.synchronizedOutput = false;\n this._onTimeout();\n }, Constants.SYNCHRONIZED_OUTPUT_TIMEOUT_MS);\n }\n }\n\n public flush(): { start: number, end: number } | undefined {\n if (this._timeout !== undefined) {\n this._coreBrowserService.window.clearTimeout(this._timeout);\n this._timeout = undefined;\n }\n\n if (!this._isBuffering) {\n return undefined;\n }\n\n const result = { start: this._start, end: this._end };\n this._isBuffering = false;\n return result;\n }\n\n public dispose(): void {\n if (this._timeout !== undefined) {\n this._coreBrowserService.window.clearTimeout(this._timeout);\n this._timeout = undefined;\n }\n }\n}\n", "/**\n * Copyright (c) 2018 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { C0 } from 'common/data/EscapeSequences';\nimport { IBufferService } from 'common/services/Services';\n\nconst enum Direction {\n UP = 'A',\n DOWN = 'B',\n RIGHT = 'C',\n LEFT = 'D'\n}\n\n/**\n * Concatenates all the arrow sequences together.\n * Resets the starting row to an unwrapped row, moves to the requested row,\n * then moves to requested col.\n */\nexport function moveToCellSequence(targetX: number, targetY: number, bufferService: IBufferService, applicationCursor: boolean): string {\n const startX = bufferService.buffer.x;\n const startY = bufferService.buffer.y;\n\n // The alt buffer should try to navigate between rows\n if (!bufferService.buffer.hasScrollback) {\n return resetStartingRow(startX, startY, targetX, targetY, bufferService, applicationCursor) +\n moveToRequestedRow(startY, targetY, bufferService, applicationCursor) +\n moveToRequestedCol(startX, startY, targetX, targetY, bufferService, applicationCursor);\n }\n\n // Only move horizontally for the normal buffer\n let direction;\n if (startY === targetY) {\n direction = startX > targetX ? Direction.LEFT : Direction.RIGHT;\n return repeat(Math.abs(startX - targetX), sequence(direction, applicationCursor));\n }\n direction = startY > targetY ? Direction.LEFT : Direction.RIGHT;\n const rowDifference = Math.abs(startY - targetY);\n const cellsToMove = colsFromRowEnd(startY > targetY ? targetX : startX, bufferService) +\n (rowDifference - 1) * bufferService.cols + 1 /* wrap around 1 row */ +\n colsFromRowBeginning(startY > targetY ? startX : targetX, bufferService);\n return repeat(cellsToMove, sequence(direction, applicationCursor));\n}\n\n/**\n * Find the number of cols from a row beginning to a col.\n */\nfunction colsFromRowBeginning(currX: number, bufferService: IBufferService): number {\n return currX - 1;\n}\n\n/**\n * Find the number of cols from a col to row end.\n */\nfunction colsFromRowEnd(currX: number, bufferService: IBufferService): number {\n return bufferService.cols - currX;\n}\n\n/**\n * If the initial position of the cursor is on a row that is wrapped, move the\n * cursor up to the first row that is not wrapped to have accurate vertical\n * positioning.\n */\nfunction resetStartingRow(startX: number, startY: number, targetX: number, targetY: number, bufferService: IBufferService, applicationCursor: boolean): string {\n if (moveToRequestedRow(startY, targetY, bufferService, applicationCursor).length === 0) {\n return '';\n }\n return repeat(bufferLine(\n startX, startY, startX,\n startY - wrappedRowsForRow(startY, bufferService), false, bufferService\n ).length, sequence(Direction.LEFT, applicationCursor));\n}\n\n/**\n * Using the reset starting and ending row, move to the requested row,\n * ignoring wrapped rows\n */\nfunction moveToRequestedRow(startY: number, targetY: number, bufferService: IBufferService, applicationCursor: boolean): string {\n const startRow = startY - wrappedRowsForRow(startY, bufferService);\n const endRow = targetY - wrappedRowsForRow(targetY, bufferService);\n\n const rowsToMove = Math.abs(startRow - endRow) - wrappedRowsCount(startY, targetY, bufferService);\n\n return repeat(rowsToMove, sequence(verticalDirection(startY, targetY), applicationCursor));\n}\n\n/**\n * Move to the requested col on the ending row\n */\nfunction moveToRequestedCol(startX: number, startY: number, targetX: number, targetY: number, bufferService: IBufferService, applicationCursor: boolean): string {\n let startRow;\n if (moveToRequestedRow(startY, targetY, bufferService, applicationCursor).length > 0) {\n startRow = targetY - wrappedRowsForRow(targetY, bufferService);\n } else {\n startRow = startY;\n }\n\n const endRow = targetY;\n const direction = horizontalDirection(startX, startY, targetX, targetY, bufferService, applicationCursor);\n\n return repeat(bufferLine(\n startX, startRow, targetX, endRow,\n direction === Direction.RIGHT, bufferService\n ).length, sequence(direction, applicationCursor));\n}\n\n/**\n * Utility functions\n */\n\n/**\n * Calculates the number of wrapped rows between the unwrapped starting and\n * ending rows. These rows need to ignored since the cursor skips over them.\n */\nfunction wrappedRowsCount(startY: number, targetY: number, bufferService: IBufferService): number {\n let wrappedRows = 0;\n const startRow = startY - wrappedRowsForRow(startY, bufferService);\n const endRow = targetY - wrappedRowsForRow(targetY, bufferService);\n\n for (let i = 0; i < Math.abs(startRow - endRow); i++) {\n const direction = verticalDirection(startY, targetY) === Direction.UP ? -1 : 1;\n const line = bufferService.buffer.lines.get(startRow + (direction * i));\n if (line?.isWrapped) {\n wrappedRows++;\n }\n }\n\n return wrappedRows;\n}\n\n/**\n * Calculates the number of wrapped rows that make up a given row.\n * @param currentRow The row to determine how many wrapped rows make it up\n */\nfunction wrappedRowsForRow(currentRow: number, bufferService: IBufferService): number {\n let rowCount = 0;\n let line = bufferService.buffer.lines.get(currentRow);\n let lineWraps = line?.isWrapped;\n\n while (lineWraps && currentRow >= 0 && currentRow < bufferService.rows) {\n rowCount++;\n line = bufferService.buffer.lines.get(--currentRow);\n lineWraps = line?.isWrapped;\n }\n\n return rowCount;\n}\n\n/**\n * Direction determiners\n */\n\n/**\n * Determines if the right or left arrow is needed\n */\nfunction horizontalDirection(startX: number, startY: number, targetX: number, targetY: number, bufferService: IBufferService, applicationCursor: boolean): Direction {\n let startRow;\n if (moveToRequestedRow(targetX, targetY, bufferService, applicationCursor).length > 0) {\n startRow = targetY - wrappedRowsForRow(targetY, bufferService);\n } else {\n startRow = startY;\n }\n\n if ((startX < targetX &&\n startRow <= targetY) || // down/right or same y/right\n (startX >= targetX &&\n startRow < targetY)) { // down/left or same y/left\n return Direction.RIGHT;\n }\n return Direction.LEFT;\n}\n\n/**\n * Determines if the up or down arrow is needed\n */\nfunction verticalDirection(startY: number, targetY: number): Direction {\n return startY > targetY ? Direction.UP : Direction.DOWN;\n}\n\n/**\n * Constructs the string of chars in the buffer from a starting row and col\n * to an ending row and col\n * @param startCol The starting column position\n * @param startRow The starting row position\n * @param endCol The ending column position\n * @param endRow The ending row position\n * @param forward Direction to move\n */\nfunction bufferLine(\n startCol: number,\n startRow: number,\n endCol: number,\n endRow: number,\n forward: boolean,\n bufferService: IBufferService\n): string {\n let currentCol = startCol;\n let currentRow = startRow;\n let bufferStr = '';\n\n while ((currentCol !== endCol || currentRow !== endRow) &&\n currentRow >= 0 &&\n currentRow < bufferService.buffer.lines.length) {\n currentCol += forward ? 1 : -1;\n\n if (forward && currentCol > bufferService.cols - 1) {\n bufferStr += bufferService.buffer.translateBufferLineToString(\n currentRow, false, startCol, currentCol\n );\n currentCol = 0;\n startCol = 0;\n currentRow++;\n } else if (!forward && currentCol < 0) {\n bufferStr += bufferService.buffer.translateBufferLineToString(\n currentRow, false, 0, startCol + 1\n );\n currentCol = bufferService.cols - 1;\n startCol = currentCol;\n currentRow--;\n }\n }\n\n return bufferStr + bufferService.buffer.translateBufferLineToString(\n currentRow, false, startCol, currentCol\n );\n}\n\n/**\n * Constructs the escape sequence for clicking an arrow\n * @param direction The direction to move\n */\nfunction sequence(direction: Direction, applicationCursor: boolean): string {\n const mod = applicationCursor ? 'O' : '[';\n return C0.ESC + mod + direction;\n}\n\n/**\n * Returns a string repeated a given number of times\n * Polyfill from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat\n * @param count The number of times to repeat the string\n * @param str The string that is to be repeated\n */\nfunction repeat(count: number, str: string): string {\n count = Math.floor(count);\n let rpt = '';\n for (let i = 0; i < count; i++) {\n rpt += str;\n }\n return rpt;\n}\n", "/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IBufferService } from 'common/services/Services';\n\n/**\n * Represents a selection within the buffer. This model only cares about column\n * and row coordinates, not wide characters.\n */\nexport class SelectionModel {\n /**\n * Whether select all is currently active.\n */\n public isSelectAllActive: boolean = false;\n\n /**\n * The minimal length of the selection from the start position. When double\n * clicking on a word, the word will be selected which makes the selection\n * start at the start of the word and makes this variable the length.\n */\n public selectionStartLength: number = 0;\n\n /**\n * The [x, y] position the selection starts at.\n */\n public selectionStart: [number, number] | undefined;\n\n /**\n * The [x, y] position the selection ends at.\n */\n public selectionEnd: [number, number] | undefined;\n\n constructor(\n private _bufferService: IBufferService\n ) {\n }\n\n /**\n * Clears the current selection.\n */\n public clearSelection(): void {\n this.selectionStart = undefined;\n this.selectionEnd = undefined;\n this.isSelectAllActive = false;\n this.selectionStartLength = 0;\n }\n\n /**\n * The final selection start, taking into consideration select all.\n */\n public get finalSelectionStart(): [number, number] | undefined {\n if (this.isSelectAllActive) {\n return [0, 0];\n }\n\n if (!this.selectionEnd || !this.selectionStart) {\n return this.selectionStart;\n }\n\n return this.areSelectionValuesReversed() ? this.selectionEnd : this.selectionStart;\n }\n\n /**\n * The final selection end, taking into consideration select all, double click\n * word selection and triple click line selection.\n */\n public get finalSelectionEnd(): [number, number] | undefined {\n if (this.isSelectAllActive) {\n return [this._bufferService.cols, this._bufferService.buffer.ybase + this._bufferService.rows - 1];\n }\n\n if (!this.selectionStart) {\n return undefined;\n }\n\n // Use the selection start + length if the end doesn't exist or they're reversed\n if (!this.selectionEnd || this.areSelectionValuesReversed()) {\n const startPlusLength = this.selectionStart[0] + this.selectionStartLength;\n if (startPlusLength > this._bufferService.cols) {\n // Ensure the trailing EOL isn't included when the selection ends on the right edge\n if (startPlusLength % this._bufferService.cols === 0) {\n return [this._bufferService.cols, this.selectionStart[1] + Math.floor(startPlusLength / this._bufferService.cols) - 1];\n }\n return [startPlusLength % this._bufferService.cols, this.selectionStart[1] + Math.floor(startPlusLength / this._bufferService.cols)];\n }\n return [startPlusLength, this.selectionStart[1]];\n }\n\n // Ensure the the word/line is selected after a double/triple click\n if (this.selectionStartLength) {\n // Select the larger of the two when start and end are on the same line\n if (this.selectionEnd[1] === this.selectionStart[1]) {\n // Keep the whole wrapped word/line selected if the content wraps multiple lines\n const startPlusLength = this.selectionStart[0] + this.selectionStartLength;\n if (startPlusLength > this._bufferService.cols) {\n return [startPlusLength % this._bufferService.cols, this.selectionStart[1] + Math.floor(startPlusLength / this._bufferService.cols)];\n }\n return [Math.max(startPlusLength, this.selectionEnd[0]), this.selectionEnd[1]];\n }\n }\n return this.selectionEnd;\n }\n\n /**\n * Returns whether the selection start and end are reversed.\n */\n public areSelectionValuesReversed(): boolean {\n const start = this.selectionStart;\n const end = this.selectionEnd;\n if (!start || !end) {\n return false;\n }\n return start[1] > end[1] || (start[1] === end[1] && start[0] > end[0]);\n }\n\n /**\n * Handle the buffer being trimmed, adjust the selection position.\n * @param amount The amount the buffer is being trimmed.\n * @returns Whether a refresh is necessary.\n */\n public handleTrim(amount: number): boolean {\n // Adjust the selection position based on the trimmed amount.\n if (this.selectionStart) {\n this.selectionStart[1] -= amount;\n }\n if (this.selectionEnd) {\n this.selectionEnd[1] -= amount;\n }\n\n // The selection has moved off the buffer, clear it.\n if (this.selectionEnd && this.selectionEnd[1] < 0) {\n this.clearSelection();\n return true;\n }\n\n // If the selection start is trimmed, ensure the start column is 0.\n if (this.selectionStart && this.selectionStart[1] < 0) {\n this.selectionStart[1] = 0;\n }\n return false;\n }\n}\n", "/**\n * Copyright (c) 2021 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IBufferRange } from '@xterm/xterm';\n\nexport function getRangeLength(range: IBufferRange, bufferCols: number): number {\n if (range.start.y > range.end.y) {\n throw new Error(`Buffer range end (${range.end.x}, ${range.end.y}) cannot be before start (${range.start.x}, ${range.start.y})`);\n }\n return bufferCols * (range.end.y - range.start.y) + (range.end.x - range.start.x + 1);\n}\n", "/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IBufferRange, ILinkifier2 } from 'browser/Types';\nimport { getCoordsRelativeToElement } from 'browser/input/Mouse';\nimport { moveToCellSequence } from 'browser/input/MoveToCell';\nimport { SelectionModel } from 'browser/selection/SelectionModel';\nimport { ISelectionRedrawRequestEvent, ISelectionRequestScrollLinesEvent } from 'browser/selection/Types';\nimport { ICoreBrowserService, IMouseService, IRenderService, ISelectionService } from 'browser/services/Services';\nimport { Disposable, toDisposable } from 'vs/base/common/lifecycle';\nimport * as Browser from 'common/Platform';\nimport { IBufferLine, IDisposable } from 'common/Types';\nimport { getRangeLength } from 'common/buffer/BufferRange';\nimport { CellData } from 'common/buffer/CellData';\nimport { IBuffer } from 'common/buffer/Types';\nimport { IBufferService, ICoreService, IOptionsService } from 'common/services/Services';\nimport { Emitter } from 'vs/base/common/event';\n\n/**\n * The number of pixels the mouse needs to be above or below the viewport in\n * order to scroll at the maximum speed.\n */\nconst DRAG_SCROLL_MAX_THRESHOLD = 50;\n\n/**\n * The maximum scrolling speed\n */\nconst DRAG_SCROLL_MAX_SPEED = 15;\n\n/**\n * The number of milliseconds between drag scroll updates.\n */\nconst DRAG_SCROLL_INTERVAL = 50;\n\n/**\n * The maximum amount of time that can have elapsed for an alt click to move the\n * cursor.\n */\nconst ALT_CLICK_MOVE_CURSOR_TIME = 500;\n\nconst NON_BREAKING_SPACE_CHAR = String.fromCharCode(160);\nconst ALL_NON_BREAKING_SPACE_REGEX = new RegExp(NON_BREAKING_SPACE_CHAR, 'g');\n\n/**\n * Represents a position of a word on a line.\n */\ninterface IWordPosition {\n start: number;\n length: number;\n}\n\n/**\n * A selection mode, this drives how the selection behaves on mouse move.\n */\nexport const enum SelectionMode {\n NORMAL,\n WORD,\n LINE,\n COLUMN\n}\n\n/**\n * A class that manages the selection of the terminal. With help from\n * SelectionModel, SelectionService handles with all logic associated with\n * dealing with the selection, including handling mouse interaction, wide\n * characters and fetching the actual text within the selection. Rendering is\n * not handled by the SelectionService but the onRedrawRequest event is fired\n * when the selection is ready to be redrawn (on an animation frame).\n */\nexport class SelectionService extends Disposable implements ISelectionService {\n public serviceBrand: undefined;\n\n protected _model: SelectionModel;\n\n /**\n * The amount to scroll every drag scroll update (depends on how far the mouse\n * drag is above or below the terminal).\n */\n private _dragScrollAmount: number = 0;\n\n /**\n * The current selection mode.\n */\n protected _activeSelectionMode: SelectionMode;\n\n /**\n * A setInterval timer that is active while the mouse is down whose callback\n * scrolls the viewport when necessary.\n */\n private _dragScrollIntervalTimer: number | undefined;\n\n /**\n * The animation frame ID used for refreshing the selection.\n */\n private _refreshAnimationFrame: number | undefined;\n\n /**\n * Whether selection is enabled.\n */\n private _enabled = true;\n\n private _mouseMoveListener: EventListener;\n private _mouseUpListener: EventListener;\n private _trimListener: IDisposable;\n private _workCell: CellData = new CellData();\n\n private _mouseDownTimeStamp: number = 0;\n private _oldHasSelection: boolean = false;\n private _oldSelectionStart: [number, number] | undefined = undefined;\n private _oldSelectionEnd: [number, number] | undefined = undefined;\n\n private readonly _onLinuxMouseSelection = this._register(new Emitter());\n public readonly onLinuxMouseSelection = this._onLinuxMouseSelection.event;\n private readonly _onRedrawRequest = this._register(new Emitter());\n public readonly onRequestRedraw = this._onRedrawRequest.event;\n private readonly _onSelectionChange = this._register(new Emitter());\n public readonly onSelectionChange = this._onSelectionChange.event;\n private readonly _onRequestScrollLines = this._register(new Emitter());\n public readonly onRequestScrollLines = this._onRequestScrollLines.event;\n\n constructor(\n private readonly _element: HTMLElement,\n private readonly _screenElement: HTMLElement,\n private readonly _linkifier: ILinkifier2,\n @IBufferService private readonly _bufferService: IBufferService,\n @ICoreService private readonly _coreService: ICoreService,\n @IMouseService private readonly _mouseService: IMouseService,\n @IOptionsService private readonly _optionsService: IOptionsService,\n @IRenderService private readonly _renderService: IRenderService,\n @ICoreBrowserService private readonly _coreBrowserService: ICoreBrowserService\n ) {\n super();\n\n // Init listeners\n this._mouseMoveListener = event => this._handleMouseMove(event as MouseEvent);\n this._mouseUpListener = event => this._handleMouseUp(event as MouseEvent);\n this._coreService.onUserInput(() => {\n if (this.hasSelection) {\n this.clearSelection();\n }\n });\n this._trimListener = this._bufferService.buffer.lines.onTrim(amount => this._handleTrim(amount));\n this._register(this._bufferService.buffers.onBufferActivate(e => this._handleBufferActivate(e)));\n\n this.enable();\n\n this._model = new SelectionModel(this._bufferService);\n this._activeSelectionMode = SelectionMode.NORMAL;\n\n this._register(toDisposable(() => {\n this._removeMouseDownListeners();\n }));\n\n // Clear selection when resizing vertically. This experience could be improved, this is the\n // simple option to fix the buggy behavior. https://github.com/xtermjs/xterm.js/issues/5300\n this._register(this._bufferService.onResize(e => {\n if (e.rowsChanged) {\n this.clearSelection();\n }\n }));\n }\n\n public reset(): void {\n this.clearSelection();\n }\n\n /**\n * Disables the selection manager. This is useful for when terminal mouse\n * are enabled.\n */\n public disable(): void {\n this.clearSelection();\n this._enabled = false;\n }\n\n /**\n * Enable the selection manager.\n */\n public enable(): void {\n this._enabled = true;\n }\n\n public get selectionStart(): [number, number] | undefined { return this._model.finalSelectionStart; }\n public get selectionEnd(): [number, number] | undefined { return this._model.finalSelectionEnd; }\n\n /**\n * Gets whether there is an active text selection.\n */\n public get hasSelection(): boolean {\n const start = this._model.finalSelectionStart;\n const end = this._model.finalSelectionEnd;\n if (!start || !end) {\n return false;\n }\n return start[0] !== end[0] || start[1] !== end[1];\n }\n\n /**\n * Gets the text currently selected.\n */\n public get selectionText(): string {\n const start = this._model.finalSelectionStart;\n const end = this._model.finalSelectionEnd;\n if (!start || !end) {\n return '';\n }\n\n const buffer = this._bufferService.buffer;\n const result: string[] = [];\n\n if (this._activeSelectionMode === SelectionMode.COLUMN) {\n // Ignore zero width selections\n if (start[0] === end[0]) {\n return '';\n }\n\n // For column selection it's not enough to rely on final selection's swapping of reversed\n // values, it also needs the x coordinates to swap independently of the y coordinate is needed\n const startCol = start[0] < end[0] ? start[0] : end[0];\n const endCol = start[0] < end[0] ? end[0] : start[0];\n for (let i = start[1]; i <= end[1]; i++) {\n const lineText = buffer.translateBufferLineToString(i, true, startCol, endCol);\n result.push(lineText);\n }\n } else {\n // Get first row\n const startRowEndCol = start[1] === end[1] ? end[0] : undefined;\n result.push(buffer.translateBufferLineToString(start[1], true, start[0], startRowEndCol));\n\n // Get middle rows\n for (let i = start[1] + 1; i <= end[1] - 1; i++) {\n const bufferLine = buffer.lines.get(i);\n const lineText = buffer.translateBufferLineToString(i, true);\n if (bufferLine?.isWrapped) {\n result[result.length - 1] += lineText;\n } else {\n result.push(lineText);\n }\n }\n\n // Get final row\n if (start[1] !== end[1]) {\n const bufferLine = buffer.lines.get(end[1]);\n const lineText = buffer.translateBufferLineToString(end[1], true, 0, end[0]);\n if (bufferLine && bufferLine!.isWrapped) {\n result[result.length - 1] += lineText;\n } else {\n result.push(lineText);\n }\n }\n }\n\n // Format string by replacing non-breaking space chars with regular spaces\n // and joining the array into a multi-line string.\n const formattedResult = result.map(line => {\n return line.replace(ALL_NON_BREAKING_SPACE_REGEX, ' ');\n }).join(Browser.isWindows ? '\\r\\n' : '\\n');\n\n return formattedResult;\n }\n\n /**\n * Clears the current terminal selection.\n */\n public clearSelection(): void {\n this._model.clearSelection();\n this._removeMouseDownListeners();\n this.refresh();\n this._onSelectionChange.fire();\n }\n\n /**\n * Queues a refresh, redrawing the selection on the next opportunity.\n * @param isLinuxMouseSelection Whether the selection should be registered as a new\n * selection on Linux.\n */\n public refresh(isLinuxMouseSelection?: boolean): void {\n // Queue the refresh for the renderer\n if (!this._refreshAnimationFrame) {\n this._refreshAnimationFrame = this._coreBrowserService.window.requestAnimationFrame(() => this._refresh());\n }\n\n // If the platform is Linux and the refresh call comes from a mouse event,\n // we need to update the selection for middle click to paste selection.\n if (Browser.isLinux && isLinuxMouseSelection) {\n const selectionText = this.selectionText;\n if (selectionText.length) {\n this._onLinuxMouseSelection.fire(this.selectionText);\n }\n }\n }\n\n /**\n * Fires the refresh event, causing consumers to pick it up and redraw the\n * selection state.\n */\n private _refresh(): void {\n this._refreshAnimationFrame = undefined;\n this._onRedrawRequest.fire({\n start: this._model.finalSelectionStart,\n end: this._model.finalSelectionEnd,\n columnSelectMode: this._activeSelectionMode === SelectionMode.COLUMN\n });\n }\n\n /**\n * Checks if the current click was inside the current selection\n * @param event The mouse event\n */\n private _isClickInSelection(event: MouseEvent): boolean {\n const coords = this._getMouseBufferCoords(event);\n const start = this._model.finalSelectionStart;\n const end = this._model.finalSelectionEnd;\n\n if (!start || !end || !coords) {\n return false;\n }\n\n return this._areCoordsInSelection(coords, start, end);\n }\n\n public isCellInSelection(x: number, y: number): boolean {\n const start = this._model.finalSelectionStart;\n const end = this._model.finalSelectionEnd;\n if (!start || !end) {\n return false;\n }\n return this._areCoordsInSelection([x, y], start, end);\n }\n\n protected _areCoordsInSelection(coords: [number, number], start: [number, number], end: [number, number]): boolean {\n return (coords[1] > start[1] && coords[1] < end[1]) ||\n (start[1] === end[1] && coords[1] === start[1] && coords[0] >= start[0] && coords[0] < end[0]) ||\n (start[1] < end[1] && coords[1] === end[1] && coords[0] < end[0]) ||\n (start[1] < end[1] && coords[1] === start[1] && coords[0] >= start[0]);\n }\n\n /**\n * Selects word at the current mouse event coordinates.\n * @param event The mouse event.\n */\n private _selectWordAtCursor(event: MouseEvent, allowWhitespaceOnlySelection: boolean): boolean {\n // Check if there is a link under the cursor first and select that if so\n const range = this._linkifier.currentLink?.link?.range;\n if (range) {\n this._model.selectionStart = [range.start.x - 1, range.start.y - 1];\n this._model.selectionStartLength = getRangeLength(range, this._bufferService.cols);\n this._model.selectionEnd = undefined;\n return true;\n }\n\n const coords = this._getMouseBufferCoords(event);\n if (coords) {\n this._selectWordAt(coords, allowWhitespaceOnlySelection);\n this._model.selectionEnd = undefined;\n return true;\n }\n return false;\n }\n\n /**\n * Selects all text within the terminal.\n */\n public selectAll(): void {\n this._model.isSelectAllActive = true;\n this.refresh();\n this._onSelectionChange.fire();\n }\n\n public selectLines(start: number, end: number): void {\n this._model.clearSelection();\n start = Math.max(start, 0);\n end = Math.min(end, this._bufferService.buffer.lines.length - 1);\n this._model.selectionStart = [0, start];\n this._model.selectionEnd = [this._bufferService.cols, end];\n this.refresh();\n this._onSelectionChange.fire();\n }\n\n /**\n * Handle the buffer being trimmed, adjust the selection position.\n * @param amount The amount the buffer is being trimmed.\n */\n private _handleTrim(amount: number): void {\n const needsRefresh = this._model.handleTrim(amount);\n if (needsRefresh) {\n this.refresh();\n }\n }\n\n /**\n * Gets the 0-based [x, y] buffer coordinates of the current mouse event.\n * @param event The mouse event.\n */\n private _getMouseBufferCoords(event: MouseEvent): [number, number] | undefined {\n const coords = this._mouseService.getCoords(event, this._screenElement, this._bufferService.cols, this._bufferService.rows, true);\n if (!coords) {\n return undefined;\n }\n\n // Convert to 0-based\n coords[0]--;\n coords[1]--;\n\n // Convert viewport coords to buffer coords\n coords[1] += this._bufferService.buffer.ydisp;\n return coords;\n }\n\n /**\n * Gets the amount the viewport should be scrolled based on how far out of the\n * terminal the mouse is.\n * @param event The mouse event.\n */\n private _getMouseEventScrollAmount(event: MouseEvent): number {\n let offset = getCoordsRelativeToElement(this._coreBrowserService.window, event, this._screenElement)[1];\n const terminalHeight = this._renderService.dimensions.css.canvas.height;\n if (offset >= 0 && offset <= terminalHeight) {\n return 0;\n }\n if (offset > terminalHeight) {\n offset -= terminalHeight;\n }\n\n offset = Math.min(Math.max(offset, -DRAG_SCROLL_MAX_THRESHOLD), DRAG_SCROLL_MAX_THRESHOLD);\n offset /= DRAG_SCROLL_MAX_THRESHOLD;\n return (offset / Math.abs(offset)) + Math.round(offset * (DRAG_SCROLL_MAX_SPEED - 1));\n }\n\n /**\n * Returns whether the selection manager should force selection, regardless of\n * whether the terminal is in mouse events mode.\n * @param event The mouse event.\n */\n public shouldForceSelection(event: MouseEvent): boolean {\n if (Browser.isMac) {\n return event.altKey && this._optionsService.rawOptions.macOptionClickForcesSelection;\n }\n\n return event.shiftKey;\n }\n\n /**\n * Handles te mousedown event, setting up for a new selection.\n * @param event The mousedown event.\n */\n public handleMouseDown(event: MouseEvent): void {\n this._mouseDownTimeStamp = event.timeStamp;\n // If we have selection, we want the context menu on right click even if the\n // terminal is in mouse mode.\n if (event.button === 2 && this.hasSelection) {\n return;\n }\n\n // Only action the primary button\n if (event.button !== 0) {\n return;\n }\n\n // Allow selection when using a specific modifier key, even when disabled\n if (!this._enabled) {\n if (!this.shouldForceSelection(event)) {\n return;\n }\n\n // Don't send the mouse down event to the current process, we want to select\n event.stopPropagation();\n }\n\n // Tell the browser not to start a regular selection\n event.preventDefault();\n\n // Reset drag scroll state\n this._dragScrollAmount = 0;\n\n if (this._enabled && event.shiftKey) {\n this._handleIncrementalClick(event);\n } else {\n if (event.detail === 1) {\n this._handleSingleClick(event);\n } else if (event.detail === 2) {\n this._handleDoubleClick(event);\n } else if (event.detail === 3) {\n this._handleTripleClick(event);\n }\n }\n\n this._addMouseDownListeners();\n this.refresh(true);\n }\n\n /**\n * Adds listeners when mousedown is triggered.\n */\n private _addMouseDownListeners(): void {\n // Listen on the document so that dragging outside of viewport works\n if (this._screenElement.ownerDocument) {\n this._screenElement.ownerDocument.addEventListener('mousemove', this._mouseMoveListener);\n this._screenElement.ownerDocument.addEventListener('mouseup', this._mouseUpListener);\n }\n this._dragScrollIntervalTimer = this._coreBrowserService.window.setInterval(() => this._dragScroll(), DRAG_SCROLL_INTERVAL);\n }\n\n /**\n * Removes the listeners that are registered when mousedown is triggered.\n */\n private _removeMouseDownListeners(): void {\n if (this._screenElement.ownerDocument) {\n this._screenElement.ownerDocument.removeEventListener('mousemove', this._mouseMoveListener);\n this._screenElement.ownerDocument.removeEventListener('mouseup', this._mouseUpListener);\n }\n this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer);\n this._dragScrollIntervalTimer = undefined;\n }\n\n /**\n * Performs an incremental click, setting the selection end position to the mouse\n * position.\n * @param event The mouse event.\n */\n private _handleIncrementalClick(event: MouseEvent): void {\n if (this._model.selectionStart) {\n this._model.selectionEnd = this._getMouseBufferCoords(event);\n }\n }\n\n /**\n * Performs a single click, resetting relevant state and setting the selection\n * start position.\n * @param event The mouse event.\n */\n private _handleSingleClick(event: MouseEvent): void {\n this._model.selectionStartLength = 0;\n this._model.isSelectAllActive = false;\n this._activeSelectionMode = this.shouldColumnSelect(event) ? SelectionMode.COLUMN : SelectionMode.NORMAL;\n\n // Initialize the new selection\n this._model.selectionStart = this._getMouseBufferCoords(event);\n if (!this._model.selectionStart) {\n return;\n }\n this._model.selectionEnd = undefined;\n\n // Ensure the line exists\n const line = this._bufferService.buffer.lines.get(this._model.selectionStart[1]);\n if (!line) {\n return;\n }\n\n // Return early if the click event is not in the buffer (eg. in scroll bar)\n if (line.length === this._model.selectionStart[0]) {\n return;\n }\n\n // If the mouse is over the second half of a wide character, adjust the\n // selection to cover the whole character\n if (line.hasWidth(this._model.selectionStart[0]) === 0) {\n this._model.selectionStart[0]++;\n }\n }\n\n /**\n * Performs a double click, selecting the current word.\n * @param event The mouse event.\n */\n private _handleDoubleClick(event: MouseEvent): void {\n if (this._selectWordAtCursor(event, true)) {\n this._activeSelectionMode = SelectionMode.WORD;\n }\n }\n\n /**\n * Performs a triple click, selecting the current line and activating line\n * select mode.\n * @param event The mouse event.\n */\n private _handleTripleClick(event: MouseEvent): void {\n const coords = this._getMouseBufferCoords(event);\n if (coords) {\n this._activeSelectionMode = SelectionMode.LINE;\n this._selectLineAt(coords[1]);\n }\n }\n\n /**\n * Returns whether the selection manager should operate in column select mode\n * @param event the mouse or keyboard event\n */\n public shouldColumnSelect(event: KeyboardEvent | MouseEvent): boolean {\n return event.altKey && !(Browser.isMac && this._optionsService.rawOptions.macOptionClickForcesSelection);\n }\n\n /**\n * Handles the mousemove event when the mouse button is down, recording the\n * end of the selection and refreshing the selection.\n * @param event The mousemove event.\n */\n private _handleMouseMove(event: MouseEvent): void {\n // If the mousemove listener is active it means that a selection is\n // currently being made, we should stop propagation to prevent mouse events\n // to be sent to the pty.\n event.stopImmediatePropagation();\n\n // Do nothing if there is no selection start, this can happen if the first\n // click in the terminal is an incremental click\n if (!this._model.selectionStart) {\n return;\n }\n\n // Record the previous position so we know whether to redraw the selection\n // at the end.\n const previousSelectionEnd = this._model.selectionEnd ? [this._model.selectionEnd[0], this._model.selectionEnd[1]] : null;\n\n // Set the initial selection end based on the mouse coordinates\n this._model.selectionEnd = this._getMouseBufferCoords(event);\n if (!this._model.selectionEnd) {\n this.refresh(true);\n return;\n }\n\n // Select the entire line if line select mode is active.\n if (this._activeSelectionMode === SelectionMode.LINE) {\n if (this._model.selectionEnd[1] < this._model.selectionStart[1]) {\n this._model.selectionEnd[0] = 0;\n } else {\n this._model.selectionEnd[0] = this._bufferService.cols;\n }\n } else if (this._activeSelectionMode === SelectionMode.WORD) {\n this._selectToWordAt(this._model.selectionEnd);\n }\n\n // Determine the amount of scrolling that will happen.\n this._dragScrollAmount = this._getMouseEventScrollAmount(event);\n\n // If the cursor was above or below the viewport, make sure it's at the\n // start or end of the viewport respectively. This should only happen when\n // NOT in column select mode.\n if (this._activeSelectionMode !== SelectionMode.COLUMN) {\n if (this._dragScrollAmount > 0) {\n this._model.selectionEnd[0] = this._bufferService.cols;\n } else if (this._dragScrollAmount < 0) {\n this._model.selectionEnd[0] = 0;\n }\n }\n\n // If the character is a wide character include the cell to the right in the\n // selection. Note that selections at the very end of the line will never\n // have a character.\n const buffer = this._bufferService.buffer;\n if (this._model.selectionEnd[1] < buffer.lines.length) {\n const line = buffer.lines.get(this._model.selectionEnd[1]);\n if (line && line.hasWidth(this._model.selectionEnd[0]) === 0) {\n if (this._model.selectionEnd[0] < this._bufferService.cols) {\n this._model.selectionEnd[0]++;\n }\n }\n }\n\n // Only draw here if the selection changes.\n if (!previousSelectionEnd ||\n previousSelectionEnd[0] !== this._model.selectionEnd[0] ||\n previousSelectionEnd[1] !== this._model.selectionEnd[1]) {\n this.refresh(true);\n }\n }\n\n /**\n * The callback that occurs every DRAG_SCROLL_INTERVAL ms that does the\n * scrolling of the viewport.\n */\n private _dragScroll(): void {\n if (!this._model.selectionEnd || !this._model.selectionStart) {\n return;\n }\n if (this._dragScrollAmount) {\n this._onRequestScrollLines.fire({ amount: this._dragScrollAmount, suppressScrollEvent: false });\n // Re-evaluate selection\n // If the cursor was above or below the viewport, make sure it's at the\n // start or end of the viewport respectively. This should only happen when\n // NOT in column select mode.\n const buffer = this._bufferService.buffer;\n if (this._dragScrollAmount > 0) {\n if (this._activeSelectionMode !== SelectionMode.COLUMN) {\n this._model.selectionEnd[0] = this._bufferService.cols;\n }\n this._model.selectionEnd[1] = Math.min(buffer.ydisp + this._bufferService.rows, buffer.lines.length - 1);\n } else {\n if (this._activeSelectionMode !== SelectionMode.COLUMN) {\n this._model.selectionEnd[0] = 0;\n }\n this._model.selectionEnd[1] = buffer.ydisp;\n }\n this.refresh();\n }\n }\n\n /**\n * Handles the mouseup event, removing the mousedown listeners.\n * @param event The mouseup event.\n */\n private _handleMouseUp(event: MouseEvent): void {\n const timeElapsed = event.timeStamp - this._mouseDownTimeStamp;\n\n this._removeMouseDownListeners();\n\n if (this.selectionText.length <= 1 && timeElapsed < ALT_CLICK_MOVE_CURSOR_TIME && event.altKey && this._optionsService.rawOptions.altClickMovesCursor) {\n if (this._bufferService.buffer.ybase === this._bufferService.buffer.ydisp) {\n const coordinates = this._mouseService.getCoords(\n event,\n this._element,\n this._bufferService.cols,\n this._bufferService.rows,\n false\n );\n if (coordinates && coordinates[0] !== undefined && coordinates[1] !== undefined) {\n const sequence = moveToCellSequence(coordinates[0] - 1, coordinates[1] - 1, this._bufferService, this._coreService.decPrivateModes.applicationCursorKeys);\n this._coreService.triggerDataEvent(sequence, true);\n }\n }\n } else {\n this._fireEventIfSelectionChanged();\n }\n }\n\n private _fireEventIfSelectionChanged(): void {\n const start = this._model.finalSelectionStart;\n const end = this._model.finalSelectionEnd;\n const hasSelection = !!start && !!end && (start[0] !== end[0] || start[1] !== end[1]);\n\n if (!hasSelection) {\n if (this._oldHasSelection) {\n this._fireOnSelectionChange(start, end, hasSelection);\n }\n return;\n }\n\n // Sanity check, these should not be undefined as there is a selection\n if (!start || !end) {\n return;\n }\n\n if (!this._oldSelectionStart || !this._oldSelectionEnd || (\n start[0] !== this._oldSelectionStart[0] || start[1] !== this._oldSelectionStart[1] ||\n end[0] !== this._oldSelectionEnd[0] || end[1] !== this._oldSelectionEnd[1])) {\n\n this._fireOnSelectionChange(start, end, hasSelection);\n }\n }\n\n private _fireOnSelectionChange(start: [number, number] | undefined, end: [number, number] | undefined, hasSelection: boolean): void {\n this._oldSelectionStart = start;\n this._oldSelectionEnd = end;\n this._oldHasSelection = hasSelection;\n this._onSelectionChange.fire();\n }\n\n private _handleBufferActivate(e: {activeBuffer: IBuffer, inactiveBuffer: IBuffer}): void {\n this.clearSelection();\n // Only adjust the selection on trim, shiftElements is rarely used (only in\n // reverseIndex) and delete in a splice is only ever used when the same\n // number of elements was just added. Given this is could actually be\n // beneficial to leave the selection as is for these cases.\n this._trimListener.dispose();\n this._trimListener = e.activeBuffer.lines.onTrim(amount => this._handleTrim(amount));\n }\n\n /**\n * Converts a viewport column (0 to cols - 1) to the character index on the\n * buffer line, the latter takes into account wide and null characters.\n * @param bufferLine The buffer line to use.\n * @param x The x index in the buffer line to convert.\n */\n private _convertViewportColToCharacterIndex(bufferLine: IBufferLine, x: number): number {\n let charIndex = x;\n for (let i = 0; x >= i; i++) {\n const length = bufferLine.loadCell(i, this._workCell).getChars().length;\n if (this._workCell.getWidth() === 0) {\n // Wide characters aren't included in the line string so decrement the\n // index so the index is back on the wide character.\n charIndex--;\n } else if (length > 1 && x !== i) {\n // Emojis take up multiple characters, so adjust accordingly. For these\n // we don't want ot include the character at the column as we're\n // returning the start index in the string, not the end index.\n charIndex += length - 1;\n }\n }\n return charIndex;\n }\n\n public setSelection(col: number, row: number, length: number): void {\n this._model.clearSelection();\n this._removeMouseDownListeners();\n this._model.selectionStart = [col, row];\n this._model.selectionStartLength = length;\n this.refresh();\n this._fireEventIfSelectionChanged();\n }\n\n public rightClickSelect(ev: MouseEvent): void {\n if (!this._isClickInSelection(ev)) {\n if (this._selectWordAtCursor(ev, false)) {\n this.refresh(true);\n }\n this._fireEventIfSelectionChanged();\n }\n }\n\n /**\n * Gets positional information for the word at the coordinated specified.\n * @param coords The coordinates to get the word at.\n */\n private _getWordAt(coords: [number, number], allowWhitespaceOnlySelection: boolean, followWrappedLinesAbove: boolean = true, followWrappedLinesBelow: boolean = true): IWordPosition | undefined {\n // Ensure coords are within viewport (eg. not within scroll bar)\n if (coords[0] >= this._bufferService.cols) {\n return undefined;\n }\n\n const buffer = this._bufferService.buffer;\n const bufferLine = buffer.lines.get(coords[1]);\n if (!bufferLine) {\n return undefined;\n }\n\n const line = buffer.translateBufferLineToString(coords[1], false);\n\n // Get actual index, taking into consideration wide characters\n let startIndex = this._convertViewportColToCharacterIndex(bufferLine, coords[0]);\n let endIndex = startIndex;\n\n // Record offset to be used later\n const charOffset = coords[0] - startIndex;\n let leftWideCharCount = 0;\n let rightWideCharCount = 0;\n let leftLongCharOffset = 0;\n let rightLongCharOffset = 0;\n\n if (line.charAt(startIndex) === ' ') {\n // Expand until non-whitespace is hit\n while (startIndex > 0 && line.charAt(startIndex - 1) === ' ') {\n startIndex--;\n }\n while (endIndex < line.length && line.charAt(endIndex + 1) === ' ') {\n endIndex++;\n }\n } else {\n // Expand until whitespace is hit. This algorithm works by scanning left\n // and right from the starting position, keeping both the index format\n // (line) and the column format (bufferLine) in sync. When a wide\n // character is hit, it is recorded and the column index is adjusted.\n let startCol = coords[0];\n let endCol = coords[0];\n\n // Consider the initial position, skip it and increment the wide char\n // variable\n if (bufferLine.getWidth(startCol) === 0) {\n leftWideCharCount++;\n startCol--;\n }\n if (bufferLine.getWidth(endCol) === 2) {\n rightWideCharCount++;\n endCol++;\n }\n\n // Adjust the end index for characters whose length are > 1 (emojis)\n const length = bufferLine.getString(endCol).length;\n if (length > 1) {\n rightLongCharOffset += length - 1;\n endIndex += length - 1;\n }\n\n // Expand the string in both directions until a space is hit\n while (startCol > 0 && startIndex > 0 && !this._isCharWordSeparator(bufferLine.loadCell(startCol - 1, this._workCell))) {\n bufferLine.loadCell(startCol - 1, this._workCell);\n const length = this._workCell.getChars().length;\n if (this._workCell.getWidth() === 0) {\n // If the next character is a wide char, record it and skip the column\n leftWideCharCount++;\n startCol--;\n } else if (length > 1) {\n // If the next character's string is longer than 1 char (eg. emoji),\n // adjust the index\n leftLongCharOffset += length - 1;\n startIndex -= length - 1;\n }\n startIndex--;\n startCol--;\n }\n while (endCol < bufferLine.length && endIndex + 1 < line.length && !this._isCharWordSeparator(bufferLine.loadCell(endCol + 1, this._workCell))) {\n bufferLine.loadCell(endCol + 1, this._workCell);\n const length = this._workCell.getChars().length;\n if (this._workCell.getWidth() === 2) {\n // If the next character is a wide char, record it and skip the column\n rightWideCharCount++;\n endCol++;\n } else if (length > 1) {\n // If the next character's string is longer than 1 char (eg. emoji),\n // adjust the index\n rightLongCharOffset += length - 1;\n endIndex += length - 1;\n }\n endIndex++;\n endCol++;\n }\n }\n\n // Incremenet the end index so it is at the start of the next character\n endIndex++;\n\n // Calculate the start _column_, converting the the string indexes back to\n // column coordinates.\n let start =\n startIndex // The index of the selection's start char in the line string\n + charOffset // The difference between the initial char's column and index\n - leftWideCharCount // The number of wide chars left of the initial char\n + leftLongCharOffset; // The number of additional chars left of the initial char added by columns with strings longer than 1 (emojis)\n\n // Calculate the length in _columns_, converting the the string indexes back\n // to column coordinates.\n let length = Math.min(this._bufferService.cols, // Disallow lengths larger than the terminal cols\n endIndex // The index of the selection's end char in the line string\n - startIndex // The index of the selection's start char in the line string\n + leftWideCharCount // The number of wide chars left of the initial char\n + rightWideCharCount // The number of wide chars right of the initial char (inclusive)\n - leftLongCharOffset // The number of additional chars left of the initial char added by columns with strings longer than 1 (emojis)\n - rightLongCharOffset); // The number of additional chars right of the initial char (inclusive) added by columns with strings longer than 1 (emojis)\n\n if (!allowWhitespaceOnlySelection && line.slice(startIndex, endIndex).trim() === '') {\n return undefined;\n }\n\n // Recurse upwards if the line is wrapped and the word wraps to the above line\n if (followWrappedLinesAbove) {\n if (start === 0 && bufferLine.getCodePoint(0) !== 32 /* ' ' */) {\n const previousBufferLine = buffer.lines.get(coords[1] - 1);\n if (previousBufferLine && bufferLine.isWrapped && previousBufferLine.getCodePoint(this._bufferService.cols - 1) !== 32 /* ' ' */) {\n const previousLineWordPosition = this._getWordAt([this._bufferService.cols - 1, coords[1] - 1], false, true, false);\n if (previousLineWordPosition) {\n const offset = this._bufferService.cols - previousLineWordPosition.start;\n start -= offset;\n length += offset;\n }\n }\n }\n }\n\n // Recurse downwards if the line is wrapped and the word wraps to the next line\n if (followWrappedLinesBelow) {\n if (start + length === this._bufferService.cols && bufferLine.getCodePoint(this._bufferService.cols - 1) !== 32 /* ' ' */) {\n const nextBufferLine = buffer.lines.get(coords[1] + 1);\n if (nextBufferLine?.isWrapped && nextBufferLine.getCodePoint(0) !== 32 /* ' ' */) {\n const nextLineWordPosition = this._getWordAt([0, coords[1] + 1], false, false, true);\n if (nextLineWordPosition) {\n length += nextLineWordPosition.length;\n }\n }\n }\n }\n\n return { start, length };\n }\n\n /**\n * Selects the word at the coordinates specified.\n * @param coords The coordinates to get the word at.\n * @param allowWhitespaceOnlySelection If whitespace should be selected\n */\n protected _selectWordAt(coords: [number, number], allowWhitespaceOnlySelection: boolean): void {\n const wordPosition = this._getWordAt(coords, allowWhitespaceOnlySelection);\n if (wordPosition) {\n // Adjust negative start value\n while (wordPosition.start < 0) {\n wordPosition.start += this._bufferService.cols;\n coords[1]--;\n }\n this._model.selectionStart = [wordPosition.start, coords[1]];\n this._model.selectionStartLength = wordPosition.length;\n }\n }\n\n /**\n * Sets the selection end to the word at the coordinated specified.\n * @param coords The coordinates to get the word at.\n */\n private _selectToWordAt(coords: [number, number]): void {\n const wordPosition = this._getWordAt(coords, true);\n if (wordPosition) {\n let endRow = coords[1];\n\n // Adjust negative start value\n while (wordPosition.start < 0) {\n wordPosition.start += this._bufferService.cols;\n endRow--;\n }\n\n // Adjust wrapped length value, this only needs to happen when values are reversed as in that\n // case we're interested in the start of the word, not the end\n if (!this._model.areSelectionValuesReversed()) {\n while (wordPosition.start + wordPosition.length > this._bufferService.cols) {\n wordPosition.length -= this._bufferService.cols;\n endRow++;\n }\n }\n\n this._model.selectionEnd = [this._model.areSelectionValuesReversed() ? wordPosition.start : wordPosition.start + wordPosition.length, endRow];\n }\n }\n\n /**\n * Gets whether the character is considered a word separator by the select\n * word logic.\n * @param cell The cell to check.\n */\n private _isCharWordSeparator(cell: CellData): boolean {\n // Zero width characters are never separators as they are always to the\n // right of wide characters\n if (cell.getWidth() === 0) {\n return false;\n }\n return this._optionsService.rawOptions.wordSeparator.indexOf(cell.getChars()) >= 0;\n }\n\n /**\n * Selects the line specified.\n * @param line The line index.\n */\n protected _selectLineAt(line: number): void {\n const wrappedRange = this._bufferService.buffer.getWrappedRangeForLine(line);\n const range: IBufferRange = {\n start: { x: 0, y: wrappedRange.first },\n end: { x: this._bufferService.cols - 1, y: wrappedRange.last }\n };\n this._model.selectionStart = [0, wrappedRange.first];\n this._model.selectionEnd = undefined;\n this._model.selectionStartLength = getRangeLength(range, this._bufferService.cols);\n }\n}\n", "/**\n * Copyright (c) 2022 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nexport class TwoKeyMap {\n private _data: { [bg: string | number]: { [fg: string | number]: TValue | undefined } | undefined } = {};\n\n public set(first: TFirst, second: TSecond, value: TValue): void {\n if (!this._data[first]) {\n this._data[first] = {};\n }\n this._data[first as string | number]![second] = value;\n }\n\n public get(first: TFirst, second: TSecond): TValue | undefined {\n return this._data[first as string | number] ? this._data[first as string | number]![second] : undefined;\n }\n\n public clear(): void {\n this._data = {};\n }\n}\n\nexport class FourKeyMap {\n private _data: TwoKeyMap> = new TwoKeyMap();\n\n public set(first: TFirst, second: TSecond, third: TThird, fourth: TFourth, value: TValue): void {\n if (!this._data.get(first, second)) {\n this._data.set(first, second, new TwoKeyMap());\n }\n this._data.get(first, second)!.set(third, fourth, value);\n }\n\n public get(first: TFirst, second: TSecond, third: TThird, fourth: TFourth): TValue | undefined {\n return this._data.get(first, second)?.get(third, fourth);\n }\n\n public clear(): void {\n this._data.clear();\n }\n}\n", "/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IColorContrastCache } from 'browser/Types';\nimport { IColor } from 'common/Types';\nimport { TwoKeyMap } from 'common/MultiKeyMap';\n\nexport class ColorContrastCache implements IColorContrastCache {\n private _color: TwoKeyMap = new TwoKeyMap();\n private _css: TwoKeyMap = new TwoKeyMap();\n\n public setCss(bg: number, fg: number, value: string | null): void {\n this._css.set(bg, fg, value);\n }\n\n public getCss(bg: number, fg: number): string | null | undefined {\n return this._css.get(bg, fg);\n }\n\n public setColor(bg: number, fg: number, value: IColor | null): void {\n this._color.set(bg, fg, value);\n }\n\n public getColor(bg: number, fg: number): IColor | null | undefined {\n return this._color.get(bg, fg);\n }\n\n public clear(): void {\n this._color.clear();\n this._css.clear();\n }\n}\n", "/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { CharData, IColor, ICoreTerminal, ITerminalOptions } from 'common/Types';\nimport { IBuffer } from 'common/buffer/Types';\nimport { IDisposable, Terminal as ITerminalApi } from '@xterm/xterm';\nimport { channels, css } from 'common/Color';\nimport type { Event } from 'vs/base/common/event';\n\n/**\n * A portion of the public API that are implemented identially internally and simply passed through.\n */\ntype InternalPassthroughApis = Omit;\n\nexport interface ITerminal extends InternalPassthroughApis, ICoreTerminal {\n screenElement: HTMLElement | undefined;\n browser: IBrowser;\n buffer: IBuffer;\n linkifier: ILinkifier2 | undefined;\n options: Required;\n\n onBlur: Event;\n onFocus: Event;\n onA11yChar: Event;\n onA11yTab: Event;\n onWillOpen: Event;\n\n cancel(ev: MouseEvent | WheelEvent | KeyboardEvent | InputEvent, force?: boolean): boolean | void;\n}\n\nexport type CustomKeyEventHandler = (event: KeyboardEvent) => boolean;\nexport type CustomWheelEventHandler = (event: WheelEvent) => boolean;\n\nexport type LineData = CharData[];\n\nexport interface ICompositionHelper {\n readonly isComposing: boolean;\n compositionstart(): void;\n compositionupdate(ev: CompositionEvent): void;\n compositionend(): void;\n updateCompositionElements(dontRecurse?: boolean): void;\n keydown(ev: KeyboardEvent): boolean;\n}\n\nexport interface IBrowser {\n isNode: boolean;\n userAgent: string;\n platform: string;\n isFirefox: boolean;\n isMac: boolean;\n isIpad: boolean;\n isIphone: boolean;\n isWindows: boolean;\n}\n\nexport interface IColorSet {\n foreground: IColor;\n background: IColor;\n cursor: IColor;\n cursorAccent: IColor;\n selectionForeground: IColor | undefined;\n selectionBackgroundTransparent: IColor;\n /** The selection blended on top of background. */\n selectionBackgroundOpaque: IColor;\n selectionInactiveBackgroundTransparent: IColor;\n selectionInactiveBackgroundOpaque: IColor;\n scrollbarSliderBackground: IColor;\n scrollbarSliderHoverBackground: IColor;\n scrollbarSliderActiveBackground: IColor;\n overviewRulerBorder: IColor;\n ansi: IColor[];\n /** Maps original colors to colors that respect minimum contrast ratio. */\n contrastCache: IColorContrastCache;\n /** Maps original colors to colors that respect _half_ of the minimum contrast ratio. */\n halfContrastCache: IColorContrastCache;\n}\n\nexport type ReadonlyColorSet = Readonly> & { ansi: Readonly['ansi']> };\n\nexport interface IColorContrastCache {\n clear(): void;\n setCss(bg: number, fg: number, value: string | null): void;\n getCss(bg: number, fg: number): string | null | undefined;\n setColor(bg: number, fg: number, value: IColor | null): void;\n getColor(bg: number, fg: number): IColor | null | undefined;\n}\n\nexport interface IPartialColorSet {\n foreground: IColor;\n background: IColor;\n cursor?: IColor;\n cursorAccent?: IColor;\n selectionBackground?: IColor;\n ansi: IColor[];\n}\n\nexport interface IViewport extends IDisposable {\n scrollBarWidth: number;\n readonly onRequestScrollLines: Event<{ amount: number, suppressScrollEvent: boolean }>;\n syncScrollArea(immediate?: boolean, force?: boolean): void;\n getLinesScrolled(ev: WheelEvent): number;\n getBufferElements(startLine: number, endLine?: number): { bufferElements: HTMLElement[], cursorElement?: HTMLElement };\n handleWheel(ev: WheelEvent): boolean;\n handleTouchStart(ev: TouchEvent): void;\n handleTouchMove(ev: TouchEvent): boolean;\n scrollLines(disp: number): void; // todo api name?\n reset(): void;\n}\n\nexport interface ILinkifierEvent {\n x1: number;\n y1: number;\n x2: number;\n y2: number;\n cols: number;\n fg: number | undefined;\n}\n\ninterface ILinkState {\n decorations: ILinkDecorations;\n isHovered: boolean;\n}\nexport interface ILinkWithState {\n link: ILink;\n state?: ILinkState;\n}\n\nexport interface ILinkifier2 extends IDisposable {\n onShowLinkUnderline: Event;\n onHideLinkUnderline: Event;\n readonly currentLink: ILinkWithState | undefined;\n}\n\nexport interface ILink {\n range: IBufferRange;\n text: string;\n decorations?: ILinkDecorations;\n activate(event: MouseEvent, text: string): void;\n hover?(event: MouseEvent, text: string): void;\n leave?(event: MouseEvent, text: string): void;\n dispose?(): void;\n}\n\nexport interface ILinkDecorations {\n pointerCursor: boolean;\n underline: boolean;\n}\n\nexport interface IBufferRange {\n start: IBufferCellPosition;\n end: IBufferCellPosition;\n}\n\nexport interface IBufferCellPosition {\n x: number;\n y: number;\n}\n\nexport type CharacterJoinerHandler = (text: string) => [number, number][];\n\nexport interface ICharacterJoiner {\n id: number;\n handler: CharacterJoinerHandler;\n}\n\nexport interface IRenderDebouncer extends IDisposable {\n refresh(rowStart: number | undefined, rowEnd: number | undefined, rowCount: number): void;\n}\n\nexport interface IRenderDebouncerWithCallback extends IRenderDebouncer {\n addRefreshCallback(callback: FrameRequestCallback): number;\n}\n\nexport interface IBufferElementProvider {\n provideBufferElements(): DocumentFragment | HTMLElement;\n}\n\n// An IIFE to generate DEFAULT_ANSI_COLORS.\nexport const DEFAULT_ANSI_COLORS = Object.freeze((() => {\n const colors = [\n // dark:\n css.toColor('#2e3436'),\n css.toColor('#cc0000'),\n css.toColor('#4e9a06'),\n css.toColor('#c4a000'),\n css.toColor('#3465a4'),\n css.toColor('#75507b'),\n css.toColor('#06989a'),\n css.toColor('#d3d7cf'),\n // bright:\n css.toColor('#555753'),\n css.toColor('#ef2929'),\n css.toColor('#8ae234'),\n css.toColor('#fce94f'),\n css.toColor('#729fcf'),\n css.toColor('#ad7fa8'),\n css.toColor('#34e2e2'),\n css.toColor('#eeeeec')\n ];\n\n // Fill in the remaining 240 ANSI colors.\n // Generate colors (16-231)\n const v = [0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff];\n for (let i = 0; i < 216; i++) {\n const r = v[(i / 36) % 6 | 0];\n const g = v[(i / 6) % 6 | 0];\n const b = v[i % 6];\n colors.push({\n css: channels.toCss(r, g, b),\n rgba: channels.toRgba(r, g, b)\n });\n }\n\n // Generate greys (232-255)\n for (let i = 0; i < 24; i++) {\n const c = 8 + i * 10;\n colors.push({\n css: channels.toCss(c, c, c),\n rgba: channels.toRgba(c, c, c)\n });\n }\n\n return colors;\n})());\n", "/**\n * Copyright (c) 2022 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { ColorContrastCache } from 'browser/ColorContrastCache';\nimport { IThemeService } from 'browser/services/Services';\nimport { DEFAULT_ANSI_COLORS, IColorContrastCache, IColorSet, ReadonlyColorSet } from 'browser/Types';\nimport { color, css, NULL_COLOR } from 'common/Color';\nimport { Disposable } from 'vs/base/common/lifecycle';\nimport { IOptionsService, ITheme } from 'common/services/Services';\nimport { AllColorIndex, IColor, SpecialColorIndex } from 'common/Types';\nimport { Emitter } from 'vs/base/common/event';\n\ninterface IRestoreColorSet {\n foreground: IColor;\n background: IColor;\n cursor: IColor;\n ansi: IColor[];\n}\n\n\nconst DEFAULT_FOREGROUND = css.toColor('#ffffff');\nconst DEFAULT_BACKGROUND = css.toColor('#000000');\nconst DEFAULT_CURSOR = css.toColor('#ffffff');\nconst DEFAULT_CURSOR_ACCENT = DEFAULT_BACKGROUND;\nconst DEFAULT_SELECTION = {\n css: 'rgba(255, 255, 255, 0.3)',\n rgba: 0xFFFFFF4D\n};\nconst DEFAULT_OVERVIEW_RULER_BORDER = DEFAULT_FOREGROUND;\n\nexport class ThemeService extends Disposable implements IThemeService {\n public serviceBrand: undefined;\n\n private _colors: IColorSet;\n private _contrastCache: IColorContrastCache = new ColorContrastCache();\n private _halfContrastCache: IColorContrastCache = new ColorContrastCache();\n private _restoreColors!: IRestoreColorSet;\n\n public get colors(): ReadonlyColorSet { return this._colors; }\n\n private readonly _onChangeColors = this._register(new Emitter());\n public readonly onChangeColors = this._onChangeColors.event;\n\n constructor(\n @IOptionsService private readonly _optionsService: IOptionsService\n ) {\n super();\n\n this._colors = {\n foreground: DEFAULT_FOREGROUND,\n background: DEFAULT_BACKGROUND,\n cursor: DEFAULT_CURSOR,\n cursorAccent: DEFAULT_CURSOR_ACCENT,\n selectionForeground: undefined,\n selectionBackgroundTransparent: DEFAULT_SELECTION,\n selectionBackgroundOpaque: color.blend(DEFAULT_BACKGROUND, DEFAULT_SELECTION),\n selectionInactiveBackgroundTransparent: DEFAULT_SELECTION,\n selectionInactiveBackgroundOpaque: color.blend(DEFAULT_BACKGROUND, DEFAULT_SELECTION),\n scrollbarSliderBackground: color.opacity(DEFAULT_FOREGROUND, 0.2),\n scrollbarSliderHoverBackground: color.opacity(DEFAULT_FOREGROUND, 0.4),\n scrollbarSliderActiveBackground: color.opacity(DEFAULT_FOREGROUND, 0.5),\n overviewRulerBorder: DEFAULT_FOREGROUND,\n ansi: DEFAULT_ANSI_COLORS.slice(),\n contrastCache: this._contrastCache,\n halfContrastCache: this._halfContrastCache\n };\n this._updateRestoreColors();\n this._setTheme(this._optionsService.rawOptions.theme);\n\n this._register(this._optionsService.onSpecificOptionChange('minimumContrastRatio', () => this._contrastCache.clear()));\n this._register(this._optionsService.onSpecificOptionChange('theme', () => this._setTheme(this._optionsService.rawOptions.theme)));\n }\n\n /**\n * Sets the terminal's theme.\n * @param theme The theme to use. If a partial theme is provided then default\n * colors will be used where colors are not defined.\n */\n private _setTheme(theme: ITheme = {}): void {\n const colors = this._colors;\n colors.foreground = parseColor(theme.foreground, DEFAULT_FOREGROUND);\n colors.background = parseColor(theme.background, DEFAULT_BACKGROUND);\n colors.cursor = color.blend(colors.background, parseColor(theme.cursor, DEFAULT_CURSOR));\n colors.cursorAccent = color.blend(colors.background, parseColor(theme.cursorAccent, DEFAULT_CURSOR_ACCENT));\n colors.selectionBackgroundTransparent = parseColor(theme.selectionBackground, DEFAULT_SELECTION);\n colors.selectionBackgroundOpaque = color.blend(colors.background, colors.selectionBackgroundTransparent);\n colors.selectionInactiveBackgroundTransparent = parseColor(theme.selectionInactiveBackground, colors.selectionBackgroundTransparent);\n colors.selectionInactiveBackgroundOpaque = color.blend(colors.background, colors.selectionInactiveBackgroundTransparent);\n colors.selectionForeground = theme.selectionForeground ? parseColor(theme.selectionForeground, NULL_COLOR) : undefined;\n if (colors.selectionForeground === NULL_COLOR) {\n colors.selectionForeground = undefined;\n }\n\n /**\n * If selection color is opaque, blend it with background with 0.3 opacity\n * Issue #2737\n */\n if (color.isOpaque(colors.selectionBackgroundTransparent)) {\n const opacity = 0.3;\n colors.selectionBackgroundTransparent = color.opacity(colors.selectionBackgroundTransparent, opacity);\n }\n if (color.isOpaque(colors.selectionInactiveBackgroundTransparent)) {\n const opacity = 0.3;\n colors.selectionInactiveBackgroundTransparent = color.opacity(colors.selectionInactiveBackgroundTransparent, opacity);\n }\n colors.scrollbarSliderBackground = parseColor(theme.scrollbarSliderBackground, color.opacity(colors.foreground, 0.2));\n colors.scrollbarSliderHoverBackground = parseColor(theme.scrollbarSliderHoverBackground, color.opacity(colors.foreground, 0.4));\n colors.scrollbarSliderActiveBackground = parseColor(theme.scrollbarSliderActiveBackground, color.opacity(colors.foreground, 0.5));\n colors.overviewRulerBorder = parseColor(theme.overviewRulerBorder, DEFAULT_OVERVIEW_RULER_BORDER);\n colors.ansi = DEFAULT_ANSI_COLORS.slice();\n colors.ansi[0] = parseColor(theme.black, DEFAULT_ANSI_COLORS[0]);\n colors.ansi[1] = parseColor(theme.red, DEFAULT_ANSI_COLORS[1]);\n colors.ansi[2] = parseColor(theme.green, DEFAULT_ANSI_COLORS[2]);\n colors.ansi[3] = parseColor(theme.yellow, DEFAULT_ANSI_COLORS[3]);\n colors.ansi[4] = parseColor(theme.blue, DEFAULT_ANSI_COLORS[4]);\n colors.ansi[5] = parseColor(theme.magenta, DEFAULT_ANSI_COLORS[5]);\n colors.ansi[6] = parseColor(theme.cyan, DEFAULT_ANSI_COLORS[6]);\n colors.ansi[7] = parseColor(theme.white, DEFAULT_ANSI_COLORS[7]);\n colors.ansi[8] = parseColor(theme.brightBlack, DEFAULT_ANSI_COLORS[8]);\n colors.ansi[9] = parseColor(theme.brightRed, DEFAULT_ANSI_COLORS[9]);\n colors.ansi[10] = parseColor(theme.brightGreen, DEFAULT_ANSI_COLORS[10]);\n colors.ansi[11] = parseColor(theme.brightYellow, DEFAULT_ANSI_COLORS[11]);\n colors.ansi[12] = parseColor(theme.brightBlue, DEFAULT_ANSI_COLORS[12]);\n colors.ansi[13] = parseColor(theme.brightMagenta, DEFAULT_ANSI_COLORS[13]);\n colors.ansi[14] = parseColor(theme.brightCyan, DEFAULT_ANSI_COLORS[14]);\n colors.ansi[15] = parseColor(theme.brightWhite, DEFAULT_ANSI_COLORS[15]);\n if (theme.extendedAnsi) {\n const colorCount = Math.min(colors.ansi.length - 16, theme.extendedAnsi.length);\n for (let i = 0; i < colorCount; i++) {\n colors.ansi[i + 16] = parseColor(theme.extendedAnsi[i], DEFAULT_ANSI_COLORS[i + 16]);\n }\n }\n // Clear our the cache\n this._contrastCache.clear();\n this._halfContrastCache.clear();\n this._updateRestoreColors();\n this._onChangeColors.fire(this.colors);\n }\n\n public restoreColor(slot?: AllColorIndex): void {\n this._restoreColor(slot);\n this._onChangeColors.fire(this.colors);\n }\n\n private _restoreColor(slot: AllColorIndex | undefined): void {\n // unset slot restores all ansi colors\n if (slot === undefined) {\n for (let i = 0; i < this._restoreColors.ansi.length; ++i) {\n this._colors.ansi[i] = this._restoreColors.ansi[i];\n }\n return;\n }\n switch (slot) {\n case SpecialColorIndex.FOREGROUND:\n this._colors.foreground = this._restoreColors.foreground;\n break;\n case SpecialColorIndex.BACKGROUND:\n this._colors.background = this._restoreColors.background;\n break;\n case SpecialColorIndex.CURSOR:\n this._colors.cursor = this._restoreColors.cursor;\n break;\n default:\n this._colors.ansi[slot] = this._restoreColors.ansi[slot];\n }\n }\n\n public modifyColors(callback: (colors: IColorSet) => void): void {\n callback(this._colors);\n // Assume the change happened\n this._onChangeColors.fire(this.colors);\n }\n\n private _updateRestoreColors(): void {\n this._restoreColors = {\n foreground: this._colors.foreground,\n background: this._colors.background,\n cursor: this._colors.cursor,\n ansi: this._colors.ansi.slice()\n };\n }\n}\n\nfunction parseColor(\n cssString: string | undefined,\n fallback: IColor\n): IColor {\n if (cssString !== undefined) {\n try {\n return css.toColor(cssString);\n } catch {\n // no-op\n }\n }\n return fallback;\n}\n", "/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n *\n * This was heavily inspired from microsoft/vscode's dependency injection system (MIT).\n */\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\nimport { IInstantiationService, IServiceIdentifier } from 'common/services/Services';\nimport { getServiceDependencies } from 'common/services/ServiceRegistry';\n\nexport class ServiceCollection {\n\n private _entries = new Map, any>();\n\n constructor(...entries: [IServiceIdentifier, any][]) {\n for (const [id, service] of entries) {\n this.set(id, service);\n }\n }\n\n public set(id: IServiceIdentifier, instance: T): T {\n const result = this._entries.get(id);\n this._entries.set(id, instance);\n return result;\n }\n\n public forEach(callback: (id: IServiceIdentifier, instance: any) => any): void {\n for (const [key, value] of this._entries.entries()) {\n callback(key, value);\n }\n }\n\n public has(id: IServiceIdentifier): boolean {\n return this._entries.has(id);\n }\n\n public get(id: IServiceIdentifier): T | undefined {\n return this._entries.get(id);\n }\n}\n\nexport class InstantiationService implements IInstantiationService {\n public serviceBrand: undefined;\n\n private readonly _services: ServiceCollection = new ServiceCollection();\n\n constructor() {\n this._services.set(IInstantiationService, this);\n }\n\n public setService(id: IServiceIdentifier, instance: T): void {\n this._services.set(id, instance);\n }\n\n public getService(id: IServiceIdentifier): T | undefined {\n return this._services.get(id);\n }\n\n public createInstance(ctor: any, ...args: any[]): T {\n const serviceDependencies = getServiceDependencies(ctor).sort((a, b) => a.index - b.index);\n\n const serviceArgs: any[] = [];\n for (const dependency of serviceDependencies) {\n const service = this._services.get(dependency.id);\n if (!service) {\n throw new Error(`[createInstance] ${ctor.name} depends on UNKNOWN service ${dependency.id._id}.`);\n }\n serviceArgs.push(service);\n }\n\n const firstServiceArgPos = serviceDependencies.length > 0 ? serviceDependencies[0].index : args.length;\n\n // check for argument mismatches, adjust static args if needed\n if (args.length !== firstServiceArgPos) {\n throw new Error(`[createInstance] First service dependency of ${ctor.name} at position ${firstServiceArgPos + 1} conflicts with ${args.length} static arguments`);\n }\n\n // now create the instance\n return new ctor(...[...args, ...serviceArgs]);\n }\n}\n", "/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { Disposable } from 'vs/base/common/lifecycle';\nimport { ILogService, IOptionsService, LogLevelEnum } from 'common/services/Services';\n\ntype LogType = (message?: any, ...optionalParams: any[]) => void;\n\ninterface IConsole {\n log: LogType;\n error: LogType;\n info: LogType;\n trace: LogType;\n warn: LogType;\n}\n\n// console is available on both node.js and browser contexts but the common\n// module doesn't depend on them so we need to explicitly declare it.\ndeclare const console: IConsole;\n\nconst optionsKeyToLogLevel: { [key: string]: LogLevelEnum } = {\n trace: LogLevelEnum.TRACE,\n debug: LogLevelEnum.DEBUG,\n info: LogLevelEnum.INFO,\n warn: LogLevelEnum.WARN,\n error: LogLevelEnum.ERROR,\n off: LogLevelEnum.OFF\n};\n\nconst LOG_PREFIX = 'xterm.js: ';\n\nexport class LogService extends Disposable implements ILogService {\n public serviceBrand: any;\n\n private _logLevel: LogLevelEnum = LogLevelEnum.OFF;\n public get logLevel(): LogLevelEnum { return this._logLevel; }\n\n constructor(\n @IOptionsService private readonly _optionsService: IOptionsService\n ) {\n super();\n this._updateLogLevel();\n this._register(this._optionsService.onSpecificOptionChange('logLevel', () => this._updateLogLevel()));\n\n // For trace logging, assume the latest created log service is valid\n traceLogger = this;\n }\n\n private _updateLogLevel(): void {\n this._logLevel = optionsKeyToLogLevel[this._optionsService.rawOptions.logLevel];\n }\n\n private _evalLazyOptionalParams(optionalParams: any[]): void {\n for (let i = 0; i < optionalParams.length; i++) {\n if (typeof optionalParams[i] === 'function') {\n optionalParams[i] = optionalParams[i]();\n }\n }\n }\n\n private _log(type: LogType, message: string, optionalParams: any[]): void {\n this._evalLazyOptionalParams(optionalParams);\n type.call(console, (this._optionsService.options.logger ? '' : LOG_PREFIX) + message, ...optionalParams);\n }\n\n public trace(message: string, ...optionalParams: any[]): void {\n if (this._logLevel <= LogLevelEnum.TRACE) {\n this._log(this._optionsService.options.logger?.trace.bind(this._optionsService.options.logger) ?? console.log, message, optionalParams);\n }\n }\n\n public debug(message: string, ...optionalParams: any[]): void {\n if (this._logLevel <= LogLevelEnum.DEBUG) {\n this._log(this._optionsService.options.logger?.debug.bind(this._optionsService.options.logger) ?? console.log, message, optionalParams);\n }\n }\n\n public info(message: string, ...optionalParams: any[]): void {\n if (this._logLevel <= LogLevelEnum.INFO) {\n this._log(this._optionsService.options.logger?.info.bind(this._optionsService.options.logger) ?? console.info, message, optionalParams);\n }\n }\n\n public warn(message: string, ...optionalParams: any[]): void {\n if (this._logLevel <= LogLevelEnum.WARN) {\n this._log(this._optionsService.options.logger?.warn.bind(this._optionsService.options.logger) ?? console.warn, message, optionalParams);\n }\n }\n\n public error(message: string, ...optionalParams: any[]): void {\n if (this._logLevel <= LogLevelEnum.ERROR) {\n this._log(this._optionsService.options.logger?.error.bind(this._optionsService.options.logger) ?? console.error, message, optionalParams);\n }\n }\n}\n\nlet traceLogger: ILogService;\nexport function setTraceLogger(logger: ILogService): void {\n traceLogger = logger;\n}\n\n/**\n * A decorator that can be used to automatically log trace calls to the decorated function.\n */\nexport function traceCall(_target: any, key: string, descriptor: any): any {\n if (typeof descriptor.value !== 'function') {\n throw new Error('not supported');\n }\n const fnKey = 'value';\n const fn = descriptor.value;\n descriptor[fnKey] = function (...args: any[]) {\n // Early exit\n if (traceLogger.logLevel !== LogLevelEnum.TRACE) {\n return fn.apply(this, args);\n }\n\n traceLogger.trace(`GlyphRenderer#${fn.name}(${args.map(e => JSON.stringify(e)).join(', ')})`);\n const result = fn.apply(this, args);\n traceLogger.trace(`GlyphRenderer#${fn.name} return`, result);\n return result;\n };\n}\n", "/**\n * Copyright (c) 2016 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { ICircularList } from 'common/Types';\nimport { Disposable } from 'vs/base/common/lifecycle';\nimport { Emitter } from 'vs/base/common/event';\n\nexport interface IInsertEvent {\n index: number;\n amount: number;\n}\n\nexport interface IDeleteEvent {\n index: number;\n amount: number;\n}\n\n/**\n * Represents a circular list; a list with a maximum size that wraps around when push is called,\n * overriding values at the start of the list.\n */\nexport class CircularList extends Disposable implements ICircularList {\n protected _array: (T | undefined)[];\n private _startIndex: number;\n private _length: number;\n\n public readonly onDeleteEmitter = this._register(new Emitter());\n public readonly onDelete = this.onDeleteEmitter.event;\n public readonly onInsertEmitter = this._register(new Emitter());\n public readonly onInsert = this.onInsertEmitter.event;\n public readonly onTrimEmitter = this._register(new Emitter());\n public readonly onTrim = this.onTrimEmitter.event;\n\n constructor(\n private _maxLength: number\n ) {\n super();\n this._array = new Array(this._maxLength);\n this._startIndex = 0;\n this._length = 0;\n }\n\n public get maxLength(): number {\n return this._maxLength;\n }\n\n public set maxLength(newMaxLength: number) {\n // There was no change in maxLength, return early.\n if (this._maxLength === newMaxLength) {\n return;\n }\n\n // Reconstruct array, starting at index 0. Only transfer values from the\n // indexes 0 to length.\n const newArray = new Array(newMaxLength);\n for (let i = 0; i < Math.min(newMaxLength, this.length); i++) {\n newArray[i] = this._array[this._getCyclicIndex(i)];\n }\n this._array = newArray;\n this._maxLength = newMaxLength;\n this._startIndex = 0;\n }\n\n public get length(): number {\n return this._length;\n }\n\n public set length(newLength: number) {\n if (newLength > this._length) {\n for (let i = this._length; i < newLength; i++) {\n this._array[i] = undefined;\n }\n }\n this._length = newLength;\n }\n\n /**\n * Gets the value at an index.\n *\n * Note that for performance reasons there is no bounds checking here, the index reference is\n * circular so this should always return a value and never throw.\n * @param index The index of the value to get.\n * @returns The value corresponding to the index.\n */\n public get(index: number): T | undefined {\n return this._array[this._getCyclicIndex(index)];\n }\n\n /**\n * Sets the value at an index.\n *\n * Note that for performance reasons there is no bounds checking here, the index reference is\n * circular so this should always return a value and never throw.\n * @param index The index to set.\n * @param value The value to set.\n */\n public set(index: number, value: T | undefined): void {\n this._array[this._getCyclicIndex(index)] = value;\n }\n\n /**\n * Pushes a new value onto the list, wrapping around to the start of the array, overriding index 0\n * if the maximum length is reached.\n * @param value The value to push onto the list.\n */\n public push(value: T): void {\n this._array[this._getCyclicIndex(this._length)] = value;\n if (this._length === this._maxLength) {\n this._startIndex = ++this._startIndex % this._maxLength;\n this.onTrimEmitter.fire(1);\n } else {\n this._length++;\n }\n }\n\n /**\n * Advance ringbuffer index and return current element for recycling.\n * Note: The buffer must be full for this method to work.\n * @throws When the buffer is not full.\n */\n public recycle(): T {\n if (this._length !== this._maxLength) {\n throw new Error('Can only recycle when the buffer is full');\n }\n this._startIndex = ++this._startIndex % this._maxLength;\n this.onTrimEmitter.fire(1);\n return this._array[this._getCyclicIndex(this._length - 1)]!;\n }\n\n /**\n * Ringbuffer is at max length.\n */\n public get isFull(): boolean {\n return this._length === this._maxLength;\n }\n\n /**\n * Removes and returns the last value on the list.\n * @returns The popped value.\n */\n public pop(): T | undefined {\n return this._array[this._getCyclicIndex(this._length-- - 1)];\n }\n\n /**\n * Deletes and/or inserts items at a particular index (in that order). Unlike\n * Array.prototype.splice, this operation does not return the deleted items as a new array in\n * order to save creating a new array. Note that this operation may shift all values in the list\n * in the worst case.\n * @param start The index to delete and/or insert.\n * @param deleteCount The number of elements to delete.\n * @param items The items to insert.\n */\n public splice(start: number, deleteCount: number, ...items: T[]): void {\n // Delete items\n if (deleteCount) {\n for (let i = start; i < this._length - deleteCount; i++) {\n this._array[this._getCyclicIndex(i)] = this._array[this._getCyclicIndex(i + deleteCount)];\n }\n this._length -= deleteCount;\n this.onDeleteEmitter.fire({ index: start, amount: deleteCount });\n }\n\n // Add items\n for (let i = this._length - 1; i >= start; i--) {\n this._array[this._getCyclicIndex(i + items.length)] = this._array[this._getCyclicIndex(i)];\n }\n for (let i = 0; i < items.length; i++) {\n this._array[this._getCyclicIndex(start + i)] = items[i];\n }\n if (items.length) {\n this.onInsertEmitter.fire({ index: start, amount: items.length });\n }\n\n // Adjust length as needed\n if (this._length + items.length > this._maxLength) {\n const countToTrim = (this._length + items.length) - this._maxLength;\n this._startIndex += countToTrim;\n this._length = this._maxLength;\n this.onTrimEmitter.fire(countToTrim);\n } else {\n this._length += items.length;\n }\n }\n\n /**\n * Trims a number of items from the start of the list.\n * @param count The number of items to remove.\n */\n public trimStart(count: number): void {\n if (count > this._length) {\n count = this._length;\n }\n this._startIndex += count;\n this._length -= count;\n this.onTrimEmitter.fire(count);\n }\n\n public shiftElements(start: number, count: number, offset: number): void {\n if (count <= 0) {\n return;\n }\n if (start < 0 || start >= this._length) {\n throw new Error('start argument out of range');\n }\n if (start + offset < 0) {\n throw new Error('Cannot shift elements in list beyond index 0');\n }\n\n if (offset > 0) {\n for (let i = count - 1; i >= 0; i--) {\n this.set(start + i + offset, this.get(start + i));\n }\n const expandListBy = (start + count + offset) - this._length;\n if (expandListBy > 0) {\n this._length += expandListBy;\n while (this._length > this._maxLength) {\n this._length--;\n this._startIndex++;\n this.onTrimEmitter.fire(1);\n }\n }\n } else {\n for (let i = 0; i < count; i++) {\n this.set(start + i + offset, this.get(start + i));\n }\n }\n }\n\n /**\n * Gets the cyclic index for the specified regular index. The cyclic index can then be used on the\n * backing array to get the element associated with the regular index.\n * @param index The regular index.\n * @returns The cyclic index.\n */\n private _getCyclicIndex(index: number): number {\n return (this._startIndex + index) % this._maxLength;\n }\n}\n", "/**\n * Copyright (c) 2018 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { CharData, IAttributeData, IBufferLine, ICellData, IExtendedAttrs } from 'common/Types';\nimport { AttributeData } from 'common/buffer/AttributeData';\nimport { CellData } from 'common/buffer/CellData';\nimport { Attributes, BgFlags, CHAR_DATA_ATTR_INDEX, CHAR_DATA_CHAR_INDEX, CHAR_DATA_WIDTH_INDEX, Content, NULL_CELL_CHAR, NULL_CELL_CODE, NULL_CELL_WIDTH, WHITESPACE_CELL_CHAR } from 'common/buffer/Constants';\nimport { stringFromCodePoint } from 'common/input/TextDecoder';\n\n/**\n * buffer memory layout:\n *\n * | uint32_t | uint32_t | uint32_t |\n * | `content` | `FG` | `BG` |\n * | wcwidth(2) comb(1) codepoint(21) | flags(8) R(8) G(8) B(8) | flags(8) R(8) G(8) B(8) |\n */\n\n\n/** typed array slots taken by one cell */\nconst CELL_SIZE = 3;\n\n/**\n * Cell member indices.\n *\n * Direct access:\n * `content = data[column * CELL_SIZE + Cell.CONTENT];`\n * `fg = data[column * CELL_SIZE + Cell.FG];`\n * `bg = data[column * CELL_SIZE + Cell.BG];`\n */\nconst enum Cell {\n CONTENT = 0,\n FG = 1, // currently simply holds all known attrs\n BG = 2 // currently unused\n}\n\nexport const DEFAULT_ATTR_DATA = Object.freeze(new AttributeData());\n\n// Work variables to avoid garbage collection\nlet $startIndex = 0;\n\n/** Factor when to cleanup underlying array buffer after shrinking. */\nconst CLEANUP_THRESHOLD = 2;\n\n/**\n * Typed array based bufferline implementation.\n *\n * There are 2 ways to insert data into the cell buffer:\n * - `setCellFromCodepoint` + `addCodepointToCell`\n * Use these for data that is already UTF32.\n * Used during normal input in `InputHandler` for faster buffer access.\n * - `setCell`\n * This method takes a CellData object and stores the data in the buffer.\n * Use `CellData.fromCharData` to create the CellData object (e.g. from JS string).\n *\n * To retrieve data from the buffer use either one of the primitive methods\n * (if only one particular value is needed) or `loadCell`. For `loadCell` in a loop\n * memory allocs / GC pressure can be greatly reduced by reusing the CellData object.\n */\nexport class BufferLine implements IBufferLine {\n protected _data: Uint32Array;\n protected _combined: {[index: number]: string} = {};\n protected _extendedAttrs: {[index: number]: IExtendedAttrs | undefined} = {};\n public length: number;\n\n constructor(cols: number, fillCellData?: ICellData, public isWrapped: boolean = false) {\n this._data = new Uint32Array(cols * CELL_SIZE);\n const cell = fillCellData || CellData.fromCharData([0, NULL_CELL_CHAR, NULL_CELL_WIDTH, NULL_CELL_CODE]);\n for (let i = 0; i < cols; ++i) {\n this.setCell(i, cell);\n }\n this.length = cols;\n }\n\n /**\n * Get cell data CharData.\n * @deprecated\n */\n public get(index: number): CharData {\n const content = this._data[index * CELL_SIZE + Cell.CONTENT];\n const cp = content & Content.CODEPOINT_MASK;\n return [\n this._data[index * CELL_SIZE + Cell.FG],\n (content & Content.IS_COMBINED_MASK)\n ? this._combined[index]\n : (cp) ? stringFromCodePoint(cp) : '',\n content >> Content.WIDTH_SHIFT,\n (content & Content.IS_COMBINED_MASK)\n ? this._combined[index].charCodeAt(this._combined[index].length - 1)\n : cp\n ];\n }\n\n /**\n * Set cell data from CharData.\n * @deprecated\n */\n public set(index: number, value: CharData): void {\n this._data[index * CELL_SIZE + Cell.FG] = value[CHAR_DATA_ATTR_INDEX];\n if (value[CHAR_DATA_CHAR_INDEX].length > 1) {\n this._combined[index] = value[1];\n this._data[index * CELL_SIZE + Cell.CONTENT] = index | Content.IS_COMBINED_MASK | (value[CHAR_DATA_WIDTH_INDEX] << Content.WIDTH_SHIFT);\n } else {\n this._data[index * CELL_SIZE + Cell.CONTENT] = value[CHAR_DATA_CHAR_INDEX].charCodeAt(0) | (value[CHAR_DATA_WIDTH_INDEX] << Content.WIDTH_SHIFT);\n }\n }\n\n /**\n * primitive getters\n * use these when only one value is needed, otherwise use `loadCell`\n */\n public getWidth(index: number): number {\n return this._data[index * CELL_SIZE + Cell.CONTENT] >> Content.WIDTH_SHIFT;\n }\n\n /** Test whether content has width. */\n public hasWidth(index: number): number {\n return this._data[index * CELL_SIZE + Cell.CONTENT] & Content.WIDTH_MASK;\n }\n\n /** Get FG cell component. */\n public getFg(index: number): number {\n return this._data[index * CELL_SIZE + Cell.FG];\n }\n\n /** Get BG cell component. */\n public getBg(index: number): number {\n return this._data[index * CELL_SIZE + Cell.BG];\n }\n\n /**\n * Test whether contains any chars.\n * Basically an empty has no content, but other cells might differ in FG/BG\n * from real empty cells.\n */\n public hasContent(index: number): number {\n return this._data[index * CELL_SIZE + Cell.CONTENT] & Content.HAS_CONTENT_MASK;\n }\n\n /**\n * Get codepoint of the cell.\n * To be in line with `code` in CharData this either returns\n * a single UTF32 codepoint or the last codepoint of a combined string.\n */\n public getCodePoint(index: number): number {\n const content = this._data[index * CELL_SIZE + Cell.CONTENT];\n if (content & Content.IS_COMBINED_MASK) {\n return this._combined[index].charCodeAt(this._combined[index].length - 1);\n }\n return content & Content.CODEPOINT_MASK;\n }\n\n /** Test whether the cell contains a combined string. */\n public isCombined(index: number): number {\n return this._data[index * CELL_SIZE + Cell.CONTENT] & Content.IS_COMBINED_MASK;\n }\n\n /** Returns the string content of the cell. */\n public getString(index: number): string {\n const content = this._data[index * CELL_SIZE + Cell.CONTENT];\n if (content & Content.IS_COMBINED_MASK) {\n return this._combined[index];\n }\n if (content & Content.CODEPOINT_MASK) {\n return stringFromCodePoint(content & Content.CODEPOINT_MASK);\n }\n // return empty string for empty cells\n return '';\n }\n\n /** Get state of protected flag. */\n public isProtected(index: number): number {\n return this._data[index * CELL_SIZE + Cell.BG] & BgFlags.PROTECTED;\n }\n\n /**\n * Load data at `index` into `cell`. This is used to access cells in a way that's more friendly\n * to GC as it significantly reduced the amount of new objects/references needed.\n */\n public loadCell(index: number, cell: ICellData): ICellData {\n $startIndex = index * CELL_SIZE;\n cell.content = this._data[$startIndex + Cell.CONTENT];\n cell.fg = this._data[$startIndex + Cell.FG];\n cell.bg = this._data[$startIndex + Cell.BG];\n if (cell.content & Content.IS_COMBINED_MASK) {\n cell.combinedData = this._combined[index];\n }\n if (cell.bg & BgFlags.HAS_EXTENDED) {\n cell.extended = this._extendedAttrs[index]!;\n }\n return cell;\n }\n\n /**\n * Set data at `index` to `cell`.\n */\n public setCell(index: number, cell: ICellData): void {\n if (cell.content & Content.IS_COMBINED_MASK) {\n this._combined[index] = cell.combinedData;\n }\n if (cell.bg & BgFlags.HAS_EXTENDED) {\n this._extendedAttrs[index] = cell.extended;\n }\n this._data[index * CELL_SIZE + Cell.CONTENT] = cell.content;\n this._data[index * CELL_SIZE + Cell.FG] = cell.fg;\n this._data[index * CELL_SIZE + Cell.BG] = cell.bg;\n }\n\n /**\n * Set cell data from input handler.\n * Since the input handler see the incoming chars as UTF32 codepoints,\n * it gets an optimized access method.\n */\n public setCellFromCodepoint(index: number, codePoint: number, width: number, attrs: IAttributeData): void {\n if (attrs.bg & BgFlags.HAS_EXTENDED) {\n this._extendedAttrs[index] = attrs.extended;\n }\n this._data[index * CELL_SIZE + Cell.CONTENT] = codePoint | (width << Content.WIDTH_SHIFT);\n this._data[index * CELL_SIZE + Cell.FG] = attrs.fg;\n this._data[index * CELL_SIZE + Cell.BG] = attrs.bg;\n }\n\n /**\n * Add a codepoint to a cell from input handler.\n * During input stage combining chars with a width of 0 follow and stack\n * onto a leading char. Since we already set the attrs\n * by the previous `setDataFromCodePoint` call, we can omit it here.\n */\n public addCodepointToCell(index: number, codePoint: number, width: number): void {\n let content = this._data[index * CELL_SIZE + Cell.CONTENT];\n if (content & Content.IS_COMBINED_MASK) {\n // we already have a combined string, simply add\n this._combined[index] += stringFromCodePoint(codePoint);\n } else {\n if (content & Content.CODEPOINT_MASK) {\n // normal case for combining chars:\n // - move current leading char + new one into combined string\n // - set combined flag\n this._combined[index] = stringFromCodePoint(content & Content.CODEPOINT_MASK) + stringFromCodePoint(codePoint);\n content &= ~Content.CODEPOINT_MASK; // set codepoint in buffer to 0\n content |= Content.IS_COMBINED_MASK;\n } else {\n // should not happen - we actually have no data in the cell yet\n // simply set the data in the cell buffer with a width of 1\n content = codePoint | (1 << Content.WIDTH_SHIFT);\n }\n }\n if (width) {\n content &= ~Content.WIDTH_MASK;\n content |= width << Content.WIDTH_SHIFT;\n }\n this._data[index * CELL_SIZE + Cell.CONTENT] = content;\n }\n\n public insertCells(pos: number, n: number, fillCellData: ICellData): void {\n pos %= this.length;\n\n // handle fullwidth at pos: reset cell one to the left if pos is second cell of a wide char\n if (pos && this.getWidth(pos - 1) === 2) {\n this.setCellFromCodepoint(pos - 1, 0, 1, fillCellData);\n }\n\n if (n < this.length - pos) {\n const cell = new CellData();\n for (let i = this.length - pos - n - 1; i >= 0; --i) {\n this.setCell(pos + n + i, this.loadCell(pos + i, cell));\n }\n for (let i = 0; i < n; ++i) {\n this.setCell(pos + i, fillCellData);\n }\n } else {\n for (let i = pos; i < this.length; ++i) {\n this.setCell(i, fillCellData);\n }\n }\n\n // handle fullwidth at line end: reset last cell if it is first cell of a wide char\n if (this.getWidth(this.length - 1) === 2) {\n this.setCellFromCodepoint(this.length - 1, 0, 1, fillCellData);\n }\n }\n\n public deleteCells(pos: number, n: number, fillCellData: ICellData): void {\n pos %= this.length;\n if (n < this.length - pos) {\n const cell = new CellData();\n for (let i = 0; i < this.length - pos - n; ++i) {\n this.setCell(pos + i, this.loadCell(pos + n + i, cell));\n }\n for (let i = this.length - n; i < this.length; ++i) {\n this.setCell(i, fillCellData);\n }\n } else {\n for (let i = pos; i < this.length; ++i) {\n this.setCell(i, fillCellData);\n }\n }\n\n // handle fullwidth at pos:\n // - reset pos-1 if wide char\n // - reset pos if width==0 (previous second cell of a wide char)\n if (pos && this.getWidth(pos - 1) === 2) {\n this.setCellFromCodepoint(pos - 1, 0, 1, fillCellData);\n }\n if (this.getWidth(pos) === 0 && !this.hasContent(pos)) {\n this.setCellFromCodepoint(pos, 0, 1, fillCellData);\n }\n }\n\n public replaceCells(start: number, end: number, fillCellData: ICellData, respectProtect: boolean = false): void {\n // full branching on respectProtect==true, hopefully getting fast JIT for standard case\n if (respectProtect) {\n if (start && this.getWidth(start - 1) === 2 && !this.isProtected(start - 1)) {\n this.setCellFromCodepoint(start - 1, 0, 1, fillCellData);\n }\n if (end < this.length && this.getWidth(end - 1) === 2 && !this.isProtected(end)) {\n this.setCellFromCodepoint(end, 0, 1, fillCellData);\n }\n while (start < end && start < this.length) {\n if (!this.isProtected(start)) {\n this.setCell(start, fillCellData);\n }\n start++;\n }\n return;\n }\n\n // handle fullwidth at start: reset cell one to the left if start is second cell of a wide char\n if (start && this.getWidth(start - 1) === 2) {\n this.setCellFromCodepoint(start - 1, 0, 1, fillCellData);\n }\n // handle fullwidth at last cell + 1: reset to empty cell if it is second part of a wide char\n if (end < this.length && this.getWidth(end - 1) === 2) {\n this.setCellFromCodepoint(end, 0, 1, fillCellData);\n }\n\n while (start < end && start < this.length) {\n this.setCell(start++, fillCellData);\n }\n }\n\n /**\n * Resize BufferLine to `cols` filling excess cells with `fillCellData`.\n * The underlying array buffer will not change if there is still enough space\n * to hold the new buffer line data.\n * Returns a boolean indicating, whether a `cleanupMemory` call would free\n * excess memory (true after shrinking > CLEANUP_THRESHOLD).\n */\n public resize(cols: number, fillCellData: ICellData): boolean {\n if (cols === this.length) {\n return this._data.length * 4 * CLEANUP_THRESHOLD < this._data.buffer.byteLength;\n }\n const uint32Cells = cols * CELL_SIZE;\n if (cols > this.length) {\n if (this._data.buffer.byteLength >= uint32Cells * 4) {\n // optimization: avoid alloc and data copy if buffer has enough room\n this._data = new Uint32Array(this._data.buffer, 0, uint32Cells);\n } else {\n // slow path: new alloc and full data copy\n const data = new Uint32Array(uint32Cells);\n data.set(this._data);\n this._data = data;\n }\n for (let i = this.length; i < cols; ++i) {\n this.setCell(i, fillCellData);\n }\n } else {\n // optimization: just shrink the view on existing buffer\n this._data = this._data.subarray(0, uint32Cells);\n // Remove any cut off combined data\n const keys = Object.keys(this._combined);\n for (let i = 0; i < keys.length; i++) {\n const key = parseInt(keys[i], 10);\n if (key >= cols) {\n delete this._combined[key];\n }\n }\n // remove any cut off extended attributes\n const extKeys = Object.keys(this._extendedAttrs);\n for (let i = 0; i < extKeys.length; i++) {\n const key = parseInt(extKeys[i], 10);\n if (key >= cols) {\n delete this._extendedAttrs[key];\n }\n }\n }\n this.length = cols;\n return uint32Cells * 4 * CLEANUP_THRESHOLD < this._data.buffer.byteLength;\n }\n\n /**\n * Cleanup underlying array buffer.\n * A cleanup will be triggered if the array buffer exceeds the actual used\n * memory by a factor of CLEANUP_THRESHOLD.\n * Returns 0 or 1 indicating whether a cleanup happened.\n */\n public cleanupMemory(): number {\n if (this._data.length * 4 * CLEANUP_THRESHOLD < this._data.buffer.byteLength) {\n const data = new Uint32Array(this._data.length);\n data.set(this._data);\n this._data = data;\n return 1;\n }\n return 0;\n }\n\n /** fill a line with fillCharData */\n public fill(fillCellData: ICellData, respectProtect: boolean = false): void {\n // full branching on respectProtect==true, hopefully getting fast JIT for standard case\n if (respectProtect) {\n for (let i = 0; i < this.length; ++i) {\n if (!this.isProtected(i)) {\n this.setCell(i, fillCellData);\n }\n }\n return;\n }\n this._combined = {};\n this._extendedAttrs = {};\n for (let i = 0; i < this.length; ++i) {\n this.setCell(i, fillCellData);\n }\n }\n\n /** alter to a full copy of line */\n public copyFrom(line: BufferLine): void {\n if (this.length !== line.length) {\n this._data = new Uint32Array(line._data);\n } else {\n // use high speed copy if lengths are equal\n this._data.set(line._data);\n }\n this.length = line.length;\n this._combined = {};\n for (const el in line._combined) {\n this._combined[el] = line._combined[el];\n }\n this._extendedAttrs = {};\n for (const el in line._extendedAttrs) {\n this._extendedAttrs[el] = line._extendedAttrs[el];\n }\n this.isWrapped = line.isWrapped;\n }\n\n /** create a new clone */\n public clone(): IBufferLine {\n const newLine = new BufferLine(0);\n newLine._data = new Uint32Array(this._data);\n newLine.length = this.length;\n for (const el in this._combined) {\n newLine._combined[el] = this._combined[el];\n }\n for (const el in this._extendedAttrs) {\n newLine._extendedAttrs[el] = this._extendedAttrs[el];\n }\n newLine.isWrapped = this.isWrapped;\n return newLine;\n }\n\n public getTrimmedLength(): number {\n for (let i = this.length - 1; i >= 0; --i) {\n if ((this._data[i * CELL_SIZE + Cell.CONTENT] & Content.HAS_CONTENT_MASK)) {\n return i + (this._data[i * CELL_SIZE + Cell.CONTENT] >> Content.WIDTH_SHIFT);\n }\n }\n return 0;\n }\n\n public getNoBgTrimmedLength(): number {\n for (let i = this.length - 1; i >= 0; --i) {\n if ((this._data[i * CELL_SIZE + Cell.CONTENT] & Content.HAS_CONTENT_MASK) || (this._data[i * CELL_SIZE + Cell.BG] & Attributes.CM_MASK)) {\n return i + (this._data[i * CELL_SIZE + Cell.CONTENT] >> Content.WIDTH_SHIFT);\n }\n }\n return 0;\n }\n\n public copyCellsFrom(src: BufferLine, srcCol: number, destCol: number, length: number, applyInReverse: boolean): void {\n const srcData = src._data;\n if (applyInReverse) {\n for (let cell = length - 1; cell >= 0; cell--) {\n for (let i = 0; i < CELL_SIZE; i++) {\n this._data[(destCol + cell) * CELL_SIZE + i] = srcData[(srcCol + cell) * CELL_SIZE + i];\n }\n if (srcData[(srcCol + cell) * CELL_SIZE + Cell.BG] & BgFlags.HAS_EXTENDED) {\n this._extendedAttrs[destCol + cell] = src._extendedAttrs[srcCol + cell];\n }\n }\n } else {\n for (let cell = 0; cell < length; cell++) {\n for (let i = 0; i < CELL_SIZE; i++) {\n this._data[(destCol + cell) * CELL_SIZE + i] = srcData[(srcCol + cell) * CELL_SIZE + i];\n }\n if (srcData[(srcCol + cell) * CELL_SIZE + Cell.BG] & BgFlags.HAS_EXTENDED) {\n this._extendedAttrs[destCol + cell] = src._extendedAttrs[srcCol + cell];\n }\n }\n }\n\n // Move any combined data over as needed, FIXME: repeat for extended attrs\n const srcCombinedKeys = Object.keys(src._combined);\n for (let i = 0; i < srcCombinedKeys.length; i++) {\n const key = parseInt(srcCombinedKeys[i], 10);\n if (key >= srcCol) {\n this._combined[key - srcCol + destCol] = src._combined[key];\n }\n }\n }\n\n /**\n * Translates the buffer line to a string.\n *\n * @param trimRight Whether to trim any empty cells on the right.\n * @param startCol The column to start the string (0-based inclusive).\n * @param endCol The column to end the string (0-based exclusive).\n * @param outColumns if specified, this array will be filled with column numbers such that\n * `returnedString[i]` is displayed at `outColumns[i]` column. `outColumns[returnedString.length]`\n * is where the character following `returnedString` will be displayed.\n *\n * When a single cell is translated to multiple UTF-16 code units (e.g. surrogate pair) in the\n * returned string, the corresponding entries in `outColumns` will have the same column number.\n */\n public translateToString(trimRight?: boolean, startCol?: number, endCol?: number, outColumns?: number[]): string {\n startCol = startCol ?? 0;\n endCol = endCol ?? this.length;\n if (trimRight) {\n endCol = Math.min(endCol, this.getTrimmedLength());\n }\n if (outColumns) {\n outColumns.length = 0;\n }\n let result = '';\n while (startCol < endCol) {\n const content = this._data[startCol * CELL_SIZE + Cell.CONTENT];\n const cp = content & Content.CODEPOINT_MASK;\n const chars = (content & Content.IS_COMBINED_MASK) ? this._combined[startCol] : (cp) ? stringFromCodePoint(cp) : WHITESPACE_CELL_CHAR;\n result += chars;\n if (outColumns) {\n for (let i = 0; i < chars.length; ++i) {\n outColumns.push(startCol);\n }\n }\n startCol += (content >> Content.WIDTH_SHIFT) || 1; // always advance by at least 1\n }\n if (outColumns) {\n outColumns.push(startCol);\n }\n return result;\n }\n}\n", "/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { BufferLine } from 'common/buffer/BufferLine';\nimport { CircularList } from 'common/CircularList';\nimport { IBufferLine, ICellData } from 'common/Types';\n\nexport interface INewLayoutResult {\n layout: number[];\n countRemoved: number;\n}\n\n/**\n * Evaluates and returns indexes to be removed after a reflow larger occurs. Lines will be removed\n * when a wrapped line unwraps.\n * @param lines The buffer lines.\n * @param oldCols The columns before resize\n * @param newCols The columns after resize.\n * @param bufferAbsoluteY The absolute y position of the cursor (baseY + cursorY).\n * @param nullCell The cell data to use when filling in empty cells.\n * @param reflowCursorLine Whether to reflow the line containing the cursor.\n */\nexport function reflowLargerGetLinesToRemove(lines: CircularList, oldCols: number, newCols: number, bufferAbsoluteY: number, nullCell: ICellData, reflowCursorLine: boolean): number[] {\n // Gather all BufferLines that need to be removed from the Buffer here so that they can be\n // batched up and only committed once\n const toRemove: number[] = [];\n\n for (let y = 0; y < lines.length - 1; y++) {\n // Check if this row is wrapped\n let i = y;\n let nextLine = lines.get(++i) as BufferLine;\n if (!nextLine.isWrapped) {\n continue;\n }\n\n // Check how many lines it's wrapped for\n const wrappedLines: BufferLine[] = [lines.get(y) as BufferLine];\n while (i < lines.length && nextLine.isWrapped) {\n wrappedLines.push(nextLine);\n nextLine = lines.get(++i) as BufferLine;\n }\n\n if (!reflowCursorLine) {\n // If these lines contain the cursor don't touch them, the program will handle fixing up\n // wrapped lines with the cursor\n if (bufferAbsoluteY >= y && bufferAbsoluteY < i) {\n y += wrappedLines.length - 1;\n continue;\n }\n }\n\n // Copy buffer data to new locations\n let destLineIndex = 0;\n let destCol = getWrappedLineTrimmedLength(wrappedLines, destLineIndex, oldCols);\n let srcLineIndex = 1;\n let srcCol = 0;\n while (srcLineIndex < wrappedLines.length) {\n const srcTrimmedTineLength = getWrappedLineTrimmedLength(wrappedLines, srcLineIndex, oldCols);\n const srcRemainingCells = srcTrimmedTineLength - srcCol;\n const destRemainingCells = newCols - destCol;\n const cellsToCopy = Math.min(srcRemainingCells, destRemainingCells);\n\n wrappedLines[destLineIndex].copyCellsFrom(wrappedLines[srcLineIndex], srcCol, destCol, cellsToCopy, false);\n\n destCol += cellsToCopy;\n if (destCol === newCols) {\n destLineIndex++;\n destCol = 0;\n }\n srcCol += cellsToCopy;\n if (srcCol === srcTrimmedTineLength) {\n srcLineIndex++;\n srcCol = 0;\n }\n\n // Make sure the last cell isn't wide, if it is copy it to the current dest\n if (destCol === 0 && destLineIndex !== 0) {\n if (wrappedLines[destLineIndex - 1].getWidth(newCols - 1) === 2) {\n wrappedLines[destLineIndex].copyCellsFrom(wrappedLines[destLineIndex - 1], newCols - 1, destCol++, 1, false);\n // Null out the end of the last row\n wrappedLines[destLineIndex - 1].setCell(newCols - 1, nullCell);\n }\n }\n }\n\n // Clear out remaining cells or fragments could remain;\n wrappedLines[destLineIndex].replaceCells(destCol, newCols, nullCell);\n\n // Work backwards and remove any rows at the end that only contain null cells\n let countToRemove = 0;\n for (let i = wrappedLines.length - 1; i > 0; i--) {\n if (i > destLineIndex || wrappedLines[i].getTrimmedLength() === 0) {\n countToRemove++;\n } else {\n break;\n }\n }\n\n if (countToRemove > 0) {\n toRemove.push(y + wrappedLines.length - countToRemove); // index\n toRemove.push(countToRemove);\n }\n\n y += wrappedLines.length - 1;\n }\n return toRemove;\n}\n\n/**\n * Creates and return the new layout for lines given an array of indexes to be removed.\n * @param lines The buffer lines.\n * @param toRemove The indexes to remove.\n */\nexport function reflowLargerCreateNewLayout(lines: CircularList, toRemove: number[]): INewLayoutResult {\n const layout: number[] = [];\n // First iterate through the list and get the actual indexes to use for rows\n let nextToRemoveIndex = 0;\n let nextToRemoveStart = toRemove[nextToRemoveIndex];\n let countRemovedSoFar = 0;\n for (let i = 0; i < lines.length; i++) {\n if (nextToRemoveStart === i) {\n const countToRemove = toRemove[++nextToRemoveIndex];\n\n // Tell markers that there was a deletion\n lines.onDeleteEmitter.fire({\n index: i - countRemovedSoFar,\n amount: countToRemove\n });\n\n i += countToRemove - 1;\n countRemovedSoFar += countToRemove;\n nextToRemoveStart = toRemove[++nextToRemoveIndex];\n } else {\n layout.push(i);\n }\n }\n return {\n layout,\n countRemoved: countRemovedSoFar\n };\n}\n\n/**\n * Applies a new layout to the buffer. This essentially does the same as many splice calls but it's\n * done all at once in a single iteration through the list since splice is very expensive.\n * @param lines The buffer lines.\n * @param newLayout The new layout to apply.\n */\nexport function reflowLargerApplyNewLayout(lines: CircularList, newLayout: number[]): void {\n // Record original lines so they don't get overridden when we rearrange the list\n const newLayoutLines: BufferLine[] = [];\n for (let i = 0; i < newLayout.length; i++) {\n newLayoutLines.push(lines.get(newLayout[i]) as BufferLine);\n }\n\n // Rearrange the list\n for (let i = 0; i < newLayoutLines.length; i++) {\n lines.set(i, newLayoutLines[i]);\n }\n lines.length = newLayout.length;\n}\n\n/**\n * Gets the new line lengths for a given wrapped line. The purpose of this function it to pre-\n * compute the wrapping points since wide characters may need to be wrapped onto the following line.\n * This function will return an array of numbers of where each line wraps to, the resulting array\n * will only contain the values `newCols` (when the line does not end with a wide character) and\n * `newCols - 1` (when the line does end with a wide character), except for the last value which\n * will contain the remaining items to fill the line.\n *\n * Calling this with a `newCols` value of `1` will lock up.\n *\n * @param wrappedLines The wrapped lines to evaluate.\n * @param oldCols The columns before resize.\n * @param newCols The columns after resize.\n */\nexport function reflowSmallerGetNewLineLengths(wrappedLines: BufferLine[], oldCols: number, newCols: number): number[] {\n const newLineLengths: number[] = [];\n const cellsNeeded = wrappedLines.map((l, i) => getWrappedLineTrimmedLength(wrappedLines, i, oldCols)).reduce((p, c) => p + c);\n\n // Use srcCol and srcLine to find the new wrapping point, use that to get the cellsAvailable and\n // linesNeeded\n let srcCol = 0;\n let srcLine = 0;\n let cellsAvailable = 0;\n while (cellsAvailable < cellsNeeded) {\n if (cellsNeeded - cellsAvailable < newCols) {\n // Add the final line and exit the loop\n newLineLengths.push(cellsNeeded - cellsAvailable);\n break;\n }\n srcCol += newCols;\n const oldTrimmedLength = getWrappedLineTrimmedLength(wrappedLines, srcLine, oldCols);\n if (srcCol > oldTrimmedLength) {\n srcCol -= oldTrimmedLength;\n srcLine++;\n }\n const endsWithWide = wrappedLines[srcLine].getWidth(srcCol - 1) === 2;\n if (endsWithWide) {\n srcCol--;\n }\n const lineLength = endsWithWide ? newCols - 1 : newCols;\n newLineLengths.push(lineLength);\n cellsAvailable += lineLength;\n }\n\n return newLineLengths;\n}\n\nexport function getWrappedLineTrimmedLength(lines: BufferLine[], i: number, cols: number): number {\n // If this is the last row in the wrapped line, get the actual trimmed length\n if (i === lines.length - 1) {\n return lines[i].getTrimmedLength();\n }\n // Detect whether the following line starts with a wide character and the end of the current line\n // is null, if so then we can be pretty sure the null character should be excluded from the line\n // length]\n const endsInNull = !(lines[i].hasContent(cols - 1)) && lines[i].getWidth(cols - 1) === 1;\n const followingLineStartsWithWide = lines[i + 1].getWidth(0) === 2;\n if (endsInNull && followingLineStartsWithWide) {\n return cols - 1;\n }\n return cols;\n}\n", "/**\n * Copyright (c) 2018 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IDisposable, IMarker } from 'common/Types';\nimport { Emitter } from 'vs/base/common/event';\nimport { dispose } from 'vs/base/common/lifecycle';\n\nexport class Marker implements IMarker {\n private static _nextId = 1;\n\n public isDisposed: boolean = false;\n private readonly _disposables: IDisposable[] = [];\n\n private readonly _id: number = Marker._nextId++;\n public get id(): number { return this._id; }\n\n private readonly _onDispose = this.register(new Emitter());\n public readonly onDispose = this._onDispose.event;\n\n constructor(\n public line: number\n ) {\n }\n\n public dispose(): void {\n if (this.isDisposed) {\n return;\n }\n this.isDisposed = true;\n this.line = -1;\n // Emit before super.dispose such that dispose listeners get a change to react\n this._onDispose.fire();\n dispose(this._disposables);\n this._disposables.length = 0;\n }\n\n public register(disposable: T): T {\n this._disposables.push(disposable);\n return disposable;\n }\n}\n", "/**\n * Copyright (c) 2016 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { ICharset } from 'common/Types';\n\n/**\n * The character sets supported by the terminal. These enable several languages\n * to be represented within the terminal with only 8-bit encoding. See ISO 2022\n * for a discussion on character sets. Only VT100 character sets are supported.\n */\nexport const CHARSETS: { [key: string]: ICharset | undefined } = {};\n\n/**\n * The default character set, US.\n */\nexport const DEFAULT_CHARSET: ICharset | undefined = CHARSETS['B'];\n\n/**\n * DEC Special Character and Line Drawing Set.\n * Reference: http://vt100.net/docs/vt102-ug/table5-13.html\n * A lot of curses apps use this if they see TERM=xterm.\n * testing: echo -e '\\e(0a\\e(B'\n * The xterm output sometimes seems to conflict with the\n * reference above. xterm seems in line with the reference\n * when running vttest however.\n * The table below now uses xterm's output from vttest.\n */\nCHARSETS['0'] = {\n '`': '\\u25c6', // '\u25C6'\n 'a': '\\u2592', // '\u2592'\n 'b': '\\u2409', // '\u2409' (HT)\n 'c': '\\u240c', // '\u240C' (FF)\n 'd': '\\u240d', // '\u240D' (CR)\n 'e': '\\u240a', // '\u240A' (LF)\n 'f': '\\u00b0', // '\u00B0'\n 'g': '\\u00b1', // '\u00B1'\n 'h': '\\u2424', // '\u2424' (NL)\n 'i': '\\u240b', // '\u240B' (VT)\n 'j': '\\u2518', // '\u2518'\n 'k': '\\u2510', // '\u2510'\n 'l': '\\u250c', // '\u250C'\n 'm': '\\u2514', // '\u2514'\n 'n': '\\u253c', // '\u253C'\n 'o': '\\u23ba', // '\u23BA'\n 'p': '\\u23bb', // '\u23BB'\n 'q': '\\u2500', // '\u2500'\n 'r': '\\u23bc', // '\u23BC'\n 's': '\\u23bd', // '\u23BD'\n 't': '\\u251c', // '\u251C'\n 'u': '\\u2524', // '\u2524'\n 'v': '\\u2534', // '\u2534'\n 'w': '\\u252c', // '\u252C'\n 'x': '\\u2502', // '\u2502'\n 'y': '\\u2264', // '\u2264'\n 'z': '\\u2265', // '\u2265'\n '{': '\\u03c0', // '\u03C0'\n '|': '\\u2260', // '\u2260'\n '}': '\\u00a3', // '\u00A3'\n '~': '\\u00b7' // '\u00B7'\n};\n\n/**\n * British character set\n * ESC (A\n * Reference: http://vt100.net/docs/vt220-rm/table2-5.html\n */\nCHARSETS['A'] = {\n '#': '\u00A3'\n};\n\n/**\n * United States character set\n * ESC (B\n */\nCHARSETS['B'] = undefined;\n\n/**\n * Dutch character set\n * ESC (4\n * Reference: http://vt100.net/docs/vt220-rm/table2-6.html\n */\nCHARSETS['4'] = {\n '#': '\u00A3',\n '@': '\u00BE',\n '[': 'ij',\n '\\\\': '\u00BD',\n ']': '|',\n '{': '\u00A8',\n '|': 'f',\n '}': '\u00BC',\n '~': '\u00B4'\n};\n\n/**\n * Finnish character set\n * ESC (C or ESC (5\n * Reference: http://vt100.net/docs/vt220-rm/table2-7.html\n */\nCHARSETS['C'] =\nCHARSETS['5'] = {\n '[': '\u00C4',\n '\\\\': '\u00D6',\n ']': '\u00C5',\n '^': '\u00DC',\n '`': '\u00E9',\n '{': '\u00E4',\n '|': '\u00F6',\n '}': '\u00E5',\n '~': '\u00FC'\n};\n\n/**\n * French character set\n * ESC (R\n * Reference: http://vt100.net/docs/vt220-rm/table2-8.html\n */\nCHARSETS['R'] = {\n '#': '\u00A3',\n '@': '\u00E0',\n '[': '\u00B0',\n '\\\\': '\u00E7',\n ']': '\u00A7',\n '{': '\u00E9',\n '|': '\u00F9',\n '}': '\u00E8',\n '~': '\u00A8'\n};\n\n/**\n * French Canadian character set\n * ESC (Q\n * Reference: http://vt100.net/docs/vt220-rm/table2-9.html\n */\nCHARSETS['Q'] = {\n '@': '\u00E0',\n '[': '\u00E2',\n '\\\\': '\u00E7',\n ']': '\u00EA',\n '^': '\u00EE',\n '`': '\u00F4',\n '{': '\u00E9',\n '|': '\u00F9',\n '}': '\u00E8',\n '~': '\u00FB'\n};\n\n/**\n * German character set\n * ESC (K\n * Reference: http://vt100.net/docs/vt220-rm/table2-10.html\n */\nCHARSETS['K'] = {\n '@': '\u00A7',\n '[': '\u00C4',\n '\\\\': '\u00D6',\n ']': '\u00DC',\n '{': '\u00E4',\n '|': '\u00F6',\n '}': '\u00FC',\n '~': '\u00DF'\n};\n\n/**\n * Italian character set\n * ESC (Y\n * Reference: http://vt100.net/docs/vt220-rm/table2-11.html\n */\nCHARSETS['Y'] = {\n '#': '\u00A3',\n '@': '\u00A7',\n '[': '\u00B0',\n '\\\\': '\u00E7',\n ']': '\u00E9',\n '`': '\u00F9',\n '{': '\u00E0',\n '|': '\u00F2',\n '}': '\u00E8',\n '~': '\u00EC'\n};\n\n/**\n * Norwegian/Danish character set\n * ESC (E or ESC (6\n * Reference: http://vt100.net/docs/vt220-rm/table2-12.html\n */\nCHARSETS['E'] =\nCHARSETS['6'] = {\n '@': '\u00C4',\n '[': '\u00C6',\n '\\\\': '\u00D8',\n ']': '\u00C5',\n '^': '\u00DC',\n '`': '\u00E4',\n '{': '\u00E6',\n '|': '\u00F8',\n '}': '\u00E5',\n '~': '\u00FC'\n};\n\n/**\n * Spanish character set\n * ESC (Z\n * Reference: http://vt100.net/docs/vt220-rm/table2-13.html\n */\nCHARSETS['Z'] = {\n '#': '\u00A3',\n '@': '\u00A7',\n '[': '\u00A1',\n '\\\\': '\u00D1',\n ']': '\u00BF',\n '{': '\u00B0',\n '|': '\u00F1',\n '}': '\u00E7'\n};\n\n/**\n * Swedish character set\n * ESC (H or ESC (7\n * Reference: http://vt100.net/docs/vt220-rm/table2-14.html\n */\nCHARSETS['H'] =\nCHARSETS['7'] = {\n '@': '\u00C9',\n '[': '\u00C4',\n '\\\\': '\u00D6',\n ']': '\u00C5',\n '^': '\u00DC',\n '`': '\u00E9',\n '{': '\u00E4',\n '|': '\u00F6',\n '}': '\u00E5',\n '~': '\u00FC'\n};\n\n/**\n * Swiss character set\n * ESC (=\n * Reference: http://vt100.net/docs/vt220-rm/table2-15.html\n */\nCHARSETS['='] = {\n '#': '\u00F9',\n '@': '\u00E0',\n '[': '\u00E9',\n '\\\\': '\u00E7',\n ']': '\u00EA',\n '^': '\u00EE',\n // eslint-disable-next-line @typescript-eslint/naming-convention\n '_': '\u00E8',\n '`': '\u00F4',\n '{': '\u00E4',\n '|': '\u00F6',\n '}': '\u00FC',\n '~': '\u00FB'\n};\n", "/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { CircularList, IInsertEvent } from 'common/CircularList';\nimport { IdleTaskQueue } from 'common/TaskQueue';\nimport { IAttributeData, IBufferLine, ICellData, ICharset } from 'common/Types';\nimport { ExtendedAttrs } from 'common/buffer/AttributeData';\nimport { BufferLine, DEFAULT_ATTR_DATA } from 'common/buffer/BufferLine';\nimport { getWrappedLineTrimmedLength, reflowLargerApplyNewLayout, reflowLargerCreateNewLayout, reflowLargerGetLinesToRemove, reflowSmallerGetNewLineLengths } from 'common/buffer/BufferReflow';\nimport { CellData } from 'common/buffer/CellData';\nimport { NULL_CELL_CHAR, NULL_CELL_CODE, NULL_CELL_WIDTH, WHITESPACE_CELL_CHAR, WHITESPACE_CELL_CODE, WHITESPACE_CELL_WIDTH } from 'common/buffer/Constants';\nimport { Marker } from 'common/buffer/Marker';\nimport { IBuffer } from 'common/buffer/Types';\nimport { DEFAULT_CHARSET } from 'common/data/Charsets';\nimport { IBufferService, IOptionsService } from 'common/services/Services';\n\nexport const MAX_BUFFER_SIZE = 4294967295; // 2^32 - 1\n\n/**\n * This class represents a terminal buffer (an internal state of the terminal), where the\n * following information is stored (in high-level):\n * - text content of this particular buffer\n * - cursor position\n * - scroll position\n */\nexport class Buffer implements IBuffer {\n public lines: CircularList;\n public ydisp: number = 0;\n public ybase: number = 0;\n public y: number = 0;\n public x: number = 0;\n public scrollBottom: number;\n public scrollTop: number;\n public tabs: { [column: number]: boolean | undefined } = {};\n public savedY: number = 0;\n public savedX: number = 0;\n public savedCurAttrData = DEFAULT_ATTR_DATA.clone();\n public savedCharset: ICharset | undefined = DEFAULT_CHARSET;\n public markers: Marker[] = [];\n private _nullCell: ICellData = CellData.fromCharData([0, NULL_CELL_CHAR, NULL_CELL_WIDTH, NULL_CELL_CODE]);\n private _whitespaceCell: ICellData = CellData.fromCharData([0, WHITESPACE_CELL_CHAR, WHITESPACE_CELL_WIDTH, WHITESPACE_CELL_CODE]);\n private _cols: number;\n private _rows: number;\n private _isClearing: boolean = false;\n\n constructor(\n private _hasScrollback: boolean,\n private _optionsService: IOptionsService,\n private _bufferService: IBufferService\n ) {\n this._cols = this._bufferService.cols;\n this._rows = this._bufferService.rows;\n this.lines = new CircularList(this._getCorrectBufferLength(this._rows));\n this.scrollTop = 0;\n this.scrollBottom = this._rows - 1;\n this.setupTabStops();\n }\n\n public getNullCell(attr?: IAttributeData): ICellData {\n if (attr) {\n this._nullCell.fg = attr.fg;\n this._nullCell.bg = attr.bg;\n this._nullCell.extended = attr.extended;\n } else {\n this._nullCell.fg = 0;\n this._nullCell.bg = 0;\n this._nullCell.extended = new ExtendedAttrs();\n }\n return this._nullCell;\n }\n\n public getWhitespaceCell(attr?: IAttributeData): ICellData {\n if (attr) {\n this._whitespaceCell.fg = attr.fg;\n this._whitespaceCell.bg = attr.bg;\n this._whitespaceCell.extended = attr.extended;\n } else {\n this._whitespaceCell.fg = 0;\n this._whitespaceCell.bg = 0;\n this._whitespaceCell.extended = new ExtendedAttrs();\n }\n return this._whitespaceCell;\n }\n\n public getBlankLine(attr: IAttributeData, isWrapped?: boolean): IBufferLine {\n return new BufferLine(this._bufferService.cols, this.getNullCell(attr), isWrapped);\n }\n\n public get hasScrollback(): boolean {\n return this._hasScrollback && this.lines.maxLength > this._rows;\n }\n\n public get isCursorInViewport(): boolean {\n const absoluteY = this.ybase + this.y;\n const relativeY = absoluteY - this.ydisp;\n return (relativeY >= 0 && relativeY < this._rows);\n }\n\n /**\n * Gets the correct buffer length based on the rows provided, the terminal's\n * scrollback and whether this buffer is flagged to have scrollback or not.\n * @param rows The terminal rows to use in the calculation.\n */\n private _getCorrectBufferLength(rows: number): number {\n if (!this._hasScrollback) {\n return rows;\n }\n\n const correctBufferLength = rows + this._optionsService.rawOptions.scrollback;\n\n return correctBufferLength > MAX_BUFFER_SIZE ? MAX_BUFFER_SIZE : correctBufferLength;\n }\n\n /**\n * Fills the buffer's viewport with blank lines.\n */\n public fillViewportRows(fillAttr?: IAttributeData): void {\n if (this.lines.length === 0) {\n if (fillAttr === undefined) {\n fillAttr = DEFAULT_ATTR_DATA;\n }\n let i = this._rows;\n while (i--) {\n this.lines.push(this.getBlankLine(fillAttr));\n }\n }\n }\n\n /**\n * Clears the buffer to it's initial state, discarding all previous data.\n */\n public clear(): void {\n this.ydisp = 0;\n this.ybase = 0;\n this.y = 0;\n this.x = 0;\n this.lines = new CircularList(this._getCorrectBufferLength(this._rows));\n this.scrollTop = 0;\n this.scrollBottom = this._rows - 1;\n this.setupTabStops();\n }\n\n /**\n * Resizes the buffer, adjusting its data accordingly.\n * @param newCols The new number of columns.\n * @param newRows The new number of rows.\n */\n public resize(newCols: number, newRows: number): void {\n // store reference to null cell with default attrs\n const nullCell = this.getNullCell(DEFAULT_ATTR_DATA);\n\n // count bufferlines with overly big memory to be cleaned afterwards\n let dirtyMemoryLines = 0;\n\n // Increase max length if needed before adjustments to allow space to fill\n // as required.\n const newMaxLength = this._getCorrectBufferLength(newRows);\n if (newMaxLength > this.lines.maxLength) {\n this.lines.maxLength = newMaxLength;\n }\n\n // if (this._cols > newCols) {\n // console.log('increase!');\n // }\n\n // The following adjustments should only happen if the buffer has been\n // initialized/filled.\n if (this.lines.length > 0) {\n // Deal with columns increasing (reducing needs to happen after reflow)\n if (this._cols < newCols) {\n for (let i = 0; i < this.lines.length; i++) {\n // +boolean for fast 0 or 1 conversion\n dirtyMemoryLines += +this.lines.get(i)!.resize(newCols, nullCell);\n }\n }\n\n // Resize rows in both directions as needed\n let addToY = 0;\n if (this._rows < newRows) {\n for (let y = this._rows; y < newRows; y++) {\n if (this.lines.length < newRows + this.ybase) {\n if (this._optionsService.rawOptions.windowsMode || this._optionsService.rawOptions.windowsPty.backend !== undefined || this._optionsService.rawOptions.windowsPty.buildNumber !== undefined) {\n // Just add the new missing rows on Windows as conpty reprints the screen with it's\n // view of the world. Once a line enters scrollback for conpty it remains there\n this.lines.push(new BufferLine(newCols, nullCell));\n } else {\n if (this.ybase > 0 && this.lines.length <= this.ybase + this.y + addToY + 1) {\n // There is room above the buffer and there are no empty elements below the line,\n // scroll up\n this.ybase--;\n addToY++;\n if (this.ydisp > 0) {\n // Viewport is at the top of the buffer, must increase downwards\n this.ydisp--;\n }\n } else {\n // Add a blank line if there is no buffer left at the top to scroll to, or if there\n // are blank lines after the cursor\n this.lines.push(new BufferLine(newCols, nullCell));\n }\n }\n }\n }\n } else { // (this._rows >= newRows)\n for (let y = this._rows; y > newRows; y--) {\n if (this.lines.length > newRows + this.ybase) {\n if (this.lines.length > this.ybase + this.y + 1) {\n // The line is a blank line below the cursor, remove it\n this.lines.pop();\n } else {\n // The line is the cursor, scroll down\n this.ybase++;\n this.ydisp++;\n }\n }\n }\n }\n\n // Reduce max length if needed after adjustments, this is done after as it\n // would otherwise cut data from the bottom of the buffer.\n if (newMaxLength < this.lines.maxLength) {\n // Trim from the top of the buffer and adjust ybase and ydisp.\n const amountToTrim = this.lines.length - newMaxLength;\n if (amountToTrim > 0) {\n this.lines.trimStart(amountToTrim);\n this.ybase = Math.max(this.ybase - amountToTrim, 0);\n this.ydisp = Math.max(this.ydisp - amountToTrim, 0);\n this.savedY = Math.max(this.savedY - amountToTrim, 0);\n }\n this.lines.maxLength = newMaxLength;\n }\n\n // Make sure that the cursor stays on screen\n this.x = Math.min(this.x, newCols - 1);\n this.y = Math.min(this.y, newRows - 1);\n if (addToY) {\n this.y += addToY;\n }\n this.savedX = Math.min(this.savedX, newCols - 1);\n\n this.scrollTop = 0;\n }\n\n this.scrollBottom = newRows - 1;\n\n if (this._isReflowEnabled) {\n this._reflow(newCols, newRows);\n\n // Trim the end of the line off if cols shrunk\n if (this._cols > newCols) {\n for (let i = 0; i < this.lines.length; i++) {\n // +boolean for fast 0 or 1 conversion\n dirtyMemoryLines += +this.lines.get(i)!.resize(newCols, nullCell);\n }\n }\n }\n\n this._cols = newCols;\n this._rows = newRows;\n\n this._memoryCleanupQueue.clear();\n // schedule memory cleanup only, if more than 10% of the lines are affected\n if (dirtyMemoryLines > 0.1 * this.lines.length) {\n this._memoryCleanupPosition = 0;\n this._memoryCleanupQueue.enqueue(() => this._batchedMemoryCleanup());\n }\n }\n\n private _memoryCleanupQueue = new IdleTaskQueue();\n private _memoryCleanupPosition = 0;\n\n private _batchedMemoryCleanup(): boolean {\n let normalRun = true;\n if (this._memoryCleanupPosition >= this.lines.length) {\n // cleanup made it once through all lines, thus rescan in loop below to also catch shifted\n // lines, which should finish rather quick if there are no more cleanups pending\n this._memoryCleanupPosition = 0;\n normalRun = false;\n }\n let counted = 0;\n while (this._memoryCleanupPosition < this.lines.length) {\n counted += this.lines.get(this._memoryCleanupPosition++)!.cleanupMemory();\n // cleanup max 100 lines per batch\n if (counted > 100) {\n return true;\n }\n }\n // normal runs always need another rescan afterwards\n // if we made it here with normalRun=false, we are in a final run\n // and can end the cleanup task for sure\n return normalRun;\n }\n\n private get _isReflowEnabled(): boolean {\n const windowsPty = this._optionsService.rawOptions.windowsPty;\n if (windowsPty && windowsPty.buildNumber) {\n return this._hasScrollback && windowsPty.backend === 'conpty' && windowsPty.buildNumber >= 21376;\n }\n return this._hasScrollback && !this._optionsService.rawOptions.windowsMode;\n }\n\n private _reflow(newCols: number, newRows: number): void {\n if (this._cols === newCols) {\n return;\n }\n\n // Iterate through rows, ignore the last one as it cannot be wrapped\n if (newCols > this._cols) {\n this._reflowLarger(newCols, newRows);\n } else {\n this._reflowSmaller(newCols, newRows);\n }\n }\n\n private _reflowLarger(newCols: number, newRows: number): void {\n const reflowCursorLine = this._optionsService.rawOptions.reflowCursorLine;\n const toRemove: number[] = reflowLargerGetLinesToRemove(this.lines, this._cols, newCols, this.ybase + this.y, this.getNullCell(DEFAULT_ATTR_DATA), reflowCursorLine);\n if (toRemove.length > 0) {\n const newLayoutResult = reflowLargerCreateNewLayout(this.lines, toRemove);\n reflowLargerApplyNewLayout(this.lines, newLayoutResult.layout);\n this._reflowLargerAdjustViewport(newCols, newRows, newLayoutResult.countRemoved);\n }\n }\n\n private _reflowLargerAdjustViewport(newCols: number, newRows: number, countRemoved: number): void {\n const nullCell = this.getNullCell(DEFAULT_ATTR_DATA);\n // Adjust viewport based on number of items removed\n let viewportAdjustments = countRemoved;\n while (viewportAdjustments-- > 0) {\n if (this.ybase === 0) {\n if (this.y > 0) {\n this.y--;\n }\n if (this.lines.length < newRows) {\n // Add an extra row at the bottom of the viewport\n this.lines.push(new BufferLine(newCols, nullCell));\n }\n } else {\n if (this.ydisp === this.ybase) {\n this.ydisp--;\n }\n this.ybase--;\n }\n }\n this.savedY = Math.max(this.savedY - countRemoved, 0);\n }\n\n private _reflowSmaller(newCols: number, newRows: number): void {\n const reflowCursorLine = this._optionsService.rawOptions.reflowCursorLine;\n const nullCell = this.getNullCell(DEFAULT_ATTR_DATA);\n // Gather all BufferLines that need to be inserted into the Buffer here so that they can be\n // batched up and only committed once\n const toInsert = [];\n let countToInsert = 0;\n // Go backwards as many lines may be trimmed and this will avoid considering them\n for (let y = this.lines.length - 1; y >= 0; y--) {\n // Check whether this line is a problem\n let nextLine = this.lines.get(y) as BufferLine;\n if (!nextLine || !nextLine.isWrapped && nextLine.getTrimmedLength() <= newCols) {\n continue;\n }\n\n // Gather wrapped lines and adjust y to be the starting line\n const wrappedLines: BufferLine[] = [nextLine];\n while (nextLine.isWrapped && y > 0) {\n nextLine = this.lines.get(--y) as BufferLine;\n wrappedLines.unshift(nextLine);\n }\n\n if (!reflowCursorLine) {\n // If these lines contain the cursor don't touch them, the program will handle fixing up\n // wrapped lines with the cursor\n const absoluteY = this.ybase + this.y;\n if (absoluteY >= y && absoluteY < y + wrappedLines.length) {\n continue;\n }\n }\n\n const lastLineLength = wrappedLines[wrappedLines.length - 1].getTrimmedLength();\n const destLineLengths = reflowSmallerGetNewLineLengths(wrappedLines, this._cols, newCols);\n const linesToAdd = destLineLengths.length - wrappedLines.length;\n let trimmedLines: number;\n if (this.ybase === 0 && this.y !== this.lines.length - 1) {\n // If the top section of the buffer is not yet filled\n trimmedLines = Math.max(0, this.y - this.lines.maxLength + linesToAdd);\n } else {\n trimmedLines = Math.max(0, this.lines.length - this.lines.maxLength + linesToAdd);\n }\n\n // Add the new lines\n const newLines: BufferLine[] = [];\n for (let i = 0; i < linesToAdd; i++) {\n const newLine = this.getBlankLine(DEFAULT_ATTR_DATA, true) as BufferLine;\n newLines.push(newLine);\n }\n if (newLines.length > 0) {\n toInsert.push({\n // countToInsert here gets the actual index, taking into account other inserted items.\n // using this we can iterate through the list forwards\n start: y + wrappedLines.length + countToInsert,\n newLines\n });\n countToInsert += newLines.length;\n }\n wrappedLines.push(...newLines);\n\n // Copy buffer data to new locations, this needs to happen backwards to do in-place\n let destLineIndex = destLineLengths.length - 1; // Math.floor(cellsNeeded / newCols);\n let destCol = destLineLengths[destLineIndex]; // cellsNeeded % newCols;\n if (destCol === 0) {\n destLineIndex--;\n destCol = destLineLengths[destLineIndex];\n }\n let srcLineIndex = wrappedLines.length - linesToAdd - 1;\n let srcCol = lastLineLength;\n while (srcLineIndex >= 0) {\n const cellsToCopy = Math.min(srcCol, destCol);\n if (wrappedLines[destLineIndex] === undefined) {\n // Sanity check that the line exists, this has been known to fail for an unknown reason\n // which would stop the reflow from happening if an exception would throw.\n break;\n }\n wrappedLines[destLineIndex].copyCellsFrom(wrappedLines[srcLineIndex], srcCol - cellsToCopy, destCol - cellsToCopy, cellsToCopy, true);\n destCol -= cellsToCopy;\n if (destCol === 0) {\n destLineIndex--;\n destCol = destLineLengths[destLineIndex];\n }\n srcCol -= cellsToCopy;\n if (srcCol === 0) {\n srcLineIndex--;\n const wrappedLinesIndex = Math.max(srcLineIndex, 0);\n srcCol = getWrappedLineTrimmedLength(wrappedLines, wrappedLinesIndex, this._cols);\n }\n }\n\n // Null out the end of the line ends if a wide character wrapped to the following line\n for (let i = 0; i < wrappedLines.length; i++) {\n if (destLineLengths[i] < newCols) {\n wrappedLines[i].setCell(destLineLengths[i], nullCell);\n }\n }\n\n // Adjust viewport as needed\n let viewportAdjustments = linesToAdd - trimmedLines;\n while (viewportAdjustments-- > 0) {\n if (this.ybase === 0) {\n if (this.y < newRows - 1) {\n this.y++;\n this.lines.pop();\n } else {\n this.ybase++;\n this.ydisp++;\n }\n } else {\n // Ensure ybase does not exceed its maximum value\n if (this.ybase < Math.min(this.lines.maxLength, this.lines.length + countToInsert) - newRows) {\n if (this.ybase === this.ydisp) {\n this.ydisp++;\n }\n this.ybase++;\n }\n }\n }\n this.savedY = Math.min(this.savedY + linesToAdd, this.ybase + newRows - 1);\n }\n\n // Rearrange lines in the buffer if there are any insertions, this is done at the end rather\n // than earlier so that it's a single O(n) pass through the buffer, instead of O(n^2) from many\n // costly calls to CircularList.splice.\n if (toInsert.length > 0) {\n // Record buffer insert events and then play them back backwards so that the indexes are\n // correct\n const insertEvents: IInsertEvent[] = [];\n\n // Record original lines so they don't get overridden when we rearrange the list\n const originalLines: BufferLine[] = [];\n for (let i = 0; i < this.lines.length; i++) {\n originalLines.push(this.lines.get(i) as BufferLine);\n }\n const originalLinesLength = this.lines.length;\n\n let originalLineIndex = originalLinesLength - 1;\n let nextToInsertIndex = 0;\n let nextToInsert = toInsert[nextToInsertIndex];\n this.lines.length = Math.min(this.lines.maxLength, this.lines.length + countToInsert);\n let countInsertedSoFar = 0;\n for (let i = Math.min(this.lines.maxLength - 1, originalLinesLength + countToInsert - 1); i >= 0; i--) {\n if (nextToInsert && nextToInsert.start > originalLineIndex + countInsertedSoFar) {\n // Insert extra lines here, adjusting i as needed\n for (let nextI = nextToInsert.newLines.length - 1; nextI >= 0; nextI--) {\n this.lines.set(i--, nextToInsert.newLines[nextI]);\n }\n i++;\n\n // Create insert events for later\n insertEvents.push({\n index: originalLineIndex + 1,\n amount: nextToInsert.newLines.length\n });\n\n countInsertedSoFar += nextToInsert.newLines.length;\n nextToInsert = toInsert[++nextToInsertIndex];\n } else {\n this.lines.set(i, originalLines[originalLineIndex--]);\n }\n }\n\n // Update markers\n let insertCountEmitted = 0;\n for (let i = insertEvents.length - 1; i >= 0; i--) {\n insertEvents[i].index += insertCountEmitted;\n this.lines.onInsertEmitter.fire(insertEvents[i]);\n insertCountEmitted += insertEvents[i].amount;\n }\n const amountToTrim = Math.max(0, originalLinesLength + countToInsert - this.lines.maxLength);\n if (amountToTrim > 0) {\n this.lines.onTrimEmitter.fire(amountToTrim);\n }\n }\n }\n\n /**\n * Translates a buffer line to a string, with optional start and end columns.\n * Wide characters will count as two columns in the resulting string. This\n * function is useful for getting the actual text underneath the raw selection\n * position.\n * @param lineIndex The absolute index of the line being translated.\n * @param trimRight Whether to trim whitespace to the right.\n * @param startCol The column to start at.\n * @param endCol The column to end at.\n */\n public translateBufferLineToString(lineIndex: number, trimRight: boolean, startCol: number = 0, endCol?: number): string {\n const line = this.lines.get(lineIndex);\n if (!line) {\n return '';\n }\n return line.translateToString(trimRight, startCol, endCol);\n }\n\n public getWrappedRangeForLine(y: number): { first: number, last: number } {\n let first = y;\n let last = y;\n // Scan upwards for wrapped lines\n while (first > 0 && this.lines.get(first)!.isWrapped) {\n first--;\n }\n // Scan downwards for wrapped lines\n while (last + 1 < this.lines.length && this.lines.get(last + 1)!.isWrapped) {\n last++;\n }\n return { first, last };\n }\n\n /**\n * Setup the tab stops.\n * @param i The index to start setting up tab stops from.\n */\n public setupTabStops(i?: number): void {\n if (i !== null && i !== undefined) {\n if (!this.tabs[i]) {\n i = this.prevStop(i);\n }\n } else {\n this.tabs = {};\n i = 0;\n }\n\n for (; i < this._cols; i += this._optionsService.rawOptions.tabStopWidth) {\n this.tabs[i] = true;\n }\n }\n\n /**\n * Move the cursor to the previous tab stop from the given position (default is current).\n * @param x The position to move the cursor to the previous tab stop.\n */\n public prevStop(x?: number): number {\n if (x === null || x === undefined) {\n x = this.x;\n }\n while (!this.tabs[--x] && x > 0);\n return x >= this._cols ? this._cols - 1 : x < 0 ? 0 : x;\n }\n\n /**\n * Move the cursor one tab stop forward from the given position (default is current).\n * @param x The position to move the cursor one tab stop forward.\n */\n public nextStop(x?: number): number {\n if (x === null || x === undefined) {\n x = this.x;\n }\n while (!this.tabs[++x] && x < this._cols);\n return x >= this._cols ? this._cols - 1 : x < 0 ? 0 : x;\n }\n\n /**\n * Clears markers on single line.\n * @param y The line to clear.\n */\n public clearMarkers(y: number): void {\n this._isClearing = true;\n for (let i = 0; i < this.markers.length; i++) {\n if (this.markers[i].line === y) {\n this.markers[i].dispose();\n this.markers.splice(i--, 1);\n }\n }\n this._isClearing = false;\n }\n\n /**\n * Clears markers on all lines\n */\n public clearAllMarkers(): void {\n this._isClearing = true;\n for (let i = 0; i < this.markers.length; i++) {\n this.markers[i].dispose();\n }\n this.markers.length = 0;\n this._isClearing = false;\n }\n\n public addMarker(y: number): Marker {\n const marker = new Marker(y);\n this.markers.push(marker);\n marker.register(this.lines.onTrim(amount => {\n marker.line -= amount;\n // The marker should be disposed when the line is trimmed from the buffer\n if (marker.line < 0) {\n marker.dispose();\n }\n }));\n marker.register(this.lines.onInsert(event => {\n if (marker.line >= event.index) {\n marker.line += event.amount;\n }\n }));\n marker.register(this.lines.onDelete(event => {\n // Delete the marker if it's within the range\n if (marker.line >= event.index && marker.line < event.index + event.amount) {\n marker.dispose();\n }\n\n // Shift the marker if it's after the deleted range\n if (marker.line > event.index) {\n marker.line -= event.amount;\n }\n }));\n marker.register(marker.onDispose(() => this._removeMarker(marker)));\n return marker;\n }\n\n private _removeMarker(marker: Marker): void {\n if (!this._isClearing) {\n this.markers.splice(this.markers.indexOf(marker), 1);\n }\n }\n}\n", "/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { Disposable } from 'vs/base/common/lifecycle';\nimport { IAttributeData } from 'common/Types';\nimport { Buffer } from 'common/buffer/Buffer';\nimport { IBuffer, IBufferSet } from 'common/buffer/Types';\nimport { IBufferService, IOptionsService } from 'common/services/Services';\nimport { Emitter } from 'vs/base/common/event';\n\n/**\n * The BufferSet represents the set of two buffers used by xterm terminals (normal and alt) and\n * provides also utilities for working with them.\n */\nexport class BufferSet extends Disposable implements IBufferSet {\n private _normal!: Buffer;\n private _alt!: Buffer;\n private _activeBuffer!: Buffer;\n\n private readonly _onBufferActivate = this._register(new Emitter<{ activeBuffer: IBuffer, inactiveBuffer: IBuffer }>());\n public readonly onBufferActivate = this._onBufferActivate.event;\n\n /**\n * Create a new BufferSet for the given terminal.\n */\n constructor(\n private readonly _optionsService: IOptionsService,\n private readonly _bufferService: IBufferService\n ) {\n super();\n this.reset();\n this._register(this._optionsService.onSpecificOptionChange('scrollback', () => this.resize(this._bufferService.cols, this._bufferService.rows)));\n this._register(this._optionsService.onSpecificOptionChange('tabStopWidth', () => this.setupTabStops()));\n }\n\n public reset(): void {\n this._normal = new Buffer(true, this._optionsService, this._bufferService);\n this._normal.fillViewportRows();\n\n // The alt buffer should never have scrollback.\n // See http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h2-The-Alternate-Screen-Buffer\n this._alt = new Buffer(false, this._optionsService, this._bufferService);\n this._activeBuffer = this._normal;\n this._onBufferActivate.fire({\n activeBuffer: this._normal,\n inactiveBuffer: this._alt\n });\n\n this.setupTabStops();\n }\n\n /**\n * Returns the alt Buffer of the BufferSet\n */\n public get alt(): Buffer {\n return this._alt;\n }\n\n /**\n * Returns the currently active Buffer of the BufferSet\n */\n public get active(): Buffer {\n return this._activeBuffer;\n }\n\n /**\n * Returns the normal Buffer of the BufferSet\n */\n public get normal(): Buffer {\n return this._normal;\n }\n\n /**\n * Sets the normal Buffer of the BufferSet as its currently active Buffer\n */\n public activateNormalBuffer(): void {\n if (this._activeBuffer === this._normal) {\n return;\n }\n this._normal.x = this._alt.x;\n this._normal.y = this._alt.y;\n // The alt buffer should always be cleared when we switch to the normal\n // buffer. This frees up memory since the alt buffer should always be new\n // when activated.\n this._alt.clearAllMarkers();\n this._alt.clear();\n this._activeBuffer = this._normal;\n this._onBufferActivate.fire({\n activeBuffer: this._normal,\n inactiveBuffer: this._alt\n });\n }\n\n /**\n * Sets the alt Buffer of the BufferSet as its currently active Buffer\n */\n public activateAltBuffer(fillAttr?: IAttributeData): void {\n if (this._activeBuffer === this._alt) {\n return;\n }\n // Since the alt buffer is always cleared when the normal buffer is\n // activated, we want to fill it when switching to it.\n this._alt.fillViewportRows(fillAttr);\n this._alt.x = this._normal.x;\n this._alt.y = this._normal.y;\n this._activeBuffer = this._alt;\n this._onBufferActivate.fire({\n activeBuffer: this._alt,\n inactiveBuffer: this._normal\n });\n }\n\n /**\n * Resizes both normal and alt buffers, adjusting their data accordingly.\n * @param newCols The new number of columns.\n * @param newRows The new number of rows.\n */\n public resize(newCols: number, newRows: number): void {\n this._normal.resize(newCols, newRows);\n this._alt.resize(newCols, newRows);\n this.setupTabStops(newCols);\n }\n\n /**\n * Setup the tab stops.\n * @param i The index to start setting up tab stops from.\n */\n public setupTabStops(i?: number): void {\n this._normal.setupTabStops(i);\n this._alt.setupTabStops(i);\n }\n}\n", "/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { Disposable } from 'vs/base/common/lifecycle';\nimport { IAttributeData, IBufferLine } from 'common/Types';\nimport { BufferSet } from 'common/buffer/BufferSet';\nimport { IBuffer, IBufferSet } from 'common/buffer/Types';\nimport { IBufferService, IOptionsService, type IBufferResizeEvent } from 'common/services/Services';\nimport { Emitter } from 'vs/base/common/event';\n\nexport const MINIMUM_COLS = 2; // Less than 2 can mess with wide chars\nexport const MINIMUM_ROWS = 1;\n\nexport class BufferService extends Disposable implements IBufferService {\n public serviceBrand: any;\n\n public cols: number;\n public rows: number;\n public buffers: IBufferSet;\n /** Whether the user is scrolling (locks the scroll position) */\n public isUserScrolling: boolean = false;\n\n private readonly _onResize = this._register(new Emitter());\n public readonly onResize = this._onResize.event;\n private readonly _onScroll = this._register(new Emitter());\n public readonly onScroll = this._onScroll.event;\n\n public get buffer(): IBuffer { return this.buffers.active; }\n\n /** An IBufferline to clone/copy from for new blank lines */\n private _cachedBlankLine: IBufferLine | undefined;\n\n constructor(@IOptionsService optionsService: IOptionsService) {\n super();\n this.cols = Math.max(optionsService.rawOptions.cols || 0, MINIMUM_COLS);\n this.rows = Math.max(optionsService.rawOptions.rows || 0, MINIMUM_ROWS);\n this.buffers = this._register(new BufferSet(optionsService, this));\n this._register(this.buffers.onBufferActivate(e => {\n this._onScroll.fire(e.activeBuffer.ydisp);\n }));\n }\n\n public resize(cols: number, rows: number): void {\n const colsChanged = this.cols !== cols;\n const rowsChanged = this.rows !== rows;\n this.cols = cols;\n this.rows = rows;\n this.buffers.resize(cols, rows);\n this._onResize.fire({ cols, rows, colsChanged, rowsChanged });\n }\n\n public reset(): void {\n this.buffers.reset();\n this.isUserScrolling = false;\n }\n\n /**\n * Scroll the terminal down 1 row, creating a blank line.\n * @param eraseAttr The attribute data to use the for blank line.\n * @param isWrapped Whether the new line is wrapped from the previous line.\n */\n public scroll(eraseAttr: IAttributeData, isWrapped: boolean = false): void {\n const buffer = this.buffer;\n\n let newLine: IBufferLine | undefined;\n newLine = this._cachedBlankLine;\n if (!newLine || newLine.length !== this.cols || newLine.getFg(0) !== eraseAttr.fg || newLine.getBg(0) !== eraseAttr.bg) {\n newLine = buffer.getBlankLine(eraseAttr, isWrapped);\n this._cachedBlankLine = newLine;\n }\n newLine.isWrapped = isWrapped;\n\n const topRow = buffer.ybase + buffer.scrollTop;\n const bottomRow = buffer.ybase + buffer.scrollBottom;\n\n if (buffer.scrollTop === 0) {\n // Determine whether the buffer is going to be trimmed after insertion.\n const willBufferBeTrimmed = buffer.lines.isFull;\n\n // Insert the line using the fastest method\n if (bottomRow === buffer.lines.length - 1) {\n if (willBufferBeTrimmed) {\n buffer.lines.recycle().copyFrom(newLine);\n } else {\n buffer.lines.push(newLine.clone());\n }\n } else {\n buffer.lines.splice(bottomRow + 1, 0, newLine.clone());\n }\n\n // Only adjust ybase and ydisp when the buffer is not trimmed\n if (!willBufferBeTrimmed) {\n buffer.ybase++;\n // Only scroll the ydisp with ybase if the user has not scrolled up\n if (!this.isUserScrolling) {\n buffer.ydisp++;\n }\n } else {\n // When the buffer is full and the user has scrolled up, keep the text\n // stable unless ydisp is right at the top\n if (this.isUserScrolling) {\n buffer.ydisp = Math.max(buffer.ydisp - 1, 0);\n }\n }\n } else {\n // scrollTop is non-zero which means no line will be going to the\n // scrollback, instead we can just shift them in-place.\n const scrollRegionHeight = bottomRow - topRow + 1 /* as it's zero-based */;\n buffer.lines.shiftElements(topRow + 1, scrollRegionHeight - 1, -1);\n buffer.lines.set(bottomRow, newLine.clone());\n }\n\n // Move the viewport to the bottom of the buffer unless the user is\n // scrolling.\n if (!this.isUserScrolling) {\n buffer.ydisp = buffer.ybase;\n }\n\n this._onScroll.fire(buffer.ydisp);\n }\n\n /**\n * Scroll the display of the terminal\n * @param disp The number of lines to scroll down (negative scroll up).\n * @param suppressScrollEvent Don't emit the scroll event as scrollLines. This is used\n * to avoid unwanted events being handled by the viewport when the event was triggered from the\n * viewport originally.\n */\n public scrollLines(disp: number, suppressScrollEvent?: boolean): void {\n const buffer = this.buffer;\n if (disp < 0) {\n if (buffer.ydisp === 0) {\n return;\n }\n this.isUserScrolling = true;\n } else if (disp + buffer.ydisp >= buffer.ybase) {\n this.isUserScrolling = false;\n }\n\n const oldYdisp = buffer.ydisp;\n buffer.ydisp = Math.max(Math.min(buffer.ydisp + disp, buffer.ybase), 0);\n\n // No change occurred, don't trigger scroll/refresh\n if (oldYdisp === buffer.ydisp) {\n return;\n }\n\n if (!suppressScrollEvent) {\n this._onScroll.fire(buffer.ydisp);\n }\n }\n}\n", "/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { Disposable, toDisposable } from 'vs/base/common/lifecycle';\nimport { isMac } from 'common/Platform';\nimport { CursorStyle, IDisposable } from 'common/Types';\nimport { FontWeight, IOptionsService, ITerminalOptions } from 'common/services/Services';\nimport { Emitter } from 'vs/base/common/event';\n\nexport const DEFAULT_OPTIONS: Readonly> = {\n cols: 80,\n rows: 24,\n cursorBlink: false,\n cursorStyle: 'block',\n cursorWidth: 1,\n cursorInactiveStyle: 'outline',\n customGlyphs: true,\n drawBoldTextInBrightColors: true,\n documentOverride: null,\n fastScrollModifier: 'alt',\n fastScrollSensitivity: 5,\n fontFamily: 'monospace',\n fontSize: 15,\n fontWeight: 'normal',\n fontWeightBold: 'bold',\n ignoreBracketedPasteMode: false,\n lineHeight: 1.0,\n letterSpacing: 0,\n linkHandler: null,\n logLevel: 'info',\n logger: null,\n scrollback: 1000,\n scrollOnEraseInDisplay: false,\n scrollOnUserInput: true,\n scrollSensitivity: 1,\n screenReaderMode: false,\n smoothScrollDuration: 0,\n macOptionIsMeta: false,\n macOptionClickForcesSelection: false,\n minimumContrastRatio: 1,\n disableStdin: false,\n allowProposedApi: false,\n allowTransparency: false,\n tabStopWidth: 8,\n theme: {},\n reflowCursorLine: false,\n rescaleOverlappingGlyphs: false,\n rightClickSelectsWord: isMac,\n windowOptions: {},\n windowsMode: false,\n windowsPty: {},\n wordSeparator: ' ()[]{}\\',\"`',\n altClickMovesCursor: true,\n convertEol: false,\n termName: 'xterm',\n cancelEvents: false,\n overviewRuler: {}\n};\n\nconst FONT_WEIGHT_OPTIONS: Extract[] = ['normal', 'bold', '100', '200', '300', '400', '500', '600', '700', '800', '900'];\n\nexport class OptionsService extends Disposable implements IOptionsService {\n public serviceBrand: any;\n\n public readonly rawOptions: Required;\n public options: Required;\n\n private readonly _onOptionChange = this._register(new Emitter());\n public readonly onOptionChange = this._onOptionChange.event;\n\n constructor(options: Partial) {\n super();\n // set the default value of each option\n const defaultOptions = { ...DEFAULT_OPTIONS };\n for (const key in options) {\n if (key in defaultOptions) {\n try {\n const newValue = options[key];\n defaultOptions[key] = this._sanitizeAndValidateOption(key, newValue);\n } catch (e) {\n console.error(e);\n }\n }\n }\n\n // set up getters and setters for each option\n this.rawOptions = defaultOptions;\n this.options = { ... defaultOptions };\n this._setupOptions();\n\n // Clear out options that could link outside xterm.js as they could easily cause an embedder\n // memory leak\n this._register(toDisposable(() => {\n this.rawOptions.linkHandler = null;\n this.rawOptions.documentOverride = null;\n }));\n }\n\n // eslint-disable-next-line @typescript-eslint/naming-convention\n public onSpecificOptionChange(key: T, listener: (value: ITerminalOptions[T]) => any): IDisposable {\n return this.onOptionChange(eventKey => {\n if (eventKey === key) {\n listener(this.rawOptions[key]);\n }\n });\n }\n\n // eslint-disable-next-line @typescript-eslint/naming-convention\n public onMultipleOptionChange(keys: (keyof ITerminalOptions)[], listener: () => any): IDisposable {\n return this.onOptionChange(eventKey => {\n if (keys.indexOf(eventKey) !== -1) {\n listener();\n }\n });\n }\n\n private _setupOptions(): void {\n const getter = (propName: string): any => {\n if (!(propName in DEFAULT_OPTIONS)) {\n throw new Error(`No option with key \"${propName}\"`);\n }\n return this.rawOptions[propName];\n };\n\n const setter = (propName: string, value: any): void => {\n if (!(propName in DEFAULT_OPTIONS)) {\n throw new Error(`No option with key \"${propName}\"`);\n }\n\n value = this._sanitizeAndValidateOption(propName, value);\n // Don't fire an option change event if they didn't change\n if (this.rawOptions[propName] !== value) {\n this.rawOptions[propName] = value;\n this._onOptionChange.fire(propName);\n }\n };\n\n for (const propName in this.rawOptions) {\n const desc = {\n get: getter.bind(this, propName),\n set: setter.bind(this, propName)\n };\n Object.defineProperty(this.options, propName, desc);\n }\n }\n\n private _sanitizeAndValidateOption(key: string, value: any): any {\n switch (key) {\n case 'cursorStyle':\n if (!value) {\n value = DEFAULT_OPTIONS[key];\n }\n if (!isCursorStyle(value)) {\n throw new Error(`\"${value}\" is not a valid value for ${key}`);\n }\n break;\n case 'wordSeparator':\n if (!value) {\n value = DEFAULT_OPTIONS[key];\n }\n break;\n case 'fontWeight':\n case 'fontWeightBold':\n if (typeof value === 'number' && 1 <= value && value <= 1000) {\n // already valid numeric value\n break;\n }\n value = FONT_WEIGHT_OPTIONS.includes(value) ? value : DEFAULT_OPTIONS[key];\n break;\n case 'cursorWidth':\n value = Math.floor(value);\n // Fall through for bounds check\n case 'lineHeight':\n case 'tabStopWidth':\n if (value < 1) {\n throw new Error(`${key} cannot be less than 1, value: ${value}`);\n }\n break;\n case 'minimumContrastRatio':\n value = Math.max(1, Math.min(21, Math.round(value * 10) / 10));\n break;\n case 'scrollback':\n value = Math.min(value, 4294967295);\n if (value < 0) {\n throw new Error(`${key} cannot be less than 0, value: ${value}`);\n }\n break;\n case 'fastScrollSensitivity':\n case 'scrollSensitivity':\n if (value <= 0) {\n throw new Error(`${key} cannot be less than or equal to 0, value: ${value}`);\n }\n break;\n case 'rows':\n case 'cols':\n if (!value && value !== 0) {\n throw new Error(`${key} must be numeric, value: ${value}`);\n }\n break;\n case 'windowsPty':\n value = value ?? {};\n break;\n }\n return value;\n }\n}\n\nfunction isCursorStyle(value: unknown): value is CursorStyle {\n return value === 'block' || value === 'underline' || value === 'bar';\n}\n", "/**\n * Copyright (c) 2016 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\n/*\n * A simple utility for cloning values\n */\nexport function clone(val: T, depth: number = 5): T {\n if (typeof val !== 'object') {\n return val;\n }\n\n // If we're cloning an array, use an array as the base, otherwise use an object\n const clonedObject: any = Array.isArray(val) ? [] : {};\n\n for (const key in val) {\n // Recursively clone eack item unless we're at the maximum depth\n clonedObject[key] = depth <= 1 ? val[key] : (val[key] && clone(val[key], depth - 1));\n }\n\n return clonedObject as T;\n}\n", "/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { clone } from 'common/Clone';\nimport { Disposable } from 'vs/base/common/lifecycle';\nimport { IDecPrivateModes, IModes } from 'common/Types';\nimport { IBufferService, ICoreService, ILogService, IOptionsService } from 'common/services/Services';\nimport { Emitter } from 'vs/base/common/event';\n\nconst DEFAULT_MODES: IModes = Object.freeze({\n insertMode: false\n});\n\nconst DEFAULT_DEC_PRIVATE_MODES: IDecPrivateModes = Object.freeze({\n applicationCursorKeys: false,\n applicationKeypad: false,\n bracketedPasteMode: false,\n cursorBlink: undefined,\n cursorStyle: undefined,\n origin: false,\n reverseWraparound: false,\n sendFocus: false,\n synchronizedOutput: false,\n wraparound: true // defaults: xterm - true, vt100 - false\n});\n\nexport class CoreService extends Disposable implements ICoreService {\n public serviceBrand: any;\n\n public isCursorInitialized: boolean = false;\n public isCursorHidden: boolean = false;\n public modes: IModes;\n public decPrivateModes: IDecPrivateModes;\n\n private readonly _onData = this._register(new Emitter());\n public readonly onData = this._onData.event;\n private readonly _onUserInput = this._register(new Emitter());\n public readonly onUserInput = this._onUserInput.event;\n private readonly _onBinary = this._register(new Emitter());\n public readonly onBinary = this._onBinary.event;\n private readonly _onRequestScrollToBottom = this._register(new Emitter());\n public readonly onRequestScrollToBottom = this._onRequestScrollToBottom.event;\n\n constructor(\n @IBufferService private readonly _bufferService: IBufferService,\n @ILogService private readonly _logService: ILogService,\n @IOptionsService private readonly _optionsService: IOptionsService\n ) {\n super();\n this.modes = clone(DEFAULT_MODES);\n this.decPrivateModes = clone(DEFAULT_DEC_PRIVATE_MODES);\n }\n\n public reset(): void {\n this.modes = clone(DEFAULT_MODES);\n this.decPrivateModes = clone(DEFAULT_DEC_PRIVATE_MODES);\n }\n\n public triggerDataEvent(data: string, wasUserInput: boolean = false): void {\n // Prevents all events to pty process if stdin is disabled\n if (this._optionsService.rawOptions.disableStdin) {\n return;\n }\n\n // Input is being sent to the terminal, the terminal should focus the prompt.\n const buffer = this._bufferService.buffer;\n if (wasUserInput && this._optionsService.rawOptions.scrollOnUserInput && buffer.ybase !== buffer.ydisp) {\n this._onRequestScrollToBottom.fire();\n }\n\n // Fire onUserInput so listeners can react as well (eg. clear selection)\n if (wasUserInput) {\n this._onUserInput.fire();\n }\n\n // Fire onData API\n this._logService.debug(`sending data \"${data}\"`);\n this._logService.trace(`sending data (codes)`, () => data.split('').map(e => e.charCodeAt(0)));\n this._onData.fire(data);\n }\n\n public triggerBinaryEvent(data: string): void {\n if (this._optionsService.rawOptions.disableStdin) {\n return;\n }\n this._logService.debug(`sending binary \"${data}\"`);\n this._logService.trace(`sending binary (codes)`, () => data.split('').map(e => e.charCodeAt(0)));\n this._onBinary.fire(data);\n }\n}\n", "/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\nimport { IBufferService, ICoreService, ICoreMouseService, IOptionsService } from 'common/services/Services';\nimport { ICoreMouseProtocol, ICoreMouseEvent, CoreMouseEncoding, CoreMouseEventType, CoreMouseButton, CoreMouseAction } from 'common/Types';\nimport { Disposable } from 'vs/base/common/lifecycle';\nimport { Emitter } from 'vs/base/common/event';\n\n/**\n * Supported default protocols.\n */\nconst DEFAULT_PROTOCOLS: { [key: string]: ICoreMouseProtocol } = {\n /**\n * NONE\n * Events: none\n * Modifiers: none\n */\n NONE: {\n events: CoreMouseEventType.NONE,\n restrict: () => false\n },\n /**\n * X10\n * Events: mousedown\n * Modifiers: none\n */\n X10: {\n events: CoreMouseEventType.DOWN,\n restrict: (e: ICoreMouseEvent) => {\n // no wheel, no move, no up\n if (e.button === CoreMouseButton.WHEEL || e.action !== CoreMouseAction.DOWN) {\n return false;\n }\n // no modifiers\n e.ctrl = false;\n e.alt = false;\n e.shift = false;\n return true;\n }\n },\n /**\n * VT200\n * Events: mousedown / mouseup / wheel\n * Modifiers: all\n */\n VT200: {\n events: CoreMouseEventType.DOWN | CoreMouseEventType.UP | CoreMouseEventType.WHEEL,\n restrict: (e: ICoreMouseEvent) => {\n // no move\n if (e.action === CoreMouseAction.MOVE) {\n return false;\n }\n return true;\n }\n },\n /**\n * DRAG\n * Events: mousedown / mouseup / wheel / mousedrag\n * Modifiers: all\n */\n DRAG: {\n events: CoreMouseEventType.DOWN | CoreMouseEventType.UP | CoreMouseEventType.WHEEL | CoreMouseEventType.DRAG,\n restrict: (e: ICoreMouseEvent) => {\n // no move without button\n if (e.action === CoreMouseAction.MOVE && e.button === CoreMouseButton.NONE) {\n return false;\n }\n return true;\n }\n },\n /**\n * ANY\n * Events: all mouse related events\n * Modifiers: all\n */\n ANY: {\n events:\n CoreMouseEventType.DOWN | CoreMouseEventType.UP | CoreMouseEventType.WHEEL\n | CoreMouseEventType.DRAG | CoreMouseEventType.MOVE,\n restrict: (e: ICoreMouseEvent) => true\n }\n};\n\nconst enum Modifiers {\n SHIFT = 4,\n ALT = 8,\n CTRL = 16\n}\n\n// helper for default encoders to generate the event code.\nfunction eventCode(e: ICoreMouseEvent, isSGR: boolean): number {\n let code = (e.ctrl ? Modifiers.CTRL : 0) | (e.shift ? Modifiers.SHIFT : 0) | (e.alt ? Modifiers.ALT : 0);\n if (e.button === CoreMouseButton.WHEEL) {\n code |= 64;\n code |= e.action;\n } else {\n code |= e.button & 3;\n if (e.button & 4) {\n code |= 64;\n }\n if (e.button & 8) {\n code |= 128;\n }\n if (e.action === CoreMouseAction.MOVE) {\n code |= CoreMouseAction.MOVE;\n } else if (e.action === CoreMouseAction.UP && !isSGR) {\n // special case - only SGR can report button on release\n // all others have to go with NONE\n code |= CoreMouseButton.NONE;\n }\n }\n return code;\n}\n\nconst S = String.fromCharCode;\n\n/**\n * Supported default encodings.\n */\nconst DEFAULT_ENCODINGS: { [key: string]: CoreMouseEncoding } = {\n /**\n * DEFAULT - CSI M Pb Px Py\n * Single byte encoding for coords and event code.\n * Can encode values up to 223 (1-based).\n */\n DEFAULT: (e: ICoreMouseEvent) => {\n const params = [eventCode(e, false) + 32, e.col + 32, e.row + 32];\n // supress mouse report if we exceed addressible range\n // Note this is handled differently by emulators\n // - xterm: sends 0;0 coords instead\n // - vte, konsole: no report\n if (params[0] > 255 || params[1] > 255 || params[2] > 255) {\n return '';\n }\n return `\\x1b[M${S(params[0])}${S(params[1])}${S(params[2])}`;\n },\n /**\n * SGR - CSI < Pb ; Px ; Py M|m\n * No encoding limitation.\n * Can report button on release and works with a well formed sequence.\n */\n SGR: (e: ICoreMouseEvent) => {\n const final = (e.action === CoreMouseAction.UP && e.button !== CoreMouseButton.WHEEL) ? 'm' : 'M';\n return `\\x1b[<${eventCode(e, true)};${e.col};${e.row}${final}`;\n },\n SGR_PIXELS: (e: ICoreMouseEvent) => {\n const final = (e.action === CoreMouseAction.UP && e.button !== CoreMouseButton.WHEEL) ? 'm' : 'M';\n return `\\x1b[<${eventCode(e, true)};${e.x};${e.y}${final}`;\n }\n};\n\n/**\n * CoreMouseService\n *\n * Provides mouse tracking reports with different protocols and encodings.\n * - protocols: NONE (default), X10, VT200, DRAG, ANY\n * - encodings: DEFAULT, SGR (UTF8, URXVT removed in #2507)\n *\n * Custom protocols/encodings can be added by `addProtocol` / `addEncoding`.\n * To activate a protocol/encoding, set `activeProtocol` / `activeEncoding`.\n * Switching a protocol will send a notification event `onProtocolChange`\n * with a list of needed events to track.\n *\n * The service handles the mouse tracking state and decides whether to send\n * a tracking report to the backend based on protocol and encoding limitations.\n * To send a mouse event call `triggerMouseEvent`.\n */\nexport class CoreMouseService extends Disposable implements ICoreMouseService {\n public serviceBrand: any;\n\n private _protocols: { [name: string]: ICoreMouseProtocol } = {};\n private _encodings: { [name: string]: CoreMouseEncoding } = {};\n private _activeProtocol: string = '';\n private _activeEncoding: string = '';\n private _lastEvent: ICoreMouseEvent | null = null;\n private _wheelPartialScroll: number = 0;\n\n private readonly _onProtocolChange = this._register(new Emitter());\n public readonly onProtocolChange = this._onProtocolChange.event;\n\n constructor(\n @IBufferService private readonly _bufferService: IBufferService,\n @ICoreService private readonly _coreService: ICoreService,\n @IOptionsService private readonly _optionsService: IOptionsService\n ) {\n super();\n // register default protocols and encodings\n for (const name of Object.keys(DEFAULT_PROTOCOLS)) this.addProtocol(name, DEFAULT_PROTOCOLS[name]);\n for (const name of Object.keys(DEFAULT_ENCODINGS)) this.addEncoding(name, DEFAULT_ENCODINGS[name]);\n // call reset to set defaults\n this.reset();\n }\n\n public addProtocol(name: string, protocol: ICoreMouseProtocol): void {\n this._protocols[name] = protocol;\n }\n\n public addEncoding(name: string, encoding: CoreMouseEncoding): void {\n this._encodings[name] = encoding;\n }\n\n public get activeProtocol(): string {\n return this._activeProtocol;\n }\n\n public get areMouseEventsActive(): boolean {\n return this._protocols[this._activeProtocol].events !== 0;\n }\n\n public set activeProtocol(name: string) {\n if (!this._protocols[name]) {\n throw new Error(`unknown protocol \"${name}\"`);\n }\n this._activeProtocol = name;\n this._onProtocolChange.fire(this._protocols[name].events);\n }\n\n public get activeEncoding(): string {\n return this._activeEncoding;\n }\n\n public set activeEncoding(name: string) {\n if (!this._encodings[name]) {\n throw new Error(`unknown encoding \"${name}\"`);\n }\n this._activeEncoding = name;\n }\n\n public reset(): void {\n this.activeProtocol = 'NONE';\n this.activeEncoding = 'DEFAULT';\n this._lastEvent = null;\n this._wheelPartialScroll = 0;\n }\n\n /**\n * Processes a wheel event, accounting for partial scrolls for trackpad, mouse scrolls.\n * This prevents hyper-sensitive scrolling in alt buffer.\n */\n public consumeWheelEvent(ev: WheelEvent, cellHeight?: number, dpr?: number): number {\n // Do nothing if it's not a vertical scroll event\n if (ev.deltaY === 0 || ev.shiftKey) {\n return 0;\n }\n\n if (cellHeight === undefined || dpr === undefined) {\n return 0;\n }\n\n const targetWheelEventPixels = cellHeight / dpr;\n let amount = this._applyScrollModifier(ev.deltaY, ev);\n\n if (ev.deltaMode === WheelEvent.DOM_DELTA_PIXEL) {\n amount /= (targetWheelEventPixels + 0.0); // Prevent integer division\n\n const isLikelyTrackpad = Math.abs(ev.deltaY) < 50;\n if (isLikelyTrackpad) {\n amount *= 0.3;\n }\n\n this._wheelPartialScroll += amount;\n amount = Math.floor(Math.abs(this._wheelPartialScroll)) * (this._wheelPartialScroll > 0 ? 1 : -1);\n this._wheelPartialScroll %= 1;\n } else if (ev.deltaMode === WheelEvent.DOM_DELTA_PAGE) {\n amount *= this._bufferService.rows;\n }\n return amount;\n }\n\n private _applyScrollModifier(amount: number, ev: WheelEvent): number {\n // Multiply the scroll speed when the modifier key is pressed\n if (ev.altKey || ev.ctrlKey || ev.shiftKey) {\n return amount * this._optionsService.rawOptions.fastScrollSensitivity * this._optionsService.rawOptions.scrollSensitivity;\n }\n return amount * this._optionsService.rawOptions.scrollSensitivity;\n }\n\n /**\n * Triggers a mouse event to be sent.\n *\n * Returns true if the event passed all protocol restrictions and a report\n * was sent, otherwise false. The return value may be used to decide whether\n * the default event action in the bowser component should be omitted.\n *\n * Note: The method will change values of the given event object\n * to fullfill protocol and encoding restrictions.\n */\n public triggerMouseEvent(e: ICoreMouseEvent): boolean {\n // range check for col/row\n if (e.col < 0 || e.col >= this._bufferService.cols\n || e.row < 0 || e.row >= this._bufferService.rows) {\n return false;\n }\n\n // filter nonsense combinations of button + action\n if (e.button === CoreMouseButton.WHEEL && e.action === CoreMouseAction.MOVE) {\n return false;\n }\n if (e.button === CoreMouseButton.NONE && e.action !== CoreMouseAction.MOVE) {\n return false;\n }\n if (e.button !== CoreMouseButton.WHEEL && (e.action === CoreMouseAction.LEFT || e.action === CoreMouseAction.RIGHT)) {\n return false;\n }\n\n // report 1-based coords\n e.col++;\n e.row++;\n\n // debounce move events at grid or pixel level\n if (e.action === CoreMouseAction.MOVE\n && this._lastEvent\n && this._equalEvents(this._lastEvent, e, this._activeEncoding === 'SGR_PIXELS')\n ) {\n return false;\n }\n\n // apply protocol restrictions\n if (!this._protocols[this._activeProtocol].restrict(e)) {\n return false;\n }\n\n // encode report and send\n const report = this._encodings[this._activeEncoding](e);\n if (report) {\n // always send DEFAULT as binary data\n if (this._activeEncoding === 'DEFAULT') {\n this._coreService.triggerBinaryEvent(report);\n } else {\n this._coreService.triggerDataEvent(report, true);\n }\n }\n\n this._lastEvent = e;\n\n return true;\n }\n\n public explainEvents(events: CoreMouseEventType): { [event: string]: boolean } {\n return {\n down: !!(events & CoreMouseEventType.DOWN),\n up: !!(events & CoreMouseEventType.UP),\n drag: !!(events & CoreMouseEventType.DRAG),\n move: !!(events & CoreMouseEventType.MOVE),\n wheel: !!(events & CoreMouseEventType.WHEEL)\n };\n }\n\n private _equalEvents(e1: ICoreMouseEvent, e2: ICoreMouseEvent, pixels: boolean): boolean {\n if (pixels) {\n if (e1.x !== e2.x) return false;\n if (e1.y !== e2.y) return false;\n } else {\n if (e1.col !== e2.col) return false;\n if (e1.row !== e2.row) return false;\n }\n if (e1.button !== e2.button) return false;\n if (e1.action !== e2.action) return false;\n if (e1.ctrl !== e2.ctrl) return false;\n if (e1.alt !== e2.alt) return false;\n if (e1.shift !== e2.shift) return false;\n return true;\n }\n}\n", "/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\nimport { IUnicodeVersionProvider, UnicodeCharProperties, UnicodeCharWidth } from 'common/services/Services';\nimport { UnicodeService } from 'common/services/UnicodeService';\n\nconst BMP_COMBINING = [\n [0x0300, 0x036F], [0x0483, 0x0486], [0x0488, 0x0489],\n [0x0591, 0x05BD], [0x05BF, 0x05BF], [0x05C1, 0x05C2],\n [0x05C4, 0x05C5], [0x05C7, 0x05C7], [0x0600, 0x0603],\n [0x0610, 0x0615], [0x064B, 0x065E], [0x0670, 0x0670],\n [0x06D6, 0x06E4], [0x06E7, 0x06E8], [0x06EA, 0x06ED],\n [0x070F, 0x070F], [0x0711, 0x0711], [0x0730, 0x074A],\n [0x07A6, 0x07B0], [0x07EB, 0x07F3], [0x0901, 0x0902],\n [0x093C, 0x093C], [0x0941, 0x0948], [0x094D, 0x094D],\n [0x0951, 0x0954], [0x0962, 0x0963], [0x0981, 0x0981],\n [0x09BC, 0x09BC], [0x09C1, 0x09C4], [0x09CD, 0x09CD],\n [0x09E2, 0x09E3], [0x0A01, 0x0A02], [0x0A3C, 0x0A3C],\n [0x0A41, 0x0A42], [0x0A47, 0x0A48], [0x0A4B, 0x0A4D],\n [0x0A70, 0x0A71], [0x0A81, 0x0A82], [0x0ABC, 0x0ABC],\n [0x0AC1, 0x0AC5], [0x0AC7, 0x0AC8], [0x0ACD, 0x0ACD],\n [0x0AE2, 0x0AE3], [0x0B01, 0x0B01], [0x0B3C, 0x0B3C],\n [0x0B3F, 0x0B3F], [0x0B41, 0x0B43], [0x0B4D, 0x0B4D],\n [0x0B56, 0x0B56], [0x0B82, 0x0B82], [0x0BC0, 0x0BC0],\n [0x0BCD, 0x0BCD], [0x0C3E, 0x0C40], [0x0C46, 0x0C48],\n [0x0C4A, 0x0C4D], [0x0C55, 0x0C56], [0x0CBC, 0x0CBC],\n [0x0CBF, 0x0CBF], [0x0CC6, 0x0CC6], [0x0CCC, 0x0CCD],\n [0x0CE2, 0x0CE3], [0x0D41, 0x0D43], [0x0D4D, 0x0D4D],\n [0x0DCA, 0x0DCA], [0x0DD2, 0x0DD4], [0x0DD6, 0x0DD6],\n [0x0E31, 0x0E31], [0x0E34, 0x0E3A], [0x0E47, 0x0E4E],\n [0x0EB1, 0x0EB1], [0x0EB4, 0x0EB9], [0x0EBB, 0x0EBC],\n [0x0EC8, 0x0ECD], [0x0F18, 0x0F19], [0x0F35, 0x0F35],\n [0x0F37, 0x0F37], [0x0F39, 0x0F39], [0x0F71, 0x0F7E],\n [0x0F80, 0x0F84], [0x0F86, 0x0F87], [0x0F90, 0x0F97],\n [0x0F99, 0x0FBC], [0x0FC6, 0x0FC6], [0x102D, 0x1030],\n [0x1032, 0x1032], [0x1036, 0x1037], [0x1039, 0x1039],\n [0x1058, 0x1059], [0x1160, 0x11FF], [0x135F, 0x135F],\n [0x1712, 0x1714], [0x1732, 0x1734], [0x1752, 0x1753],\n [0x1772, 0x1773], [0x17B4, 0x17B5], [0x17B7, 0x17BD],\n [0x17C6, 0x17C6], [0x17C9, 0x17D3], [0x17DD, 0x17DD],\n [0x180B, 0x180D], [0x18A9, 0x18A9], [0x1920, 0x1922],\n [0x1927, 0x1928], [0x1932, 0x1932], [0x1939, 0x193B],\n [0x1A17, 0x1A18], [0x1B00, 0x1B03], [0x1B34, 0x1B34],\n [0x1B36, 0x1B3A], [0x1B3C, 0x1B3C], [0x1B42, 0x1B42],\n [0x1B6B, 0x1B73], [0x1DC0, 0x1DCA], [0x1DFE, 0x1DFF],\n [0x200B, 0x200F], [0x202A, 0x202E], [0x2060, 0x2063],\n [0x206A, 0x206F], [0x20D0, 0x20EF], [0x302A, 0x302F],\n [0x3099, 0x309A], [0xA806, 0xA806], [0xA80B, 0xA80B],\n [0xA825, 0xA826], [0xFB1E, 0xFB1E], [0xFE00, 0xFE0F],\n [0xFE20, 0xFE23], [0xFEFF, 0xFEFF], [0xFFF9, 0xFFFB]\n];\nconst HIGH_COMBINING = [\n [0x10A01, 0x10A03], [0x10A05, 0x10A06], [0x10A0C, 0x10A0F],\n [0x10A38, 0x10A3A], [0x10A3F, 0x10A3F], [0x1D167, 0x1D169],\n [0x1D173, 0x1D182], [0x1D185, 0x1D18B], [0x1D1AA, 0x1D1AD],\n [0x1D242, 0x1D244], [0xE0001, 0xE0001], [0xE0020, 0xE007F],\n [0xE0100, 0xE01EF]\n];\n\n// BMP lookup table, lazy initialized during first addon loading\nlet table: Uint8Array;\n\nfunction bisearch(ucs: number, data: number[][]): boolean {\n let min = 0;\n let max = data.length - 1;\n let mid;\n if (ucs < data[0][0] || ucs > data[max][1]) {\n return false;\n }\n while (max >= min) {\n mid = (min + max) >> 1;\n if (ucs > data[mid][1]) {\n min = mid + 1;\n } else if (ucs < data[mid][0]) {\n max = mid - 1;\n } else {\n return true;\n }\n }\n return false;\n}\n\nexport class UnicodeV6 implements IUnicodeVersionProvider {\n public readonly version = '6';\n\n constructor() {\n // init lookup table once\n if (!table) {\n table = new Uint8Array(65536);\n table.fill(1);\n table[0] = 0;\n // control chars\n table.fill(0, 1, 32);\n table.fill(0, 0x7f, 0xa0);\n\n // apply wide char rules first\n // wide chars\n table.fill(2, 0x1100, 0x1160);\n table[0x2329] = 2;\n table[0x232a] = 2;\n table.fill(2, 0x2e80, 0xa4d0);\n table[0x303f] = 1; // wrongly in last line\n\n table.fill(2, 0xac00, 0xd7a4);\n table.fill(2, 0xf900, 0xfb00);\n table.fill(2, 0xfe10, 0xfe1a);\n table.fill(2, 0xfe30, 0xfe70);\n table.fill(2, 0xff00, 0xff61);\n table.fill(2, 0xffe0, 0xffe7);\n\n // apply combining last to ensure we overwrite\n // wrongly wide set chars:\n // the original algo evals combining first and falls\n // through to wide check so we simply do here the opposite\n // combining 0\n for (let r = 0; r < BMP_COMBINING.length; ++r) {\n table.fill(0, BMP_COMBINING[r][0], BMP_COMBINING[r][1] + 1);\n }\n }\n }\n\n public wcwidth(num: number): UnicodeCharWidth {\n if (num < 32) return 0;\n if (num < 127) return 1;\n if (num < 65536) return table[num] as UnicodeCharWidth;\n if (bisearch(num, HIGH_COMBINING)) return 0;\n if ((num >= 0x20000 && num <= 0x2fffd) || (num >= 0x30000 && num <= 0x3fffd)) return 2;\n return 1;\n }\n\n public charProperties(codepoint: number, preceding: UnicodeCharProperties): UnicodeCharProperties {\n let width = this.wcwidth(codepoint);\n let shouldJoin = width === 0 && preceding !== 0;\n if (shouldJoin) {\n const oldWidth = UnicodeService.extractWidth(preceding);\n if (oldWidth === 0) {\n shouldJoin = false;\n } else if (oldWidth > width) {\n width = oldWidth;\n }\n }\n return UnicodeService.createPropertyValue(0, width, shouldJoin);\n }\n}\n", "/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { UnicodeV6 } from 'common/input/UnicodeV6';\nimport { IUnicodeService, IUnicodeVersionProvider, UnicodeCharProperties, UnicodeCharWidth } from 'common/services/Services';\nimport { Emitter } from 'vs/base/common/event';\n\nexport class UnicodeService implements IUnicodeService {\n public serviceBrand: any;\n\n private _providers: {[key: string]: IUnicodeVersionProvider} = Object.create(null);\n private _active: string = '';\n private _activeProvider: IUnicodeVersionProvider;\n\n private readonly _onChange = new Emitter();\n public readonly onChange = this._onChange.event;\n\n public static extractShouldJoin(value: UnicodeCharProperties): boolean {\n return (value & 1) !== 0;\n }\n public static extractWidth(value: UnicodeCharProperties): UnicodeCharWidth {\n return ((value >> 1) & 0x3) as UnicodeCharWidth;\n }\n public static extractCharKind(value: UnicodeCharProperties): number {\n return value >> 3;\n }\n public static createPropertyValue(state: number, width: number, shouldJoin: boolean = false): UnicodeCharProperties {\n return ((state & 0xffffff) << 3) | ((width & 3) << 1) | (shouldJoin?1:0);\n }\n\n constructor() {\n const defaultProvider = new UnicodeV6();\n this.register(defaultProvider);\n this._active = defaultProvider.version;\n this._activeProvider = defaultProvider;\n }\n\n public dispose(): void {\n this._onChange.dispose();\n }\n\n public get versions(): string[] {\n return Object.keys(this._providers);\n }\n\n public get activeVersion(): string {\n return this._active;\n }\n\n public set activeVersion(version: string) {\n if (!this._providers[version]) {\n throw new Error(`unknown Unicode version \"${version}\"`);\n }\n this._active = version;\n this._activeProvider = this._providers[version];\n this._onChange.fire(version);\n }\n\n public register(provider: IUnicodeVersionProvider): void {\n this._providers[provider.version] = provider;\n }\n\n /**\n * Unicode version dependent interface.\n */\n public wcwidth(num: number): UnicodeCharWidth {\n return this._activeProvider.wcwidth(num);\n }\n\n public getStringCellWidth(s: string): number {\n let result = 0;\n let precedingInfo = 0;\n const length = s.length;\n for (let i = 0; i < length; ++i) {\n let code = s.charCodeAt(i);\n // surrogate pair first\n if (0xD800 <= code && code <= 0xDBFF) {\n if (++i >= length) {\n // this should not happen with strings retrieved from\n // Buffer.translateToString as it converts from UTF-32\n // and therefore always should contain the second part\n // for any other string we still have to handle it somehow:\n // simply treat the lonely surrogate first as a single char (UCS-2 behavior)\n return result + this.wcwidth(code);\n }\n const second = s.charCodeAt(i);\n // convert surrogate pair to high codepoint only for valid second part (UTF-16)\n // otherwise treat them independently (UCS-2 behavior)\n if (0xDC00 <= second && second <= 0xDFFF) {\n code = (code - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;\n } else {\n result += this.wcwidth(second);\n }\n }\n const currentInfo = this.charProperties(code, precedingInfo);\n let chWidth = UnicodeService.extractWidth(currentInfo);\n if (UnicodeService.extractShouldJoin(currentInfo)) {\n chWidth -= UnicodeService.extractWidth(precedingInfo);\n }\n result += chWidth;\n precedingInfo = currentInfo;\n }\n return result;\n }\n\n public charProperties(codepoint: number, preceding: UnicodeCharProperties): UnicodeCharProperties {\n return this._activeProvider.charProperties(codepoint, preceding);\n }\n}\n", "/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { ICharsetService } from 'common/services/Services';\nimport { ICharset } from 'common/Types';\n\nexport class CharsetService implements ICharsetService {\n public serviceBrand: any;\n\n public charset: ICharset | undefined;\n public glevel: number = 0;\n\n private _charsets: (ICharset | undefined)[] = [];\n\n public reset(): void {\n this.charset = undefined;\n this._charsets = [];\n this.glevel = 0;\n }\n\n public setgLevel(g: number): void {\n this.glevel = g;\n this.charset = this._charsets[g];\n }\n\n public setgCharset(g: number, charset: ICharset | undefined): void {\n this._charsets[g] = charset;\n if (this.glevel === g) {\n this.charset = charset;\n }\n }\n}\n", "/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { CHAR_DATA_CODE_INDEX, NULL_CELL_CODE, WHITESPACE_CELL_CODE } from 'common/buffer/Constants';\nimport { IBufferService } from 'common/services/Services';\n\nexport function updateWindowsModeWrappedState(bufferService: IBufferService): void {\n // Winpty does not support wraparound mode which means that lines will never\n // be marked as wrapped. This causes issues for things like copying a line\n // retaining the wrapped new line characters or if consumers are listening\n // in on the data stream.\n //\n // The workaround for this is to listen to every incoming line feed and mark\n // the line as wrapped if the last character in the previous line is not a\n // space. This is certainly not without its problems, but generally on\n // Windows when text reaches the end of the terminal it's likely going to be\n // wrapped.\n const line = bufferService.buffer.lines.get(bufferService.buffer.ybase + bufferService.buffer.y - 1);\n const lastChar = line?.get(bufferService.cols - 1);\n\n const nextLine = bufferService.buffer.lines.get(bufferService.buffer.ybase + bufferService.buffer.y);\n if (nextLine && lastChar) {\n nextLine.isWrapped = (lastChar[CHAR_DATA_CODE_INDEX] !== NULL_CELL_CODE && lastChar[CHAR_DATA_CODE_INDEX] !== WHITESPACE_CELL_CODE);\n }\n}\n", "/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\nimport { IParams, ParamsArray } from 'common/parser/Types';\n\n// max value supported for a single param/subparam (clamped to positive int32 range)\nconst MAX_VALUE = 0x7FFFFFFF;\n// max allowed subparams for a single sequence (hardcoded limitation)\nconst MAX_SUBPARAMS = 256;\n\n/**\n * Params storage class.\n * This type is used by the parser to accumulate sequence parameters and sub parameters\n * and transmit them to the input handler actions.\n *\n * NOTES:\n * - params object for action handlers is borrowed, use `.toArray` or `.clone` to get a copy\n * - never read beyond `params.length - 1` (likely to contain arbitrary data)\n * - `.getSubParams` returns a borrowed typed array, use `.getSubParamsAll` for cloned sub params\n * - hardcoded limitations:\n * - max. value for a single (sub) param is 2^31 - 1 (greater values are clamped to that)\n * - max. 256 sub params possible\n * - negative values are not allowed beside -1 (placeholder for default value)\n *\n * About ZDM (Zero Default Mode):\n * ZDM is not orchestrated by this class. If the parser is in ZDM,\n * it should add 0 for empty params, otherwise -1. This does not apply\n * to subparams, empty subparams should always be added with -1.\n */\nexport class Params implements IParams {\n // params store and length\n public params: Int32Array;\n public length: number;\n\n // sub params store and length\n protected _subParams: Int32Array;\n protected _subParamsLength: number;\n\n // sub params offsets from param: param idx --> [start, end] offset\n private _subParamsIdx: Uint16Array;\n private _rejectDigits: boolean;\n private _rejectSubDigits: boolean;\n private _digitIsSub: boolean;\n\n /**\n * Create a `Params` type from JS array representation.\n */\n public static fromArray(values: ParamsArray): Params {\n const params = new Params();\n if (!values.length) {\n return params;\n }\n // skip leading sub params\n for (let i = (Array.isArray(values[0])) ? 1 : 0; i < values.length; ++i) {\n const value = values[i];\n if (Array.isArray(value)) {\n for (let k = 0; k < value.length; ++k) {\n params.addSubParam(value[k]);\n }\n } else {\n params.addParam(value);\n }\n }\n return params;\n }\n\n /**\n * @param maxLength max length of storable parameters\n * @param maxSubParamsLength max length of storable sub parameters\n */\n constructor(public maxLength: number = 32, public maxSubParamsLength: number = 32) {\n if (maxSubParamsLength > MAX_SUBPARAMS) {\n throw new Error('maxSubParamsLength must not be greater than 256');\n }\n this.params = new Int32Array(maxLength);\n this.length = 0;\n this._subParams = new Int32Array(maxSubParamsLength);\n this._subParamsLength = 0;\n this._subParamsIdx = new Uint16Array(maxLength);\n this._rejectDigits = false;\n this._rejectSubDigits = false;\n this._digitIsSub = false;\n }\n\n /**\n * Clone object.\n */\n public clone(): Params {\n const newParams = new Params(this.maxLength, this.maxSubParamsLength);\n newParams.params.set(this.params);\n newParams.length = this.length;\n newParams._subParams.set(this._subParams);\n newParams._subParamsLength = this._subParamsLength;\n newParams._subParamsIdx.set(this._subParamsIdx);\n newParams._rejectDigits = this._rejectDigits;\n newParams._rejectSubDigits = this._rejectSubDigits;\n newParams._digitIsSub = this._digitIsSub;\n return newParams;\n }\n\n /**\n * Get a JS array representation of the current parameters and sub parameters.\n * The array is structured as follows:\n * sequence: \"1;2:3:4;5::6\"\n * array : [1, 2, [3, 4], 5, [-1, 6]]\n */\n public toArray(): ParamsArray {\n const res: ParamsArray = [];\n for (let i = 0; i < this.length; ++i) {\n res.push(this.params[i]);\n const start = this._subParamsIdx[i] >> 8;\n const end = this._subParamsIdx[i] & 0xFF;\n if (end - start > 0) {\n res.push(Array.prototype.slice.call(this._subParams, start, end));\n }\n }\n return res;\n }\n\n /**\n * Reset to initial empty state.\n */\n public reset(): void {\n this.length = 0;\n this._subParamsLength = 0;\n this._rejectDigits = false;\n this._rejectSubDigits = false;\n this._digitIsSub = false;\n }\n\n /**\n * Add a parameter value.\n * `Params` only stores up to `maxLength` parameters, any later\n * parameter will be ignored.\n * Note: VT devices only stored up to 16 values, xterm seems to\n * store up to 30.\n */\n public addParam(value: number): void {\n this._digitIsSub = false;\n if (this.length >= this.maxLength) {\n this._rejectDigits = true;\n return;\n }\n if (value < -1) {\n throw new Error('values lesser than -1 are not allowed');\n }\n this._subParamsIdx[this.length] = this._subParamsLength << 8 | this._subParamsLength;\n this.params[this.length++] = value > MAX_VALUE ? MAX_VALUE : value;\n }\n\n /**\n * Add a sub parameter value.\n * The sub parameter is automatically associated with the last parameter value.\n * Thus it is not possible to add a subparameter without any parameter added yet.\n * `Params` only stores up to `subParamsLength` sub parameters, any later\n * sub parameter will be ignored.\n */\n public addSubParam(value: number): void {\n this._digitIsSub = true;\n if (!this.length) {\n return;\n }\n if (this._rejectDigits || this._subParamsLength >= this.maxSubParamsLength) {\n this._rejectSubDigits = true;\n return;\n }\n if (value < -1) {\n throw new Error('values lesser than -1 are not allowed');\n }\n this._subParams[this._subParamsLength++] = value > MAX_VALUE ? MAX_VALUE : value;\n this._subParamsIdx[this.length - 1]++;\n }\n\n /**\n * Whether parameter at index `idx` has sub parameters.\n */\n public hasSubParams(idx: number): boolean {\n return ((this._subParamsIdx[idx] & 0xFF) - (this._subParamsIdx[idx] >> 8) > 0);\n }\n\n /**\n * Return sub parameters for parameter at index `idx`.\n * Note: The values are borrowed, thus you need to copy\n * the values if you need to hold them in nonlocal scope.\n */\n public getSubParams(idx: number): Int32Array | null {\n const start = this._subParamsIdx[idx] >> 8;\n const end = this._subParamsIdx[idx] & 0xFF;\n if (end - start > 0) {\n return this._subParams.subarray(start, end);\n }\n return null;\n }\n\n /**\n * Return all sub parameters as {idx: subparams} mapping.\n * Note: The values are not borrowed.\n */\n public getSubParamsAll(): {[idx: number]: Int32Array} {\n const result: {[idx: number]: Int32Array} = {};\n for (let i = 0; i < this.length; ++i) {\n const start = this._subParamsIdx[i] >> 8;\n const end = this._subParamsIdx[i] & 0xFF;\n if (end - start > 0) {\n result[i] = this._subParams.slice(start, end);\n }\n }\n return result;\n }\n\n /**\n * Add a single digit value to current parameter.\n * This is used by the parser to account digits on a char by char basis.\n */\n public addDigit(value: number): void {\n let length;\n if (this._rejectDigits\n || !(length = this._digitIsSub ? this._subParamsLength : this.length)\n || (this._digitIsSub && this._rejectSubDigits)\n ) {\n return;\n }\n\n const store = this._digitIsSub ? this._subParams : this.params;\n const cur = store[length - 1];\n store[length - 1] = ~cur ? Math.min(cur * 10 + value, MAX_VALUE) : value;\n }\n}\n", "/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IOscHandler, IHandlerCollection, OscFallbackHandlerType, IOscParser, ISubParserStackState } from 'common/parser/Types';\nimport { OscState, PAYLOAD_LIMIT } from 'common/parser/Constants';\nimport { utf32ToString } from 'common/input/TextDecoder';\nimport { IDisposable } from 'common/Types';\n\nconst EMPTY_HANDLERS: IOscHandler[] = [];\n\nexport class OscParser implements IOscParser {\n private _state = OscState.START;\n private _active = EMPTY_HANDLERS;\n private _id = -1;\n private _handlers: IHandlerCollection = Object.create(null);\n private _handlerFb: OscFallbackHandlerType = () => { };\n private _stack: ISubParserStackState = {\n paused: false,\n loopPosition: 0,\n fallThrough: false\n };\n\n public registerHandler(ident: number, handler: IOscHandler): IDisposable {\n if (this._handlers[ident] === undefined) {\n this._handlers[ident] = [];\n }\n const handlerList = this._handlers[ident];\n handlerList.push(handler);\n return {\n dispose: () => {\n const handlerIndex = handlerList.indexOf(handler);\n if (handlerIndex !== -1) {\n handlerList.splice(handlerIndex, 1);\n }\n }\n };\n }\n public clearHandler(ident: number): void {\n if (this._handlers[ident]) delete this._handlers[ident];\n }\n public setHandlerFallback(handler: OscFallbackHandlerType): void {\n this._handlerFb = handler;\n }\n\n public dispose(): void {\n this._handlers = Object.create(null);\n this._handlerFb = () => { };\n this._active = EMPTY_HANDLERS;\n }\n\n public reset(): void {\n // force cleanup handlers if payload was already sent\n if (this._state === OscState.PAYLOAD) {\n for (let j = this._stack.paused ? this._stack.loopPosition - 1 : this._active.length - 1; j >= 0; --j) {\n this._active[j].end(false);\n }\n }\n this._stack.paused = false;\n this._active = EMPTY_HANDLERS;\n this._id = -1;\n this._state = OscState.START;\n }\n\n private _start(): void {\n this._active = this._handlers[this._id] || EMPTY_HANDLERS;\n if (!this._active.length) {\n this._handlerFb(this._id, 'START');\n } else {\n for (let j = this._active.length - 1; j >= 0; j--) {\n this._active[j].start();\n }\n }\n }\n\n private _put(data: Uint32Array, start: number, end: number): void {\n if (!this._active.length) {\n this._handlerFb(this._id, 'PUT', utf32ToString(data, start, end));\n } else {\n for (let j = this._active.length - 1; j >= 0; j--) {\n this._active[j].put(data, start, end);\n }\n }\n }\n\n public start(): void {\n // always reset leftover handlers\n this.reset();\n this._state = OscState.ID;\n }\n\n /**\n * Put data to current OSC command.\n * Expects the identifier of the OSC command in the form\n * OSC id ; payload ST/BEL\n * Payload chunks are not further processed and get\n * directly passed to the handlers.\n */\n public put(data: Uint32Array, start: number, end: number): void {\n if (this._state === OscState.ABORT) {\n return;\n }\n if (this._state === OscState.ID) {\n while (start < end) {\n const code = data[start++];\n if (code === 0x3b) {\n this._state = OscState.PAYLOAD;\n this._start();\n break;\n }\n if (code < 0x30 || 0x39 < code) {\n this._state = OscState.ABORT;\n return;\n }\n if (this._id === -1) {\n this._id = 0;\n }\n this._id = this._id * 10 + code - 48;\n }\n }\n if (this._state === OscState.PAYLOAD && end - start > 0) {\n this._put(data, start, end);\n }\n }\n\n /**\n * Indicates end of an OSC command.\n * Whether the OSC got aborted or finished normally\n * is indicated by `success`.\n */\n public end(success: boolean, promiseResult: boolean = true): void | Promise {\n if (this._state === OscState.START) {\n return;\n }\n // do nothing if command was faulty\n if (this._state !== OscState.ABORT) {\n // if we are still in ID state and get an early end\n // means that the command has no payload thus we still have\n // to announce START and send END right after\n if (this._state === OscState.ID) {\n this._start();\n }\n\n if (!this._active.length) {\n this._handlerFb(this._id, 'END', success);\n } else {\n let handlerResult: boolean | Promise = false;\n let j = this._active.length - 1;\n let fallThrough = false;\n if (this._stack.paused) {\n j = this._stack.loopPosition - 1;\n handlerResult = promiseResult;\n fallThrough = this._stack.fallThrough;\n this._stack.paused = false;\n }\n if (!fallThrough && handlerResult === false) {\n for (; j >= 0; j--) {\n handlerResult = this._active[j].end(success);\n if (handlerResult === true) {\n break;\n } else if (handlerResult instanceof Promise) {\n this._stack.paused = true;\n this._stack.loopPosition = j;\n this._stack.fallThrough = false;\n return handlerResult;\n }\n }\n j--;\n }\n // cleanup left over handlers\n // we always have to call .end for proper cleanup,\n // here we use `success` to indicate whether a handler should execute\n for (; j >= 0; j--) {\n handlerResult = this._active[j].end(false);\n if (handlerResult instanceof Promise) {\n this._stack.paused = true;\n this._stack.loopPosition = j;\n this._stack.fallThrough = true;\n return handlerResult;\n }\n }\n }\n\n }\n this._active = EMPTY_HANDLERS;\n this._id = -1;\n this._state = OscState.START;\n }\n}\n\n/**\n * Convenient class to allow attaching string based handler functions\n * as OSC handlers.\n */\nexport class OscHandler implements IOscHandler {\n private _data = '';\n private _hitLimit: boolean = false;\n\n constructor(private _handler: (data: string) => boolean | Promise) { }\n\n public start(): void {\n this._data = '';\n this._hitLimit = false;\n }\n\n public put(data: Uint32Array, start: number, end: number): void {\n if (this._hitLimit) {\n return;\n }\n this._data += utf32ToString(data, start, end);\n if (this._data.length > PAYLOAD_LIMIT) {\n this._data = '';\n this._hitLimit = true;\n }\n }\n\n public end(success: boolean): boolean | Promise {\n let ret: boolean | Promise = false;\n if (this._hitLimit) {\n ret = false;\n } else if (success) {\n ret = this._handler(this._data);\n if (ret instanceof Promise) {\n // need to hold data until `ret` got resolved\n // dont care for errors, data will be freed anyway on next start\n return ret.then(res => {\n this._data = '';\n this._hitLimit = false;\n return res;\n });\n }\n }\n this._data = '';\n this._hitLimit = false;\n return ret;\n }\n}\n", "/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IDisposable } from 'common/Types';\nimport { IDcsHandler, IParams, IHandlerCollection, IDcsParser, DcsFallbackHandlerType, ISubParserStackState } from 'common/parser/Types';\nimport { utf32ToString } from 'common/input/TextDecoder';\nimport { Params } from 'common/parser/Params';\nimport { PAYLOAD_LIMIT } from 'common/parser/Constants';\n\nconst EMPTY_HANDLERS: IDcsHandler[] = [];\n\nexport class DcsParser implements IDcsParser {\n private _handlers: IHandlerCollection = Object.create(null);\n private _active: IDcsHandler[] = EMPTY_HANDLERS;\n private _ident: number = 0;\n private _handlerFb: DcsFallbackHandlerType = () => { };\n private _stack: ISubParserStackState = {\n paused: false,\n loopPosition: 0,\n fallThrough: false\n };\n\n public dispose(): void {\n this._handlers = Object.create(null);\n this._handlerFb = () => { };\n this._active = EMPTY_HANDLERS;\n }\n\n public registerHandler(ident: number, handler: IDcsHandler): IDisposable {\n if (this._handlers[ident] === undefined) {\n this._handlers[ident] = [];\n }\n const handlerList = this._handlers[ident];\n handlerList.push(handler);\n return {\n dispose: () => {\n const handlerIndex = handlerList.indexOf(handler);\n if (handlerIndex !== -1) {\n handlerList.splice(handlerIndex, 1);\n }\n }\n };\n }\n\n public clearHandler(ident: number): void {\n if (this._handlers[ident]) delete this._handlers[ident];\n }\n\n public setHandlerFallback(handler: DcsFallbackHandlerType): void {\n this._handlerFb = handler;\n }\n\n public reset(): void {\n // force cleanup leftover handlers\n if (this._active.length) {\n for (let j = this._stack.paused ? this._stack.loopPosition - 1 : this._active.length - 1; j >= 0; --j) {\n this._active[j].unhook(false);\n }\n }\n this._stack.paused = false;\n this._active = EMPTY_HANDLERS;\n this._ident = 0;\n }\n\n public hook(ident: number, params: IParams): void {\n // always reset leftover handlers\n this.reset();\n this._ident = ident;\n this._active = this._handlers[ident] || EMPTY_HANDLERS;\n if (!this._active.length) {\n this._handlerFb(this._ident, 'HOOK', params);\n } else {\n for (let j = this._active.length - 1; j >= 0; j--) {\n this._active[j].hook(params);\n }\n }\n }\n\n public put(data: Uint32Array, start: number, end: number): void {\n if (!this._active.length) {\n this._handlerFb(this._ident, 'PUT', utf32ToString(data, start, end));\n } else {\n for (let j = this._active.length - 1; j >= 0; j--) {\n this._active[j].put(data, start, end);\n }\n }\n }\n\n public unhook(success: boolean, promiseResult: boolean = true): void | Promise {\n if (!this._active.length) {\n this._handlerFb(this._ident, 'UNHOOK', success);\n } else {\n let handlerResult: boolean | Promise = false;\n let j = this._active.length - 1;\n let fallThrough = false;\n if (this._stack.paused) {\n j = this._stack.loopPosition - 1;\n handlerResult = promiseResult;\n fallThrough = this._stack.fallThrough;\n this._stack.paused = false;\n }\n if (!fallThrough && handlerResult === false) {\n for (; j >= 0; j--) {\n handlerResult = this._active[j].unhook(success);\n if (handlerResult === true) {\n break;\n } else if (handlerResult instanceof Promise) {\n this._stack.paused = true;\n this._stack.loopPosition = j;\n this._stack.fallThrough = false;\n return handlerResult;\n }\n }\n j--;\n }\n // cleanup left over handlers (fallThrough for async)\n for (; j >= 0; j--) {\n handlerResult = this._active[j].unhook(false);\n if (handlerResult instanceof Promise) {\n this._stack.paused = true;\n this._stack.loopPosition = j;\n this._stack.fallThrough = true;\n return handlerResult;\n }\n }\n }\n this._active = EMPTY_HANDLERS;\n this._ident = 0;\n }\n}\n\n// predefine empty params as [0] (ZDM)\nconst EMPTY_PARAMS = new Params();\nEMPTY_PARAMS.addParam(0);\n\n/**\n * Convenient class to create a DCS handler from a single callback function.\n * Note: The payload is currently limited to 50 MB (hardcoded).\n */\nexport class DcsHandler implements IDcsHandler {\n private _data = '';\n private _params: IParams = EMPTY_PARAMS;\n private _hitLimit: boolean = false;\n\n constructor(private _handler: (data: string, params: IParams) => boolean | Promise) { }\n\n public hook(params: IParams): void {\n // since we need to preserve params until `unhook`, we have to clone it\n // (only borrowed from parser and spans multiple parser states)\n // perf optimization:\n // clone only, if we have non empty params, otherwise stick with default\n this._params = (params.length > 1 || params.params[0]) ? params.clone() : EMPTY_PARAMS;\n this._data = '';\n this._hitLimit = false;\n }\n\n public put(data: Uint32Array, start: number, end: number): void {\n if (this._hitLimit) {\n return;\n }\n this._data += utf32ToString(data, start, end);\n if (this._data.length > PAYLOAD_LIMIT) {\n this._data = '';\n this._hitLimit = true;\n }\n }\n\n public unhook(success: boolean): boolean | Promise {\n let ret: boolean | Promise = false;\n if (this._hitLimit) {\n ret = false;\n } else if (success) {\n ret = this._handler(this._data, this._params);\n if (ret instanceof Promise) {\n // need to hold data and params until `ret` got resolved\n // dont care for errors, data will be freed anyway on next start\n return ret.then(res => {\n this._params = EMPTY_PARAMS;\n this._data = '';\n this._hitLimit = false;\n return res;\n });\n }\n }\n this._params = EMPTY_PARAMS;\n this._data = '';\n this._hitLimit = false;\n return ret;\n }\n}\n", "/**\n * Copyright (c) 2018 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IParsingState, IDcsHandler, IEscapeSequenceParser, IParams, IOscHandler, IHandlerCollection, CsiHandlerType, OscFallbackHandlerType, IOscParser, EscHandlerType, IDcsParser, DcsFallbackHandlerType, IFunctionIdentifier, ExecuteFallbackHandlerType, CsiFallbackHandlerType, EscFallbackHandlerType, PrintHandlerType, PrintFallbackHandlerType, ExecuteHandlerType, IParserStackState, ParserStackType, ResumableHandlersType } from 'common/parser/Types';\nimport { ParserState, ParserAction } from 'common/parser/Constants';\nimport { Disposable, toDisposable } from 'vs/base/common/lifecycle';\nimport { IDisposable } from 'common/Types';\nimport { Params } from 'common/parser/Params';\nimport { OscParser } from 'common/parser/OscParser';\nimport { DcsParser } from 'common/parser/DcsParser';\n\n/**\n * Table values are generated like this:\n * index: currentState << TableValue.INDEX_STATE_SHIFT | charCode\n * value: action << TableValue.TRANSITION_ACTION_SHIFT | nextState\n */\nconst enum TableAccess {\n TRANSITION_ACTION_SHIFT = 4,\n TRANSITION_STATE_MASK = 15,\n INDEX_STATE_SHIFT = 8\n}\n\n/**\n * Transition table for EscapeSequenceParser.\n */\nexport class TransitionTable {\n public table: Uint8Array;\n\n constructor(length: number) {\n this.table = new Uint8Array(length);\n }\n\n /**\n * Set default transition.\n * @param action default action\n * @param next default next state\n */\n public setDefault(action: ParserAction, next: ParserState): void {\n this.table.fill(action << TableAccess.TRANSITION_ACTION_SHIFT | next);\n }\n\n /**\n * Add a transition to the transition table.\n * @param code input character code\n * @param state current parser state\n * @param action parser action to be done\n * @param next next parser state\n */\n public add(code: number, state: ParserState, action: ParserAction, next: ParserState): void {\n this.table[state << TableAccess.INDEX_STATE_SHIFT | code] = action << TableAccess.TRANSITION_ACTION_SHIFT | next;\n }\n\n /**\n * Add transitions for multiple input character codes.\n * @param codes input character code array\n * @param state current parser state\n * @param action parser action to be done\n * @param next next parser state\n */\n public addMany(codes: number[], state: ParserState, action: ParserAction, next: ParserState): void {\n for (let i = 0; i < codes.length; i++) {\n this.table[state << TableAccess.INDEX_STATE_SHIFT | codes[i]] = action << TableAccess.TRANSITION_ACTION_SHIFT | next;\n }\n }\n}\n\n\n// Pseudo-character placeholder for printable non-ascii characters (unicode).\nconst NON_ASCII_PRINTABLE = 0xA0;\n\n\n/**\n * VT500 compatible transition table.\n * Taken from https://vt100.net/emu/dec_ansi_parser.\n */\nexport const VT500_TRANSITION_TABLE = (function (): TransitionTable {\n const table: TransitionTable = new TransitionTable(4095);\n\n // range macro for byte\n const BYTE_VALUES = 256;\n const blueprint = Array.apply(null, Array(BYTE_VALUES)).map((unused: any, i: number) => i);\n const r = (start: number, end: number): number[] => blueprint.slice(start, end);\n\n // Default definitions.\n const PRINTABLES = r(0x20, 0x7f); // 0x20 (SP) included, 0x7F (DEL) excluded\n const EXECUTABLES = r(0x00, 0x18);\n EXECUTABLES.push(0x19);\n EXECUTABLES.push.apply(EXECUTABLES, r(0x1c, 0x20));\n\n const states: number[] = r(ParserState.GROUND, ParserState.DCS_PASSTHROUGH + 1);\n let state: any;\n\n // set default transition\n table.setDefault(ParserAction.ERROR, ParserState.GROUND);\n // printables\n table.addMany(PRINTABLES, ParserState.GROUND, ParserAction.PRINT, ParserState.GROUND);\n // global anywhere rules\n for (state in states) {\n table.addMany([0x18, 0x1a, 0x99, 0x9a], state, ParserAction.EXECUTE, ParserState.GROUND);\n table.addMany(r(0x80, 0x90), state, ParserAction.EXECUTE, ParserState.GROUND);\n table.addMany(r(0x90, 0x98), state, ParserAction.EXECUTE, ParserState.GROUND);\n table.add(0x9c, state, ParserAction.IGNORE, ParserState.GROUND); // ST as terminator\n table.add(0x1b, state, ParserAction.CLEAR, ParserState.ESCAPE); // ESC\n table.add(0x9d, state, ParserAction.OSC_START, ParserState.OSC_STRING); // OSC\n table.addMany([0x98, 0x9e, 0x9f], state, ParserAction.IGNORE, ParserState.SOS_PM_APC_STRING);\n table.add(0x9b, state, ParserAction.CLEAR, ParserState.CSI_ENTRY); // CSI\n table.add(0x90, state, ParserAction.CLEAR, ParserState.DCS_ENTRY); // DCS\n }\n // rules for executables and 7f\n table.addMany(EXECUTABLES, ParserState.GROUND, ParserAction.EXECUTE, ParserState.GROUND);\n table.addMany(EXECUTABLES, ParserState.ESCAPE, ParserAction.EXECUTE, ParserState.ESCAPE);\n table.add(0x7f, ParserState.ESCAPE, ParserAction.IGNORE, ParserState.ESCAPE);\n table.addMany(EXECUTABLES, ParserState.OSC_STRING, ParserAction.IGNORE, ParserState.OSC_STRING);\n table.addMany(EXECUTABLES, ParserState.CSI_ENTRY, ParserAction.EXECUTE, ParserState.CSI_ENTRY);\n table.add(0x7f, ParserState.CSI_ENTRY, ParserAction.IGNORE, ParserState.CSI_ENTRY);\n table.addMany(EXECUTABLES, ParserState.CSI_PARAM, ParserAction.EXECUTE, ParserState.CSI_PARAM);\n table.add(0x7f, ParserState.CSI_PARAM, ParserAction.IGNORE, ParserState.CSI_PARAM);\n table.addMany(EXECUTABLES, ParserState.CSI_IGNORE, ParserAction.EXECUTE, ParserState.CSI_IGNORE);\n table.addMany(EXECUTABLES, ParserState.CSI_INTERMEDIATE, ParserAction.EXECUTE, ParserState.CSI_INTERMEDIATE);\n table.add(0x7f, ParserState.CSI_INTERMEDIATE, ParserAction.IGNORE, ParserState.CSI_INTERMEDIATE);\n table.addMany(EXECUTABLES, ParserState.ESCAPE_INTERMEDIATE, ParserAction.EXECUTE, ParserState.ESCAPE_INTERMEDIATE);\n table.add(0x7f, ParserState.ESCAPE_INTERMEDIATE, ParserAction.IGNORE, ParserState.ESCAPE_INTERMEDIATE);\n // osc\n table.add(0x5d, ParserState.ESCAPE, ParserAction.OSC_START, ParserState.OSC_STRING);\n table.addMany(PRINTABLES, ParserState.OSC_STRING, ParserAction.OSC_PUT, ParserState.OSC_STRING);\n table.add(0x7f, ParserState.OSC_STRING, ParserAction.OSC_PUT, ParserState.OSC_STRING);\n table.addMany([0x9c, 0x1b, 0x18, 0x1a, 0x07], ParserState.OSC_STRING, ParserAction.OSC_END, ParserState.GROUND);\n table.addMany(r(0x1c, 0x20), ParserState.OSC_STRING, ParserAction.IGNORE, ParserState.OSC_STRING);\n // sos/pm/apc does nothing\n table.addMany([0x58, 0x5e, 0x5f], ParserState.ESCAPE, ParserAction.IGNORE, ParserState.SOS_PM_APC_STRING);\n table.addMany(PRINTABLES, ParserState.SOS_PM_APC_STRING, ParserAction.IGNORE, ParserState.SOS_PM_APC_STRING);\n table.addMany(EXECUTABLES, ParserState.SOS_PM_APC_STRING, ParserAction.IGNORE, ParserState.SOS_PM_APC_STRING);\n table.add(0x9c, ParserState.SOS_PM_APC_STRING, ParserAction.IGNORE, ParserState.GROUND);\n table.add(0x7f, ParserState.SOS_PM_APC_STRING, ParserAction.IGNORE, ParserState.SOS_PM_APC_STRING);\n // csi entries\n table.add(0x5b, ParserState.ESCAPE, ParserAction.CLEAR, ParserState.CSI_ENTRY);\n table.addMany(r(0x40, 0x7f), ParserState.CSI_ENTRY, ParserAction.CSI_DISPATCH, ParserState.GROUND);\n table.addMany(r(0x30, 0x3c), ParserState.CSI_ENTRY, ParserAction.PARAM, ParserState.CSI_PARAM);\n table.addMany([0x3c, 0x3d, 0x3e, 0x3f], ParserState.CSI_ENTRY, ParserAction.COLLECT, ParserState.CSI_PARAM);\n table.addMany(r(0x30, 0x3c), ParserState.CSI_PARAM, ParserAction.PARAM, ParserState.CSI_PARAM);\n table.addMany(r(0x40, 0x7f), ParserState.CSI_PARAM, ParserAction.CSI_DISPATCH, ParserState.GROUND);\n table.addMany([0x3c, 0x3d, 0x3e, 0x3f], ParserState.CSI_PARAM, ParserAction.IGNORE, ParserState.CSI_IGNORE);\n table.addMany(r(0x20, 0x40), ParserState.CSI_IGNORE, ParserAction.IGNORE, ParserState.CSI_IGNORE);\n table.add(0x7f, ParserState.CSI_IGNORE, ParserAction.IGNORE, ParserState.CSI_IGNORE);\n table.addMany(r(0x40, 0x7f), ParserState.CSI_IGNORE, ParserAction.IGNORE, ParserState.GROUND);\n table.addMany(r(0x20, 0x30), ParserState.CSI_ENTRY, ParserAction.COLLECT, ParserState.CSI_INTERMEDIATE);\n table.addMany(r(0x20, 0x30), ParserState.CSI_INTERMEDIATE, ParserAction.COLLECT, ParserState.CSI_INTERMEDIATE);\n table.addMany(r(0x30, 0x40), ParserState.CSI_INTERMEDIATE, ParserAction.IGNORE, ParserState.CSI_IGNORE);\n table.addMany(r(0x40, 0x7f), ParserState.CSI_INTERMEDIATE, ParserAction.CSI_DISPATCH, ParserState.GROUND);\n table.addMany(r(0x20, 0x30), ParserState.CSI_PARAM, ParserAction.COLLECT, ParserState.CSI_INTERMEDIATE);\n // esc_intermediate\n table.addMany(r(0x20, 0x30), ParserState.ESCAPE, ParserAction.COLLECT, ParserState.ESCAPE_INTERMEDIATE);\n table.addMany(r(0x20, 0x30), ParserState.ESCAPE_INTERMEDIATE, ParserAction.COLLECT, ParserState.ESCAPE_INTERMEDIATE);\n table.addMany(r(0x30, 0x7f), ParserState.ESCAPE_INTERMEDIATE, ParserAction.ESC_DISPATCH, ParserState.GROUND);\n table.addMany(r(0x30, 0x50), ParserState.ESCAPE, ParserAction.ESC_DISPATCH, ParserState.GROUND);\n table.addMany(r(0x51, 0x58), ParserState.ESCAPE, ParserAction.ESC_DISPATCH, ParserState.GROUND);\n table.addMany([0x59, 0x5a, 0x5c], ParserState.ESCAPE, ParserAction.ESC_DISPATCH, ParserState.GROUND);\n table.addMany(r(0x60, 0x7f), ParserState.ESCAPE, ParserAction.ESC_DISPATCH, ParserState.GROUND);\n // dcs entry\n table.add(0x50, ParserState.ESCAPE, ParserAction.CLEAR, ParserState.DCS_ENTRY);\n table.addMany(EXECUTABLES, ParserState.DCS_ENTRY, ParserAction.IGNORE, ParserState.DCS_ENTRY);\n table.add(0x7f, ParserState.DCS_ENTRY, ParserAction.IGNORE, ParserState.DCS_ENTRY);\n table.addMany(r(0x1c, 0x20), ParserState.DCS_ENTRY, ParserAction.IGNORE, ParserState.DCS_ENTRY);\n table.addMany(r(0x20, 0x30), ParserState.DCS_ENTRY, ParserAction.COLLECT, ParserState.DCS_INTERMEDIATE);\n table.addMany(r(0x30, 0x3c), ParserState.DCS_ENTRY, ParserAction.PARAM, ParserState.DCS_PARAM);\n table.addMany([0x3c, 0x3d, 0x3e, 0x3f], ParserState.DCS_ENTRY, ParserAction.COLLECT, ParserState.DCS_PARAM);\n table.addMany(EXECUTABLES, ParserState.DCS_IGNORE, ParserAction.IGNORE, ParserState.DCS_IGNORE);\n table.addMany(r(0x20, 0x80), ParserState.DCS_IGNORE, ParserAction.IGNORE, ParserState.DCS_IGNORE);\n table.addMany(r(0x1c, 0x20), ParserState.DCS_IGNORE, ParserAction.IGNORE, ParserState.DCS_IGNORE);\n table.addMany(EXECUTABLES, ParserState.DCS_PARAM, ParserAction.IGNORE, ParserState.DCS_PARAM);\n table.add(0x7f, ParserState.DCS_PARAM, ParserAction.IGNORE, ParserState.DCS_PARAM);\n table.addMany(r(0x1c, 0x20), ParserState.DCS_PARAM, ParserAction.IGNORE, ParserState.DCS_PARAM);\n table.addMany(r(0x30, 0x3c), ParserState.DCS_PARAM, ParserAction.PARAM, ParserState.DCS_PARAM);\n table.addMany([0x3c, 0x3d, 0x3e, 0x3f], ParserState.DCS_PARAM, ParserAction.IGNORE, ParserState.DCS_IGNORE);\n table.addMany(r(0x20, 0x30), ParserState.DCS_PARAM, ParserAction.COLLECT, ParserState.DCS_INTERMEDIATE);\n table.addMany(EXECUTABLES, ParserState.DCS_INTERMEDIATE, ParserAction.IGNORE, ParserState.DCS_INTERMEDIATE);\n table.add(0x7f, ParserState.DCS_INTERMEDIATE, ParserAction.IGNORE, ParserState.DCS_INTERMEDIATE);\n table.addMany(r(0x1c, 0x20), ParserState.DCS_INTERMEDIATE, ParserAction.IGNORE, ParserState.DCS_INTERMEDIATE);\n table.addMany(r(0x20, 0x30), ParserState.DCS_INTERMEDIATE, ParserAction.COLLECT, ParserState.DCS_INTERMEDIATE);\n table.addMany(r(0x30, 0x40), ParserState.DCS_INTERMEDIATE, ParserAction.IGNORE, ParserState.DCS_IGNORE);\n table.addMany(r(0x40, 0x7f), ParserState.DCS_INTERMEDIATE, ParserAction.DCS_HOOK, ParserState.DCS_PASSTHROUGH);\n table.addMany(r(0x40, 0x7f), ParserState.DCS_PARAM, ParserAction.DCS_HOOK, ParserState.DCS_PASSTHROUGH);\n table.addMany(r(0x40, 0x7f), ParserState.DCS_ENTRY, ParserAction.DCS_HOOK, ParserState.DCS_PASSTHROUGH);\n table.addMany(EXECUTABLES, ParserState.DCS_PASSTHROUGH, ParserAction.DCS_PUT, ParserState.DCS_PASSTHROUGH);\n table.addMany(PRINTABLES, ParserState.DCS_PASSTHROUGH, ParserAction.DCS_PUT, ParserState.DCS_PASSTHROUGH);\n table.add(0x7f, ParserState.DCS_PASSTHROUGH, ParserAction.IGNORE, ParserState.DCS_PASSTHROUGH);\n table.addMany([0x1b, 0x9c, 0x18, 0x1a], ParserState.DCS_PASSTHROUGH, ParserAction.DCS_UNHOOK, ParserState.GROUND);\n // special handling of unicode chars\n table.add(NON_ASCII_PRINTABLE, ParserState.GROUND, ParserAction.PRINT, ParserState.GROUND);\n table.add(NON_ASCII_PRINTABLE, ParserState.OSC_STRING, ParserAction.OSC_PUT, ParserState.OSC_STRING);\n table.add(NON_ASCII_PRINTABLE, ParserState.CSI_IGNORE, ParserAction.IGNORE, ParserState.CSI_IGNORE);\n table.add(NON_ASCII_PRINTABLE, ParserState.DCS_IGNORE, ParserAction.IGNORE, ParserState.DCS_IGNORE);\n table.add(NON_ASCII_PRINTABLE, ParserState.DCS_PASSTHROUGH, ParserAction.DCS_PUT, ParserState.DCS_PASSTHROUGH);\n return table;\n})();\n\n\n/**\n * EscapeSequenceParser.\n * This class implements the ANSI/DEC compatible parser described by\n * Paul Williams (https://vt100.net/emu/dec_ansi_parser).\n *\n * To implement custom ANSI compliant escape sequences it is not needed to\n * alter this parser, instead consider registering a custom handler.\n * For non ANSI compliant sequences change the transition table with\n * the optional `transitions` constructor argument and\n * reimplement the `parse` method.\n *\n * This parser is currently hardcoded to operate in ZDM (Zero Default Mode)\n * as suggested by the original parser, thus empty parameters are set to 0.\n * This this is not in line with the latest ECMA-48 specification\n * (ZDM was part of the early specs and got completely removed later on).\n *\n * Other than the original parser from vt100.net this parser supports\n * sub parameters in digital parameters separated by colons. Empty sub parameters\n * are set to -1 (no ZDM for sub parameters).\n *\n * About prefix and intermediate bytes:\n * This parser follows the assumptions of the vt100.net parser with these restrictions:\n * - only one prefix byte is allowed as first parameter byte, byte range 0x3c .. 0x3f\n * - max. two intermediates are respected, byte range 0x20 .. 0x2f\n * Note that this is not in line with ECMA-48 which does not limit either of those.\n * Furthermore ECMA-48 allows the prefix byte range at any param byte position. Currently\n * there are no known sequences that follow the broader definition of the specification.\n *\n * TODO: implement error recovery hook via error handler return values\n */\nexport class EscapeSequenceParser extends Disposable implements IEscapeSequenceParser {\n public initialState: number;\n public currentState: number;\n public precedingJoinState: number; // UnicodeJoinProperties\n\n // buffers over several parse calls\n protected _params: Params;\n protected _collect: number;\n\n // handler lookup containers\n protected _printHandler: PrintHandlerType;\n protected _executeHandlers: { [flag: number]: ExecuteHandlerType };\n protected _csiHandlers: IHandlerCollection;\n protected _escHandlers: IHandlerCollection;\n protected readonly _oscParser: IOscParser;\n protected readonly _dcsParser: IDcsParser;\n protected _errorHandler: (state: IParsingState) => IParsingState;\n\n // fallback handlers\n protected _printHandlerFb: PrintFallbackHandlerType;\n protected _executeHandlerFb: ExecuteFallbackHandlerType;\n protected _csiHandlerFb: CsiFallbackHandlerType;\n protected _escHandlerFb: EscFallbackHandlerType;\n protected _errorHandlerFb: (state: IParsingState) => IParsingState;\n\n // parser stack save for async handler support\n protected _parseStack: IParserStackState = {\n state: ParserStackType.NONE,\n handlers: [],\n handlerPos: 0,\n transition: 0,\n chunkPos: 0\n };\n\n constructor(\n protected readonly _transitions: TransitionTable = VT500_TRANSITION_TABLE\n ) {\n super();\n\n this.initialState = ParserState.GROUND;\n this.currentState = this.initialState;\n this._params = new Params(); // defaults to 32 storable params/subparams\n this._params.addParam(0); // ZDM\n this._collect = 0;\n this.precedingJoinState = 0;\n\n // set default fallback handlers and handler lookup containers\n this._printHandlerFb = (data, start, end): void => { };\n this._executeHandlerFb = (code: number): void => { };\n this._csiHandlerFb = (ident: number, params: IParams): void => { };\n this._escHandlerFb = (ident: number): void => { };\n this._errorHandlerFb = (state: IParsingState): IParsingState => state;\n this._printHandler = this._printHandlerFb;\n this._executeHandlers = Object.create(null);\n this._csiHandlers = Object.create(null);\n this._escHandlers = Object.create(null);\n this._register(toDisposable(() => {\n this._csiHandlers = Object.create(null);\n this._executeHandlers = Object.create(null);\n this._escHandlers = Object.create(null);\n }));\n this._oscParser = this._register(new OscParser());\n this._dcsParser = this._register(new DcsParser());\n this._errorHandler = this._errorHandlerFb;\n\n // swallow 7bit ST (ESC+\\)\n this.registerEscHandler({ final: '\\\\' }, () => true);\n }\n\n protected _identifier(id: IFunctionIdentifier, finalRange: number[] = [0x40, 0x7e]): number {\n let res = 0;\n if (id.prefix) {\n if (id.prefix.length > 1) {\n throw new Error('only one byte as prefix supported');\n }\n res = id.prefix.charCodeAt(0);\n if (res && 0x3c > res || res > 0x3f) {\n throw new Error('prefix must be in range 0x3c .. 0x3f');\n }\n }\n if (id.intermediates) {\n if (id.intermediates.length > 2) {\n throw new Error('only two bytes as intermediates are supported');\n }\n for (let i = 0; i < id.intermediates.length; ++i) {\n const intermediate = id.intermediates.charCodeAt(i);\n if (0x20 > intermediate || intermediate > 0x2f) {\n throw new Error('intermediate must be in range 0x20 .. 0x2f');\n }\n res <<= 8;\n res |= intermediate;\n }\n }\n if (id.final.length !== 1) {\n throw new Error('final must be a single byte');\n }\n const finalCode = id.final.charCodeAt(0);\n if (finalRange[0] > finalCode || finalCode > finalRange[1]) {\n throw new Error(`final must be in range ${finalRange[0]} .. ${finalRange[1]}`);\n }\n res <<= 8;\n res |= finalCode;\n\n return res;\n }\n\n public identToString(ident: number): string {\n const res: string[] = [];\n while (ident) {\n res.push(String.fromCharCode(ident & 0xFF));\n ident >>= 8;\n }\n return res.reverse().join('');\n }\n\n public setPrintHandler(handler: PrintHandlerType): void {\n this._printHandler = handler;\n }\n public clearPrintHandler(): void {\n this._printHandler = this._printHandlerFb;\n }\n\n public registerEscHandler(id: IFunctionIdentifier, handler: EscHandlerType): IDisposable {\n const ident = this._identifier(id, [0x30, 0x7e]);\n if (this._escHandlers[ident] === undefined) {\n this._escHandlers[ident] = [];\n }\n const handlerList = this._escHandlers[ident];\n handlerList.push(handler);\n return {\n dispose: () => {\n const handlerIndex = handlerList.indexOf(handler);\n if (handlerIndex !== -1) {\n handlerList.splice(handlerIndex, 1);\n }\n }\n };\n }\n public clearEscHandler(id: IFunctionIdentifier): void {\n if (this._escHandlers[this._identifier(id, [0x30, 0x7e])]) delete this._escHandlers[this._identifier(id, [0x30, 0x7e])];\n }\n public setEscHandlerFallback(handler: EscFallbackHandlerType): void {\n this._escHandlerFb = handler;\n }\n\n public setExecuteHandler(flag: string, handler: ExecuteHandlerType): void {\n this._executeHandlers[flag.charCodeAt(0)] = handler;\n }\n public clearExecuteHandler(flag: string): void {\n if (this._executeHandlers[flag.charCodeAt(0)]) delete this._executeHandlers[flag.charCodeAt(0)];\n }\n public setExecuteHandlerFallback(handler: ExecuteFallbackHandlerType): void {\n this._executeHandlerFb = handler;\n }\n\n public registerCsiHandler(id: IFunctionIdentifier, handler: CsiHandlerType): IDisposable {\n const ident = this._identifier(id);\n if (this._csiHandlers[ident] === undefined) {\n this._csiHandlers[ident] = [];\n }\n const handlerList = this._csiHandlers[ident];\n handlerList.push(handler);\n return {\n dispose: () => {\n const handlerIndex = handlerList.indexOf(handler);\n if (handlerIndex !== -1) {\n handlerList.splice(handlerIndex, 1);\n }\n }\n };\n }\n public clearCsiHandler(id: IFunctionIdentifier): void {\n if (this._csiHandlers[this._identifier(id)]) delete this._csiHandlers[this._identifier(id)];\n }\n public setCsiHandlerFallback(callback: (ident: number, params: IParams) => void): void {\n this._csiHandlerFb = callback;\n }\n\n public registerDcsHandler(id: IFunctionIdentifier, handler: IDcsHandler): IDisposable {\n return this._dcsParser.registerHandler(this._identifier(id), handler);\n }\n public clearDcsHandler(id: IFunctionIdentifier): void {\n this._dcsParser.clearHandler(this._identifier(id));\n }\n public setDcsHandlerFallback(handler: DcsFallbackHandlerType): void {\n this._dcsParser.setHandlerFallback(handler);\n }\n\n public registerOscHandler(ident: number, handler: IOscHandler): IDisposable {\n return this._oscParser.registerHandler(ident, handler);\n }\n public clearOscHandler(ident: number): void {\n this._oscParser.clearHandler(ident);\n }\n public setOscHandlerFallback(handler: OscFallbackHandlerType): void {\n this._oscParser.setHandlerFallback(handler);\n }\n\n public setErrorHandler(callback: (state: IParsingState) => IParsingState): void {\n this._errorHandler = callback;\n }\n public clearErrorHandler(): void {\n this._errorHandler = this._errorHandlerFb;\n }\n\n /**\n * Reset parser to initial values.\n *\n * This can also be used to lift the improper continuation error condition\n * when dealing with async handlers. Use this only as a last resort to silence\n * that error when the terminal has no pending data to be processed. Note that\n * the interrupted async handler might continue its work in the future messing\n * up the terminal state even further.\n */\n public reset(): void {\n this.currentState = this.initialState;\n this._oscParser.reset();\n this._dcsParser.reset();\n this._params.reset();\n this._params.addParam(0); // ZDM\n this._collect = 0;\n this.precedingJoinState = 0;\n // abort pending continuation from async handler\n // Here the RESET type indicates, that the next parse call will\n // ignore any saved stack, instead continues sync with next codepoint from GROUND\n if (this._parseStack.state !== ParserStackType.NONE) {\n this._parseStack.state = ParserStackType.RESET;\n this._parseStack.handlers = []; // also release handlers ref\n }\n }\n\n /**\n * Async parse support.\n */\n protected _preserveStack(\n state: ParserStackType,\n handlers: ResumableHandlersType,\n handlerPos: number,\n transition: number,\n chunkPos: number\n ): void {\n this._parseStack.state = state;\n this._parseStack.handlers = handlers;\n this._parseStack.handlerPos = handlerPos;\n this._parseStack.transition = transition;\n this._parseStack.chunkPos = chunkPos;\n }\n\n /**\n * Parse UTF32 codepoints in `data` up to `length`.\n *\n * Note: For several actions with high data load the parsing is optimized\n * by using local read ahead loops with hardcoded conditions to\n * avoid costly table lookups. Make sure that any change of table values\n * will be reflected in the loop conditions as well and vice versa.\n * Affected states/actions:\n * - GROUND:PRINT\n * - CSI_PARAM:PARAM\n * - DCS_PARAM:PARAM\n * - OSC_STRING:OSC_PUT\n * - DCS_PASSTHROUGH:DCS_PUT\n *\n * Note on asynchronous handler support:\n * Any handler returning a promise will be treated as asynchronous.\n * To keep the in-band blocking working for async handlers, `parse` pauses execution,\n * creates a stack save and returns the promise to the caller.\n * For proper continuation of the paused state it is important\n * to await the promise resolving. On resolve the parse must be repeated\n * with the same chunk of data and the resolved value in `promiseResult`\n * until no promise is returned.\n *\n * Important: With only sync handlers defined, parsing is completely synchronous as well.\n * As soon as an async handler is involved, synchronous parsing is not possible anymore.\n *\n * Boilerplate for proper parsing of multiple chunks with async handlers:\n *\n * ```typescript\n * async function parseMultipleChunks(chunks: Uint32Array[]): Promise {\n * for (const chunk of chunks) {\n * let result: void | Promise;\n * let prev: boolean | undefined;\n * while (result = parser.parse(chunk, chunk.length, prev)) {\n * prev = await result;\n * }\n * }\n * // finished parsing all chunks...\n * }\n * ```\n */\n public parse(data: Uint32Array, length: number, promiseResult?: boolean): void | Promise {\n let code = 0;\n let transition = 0;\n let start = 0;\n let handlerResult: void | boolean | Promise;\n\n // resume from async handler\n if (this._parseStack.state) {\n // allow sync parser reset even in continuation mode\n // Note: can be used to recover parser from improper continuation error below\n if (this._parseStack.state === ParserStackType.RESET) {\n this._parseStack.state = ParserStackType.NONE;\n start = this._parseStack.chunkPos + 1; // continue with next codepoint in GROUND\n } else {\n if (promiseResult === undefined || this._parseStack.state === ParserStackType.FAIL) {\n /**\n * Reject further parsing on improper continuation after pausing. This is a really bad\n * condition with screwed up execution order and prolly messed up terminal state,\n * therefore we exit hard with an exception and reject any further parsing.\n *\n * Note: With `Terminal.write` usage this exception should never occur, as the top level\n * calls are guaranteed to handle async conditions properly. If you ever encounter this\n * exception in your terminal integration it indicates, that you injected data chunks to\n * `InputHandler.parse` or `EscapeSequenceParser.parse` synchronously without waiting for\n * continuation of a running async handler.\n *\n * It is possible to get rid of this error by calling `reset`. But dont rely on that, as\n * the pending async handler still might mess up the terminal later. Instead fix the\n * faulty async handling, so this error will not be thrown anymore.\n */\n this._parseStack.state = ParserStackType.FAIL;\n throw new Error('improper continuation due to previous async handler, giving up parsing');\n }\n\n // we have to resume the old handler loop if:\n // - return value of the promise was `false`\n // - handlers are not exhausted yet\n const handlers = this._parseStack.handlers;\n let handlerPos = this._parseStack.handlerPos - 1;\n switch (this._parseStack.state) {\n case ParserStackType.CSI:\n if (promiseResult === false && handlerPos > -1) {\n for (; handlerPos >= 0; handlerPos--) {\n handlerResult = (handlers as CsiHandlerType[])[handlerPos](this._params);\n if (handlerResult === true) {\n break;\n } else if (handlerResult instanceof Promise) {\n this._parseStack.handlerPos = handlerPos;\n return handlerResult;\n }\n }\n }\n this._parseStack.handlers = [];\n break;\n case ParserStackType.ESC:\n if (promiseResult === false && handlerPos > -1) {\n for (; handlerPos >= 0; handlerPos--) {\n handlerResult = (handlers as EscHandlerType[])[handlerPos]();\n if (handlerResult === true) {\n break;\n } else if (handlerResult instanceof Promise) {\n this._parseStack.handlerPos = handlerPos;\n return handlerResult;\n }\n }\n }\n this._parseStack.handlers = [];\n break;\n case ParserStackType.DCS:\n code = data[this._parseStack.chunkPos];\n handlerResult = this._dcsParser.unhook(code !== 0x18 && code !== 0x1a, promiseResult);\n if (handlerResult) {\n return handlerResult;\n }\n if (code === 0x1b) this._parseStack.transition |= ParserState.ESCAPE;\n this._params.reset();\n this._params.addParam(0); // ZDM\n this._collect = 0;\n break;\n case ParserStackType.OSC:\n code = data[this._parseStack.chunkPos];\n handlerResult = this._oscParser.end(code !== 0x18 && code !== 0x1a, promiseResult);\n if (handlerResult) {\n return handlerResult;\n }\n if (code === 0x1b) this._parseStack.transition |= ParserState.ESCAPE;\n this._params.reset();\n this._params.addParam(0); // ZDM\n this._collect = 0;\n break;\n }\n // cleanup before continuing with the main sync loop\n this._parseStack.state = ParserStackType.NONE;\n start = this._parseStack.chunkPos + 1;\n this.precedingJoinState = 0;\n this.currentState = this._parseStack.transition & TableAccess.TRANSITION_STATE_MASK;\n }\n }\n\n // continue with main sync loop\n\n // process input string\n for (let i = start; i < length; ++i) {\n code = data[i];\n\n // normal transition & action lookup\n transition = this._transitions.table[this.currentState << TableAccess.INDEX_STATE_SHIFT | (code < 0xa0 ? code : NON_ASCII_PRINTABLE)];\n switch (transition >> TableAccess.TRANSITION_ACTION_SHIFT) {\n case ParserAction.PRINT:\n // read ahead with loop unrolling\n // Note: 0x20 (SP) is included, 0x7F (DEL) is excluded\n for (let j = i + 1; ; ++j) {\n if (j >= length || (code = data[j]) < 0x20 || (code > 0x7e && code < NON_ASCII_PRINTABLE)) {\n this._printHandler(data, i, j);\n i = j - 1;\n break;\n }\n if (++j >= length || (code = data[j]) < 0x20 || (code > 0x7e && code < NON_ASCII_PRINTABLE)) {\n this._printHandler(data, i, j);\n i = j - 1;\n break;\n }\n if (++j >= length || (code = data[j]) < 0x20 || (code > 0x7e && code < NON_ASCII_PRINTABLE)) {\n this._printHandler(data, i, j);\n i = j - 1;\n break;\n }\n if (++j >= length || (code = data[j]) < 0x20 || (code > 0x7e && code < NON_ASCII_PRINTABLE)) {\n this._printHandler(data, i, j);\n i = j - 1;\n break;\n }\n }\n break;\n case ParserAction.EXECUTE:\n if (this._executeHandlers[code]) this._executeHandlers[code]();\n else this._executeHandlerFb(code);\n this.precedingJoinState = 0;\n break;\n case ParserAction.IGNORE:\n break;\n case ParserAction.ERROR:\n const inject: IParsingState = this._errorHandler(\n {\n position: i,\n code,\n currentState: this.currentState,\n collect: this._collect,\n params: this._params,\n abort: false\n });\n if (inject.abort) return;\n // inject values: currently not implemented\n break;\n case ParserAction.CSI_DISPATCH:\n // Trigger CSI Handler\n const handlers = this._csiHandlers[this._collect << 8 | code];\n let j = handlers ? handlers.length - 1 : -1;\n for (; j >= 0; j--) {\n // true means success and to stop bubbling\n // a promise indicates an async handler that needs to finish before progressing\n handlerResult = handlers[j](this._params);\n if (handlerResult === true) {\n break;\n } else if (handlerResult instanceof Promise) {\n this._preserveStack(ParserStackType.CSI, handlers, j, transition, i);\n return handlerResult;\n }\n }\n if (j < 0) {\n this._csiHandlerFb(this._collect << 8 | code, this._params);\n }\n this.precedingJoinState = 0;\n break;\n case ParserAction.PARAM:\n // inner loop: digits (0x30 - 0x39) and ; (0x3b) and : (0x3a)\n do {\n switch (code) {\n case 0x3b:\n this._params.addParam(0); // ZDM\n break;\n case 0x3a:\n this._params.addSubParam(-1);\n break;\n default: // 0x30 - 0x39\n this._params.addDigit(code - 48);\n }\n } while (++i < length && (code = data[i]) > 0x2f && code < 0x3c);\n i--;\n break;\n case ParserAction.COLLECT:\n this._collect <<= 8;\n this._collect |= code;\n break;\n case ParserAction.ESC_DISPATCH:\n const handlersEsc = this._escHandlers[this._collect << 8 | code];\n let jj = handlersEsc ? handlersEsc.length - 1 : -1;\n for (; jj >= 0; jj--) {\n // true means success and to stop bubbling\n // a promise indicates an async handler that needs to finish before progressing\n handlerResult = handlersEsc[jj]();\n if (handlerResult === true) {\n break;\n } else if (handlerResult instanceof Promise) {\n this._preserveStack(ParserStackType.ESC, handlersEsc, jj, transition, i);\n return handlerResult;\n }\n }\n if (jj < 0) {\n this._escHandlerFb(this._collect << 8 | code);\n }\n this.precedingJoinState = 0;\n break;\n case ParserAction.CLEAR:\n this._params.reset();\n this._params.addParam(0); // ZDM\n this._collect = 0;\n break;\n case ParserAction.DCS_HOOK:\n this._dcsParser.hook(this._collect << 8 | code, this._params);\n break;\n case ParserAction.DCS_PUT:\n // inner loop - exit DCS_PUT: 0x18, 0x1a, 0x1b, 0x7f, 0x80 - 0x9f\n // unhook triggered by: 0x1b, 0x9c (success) and 0x18, 0x1a (abort)\n for (let j = i + 1; ; ++j) {\n if (j >= length || (code = data[j]) === 0x18 || code === 0x1a || code === 0x1b || (code > 0x7f && code < NON_ASCII_PRINTABLE)) {\n this._dcsParser.put(data, i, j);\n i = j - 1;\n break;\n }\n }\n break;\n case ParserAction.DCS_UNHOOK:\n handlerResult = this._dcsParser.unhook(code !== 0x18 && code !== 0x1a);\n if (handlerResult) {\n this._preserveStack(ParserStackType.DCS, [], 0, transition, i);\n return handlerResult;\n }\n if (code === 0x1b) transition |= ParserState.ESCAPE;\n this._params.reset();\n this._params.addParam(0); // ZDM\n this._collect = 0;\n this.precedingJoinState = 0;\n break;\n case ParserAction.OSC_START:\n this._oscParser.start();\n break;\n case ParserAction.OSC_PUT:\n // inner loop: 0x20 (SP) included, 0x7F (DEL) included\n for (let j = i + 1; ; j++) {\n if (j >= length || (code = data[j]) < 0x20 || (code > 0x7f && code < NON_ASCII_PRINTABLE)) {\n this._oscParser.put(data, i, j);\n i = j - 1;\n break;\n }\n }\n break;\n case ParserAction.OSC_END:\n handlerResult = this._oscParser.end(code !== 0x18 && code !== 0x1a);\n if (handlerResult) {\n this._preserveStack(ParserStackType.OSC, [], 0, transition, i);\n return handlerResult;\n }\n if (code === 0x1b) transition |= ParserState.ESCAPE;\n this._params.reset();\n this._params.addParam(0); // ZDM\n this._collect = 0;\n this.precedingJoinState = 0;\n break;\n }\n this.currentState = transition & TableAccess.TRANSITION_STATE_MASK;\n }\n }\n}\n", "/**\n * Copyright (c) 2021 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\n\n// 'rgb:' rule - matching: r/g/b | rr/gg/bb | rrr/ggg/bbb | rrrr/gggg/bbbb (hex digits)\nconst RGB_REX = /^([\\da-f])\\/([\\da-f])\\/([\\da-f])$|^([\\da-f]{2})\\/([\\da-f]{2})\\/([\\da-f]{2})$|^([\\da-f]{3})\\/([\\da-f]{3})\\/([\\da-f]{3})$|^([\\da-f]{4})\\/([\\da-f]{4})\\/([\\da-f]{4})$/;\n// '#...' rule - matching any hex digits\nconst HASH_REX = /^[\\da-f]+$/;\n\n/**\n * Parse color spec to RGB values (8 bit per channel).\n * See `man xparsecolor` for details about certain format specifications.\n *\n * Supported formats:\n * - rgb:// with , , in h | hh | hhh | hhhh\n * - #RGB, #RRGGBB, #RRRGGGBBB, #RRRRGGGGBBBB\n *\n * All other formats like rgbi: or device-independent string specifications\n * with float numbering are not supported.\n */\nexport function parseColor(data: string): [number, number, number] | undefined {\n if (!data) return;\n // also handle uppercases\n let low = data.toLowerCase();\n if (low.indexOf('rgb:') === 0) {\n // 'rgb:' specifier\n low = low.slice(4);\n const m = RGB_REX.exec(low);\n if (m) {\n const base = m[1] ? 15 : m[4] ? 255 : m[7] ? 4095 : 65535;\n return [\n Math.round(parseInt(m[1] || m[4] || m[7] || m[10], 16) / base * 255),\n Math.round(parseInt(m[2] || m[5] || m[8] || m[11], 16) / base * 255),\n Math.round(parseInt(m[3] || m[6] || m[9] || m[12], 16) / base * 255)\n ];\n }\n } else if (low.indexOf('#') === 0) {\n // '#' specifier\n low = low.slice(1);\n if (HASH_REX.exec(low) && [3, 6, 9, 12].includes(low.length)) {\n const adv = low.length / 3;\n const result: [number, number, number] = [0, 0, 0];\n for (let i = 0; i < 3; ++i) {\n const c = parseInt(low.slice(adv * i, adv * i + adv), 16);\n result[i] = adv === 1 ? c << 4 : adv === 2 ? c : adv === 3 ? c >> 4 : c >> 8;\n }\n return result;\n }\n }\n\n // Named colors are currently not supported due to the large addition to the xterm.js bundle size\n // they would add. In order to support named colors, we would need some way of optionally loading\n // additional payloads so startup/download time is not bloated (see #3530).\n}\n\n// pad hex output to requested bit width\nfunction pad(n: number, bits: number): string {\n const s = n.toString(16);\n const s2 = s.length < 2 ? '0' + s : s;\n switch (bits) {\n case 4:\n return s[0];\n case 8:\n return s2;\n case 12:\n return (s2 + s2).slice(0, 3);\n default:\n return s2 + s2;\n }\n}\n\n/**\n * Convert a given color to rgb:../../.. string of `bits` depth.\n */\nexport function toRgbString(color: [number, number, number], bits: number = 16): string {\n const [r, g, b] = color;\n return `rgb:${pad(r, bits)}/${pad(g, bits)}/${pad(b, bits)}`;\n}\n", "/**\n * Copyright (c) 2014 The xterm.js authors. All rights reserved.\n * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)\n * @license MIT\n */\n\nimport { IInputHandler, IAttributeData, IDisposable, IWindowOptions, IColorEvent, IParseStack, ColorIndex, ColorRequestType, SpecialColorIndex } from 'common/Types';\nimport { C0, C1 } from 'common/data/EscapeSequences';\nimport { CHARSETS, DEFAULT_CHARSET } from 'common/data/Charsets';\nimport { EscapeSequenceParser } from 'common/parser/EscapeSequenceParser';\nimport { Disposable } from 'vs/base/common/lifecycle';\nimport { StringToUtf32, stringFromCodePoint, Utf8ToUtf32 } from 'common/input/TextDecoder';\nimport { BufferLine, DEFAULT_ATTR_DATA } from 'common/buffer/BufferLine';\nimport { IParsingState, IEscapeSequenceParser, IParams, IFunctionIdentifier } from 'common/parser/Types';\nimport { NULL_CELL_CODE, NULL_CELL_WIDTH, Attributes, FgFlags, BgFlags, Content, UnderlineStyle } from 'common/buffer/Constants';\nimport { CellData } from 'common/buffer/CellData';\nimport { AttributeData } from 'common/buffer/AttributeData';\nimport { ICoreService, IBufferService, IOptionsService, ILogService, ICoreMouseService, ICharsetService, IUnicodeService, LogLevelEnum, IOscLinkService } from 'common/services/Services';\nimport { UnicodeService } from 'common/services/UnicodeService';\nimport { OscHandler } from 'common/parser/OscParser';\nimport { DcsHandler } from 'common/parser/DcsParser';\nimport { IBuffer } from 'common/buffer/Types';\nimport { parseColor } from 'common/input/XParseColor';\nimport { Emitter } from 'vs/base/common/event';\n\n/**\n * Map collect to glevel. Used in `selectCharset`.\n */\nconst GLEVEL: { [key: string]: number } = { '(': 0, ')': 1, '*': 2, '+': 3, '-': 1, '.': 2 };\n\n/**\n * VT commands done by the parser - FIXME: move this to the parser?\n */\n// @vt: #Y ESC CSI \"Control Sequence Introducer\" \"ESC [\" \"Start of a CSI sequence.\"\n// @vt: #Y ESC OSC \"Operating System Command\" \"ESC ]\" \"Start of an OSC sequence.\"\n// @vt: #Y ESC DCS \"Device Control String\" \"ESC P\" \"Start of a DCS sequence.\"\n// @vt: #Y ESC ST \"String Terminator\" \"ESC \\\" \"Terminator used for string type sequences.\"\n// @vt: #Y ESC PM \"Privacy Message\" \"ESC ^\" \"Start of a privacy message.\"\n// @vt: #Y ESC APC \"Application Program Command\" \"ESC _\" \"Start of an APC sequence.\"\n// @vt: #Y C1 CSI \"Control Sequence Introducer\" \"\\x9B\" \"Start of a CSI sequence.\"\n// @vt: #Y C1 OSC \"Operating System Command\" \"\\x9D\" \"Start of an OSC sequence.\"\n// @vt: #Y C1 DCS \"Device Control String\" \"\\x90\" \"Start of a DCS sequence.\"\n// @vt: #Y C1 ST \"String Terminator\" \"\\x9C\" \"Terminator used for string type sequences.\"\n// @vt: #Y C1 PM \"Privacy Message\" \"\\x9E\" \"Start of a privacy message.\"\n// @vt: #Y C1 APC \"Application Program Command\" \"\\x9F\" \"Start of an APC sequence.\"\n// @vt: #Y C0 NUL \"Null\" \"\\0, \\x00\" \"NUL is ignored.\"\n// @vt: #Y C0 ESC \"Escape\" \"\\e, \\x1B\" \"Start of a sequence. Cancels any other sequence.\"\n\n/**\n * Document xterm VT features here that are currently unsupported\n */\n// @vt: #E[Supported via @xterm/addon-image.] DCS SIXEL \"SIXEL Graphics\" \"DCS Ps ; Ps ; Ps ; q \tPt ST\" \"Draw SIXEL image.\"\n// @vt: #N DCS DECUDK \"User Defined Keys\" \"DCS Ps ; Ps \\| Pt ST\" \"Definitions for user-defined keys.\"\n// @vt: #N DCS XTGETTCAP \"Request Terminfo String\" \"DCS + q Pt ST\" \"Request Terminfo String.\"\n// @vt: #N DCS XTSETTCAP \"Set Terminfo Data\" \"DCS + p Pt ST\" \"Set Terminfo Data.\"\n// @vt: #N OSC 1 \"Set Icon Name\" \"OSC 1 ; Pt BEL\" \"Set icon name.\"\n\n/**\n * Max length of the UTF32 input buffer. Real memory consumption is 4 times higher.\n */\nconst MAX_PARSEBUFFER_LENGTH = 131072;\n\n/**\n * Limit length of title and icon name stacks.\n */\nconst STACK_LIMIT = 10;\n\n// map params to window option\nfunction paramToWindowOption(n: number, opts: IWindowOptions): boolean {\n if (n > 24) {\n return opts.setWinLines || false;\n }\n switch (n) {\n case 1: return !!opts.restoreWin;\n case 2: return !!opts.minimizeWin;\n case 3: return !!opts.setWinPosition;\n case 4: return !!opts.setWinSizePixels;\n case 5: return !!opts.raiseWin;\n case 6: return !!opts.lowerWin;\n case 7: return !!opts.refreshWin;\n case 8: return !!opts.setWinSizeChars;\n case 9: return !!opts.maximizeWin;\n case 10: return !!opts.fullscreenWin;\n case 11: return !!opts.getWinState;\n case 13: return !!opts.getWinPosition;\n case 14: return !!opts.getWinSizePixels;\n case 15: return !!opts.getScreenSizePixels;\n case 16: return !!opts.getCellSizePixels;\n case 18: return !!opts.getWinSizeChars;\n case 19: return !!opts.getScreenSizeChars;\n case 20: return !!opts.getIconTitle;\n case 21: return !!opts.getWinTitle;\n case 22: return !!opts.pushTitle;\n case 23: return !!opts.popTitle;\n case 24: return !!opts.setWinLines;\n }\n return false;\n}\n\nexport enum WindowsOptionsReportType {\n GET_WIN_SIZE_PIXELS = 0,\n GET_CELL_SIZE_PIXELS = 1\n}\n\n// create a warning log if an async handler takes longer than the limit (in ms)\nconst SLOW_ASYNC_LIMIT = 5000;\n\n// Work variables to avoid garbage collection\nlet $temp = 0;\n\n/**\n * The terminal's standard implementation of IInputHandler, this handles all\n * input from the Parser.\n *\n * Refer to http://invisible-island.net/xterm/ctlseqs/ctlseqs.html to understand\n * each function's header comment.\n */\nexport class InputHandler extends Disposable implements IInputHandler {\n private _parseBuffer: Uint32Array = new Uint32Array(4096);\n private _stringDecoder: StringToUtf32 = new StringToUtf32();\n private _utf8Decoder: Utf8ToUtf32 = new Utf8ToUtf32();\n private _windowTitle = '';\n private _iconName = '';\n private _dirtyRowTracker: IDirtyRowTracker;\n protected _windowTitleStack: string[] = [];\n protected _iconNameStack: string[] = [];\n\n private _curAttrData: IAttributeData = DEFAULT_ATTR_DATA.clone();\n public getAttrData(): IAttributeData { return this._curAttrData; }\n private _eraseAttrDataInternal: IAttributeData = DEFAULT_ATTR_DATA.clone();\n\n private _activeBuffer: IBuffer;\n\n private readonly _onRequestBell = this._register(new Emitter());\n public readonly onRequestBell = this._onRequestBell.event;\n private readonly _onRequestRefreshRows = this._register(new Emitter<{ start: number, end: number } | undefined>());\n public readonly onRequestRefreshRows = this._onRequestRefreshRows.event;\n private readonly _onRequestReset = this._register(new Emitter());\n public readonly onRequestReset = this._onRequestReset.event;\n private readonly _onRequestSendFocus = this._register(new Emitter());\n public readonly onRequestSendFocus = this._onRequestSendFocus.event;\n private readonly _onRequestSyncScrollBar = this._register(new Emitter());\n public readonly onRequestSyncScrollBar = this._onRequestSyncScrollBar.event;\n private readonly _onRequestWindowsOptionsReport = this._register(new Emitter());\n public readonly onRequestWindowsOptionsReport = this._onRequestWindowsOptionsReport.event;\n\n private readonly _onA11yChar = this._register(new Emitter());\n public readonly onA11yChar = this._onA11yChar.event;\n private readonly _onA11yTab = this._register(new Emitter());\n public readonly onA11yTab = this._onA11yTab.event;\n private readonly _onCursorMove = this._register(new Emitter());\n public readonly onCursorMove = this._onCursorMove.event;\n private readonly _onLineFeed = this._register(new Emitter());\n public readonly onLineFeed = this._onLineFeed.event;\n private readonly _onScroll = this._register(new Emitter());\n public readonly onScroll = this._onScroll.event;\n private readonly _onTitleChange = this._register(new Emitter());\n public readonly onTitleChange = this._onTitleChange.event;\n private readonly _onColor = this._register(new Emitter());\n public readonly onColor = this._onColor.event;\n\n private _parseStack: IParseStack = {\n paused: false,\n cursorStartX: 0,\n cursorStartY: 0,\n decodedLength: 0,\n position: 0\n };\n\n constructor(\n private readonly _bufferService: IBufferService,\n private readonly _charsetService: ICharsetService,\n private readonly _coreService: ICoreService,\n private readonly _logService: ILogService,\n private readonly _optionsService: IOptionsService,\n private readonly _oscLinkService: IOscLinkService,\n private readonly _coreMouseService: ICoreMouseService,\n private readonly _unicodeService: IUnicodeService,\n private readonly _parser: IEscapeSequenceParser = new EscapeSequenceParser()\n ) {\n super();\n this._register(this._parser);\n this._dirtyRowTracker = new DirtyRowTracker(this._bufferService);\n\n // Track properties used in performance critical code manually to avoid using slow getters\n this._activeBuffer = this._bufferService.buffer;\n this._register(this._bufferService.buffers.onBufferActivate(e => this._activeBuffer = e.activeBuffer));\n\n /**\n * custom fallback handlers\n */\n this._parser.setCsiHandlerFallback((ident, params) => {\n this._logService.debug('Unknown CSI code: ', { identifier: this._parser.identToString(ident), params: params.toArray() });\n });\n this._parser.setEscHandlerFallback(ident => {\n this._logService.debug('Unknown ESC code: ', { identifier: this._parser.identToString(ident) });\n });\n this._parser.setExecuteHandlerFallback(code => {\n this._logService.debug('Unknown EXECUTE code: ', { code });\n });\n this._parser.setOscHandlerFallback((identifier, action, data) => {\n this._logService.debug('Unknown OSC code: ', { identifier, action, data });\n });\n this._parser.setDcsHandlerFallback((ident, action, payload) => {\n if (action === 'HOOK') {\n payload = payload.toArray();\n }\n this._logService.debug('Unknown DCS code: ', { identifier: this._parser.identToString(ident), action, payload });\n });\n\n /**\n * print handler\n */\n this._parser.setPrintHandler((data, start, end) => this.print(data, start, end));\n\n /**\n * CSI handler\n */\n this._parser.registerCsiHandler({ final: '@' }, params => this.insertChars(params));\n this._parser.registerCsiHandler({ intermediates: ' ', final: '@' }, params => this.scrollLeft(params));\n this._parser.registerCsiHandler({ final: 'A' }, params => this.cursorUp(params));\n this._parser.registerCsiHandler({ intermediates: ' ', final: 'A' }, params => this.scrollRight(params));\n this._parser.registerCsiHandler({ final: 'B' }, params => this.cursorDown(params));\n this._parser.registerCsiHandler({ final: 'C' }, params => this.cursorForward(params));\n this._parser.registerCsiHandler({ final: 'D' }, params => this.cursorBackward(params));\n this._parser.registerCsiHandler({ final: 'E' }, params => this.cursorNextLine(params));\n this._parser.registerCsiHandler({ final: 'F' }, params => this.cursorPrecedingLine(params));\n this._parser.registerCsiHandler({ final: 'G' }, params => this.cursorCharAbsolute(params));\n this._parser.registerCsiHandler({ final: 'H' }, params => this.cursorPosition(params));\n this._parser.registerCsiHandler({ final: 'I' }, params => this.cursorForwardTab(params));\n this._parser.registerCsiHandler({ final: 'J' }, params => this.eraseInDisplay(params, false));\n this._parser.registerCsiHandler({ prefix: '?', final: 'J' }, params => this.eraseInDisplay(params, true));\n this._parser.registerCsiHandler({ final: 'K' }, params => this.eraseInLine(params, false));\n this._parser.registerCsiHandler({ prefix: '?', final: 'K' }, params => this.eraseInLine(params, true));\n this._parser.registerCsiHandler({ final: 'L' }, params => this.insertLines(params));\n this._parser.registerCsiHandler({ final: 'M' }, params => this.deleteLines(params));\n this._parser.registerCsiHandler({ final: 'P' }, params => this.deleteChars(params));\n this._parser.registerCsiHandler({ final: 'S' }, params => this.scrollUp(params));\n this._parser.registerCsiHandler({ final: 'T' }, params => this.scrollDown(params));\n this._parser.registerCsiHandler({ final: 'X' }, params => this.eraseChars(params));\n this._parser.registerCsiHandler({ final: 'Z' }, params => this.cursorBackwardTab(params));\n this._parser.registerCsiHandler({ final: '`' }, params => this.charPosAbsolute(params));\n this._parser.registerCsiHandler({ final: 'a' }, params => this.hPositionRelative(params));\n this._parser.registerCsiHandler({ final: 'b' }, params => this.repeatPrecedingCharacter(params));\n this._parser.registerCsiHandler({ final: 'c' }, params => this.sendDeviceAttributesPrimary(params));\n this._parser.registerCsiHandler({ prefix: '>', final: 'c' }, params => this.sendDeviceAttributesSecondary(params));\n this._parser.registerCsiHandler({ final: 'd' }, params => this.linePosAbsolute(params));\n this._parser.registerCsiHandler({ final: 'e' }, params => this.vPositionRelative(params));\n this._parser.registerCsiHandler({ final: 'f' }, params => this.hVPosition(params));\n this._parser.registerCsiHandler({ final: 'g' }, params => this.tabClear(params));\n this._parser.registerCsiHandler({ final: 'h' }, params => this.setMode(params));\n this._parser.registerCsiHandler({ prefix: '?', final: 'h' }, params => this.setModePrivate(params));\n this._parser.registerCsiHandler({ final: 'l' }, params => this.resetMode(params));\n this._parser.registerCsiHandler({ prefix: '?', final: 'l' }, params => this.resetModePrivate(params));\n this._parser.registerCsiHandler({ final: 'm' }, params => this.charAttributes(params));\n this._parser.registerCsiHandler({ final: 'n' }, params => this.deviceStatus(params));\n this._parser.registerCsiHandler({ prefix: '?', final: 'n' }, params => this.deviceStatusPrivate(params));\n this._parser.registerCsiHandler({ intermediates: '!', final: 'p' }, params => this.softReset(params));\n this._parser.registerCsiHandler({ intermediates: ' ', final: 'q' }, params => this.setCursorStyle(params));\n this._parser.registerCsiHandler({ final: 'r' }, params => this.setScrollRegion(params));\n this._parser.registerCsiHandler({ final: 's' }, params => this.saveCursor(params));\n this._parser.registerCsiHandler({ final: 't' }, params => this.windowOptions(params));\n this._parser.registerCsiHandler({ final: 'u' }, params => this.restoreCursor(params));\n this._parser.registerCsiHandler({ intermediates: '\\'', final: '}' }, params => this.insertColumns(params));\n this._parser.registerCsiHandler({ intermediates: '\\'', final: '~' }, params => this.deleteColumns(params));\n this._parser.registerCsiHandler({ intermediates: '\"', final: 'q' }, params => this.selectProtected(params));\n this._parser.registerCsiHandler({ intermediates: '$', final: 'p' }, params => this.requestMode(params, true));\n this._parser.registerCsiHandler({ prefix: '?', intermediates: '$', final: 'p' }, params => this.requestMode(params, false));\n\n /**\n * execute handler\n */\n this._parser.setExecuteHandler(C0.BEL, () => this.bell());\n this._parser.setExecuteHandler(C0.LF, () => this.lineFeed());\n this._parser.setExecuteHandler(C0.VT, () => this.lineFeed());\n this._parser.setExecuteHandler(C0.FF, () => this.lineFeed());\n this._parser.setExecuteHandler(C0.CR, () => this.carriageReturn());\n this._parser.setExecuteHandler(C0.BS, () => this.backspace());\n this._parser.setExecuteHandler(C0.HT, () => this.tab());\n this._parser.setExecuteHandler(C0.SO, () => this.shiftOut());\n this._parser.setExecuteHandler(C0.SI, () => this.shiftIn());\n // FIXME: What do to with missing? Old code just added those to print.\n\n this._parser.setExecuteHandler(C1.IND, () => this.index());\n this._parser.setExecuteHandler(C1.NEL, () => this.nextLine());\n this._parser.setExecuteHandler(C1.HTS, () => this.tabSet());\n\n /**\n * OSC handler\n */\n // 0 - icon name + title\n this._parser.registerOscHandler(0, new OscHandler(data => { this.setTitle(data); this.setIconName(data); return true; }));\n // 1 - icon name\n this._parser.registerOscHandler(1, new OscHandler(data => this.setIconName(data)));\n // 2 - title\n this._parser.registerOscHandler(2, new OscHandler(data => this.setTitle(data)));\n // 3 - set property X in the form \"prop=value\"\n // 4 - Change Color Number\n this._parser.registerOscHandler(4, new OscHandler(data => this.setOrReportIndexedColor(data)));\n // 5 - Change Special Color Number\n // 6 - Enable/disable Special Color Number c\n // 7 - current directory? (not in xterm spec, see https://gitlab.com/gnachman/iterm2/issues/3939)\n // 8 - create hyperlink (not in xterm spec, see https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda)\n this._parser.registerOscHandler(8, new OscHandler(data => this.setHyperlink(data)));\n // 10 - Change VT100 text foreground color to Pt.\n this._parser.registerOscHandler(10, new OscHandler(data => this.setOrReportFgColor(data)));\n // 11 - Change VT100 text background color to Pt.\n this._parser.registerOscHandler(11, new OscHandler(data => this.setOrReportBgColor(data)));\n // 12 - Change text cursor color to Pt.\n this._parser.registerOscHandler(12, new OscHandler(data => this.setOrReportCursorColor(data)));\n // 13 - Change mouse foreground color to Pt.\n // 14 - Change mouse background color to Pt.\n // 15 - Change Tektronix foreground color to Pt.\n // 16 - Change Tektronix background color to Pt.\n // 17 - Change highlight background color to Pt.\n // 18 - Change Tektronix cursor color to Pt.\n // 19 - Change highlight foreground color to Pt.\n // 46 - Change Log File to Pt.\n // 50 - Set Font to Pt.\n // 51 - reserved for Emacs shell.\n // 52 - Manipulate Selection Data.\n // 104 ; c - Reset Color Number c.\n this._parser.registerOscHandler(104, new OscHandler(data => this.restoreIndexedColor(data)));\n // 105 ; c - Reset Special Color Number c.\n // 106 ; c; f - Enable/disable Special Color Number c.\n // 110 - Reset VT100 text foreground color.\n this._parser.registerOscHandler(110, new OscHandler(data => this.restoreFgColor(data)));\n // 111 - Reset VT100 text background color.\n this._parser.registerOscHandler(111, new OscHandler(data => this.restoreBgColor(data)));\n // 112 - Reset text cursor color.\n this._parser.registerOscHandler(112, new OscHandler(data => this.restoreCursorColor(data)));\n // 113 - Reset mouse foreground color.\n // 114 - Reset mouse background color.\n // 115 - Reset Tektronix foreground color.\n // 116 - Reset Tektronix background color.\n // 117 - Reset highlight color.\n // 118 - Reset Tektronix cursor color.\n // 119 - Reset highlight foreground color.\n\n /**\n * ESC handlers\n */\n this._parser.registerEscHandler({ final: '7' }, () => this.saveCursor());\n this._parser.registerEscHandler({ final: '8' }, () => this.restoreCursor());\n this._parser.registerEscHandler({ final: 'D' }, () => this.index());\n this._parser.registerEscHandler({ final: 'E' }, () => this.nextLine());\n this._parser.registerEscHandler({ final: 'H' }, () => this.tabSet());\n this._parser.registerEscHandler({ final: 'M' }, () => this.reverseIndex());\n this._parser.registerEscHandler({ final: '=' }, () => this.keypadApplicationMode());\n this._parser.registerEscHandler({ final: '>' }, () => this.keypadNumericMode());\n this._parser.registerEscHandler({ final: 'c' }, () => this.fullReset());\n this._parser.registerEscHandler({ final: 'n' }, () => this.setgLevel(2));\n this._parser.registerEscHandler({ final: 'o' }, () => this.setgLevel(3));\n this._parser.registerEscHandler({ final: '|' }, () => this.setgLevel(3));\n this._parser.registerEscHandler({ final: '}' }, () => this.setgLevel(2));\n this._parser.registerEscHandler({ final: '~' }, () => this.setgLevel(1));\n this._parser.registerEscHandler({ intermediates: '%', final: '@' }, () => this.selectDefaultCharset());\n this._parser.registerEscHandler({ intermediates: '%', final: 'G' }, () => this.selectDefaultCharset());\n for (const flag in CHARSETS) {\n this._parser.registerEscHandler({ intermediates: '(', final: flag }, () => this.selectCharset('(' + flag));\n this._parser.registerEscHandler({ intermediates: ')', final: flag }, () => this.selectCharset(')' + flag));\n this._parser.registerEscHandler({ intermediates: '*', final: flag }, () => this.selectCharset('*' + flag));\n this._parser.registerEscHandler({ intermediates: '+', final: flag }, () => this.selectCharset('+' + flag));\n this._parser.registerEscHandler({ intermediates: '-', final: flag }, () => this.selectCharset('-' + flag));\n this._parser.registerEscHandler({ intermediates: '.', final: flag }, () => this.selectCharset('.' + flag));\n this._parser.registerEscHandler({ intermediates: '/', final: flag }, () => this.selectCharset('/' + flag)); // TODO: supported?\n }\n this._parser.registerEscHandler({ intermediates: '#', final: '8' }, () => this.screenAlignmentPattern());\n\n /**\n * error handler\n */\n this._parser.setErrorHandler((state: IParsingState) => {\n this._logService.error('Parsing error: ', state);\n return state;\n });\n\n /**\n * DCS handler\n */\n this._parser.registerDcsHandler({ intermediates: '$', final: 'q' }, new DcsHandler((data, params) => this.requestStatusString(data, params)));\n }\n\n /**\n * Async parse support.\n */\n private _preserveStack(cursorStartX: number, cursorStartY: number, decodedLength: number, position: number): void {\n this._parseStack.paused = true;\n this._parseStack.cursorStartX = cursorStartX;\n this._parseStack.cursorStartY = cursorStartY;\n this._parseStack.decodedLength = decodedLength;\n this._parseStack.position = position;\n }\n\n private _logSlowResolvingAsync(p: Promise): void {\n // log a limited warning about an async handler taking too long\n if (this._logService.logLevel <= LogLevelEnum.WARN) {\n Promise.race([p, new Promise((res, rej) => setTimeout(() => rej('#SLOW_TIMEOUT'), SLOW_ASYNC_LIMIT))])\n .catch(err => {\n if (err !== '#SLOW_TIMEOUT') {\n throw err;\n }\n console.warn(`async parser handler taking longer than ${SLOW_ASYNC_LIMIT} ms`);\n });\n }\n }\n\n private _getCurrentLinkId(): number {\n return this._curAttrData.extended.urlId;\n }\n\n /**\n * Parse call with async handler support.\n *\n * Whether the stack state got preserved for the next call, is indicated by the return value:\n * - undefined (void):\n * all handlers were sync, no stack save, continue normally with next chunk\n * - Promise\\:\n * execution stopped at async handler, stack saved, continue with same chunk and the promise\n * resolve value as `promiseResult` until the method returns `undefined`\n *\n * Note: This method should only be called by `Terminal.write` to ensure correct execution order\n * and proper continuation of async parser handlers.\n */\n public parse(data: string | Uint8Array, promiseResult?: boolean): void | Promise {\n let result: void | Promise;\n let cursorStartX = this._activeBuffer.x;\n let cursorStartY = this._activeBuffer.y;\n let start = 0;\n const wasPaused = this._parseStack.paused;\n\n if (wasPaused) {\n // assumption: _parseBuffer never mutates between async calls\n if (result = this._parser.parse(this._parseBuffer, this._parseStack.decodedLength, promiseResult)) {\n this._logSlowResolvingAsync(result);\n return result;\n }\n cursorStartX = this._parseStack.cursorStartX;\n cursorStartY = this._parseStack.cursorStartY;\n this._parseStack.paused = false;\n if (data.length > MAX_PARSEBUFFER_LENGTH) {\n start = this._parseStack.position + MAX_PARSEBUFFER_LENGTH;\n }\n }\n\n // Log debug data, the log level gate is to prevent extra work in this hot path\n if (this._logService.logLevel <= LogLevelEnum.DEBUG) {\n this._logService.debug(`parsing data ${typeof data === 'string' ? ` \"${data}\"` : ` \"${Array.prototype.map.call(data, e => String.fromCharCode(e)).join('')}\"`}`);\n }\n if (this._logService.logLevel === LogLevelEnum.TRACE) {\n this._logService.trace(`parsing data (codes)`, typeof data === 'string'\n ? data.split('').map(e => e.charCodeAt(0))\n : data\n );\n }\n\n // resize input buffer if needed\n if (this._parseBuffer.length < data.length) {\n if (this._parseBuffer.length < MAX_PARSEBUFFER_LENGTH) {\n this._parseBuffer = new Uint32Array(Math.min(data.length, MAX_PARSEBUFFER_LENGTH));\n }\n }\n\n // Clear the dirty row service so we know which lines changed as a result of parsing\n // Important: do not clear between async calls, otherwise we lost pending update information.\n if (!wasPaused) {\n this._dirtyRowTracker.clearRange();\n }\n\n // process big data in smaller chunks\n if (data.length > MAX_PARSEBUFFER_LENGTH) {\n for (let i = start; i < data.length; i += MAX_PARSEBUFFER_LENGTH) {\n const end = i + MAX_PARSEBUFFER_LENGTH < data.length ? i + MAX_PARSEBUFFER_LENGTH : data.length;\n const len = (typeof data === 'string')\n ? this._stringDecoder.decode(data.substring(i, end), this._parseBuffer)\n : this._utf8Decoder.decode(data.subarray(i, end), this._parseBuffer);\n if (result = this._parser.parse(this._parseBuffer, len)) {\n this._preserveStack(cursorStartX, cursorStartY, len, i);\n this._logSlowResolvingAsync(result);\n return result;\n }\n }\n } else {\n if (!wasPaused) {\n const len = (typeof data === 'string')\n ? this._stringDecoder.decode(data, this._parseBuffer)\n : this._utf8Decoder.decode(data, this._parseBuffer);\n if (result = this._parser.parse(this._parseBuffer, len)) {\n this._preserveStack(cursorStartX, cursorStartY, len, 0);\n this._logSlowResolvingAsync(result);\n return result;\n }\n }\n }\n\n if (this._activeBuffer.x !== cursorStartX || this._activeBuffer.y !== cursorStartY) {\n this._onCursorMove.fire();\n }\n\n // Refresh any dirty rows accumulated as part of parsing, fire only for rows within the\n // _viewport_ which is relative to ydisp, not relative to ybase.\n const viewportEnd = this._dirtyRowTracker.end + (this._bufferService.buffer.ybase - this._bufferService.buffer.ydisp);\n const viewportStart = this._dirtyRowTracker.start + (this._bufferService.buffer.ybase - this._bufferService.buffer.ydisp);\n if (viewportStart < this._bufferService.rows) {\n this._onRequestRefreshRows.fire({\n start: Math.min(viewportStart, this._bufferService.rows - 1),\n end: Math.min(viewportEnd, this._bufferService.rows - 1)\n });\n }\n }\n\n public print(data: Uint32Array, start: number, end: number): void {\n let code: number;\n let chWidth: number;\n const charset = this._charsetService.charset;\n const screenReaderMode = this._optionsService.rawOptions.screenReaderMode;\n const cols = this._bufferService.cols;\n const wraparoundMode = this._coreService.decPrivateModes.wraparound;\n const insertMode = this._coreService.modes.insertMode;\n const curAttr = this._curAttrData;\n let bufferRow = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y)!;\n\n this._dirtyRowTracker.markDirty(this._activeBuffer.y);\n\n // handle wide chars: reset start_cell-1 if we would overwrite the second cell of a wide char\n if (this._activeBuffer.x && end - start > 0 && bufferRow.getWidth(this._activeBuffer.x - 1) === 2) {\n bufferRow.setCellFromCodepoint(this._activeBuffer.x - 1, 0, 1, curAttr);\n }\n\n let precedingJoinState = this._parser.precedingJoinState;\n for (let pos = start; pos < end; ++pos) {\n code = data[pos];\n\n // get charset replacement character\n // charset is only defined for ASCII, therefore we only\n // search for an replacement char if code < 127\n if (code < 127 && charset) {\n const ch = charset[String.fromCharCode(code)];\n if (ch) {\n code = ch.charCodeAt(0);\n }\n }\n\n const currentInfo = this._unicodeService.charProperties(code, precedingJoinState);\n chWidth = UnicodeService.extractWidth(currentInfo);\n const shouldJoin = UnicodeService.extractShouldJoin(currentInfo);\n const oldWidth = shouldJoin ? UnicodeService.extractWidth(precedingJoinState) : 0;\n precedingJoinState = currentInfo;\n\n if (screenReaderMode) {\n this._onA11yChar.fire(stringFromCodePoint(code));\n }\n if (this._getCurrentLinkId()) {\n this._oscLinkService.addLineToLink(this._getCurrentLinkId(), this._activeBuffer.ybase + this._activeBuffer.y);\n }\n\n // goto next line if ch would overflow\n // NOTE: To avoid costly width checks here,\n // the terminal does not allow a cols < 2.\n if (this._activeBuffer.x + chWidth - oldWidth > cols) {\n // autowrap - DECAWM\n // automatically wraps to the beginning of the next line\n if (wraparoundMode) {\n const oldRow = bufferRow;\n let oldCol = this._activeBuffer.x - oldWidth;\n this._activeBuffer.x = oldWidth;\n this._activeBuffer.y++;\n if (this._activeBuffer.y === this._activeBuffer.scrollBottom + 1) {\n this._activeBuffer.y--;\n this._bufferService.scroll(this._eraseAttrData(), true);\n } else {\n if (this._activeBuffer.y >= this._bufferService.rows) {\n this._activeBuffer.y = this._bufferService.rows - 1;\n }\n // The line already exists (eg. the initial viewport), mark it as a\n // wrapped line\n this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y)!.isWrapped = true;\n }\n // row changed, get it again\n bufferRow = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y)!;\n if (oldWidth > 0 && bufferRow instanceof BufferLine) {\n // Combining character widens 1 column to 2.\n // Move old character to next line.\n bufferRow.copyCellsFrom(oldRow as BufferLine,\n oldCol, 0, oldWidth, false);\n }\n // clear left over cells to the right\n while (oldCol < cols) {\n oldRow.setCellFromCodepoint(oldCol++, 0, 1, curAttr);\n }\n } else {\n this._activeBuffer.x = cols - 1;\n if (chWidth === 2) {\n // FIXME: check for xterm behavior\n // What to do here? We got a wide char that does not fit into last cell\n continue;\n }\n }\n }\n\n // insert combining char at last cursor position\n // this._activeBuffer.x should never be 0 for a combining char\n // since they always follow a cell consuming char\n // therefore we can test for this._activeBuffer.x to avoid overflow left\n if (shouldJoin && this._activeBuffer.x) {\n const offset = bufferRow.getWidth(this._activeBuffer.x - 1) ? 1 : 2;\n // if empty cell after fullwidth, need to go 2 cells back\n // it is save to step 2 cells back here\n // since an empty cell is only set by fullwidth chars\n bufferRow.addCodepointToCell(this._activeBuffer.x - offset,\n code, chWidth);\n for (let delta = chWidth - oldWidth; --delta >= 0;) {\n bufferRow.setCellFromCodepoint(this._activeBuffer.x++, 0, 0, curAttr);\n }\n continue;\n }\n\n // insert mode: move characters to right\n if (insertMode) {\n // right shift cells according to the width\n bufferRow.insertCells(this._activeBuffer.x, chWidth - oldWidth, this._activeBuffer.getNullCell(curAttr));\n // test last cell - since the last cell has only room for\n // a halfwidth char any fullwidth shifted there is lost\n // and will be set to empty cell\n if (bufferRow.getWidth(cols - 1) === 2) {\n bufferRow.setCellFromCodepoint(cols - 1, NULL_CELL_CODE, NULL_CELL_WIDTH, curAttr);\n }\n }\n\n // write current char to buffer and advance cursor\n bufferRow.setCellFromCodepoint(this._activeBuffer.x++, code, chWidth, curAttr);\n\n // fullwidth char - also set next cell to placeholder stub and advance cursor\n // for graphemes bigger than fullwidth we can simply loop to zero\n // we already made sure above, that this._activeBuffer.x + chWidth will not overflow right\n if (chWidth > 0) {\n while (--chWidth) {\n // other than a regular empty cell a cell following a wide char has no width\n bufferRow.setCellFromCodepoint(this._activeBuffer.x++, 0, 0, curAttr);\n }\n }\n }\n\n this._parser.precedingJoinState = precedingJoinState;\n\n // handle wide chars: reset cell to the right if it is second cell of a wide char\n if (this._activeBuffer.x < cols && end - start > 0 && bufferRow.getWidth(this._activeBuffer.x) === 0 && !bufferRow.hasContent(this._activeBuffer.x)) {\n bufferRow.setCellFromCodepoint(this._activeBuffer.x, 0, 1, curAttr);\n }\n\n this._dirtyRowTracker.markDirty(this._activeBuffer.y);\n }\n\n /**\n * Forward registerCsiHandler from parser.\n */\n public registerCsiHandler(id: IFunctionIdentifier, callback: (params: IParams) => boolean | Promise): IDisposable {\n if (id.final === 't' && !id.prefix && !id.intermediates) {\n // security: always check whether window option is allowed\n return this._parser.registerCsiHandler(id, params => {\n if (!paramToWindowOption(params.params[0], this._optionsService.rawOptions.windowOptions)) {\n return true;\n }\n return callback(params);\n });\n }\n return this._parser.registerCsiHandler(id, callback);\n }\n\n /**\n * Forward registerDcsHandler from parser.\n */\n public registerDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: IParams) => boolean | Promise): IDisposable {\n return this._parser.registerDcsHandler(id, new DcsHandler(callback));\n }\n\n /**\n * Forward registerEscHandler from parser.\n */\n public registerEscHandler(id: IFunctionIdentifier, callback: () => boolean | Promise): IDisposable {\n return this._parser.registerEscHandler(id, callback);\n }\n\n /**\n * Forward registerOscHandler from parser.\n */\n public registerOscHandler(ident: number, callback: (data: string) => boolean | Promise): IDisposable {\n return this._parser.registerOscHandler(ident, new OscHandler(callback));\n }\n\n /**\n * BEL\n * Bell (Ctrl-G).\n *\n * @vt: #Y C0 BEL \"Bell\" \"\\a, \\x07\" \"Ring the bell.\"\n * The behavior of the bell is further customizable with `ITerminalOptions.bellStyle`\n * and `ITerminalOptions.bellSound`.\n */\n public bell(): boolean {\n this._onRequestBell.fire();\n return true;\n }\n\n /**\n * LF\n * Line Feed or New Line (NL). (LF is Ctrl-J).\n *\n * @vt: #Y C0 LF \"Line Feed\" \"\\n, \\x0A\" \"Move the cursor one row down, scrolling if needed.\"\n * Scrolling is restricted to scroll margins and will only happen on the bottom line.\n *\n * @vt: #Y C0 VT \"Vertical Tabulation\" \"\\v, \\x0B\" \"Treated as LF.\"\n * @vt: #Y C0 FF \"Form Feed\" \"\\f, \\x0C\" \"Treated as LF.\"\n */\n public lineFeed(): boolean {\n this._dirtyRowTracker.markDirty(this._activeBuffer.y);\n if (this._optionsService.rawOptions.convertEol) {\n this._activeBuffer.x = 0;\n }\n this._activeBuffer.y++;\n if (this._activeBuffer.y === this._activeBuffer.scrollBottom + 1) {\n this._activeBuffer.y--;\n this._bufferService.scroll(this._eraseAttrData());\n } else if (this._activeBuffer.y >= this._bufferService.rows) {\n this._activeBuffer.y = this._bufferService.rows - 1;\n } else {\n // There was an explicit line feed (not just a carriage return), so clear the wrapped state of\n // the line. This is particularly important on conpty/Windows where revisiting lines to\n // reprint is common, especially on resize. Note that the windowsMode wrapped line heuristics\n // can mess with this so windowsMode should be disabled, which is recommended on Windows build\n // 21376 and above.\n this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y)!.isWrapped = false;\n }\n // If the end of the line is hit, prevent this action from wrapping around to the next line.\n if (this._activeBuffer.x >= this._bufferService.cols) {\n this._activeBuffer.x--;\n }\n this._dirtyRowTracker.markDirty(this._activeBuffer.y);\n\n this._onLineFeed.fire();\n return true;\n }\n\n /**\n * CR\n * Carriage Return (Ctrl-M).\n *\n * @vt: #Y C0 CR \"Carriage Return\" \"\\r, \\x0D\" \"Move the cursor to the beginning of the row.\"\n */\n public carriageReturn(): boolean {\n this._activeBuffer.x = 0;\n return true;\n }\n\n /**\n * BS\n * Backspace (Ctrl-H).\n *\n * @vt: #Y C0 BS \"Backspace\" \"\\b, \\x08\" \"Move the cursor one position to the left.\"\n * By default it is not possible to move the cursor past the leftmost position.\n * If `reverse wrap-around` (`CSI ? 45 h`) is set, a previous soft line wrap (DECAWM)\n * can be undone with BS within the scroll margins. In that case the cursor will wrap back\n * to the end of the previous row. Note that it is not possible to peek back into the scrollbuffer\n * with the cursor, thus at the home position (top-leftmost cell) this has no effect.\n */\n public backspace(): boolean {\n // reverse wrap-around is disabled\n if (!this._coreService.decPrivateModes.reverseWraparound) {\n this._restrictCursor();\n if (this._activeBuffer.x > 0) {\n this._activeBuffer.x--;\n }\n return true;\n }\n\n // reverse wrap-around is enabled\n // other than for normal operation mode, reverse wrap-around allows the cursor\n // to be at x=cols to be able to address the last cell of a row by BS\n this._restrictCursor(this._bufferService.cols);\n\n if (this._activeBuffer.x > 0) {\n this._activeBuffer.x--;\n } else {\n /**\n * reverse wrap-around handling:\n * Our implementation deviates from xterm on purpose. Details:\n * - only previous soft NLs can be reversed (isWrapped=true)\n * - only works within scrollborders (top/bottom, left/right not yet supported)\n * - cannot peek into scrollbuffer\n * - any cursor movement sequence keeps working as expected\n */\n if (this._activeBuffer.x === 0\n && this._activeBuffer.y > this._activeBuffer.scrollTop\n && this._activeBuffer.y <= this._activeBuffer.scrollBottom\n && this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y)?.isWrapped) {\n this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y)!.isWrapped = false;\n this._activeBuffer.y--;\n this._activeBuffer.x = this._bufferService.cols - 1;\n // find last taken cell - last cell can have 3 different states:\n // - hasContent(true) + hasWidth(1): narrow char - we are done\n // - hasWidth(0): second part of wide char - we are done\n // - hasContent(false) + hasWidth(1): empty cell due to early wrapping wide char, go one\n // cell further back\n const line = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y)!;\n if (line.hasWidth(this._activeBuffer.x) && !line.hasContent(this._activeBuffer.x)) {\n this._activeBuffer.x--;\n // We do this only once, since width=1 + hasContent=false currently happens only once\n // before early wrapping of a wide char.\n // This needs to be fixed once we support graphemes taking more than 2 cells.\n }\n }\n }\n this._restrictCursor();\n return true;\n }\n\n /**\n * TAB\n * Horizontal Tab (HT) (Ctrl-I).\n *\n * @vt: #Y C0 HT \"Horizontal Tabulation\" \"\\t, \\x09\" \"Move the cursor to the next character tab stop.\"\n */\n public tab(): boolean {\n if (this._activeBuffer.x >= this._bufferService.cols) {\n return true;\n }\n const originalX = this._activeBuffer.x;\n this._activeBuffer.x = this._activeBuffer.nextStop();\n if (this._optionsService.rawOptions.screenReaderMode) {\n this._onA11yTab.fire(this._activeBuffer.x - originalX);\n }\n return true;\n }\n\n /**\n * SO\n * Shift Out (Ctrl-N) -> Switch to Alternate Character Set. This invokes the\n * G1 character set.\n *\n * @vt: #P[Only limited ISO-2022 charset support.] C0 SO \"Shift Out\" \"\\x0E\" \"Switch to an alternative character set.\"\n */\n public shiftOut(): boolean {\n this._charsetService.setgLevel(1);\n return true;\n }\n\n /**\n * SI\n * Shift In (Ctrl-O) -> Switch to Standard Character Set. This invokes the G0\n * character set (the default).\n *\n * @vt: #Y C0 SI \"Shift In\" \"\\x0F\" \"Return to regular character set after Shift Out.\"\n */\n public shiftIn(): boolean {\n this._charsetService.setgLevel(0);\n return true;\n }\n\n /**\n * Restrict cursor to viewport size / scroll margin (origin mode).\n */\n private _restrictCursor(maxCol: number = this._bufferService.cols - 1): void {\n this._activeBuffer.x = Math.min(maxCol, Math.max(0, this._activeBuffer.x));\n this._activeBuffer.y = this._coreService.decPrivateModes.origin\n ? Math.min(this._activeBuffer.scrollBottom, Math.max(this._activeBuffer.scrollTop, this._activeBuffer.y))\n : Math.min(this._bufferService.rows - 1, Math.max(0, this._activeBuffer.y));\n this._dirtyRowTracker.markDirty(this._activeBuffer.y);\n }\n\n /**\n * Set absolute cursor position.\n */\n private _setCursor(x: number, y: number): void {\n this._dirtyRowTracker.markDirty(this._activeBuffer.y);\n if (this._coreService.decPrivateModes.origin) {\n this._activeBuffer.x = x;\n this._activeBuffer.y = this._activeBuffer.scrollTop + y;\n } else {\n this._activeBuffer.x = x;\n this._activeBuffer.y = y;\n }\n this._restrictCursor();\n this._dirtyRowTracker.markDirty(this._activeBuffer.y);\n }\n\n /**\n * Set relative cursor position.\n */\n private _moveCursor(x: number, y: number): void {\n // for relative changes we have to make sure we are within 0 .. cols/rows - 1\n // before calculating the new position\n this._restrictCursor();\n this._setCursor(this._activeBuffer.x + x, this._activeBuffer.y + y);\n }\n\n /**\n * CSI Ps A\n * Cursor Up Ps Times (default = 1) (CUU).\n *\n * @vt: #Y CSI CUU \"Cursor Up\" \"CSI Ps A\" \"Move cursor `Ps` times up (default=1).\"\n * If the cursor would pass the top scroll margin, it will stop there.\n */\n public cursorUp(params: IParams): boolean {\n // stop at scrollTop\n const diffToTop = this._activeBuffer.y - this._activeBuffer.scrollTop;\n if (diffToTop >= 0) {\n this._moveCursor(0, -Math.min(diffToTop, params.params[0] || 1));\n } else {\n this._moveCursor(0, -(params.params[0] || 1));\n }\n return true;\n }\n\n /**\n * CSI Ps B\n * Cursor Down Ps Times (default = 1) (CUD).\n *\n * @vt: #Y CSI CUD \"Cursor Down\" \"CSI Ps B\" \"Move cursor `Ps` times down (default=1).\"\n * If the cursor would pass the bottom scroll margin, it will stop there.\n */\n public cursorDown(params: IParams): boolean {\n // stop at scrollBottom\n const diffToBottom = this._activeBuffer.scrollBottom - this._activeBuffer.y;\n if (diffToBottom >= 0) {\n this._moveCursor(0, Math.min(diffToBottom, params.params[0] || 1));\n } else {\n this._moveCursor(0, params.params[0] || 1);\n }\n return true;\n }\n\n /**\n * CSI Ps C\n * Cursor Forward Ps Times (default = 1) (CUF).\n *\n * @vt: #Y CSI CUF \"Cursor Forward\" \"CSI Ps C\" \"Move cursor `Ps` times forward (default=1).\"\n */\n public cursorForward(params: IParams): boolean {\n this._moveCursor(params.params[0] || 1, 0);\n return true;\n }\n\n /**\n * CSI Ps D\n * Cursor Backward Ps Times (default = 1) (CUB).\n *\n * @vt: #Y CSI CUB \"Cursor Backward\" \"CSI Ps D\" \"Move cursor `Ps` times backward (default=1).\"\n */\n public cursorBackward(params: IParams): boolean {\n this._moveCursor(-(params.params[0] || 1), 0);\n return true;\n }\n\n /**\n * CSI Ps E\n * Cursor Next Line Ps Times (default = 1) (CNL).\n * Other than cursorDown (CUD) also set the cursor to first column.\n *\n * @vt: #Y CSI CNL \"Cursor Next Line\" \"CSI Ps E\" \"Move cursor `Ps` times down (default=1) and to the first column.\"\n * Same as CUD, additionally places the cursor at the first column.\n */\n public cursorNextLine(params: IParams): boolean {\n this.cursorDown(params);\n this._activeBuffer.x = 0;\n return true;\n }\n\n /**\n * CSI Ps F\n * Cursor Previous Line Ps Times (default = 1) (CPL).\n * Other than cursorUp (CUU) also set the cursor to first column.\n *\n * @vt: #Y CSI CPL \"Cursor Backward\" \"CSI Ps F\" \"Move cursor `Ps` times up (default=1) and to the first column.\"\n * Same as CUU, additionally places the cursor at the first column.\n */\n public cursorPrecedingLine(params: IParams): boolean {\n this.cursorUp(params);\n this._activeBuffer.x = 0;\n return true;\n }\n\n /**\n * CSI Ps G\n * Cursor Character Absolute [column] (default = [row,1]) (CHA).\n *\n * @vt: #Y CSI CHA \"Cursor Horizontal Absolute\" \"CSI Ps G\" \"Move cursor to `Ps`-th column of the active row (default=1).\"\n */\n public cursorCharAbsolute(params: IParams): boolean {\n this._setCursor((params.params[0] || 1) - 1, this._activeBuffer.y);\n return true;\n }\n\n /**\n * CSI Ps ; Ps H\n * Cursor Position [row;column] (default = [1,1]) (CUP).\n *\n * @vt: #Y CSI CUP \"Cursor Position\" \"CSI Ps ; Ps H\" \"Set cursor to position [`Ps`, `Ps`] (default = [1, 1]).\"\n * If ORIGIN mode is set, places the cursor to the absolute position within the scroll margins.\n * If ORIGIN mode is not set, places the cursor to the absolute position within the viewport.\n * Note that the coordinates are 1-based, thus the top left position starts at `1 ; 1`.\n */\n public cursorPosition(params: IParams): boolean {\n this._setCursor(\n // col\n (params.length >= 2) ? (params.params[1] || 1) - 1 : 0,\n // row\n (params.params[0] || 1) - 1\n );\n return true;\n }\n\n /**\n * CSI Pm ` Character Position Absolute\n * [column] (default = [row,1]) (HPA).\n * Currently same functionality as CHA.\n *\n * @vt: #Y CSI HPA \"Horizontal Position Absolute\" \"CSI Ps ` \" \"Same as CHA.\"\n */\n public charPosAbsolute(params: IParams): boolean {\n this._setCursor((params.params[0] || 1) - 1, this._activeBuffer.y);\n return true;\n }\n\n /**\n * CSI Pm a Character Position Relative\n * [columns] (default = [row,col+1]) (HPR)\n *\n * @vt: #Y CSI HPR \"Horizontal Position Relative\" \"CSI Ps a\" \"Same as CUF.\"\n */\n public hPositionRelative(params: IParams): boolean {\n this._moveCursor(params.params[0] || 1, 0);\n return true;\n }\n\n /**\n * CSI Pm d Vertical Position Absolute (VPA)\n * [row] (default = [1,column])\n *\n * @vt: #Y CSI VPA \"Vertical Position Absolute\" \"CSI Ps d\" \"Move cursor to `Ps`-th row (default=1).\"\n */\n public linePosAbsolute(params: IParams): boolean {\n this._setCursor(this._activeBuffer.x, (params.params[0] || 1) - 1);\n return true;\n }\n\n /**\n * CSI Pm e Vertical Position Relative (VPR)\n * [rows] (default = [row+1,column])\n * reuse CSI Ps B ?\n *\n * @vt: #Y CSI VPR \"Vertical Position Relative\" \"CSI Ps e\" \"Move cursor `Ps` times down (default=1).\"\n */\n public vPositionRelative(params: IParams): boolean {\n this._moveCursor(0, params.params[0] || 1);\n return true;\n }\n\n /**\n * CSI Ps ; Ps f\n * Horizontal and Vertical Position [row;column] (default =\n * [1,1]) (HVP).\n * Same as CUP.\n *\n * @vt: #Y CSI HVP \"Horizontal and Vertical Position\" \"CSI Ps ; Ps f\" \"Same as CUP.\"\n */\n public hVPosition(params: IParams): boolean {\n this.cursorPosition(params);\n return true;\n }\n\n /**\n * CSI Ps g Tab Clear (TBC).\n * Ps = 0 -> Clear Current Column (default).\n * Ps = 3 -> Clear All.\n * Potentially:\n * Ps = 2 -> Clear Stops on Line.\n * http://vt100.net/annarbor/aaa-ug/section6.html\n *\n * @vt: #Y CSI TBC \"Tab Clear\" \"CSI Ps g\" \"Clear tab stops at current position (0) or all (3) (default=0).\"\n * Clearing tabstops off the active row (Ps = 2, VT100) is currently not supported.\n */\n public tabClear(params: IParams): boolean {\n const param = params.params[0];\n if (param === 0) {\n delete this._activeBuffer.tabs[this._activeBuffer.x];\n } else if (param === 3) {\n this._activeBuffer.tabs = {};\n }\n return true;\n }\n\n /**\n * CSI Ps I\n * Cursor Forward Tabulation Ps tab stops (default = 1) (CHT).\n *\n * @vt: #Y CSI CHT \"Cursor Horizontal Tabulation\" \"CSI Ps I\" \"Move cursor `Ps` times tabs forward (default=1).\"\n */\n public cursorForwardTab(params: IParams): boolean {\n if (this._activeBuffer.x >= this._bufferService.cols) {\n return true;\n }\n let param = params.params[0] || 1;\n while (param--) {\n this._activeBuffer.x = this._activeBuffer.nextStop();\n }\n return true;\n }\n\n /**\n * CSI Ps Z Cursor Backward Tabulation Ps tab stops (default = 1) (CBT).\n *\n * @vt: #Y CSI CBT \"Cursor Backward Tabulation\" \"CSI Ps Z\" \"Move cursor `Ps` tabs backward (default=1).\"\n */\n public cursorBackwardTab(params: IParams): boolean {\n if (this._activeBuffer.x >= this._bufferService.cols) {\n return true;\n }\n let param = params.params[0] || 1;\n\n while (param--) {\n this._activeBuffer.x = this._activeBuffer.prevStop();\n }\n return true;\n }\n\n /**\n * CSI Ps \" q Select Character Protection Attribute (DECSCA).\n *\n * @vt: #Y CSI DECSCA \"Select Character Protection Attribute\" \"CSI Ps \" q\" \"Whether DECSED and DECSEL can erase (0=default, 2) or not (1).\"\n */\n public selectProtected(params: IParams): boolean {\n const p = params.params[0];\n if (p === 1) this._curAttrData.bg |= BgFlags.PROTECTED;\n if (p === 2 || p === 0) this._curAttrData.bg &= ~BgFlags.PROTECTED;\n return true;\n }\n\n\n /**\n * Helper method to erase cells in a terminal row.\n * The cell gets replaced with the eraseChar of the terminal.\n * @param y The row index relative to the viewport.\n * @param start The start x index of the range to be erased.\n * @param end The end x index of the range to be erased (exclusive).\n * @param clearWrap clear the isWrapped flag\n * @param respectProtect Whether to respect the protection attribute (DECSCA).\n */\n private _eraseInBufferLine(y: number, start: number, end: number, clearWrap: boolean = false, respectProtect: boolean = false): void {\n const line = this._activeBuffer.lines.get(this._activeBuffer.ybase + y)!;\n line.replaceCells(\n start,\n end,\n this._activeBuffer.getNullCell(this._eraseAttrData()),\n respectProtect\n );\n if (clearWrap) {\n line.isWrapped = false;\n }\n }\n\n /**\n * Helper method to reset cells in a terminal row. The cell gets replaced with the eraseChar of\n * the terminal and the isWrapped property is set to false.\n * @param y row index\n */\n private _resetBufferLine(y: number, respectProtect: boolean = false): void {\n const line = this._activeBuffer.lines.get(this._activeBuffer.ybase + y);\n if (line) {\n line.fill(this._activeBuffer.getNullCell(this._eraseAttrData()), respectProtect);\n this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase + y);\n line.isWrapped = false;\n }\n }\n\n /**\n * CSI Ps J Erase in Display (ED).\n * Ps = 0 -> Erase Below (default).\n * Ps = 1 -> Erase Above.\n * Ps = 2 -> Erase All.\n * Ps = 3 -> Erase Saved Lines (xterm).\n * CSI ? Ps J\n * Erase in Display (DECSED).\n * Ps = 0 -> Selective Erase Below (default).\n * Ps = 1 -> Selective Erase Above.\n * Ps = 2 -> Selective Erase All.\n *\n * @vt: #Y CSI ED \"Erase In Display\" \"CSI Ps J\" \"Erase various parts of the viewport.\"\n * Supported param values:\n *\n * | Ps | Effect |\n * | -- | ------------------------------------------------------------ |\n * | 0 | Erase from the cursor through the end of the viewport. |\n * | 1 | Erase from the beginning of the viewport through the cursor. |\n * | 2 | Erase complete viewport. |\n * | 3 | Erase scrollback. |\n *\n * @vt: #Y CSI DECSED \"Selective Erase In Display\" \"CSI ? Ps J\" \"Same as ED with respecting protection flag.\"\n */\n public eraseInDisplay(params: IParams, respectProtect: boolean = false): boolean {\n this._restrictCursor(this._bufferService.cols);\n let j;\n switch (params.params[0]) {\n case 0:\n j = this._activeBuffer.y;\n this._dirtyRowTracker.markDirty(j);\n this._eraseInBufferLine(j++, this._activeBuffer.x, this._bufferService.cols, this._activeBuffer.x === 0, respectProtect);\n for (; j < this._bufferService.rows; j++) {\n this._resetBufferLine(j, respectProtect);\n }\n this._dirtyRowTracker.markDirty(j);\n break;\n case 1:\n j = this._activeBuffer.y;\n this._dirtyRowTracker.markDirty(j);\n // Deleted front part of line and everything before. This line will no longer be wrapped.\n this._eraseInBufferLine(j, 0, this._activeBuffer.x + 1, true, respectProtect);\n if (this._activeBuffer.x + 1 >= this._bufferService.cols) {\n // Deleted entire previous line. This next line can no longer be wrapped.\n this._activeBuffer.lines.get(j + 1)!.isWrapped = false;\n }\n while (j--) {\n this._resetBufferLine(j, respectProtect);\n }\n this._dirtyRowTracker.markDirty(0);\n break;\n case 2:\n if (this._optionsService.rawOptions.scrollOnEraseInDisplay) {\n j = this._bufferService.rows;\n this._dirtyRowTracker.markRangeDirty(0, j - 1);\n while (j--) {\n const currentLine = this._activeBuffer.lines.get(this._activeBuffer.ybase + j);\n if (currentLine?.getTrimmedLength()) {\n break;\n }\n }\n for (; j >= 0; j--) {\n this._bufferService.scroll(this._eraseAttrData());\n }\n }\n else {\n j = this._bufferService.rows;\n this._dirtyRowTracker.markDirty(j - 1);\n while (j--) {\n this._resetBufferLine(j, respectProtect);\n }\n this._dirtyRowTracker.markDirty(0);\n }\n break;\n case 3:\n // Clear scrollback (everything not in viewport)\n const scrollBackSize = this._activeBuffer.lines.length - this._bufferService.rows;\n if (scrollBackSize > 0) {\n this._activeBuffer.lines.trimStart(scrollBackSize);\n this._activeBuffer.ybase = Math.max(this._activeBuffer.ybase - scrollBackSize, 0);\n this._activeBuffer.ydisp = Math.max(this._activeBuffer.ydisp - scrollBackSize, 0);\n // Force a scroll event to refresh viewport\n this._onScroll.fire(0);\n }\n break;\n }\n return true;\n }\n\n /**\n * CSI Ps K Erase in Line (EL).\n * Ps = 0 -> Erase to Right (default).\n * Ps = 1 -> Erase to Left.\n * Ps = 2 -> Erase All.\n * CSI ? Ps K\n * Erase in Line (DECSEL).\n * Ps = 0 -> Selective Erase to Right (default).\n * Ps = 1 -> Selective Erase to Left.\n * Ps = 2 -> Selective Erase All.\n *\n * @vt: #Y CSI EL \"Erase In Line\" \"CSI Ps K\" \"Erase various parts of the active row.\"\n * Supported param values:\n *\n * | Ps | Effect |\n * | -- | -------------------------------------------------------- |\n * | 0 | Erase from the cursor through the end of the row. |\n * | 1 | Erase from the beginning of the line through the cursor. |\n * | 2 | Erase complete line. |\n *\n * @vt: #Y CSI DECSEL \"Selective Erase In Line\" \"CSI ? Ps K\" \"Same as EL with respecting protecting flag.\"\n */\n public eraseInLine(params: IParams, respectProtect: boolean = false): boolean {\n this._restrictCursor(this._bufferService.cols);\n switch (params.params[0]) {\n case 0:\n this._eraseInBufferLine(this._activeBuffer.y, this._activeBuffer.x, this._bufferService.cols, this._activeBuffer.x === 0, respectProtect);\n break;\n case 1:\n this._eraseInBufferLine(this._activeBuffer.y, 0, this._activeBuffer.x + 1, false, respectProtect);\n break;\n case 2:\n this._eraseInBufferLine(this._activeBuffer.y, 0, this._bufferService.cols, true, respectProtect);\n break;\n }\n this._dirtyRowTracker.markDirty(this._activeBuffer.y);\n return true;\n }\n\n /**\n * CSI Ps L\n * Insert Ps Line(s) (default = 1) (IL).\n *\n * @vt: #Y CSI IL \"Insert Line\" \"CSI Ps L\" \"Insert `Ps` blank lines at active row (default=1).\"\n * For every inserted line at the scroll top one line at the scroll bottom gets removed.\n * The cursor is set to the first column.\n * IL has no effect if the cursor is outside the scroll margins.\n */\n public insertLines(params: IParams): boolean {\n this._restrictCursor();\n let param = params.params[0] || 1;\n\n if (this._activeBuffer.y > this._activeBuffer.scrollBottom || this._activeBuffer.y < this._activeBuffer.scrollTop) {\n return true;\n }\n\n const row: number = this._activeBuffer.ybase + this._activeBuffer.y;\n\n const scrollBottomRowsOffset = this._bufferService.rows - 1 - this._activeBuffer.scrollBottom;\n const scrollBottomAbsolute = this._bufferService.rows - 1 + this._activeBuffer.ybase - scrollBottomRowsOffset + 1;\n while (param--) {\n // test: echo -e '\\e[44m\\e[1L\\e[0m'\n // blankLine(true) - xterm/linux behavior\n this._activeBuffer.lines.splice(scrollBottomAbsolute - 1, 1);\n this._activeBuffer.lines.splice(row, 0, this._activeBuffer.getBlankLine(this._eraseAttrData()));\n }\n\n this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y, this._activeBuffer.scrollBottom);\n this._activeBuffer.x = 0; // see https://vt100.net/docs/vt220-rm/chapter4.html - vt220 only?\n return true;\n }\n\n /**\n * CSI Ps M\n * Delete Ps Line(s) (default = 1) (DL).\n *\n * @vt: #Y CSI DL \"Delete Line\" \"CSI Ps M\" \"Delete `Ps` lines at active row (default=1).\"\n * For every deleted line at the scroll top one blank line at the scroll bottom gets appended.\n * The cursor is set to the first column.\n * DL has no effect if the cursor is outside the scroll margins.\n */\n public deleteLines(params: IParams): boolean {\n this._restrictCursor();\n let param = params.params[0] || 1;\n\n if (this._activeBuffer.y > this._activeBuffer.scrollBottom || this._activeBuffer.y < this._activeBuffer.scrollTop) {\n return true;\n }\n\n const row: number = this._activeBuffer.ybase + this._activeBuffer.y;\n\n let j: number;\n j = this._bufferService.rows - 1 - this._activeBuffer.scrollBottom;\n j = this._bufferService.rows - 1 + this._activeBuffer.ybase - j;\n while (param--) {\n // test: echo -e '\\e[44m\\e[1M\\e[0m'\n // blankLine(true) - xterm/linux behavior\n this._activeBuffer.lines.splice(row, 1);\n this._activeBuffer.lines.splice(j, 0, this._activeBuffer.getBlankLine(this._eraseAttrData()));\n }\n\n this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y, this._activeBuffer.scrollBottom);\n this._activeBuffer.x = 0; // see https://vt100.net/docs/vt220-rm/chapter4.html - vt220 only?\n return true;\n }\n\n /**\n * CSI Ps @\n * Insert Ps (Blank) Character(s) (default = 1) (ICH).\n *\n * @vt: #Y CSI ICH \"Insert Characters\" \"CSI Ps @\" \"Insert `Ps` (blank) characters (default = 1).\"\n * The ICH sequence inserts `Ps` blank characters. The cursor remains at the beginning of the\n * blank characters. Text between the cursor and right margin moves to the right. Characters moved\n * past the right margin are lost.\n *\n *\n * FIXME: check against xterm - should not work outside of scroll margins (see VT520 manual)\n */\n public insertChars(params: IParams): boolean {\n this._restrictCursor();\n const line = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y);\n if (line) {\n line.insertCells(\n this._activeBuffer.x,\n params.params[0] || 1,\n this._activeBuffer.getNullCell(this._eraseAttrData())\n );\n this._dirtyRowTracker.markDirty(this._activeBuffer.y);\n }\n return true;\n }\n\n /**\n * CSI Ps P\n * Delete Ps Character(s) (default = 1) (DCH).\n *\n * @vt: #Y CSI DCH \"Delete Character\" \"CSI Ps P\" \"Delete `Ps` characters (default=1).\"\n * As characters are deleted, the remaining characters between the cursor and right margin move to\n * the left. Character attributes move with the characters. The terminal adds blank characters at\n * the right margin.\n *\n *\n * FIXME: check against xterm - should not work outside of scroll margins (see VT520 manual)\n */\n public deleteChars(params: IParams): boolean {\n this._restrictCursor();\n const line = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y);\n if (line) {\n line.deleteCells(\n this._activeBuffer.x,\n params.params[0] || 1,\n this._activeBuffer.getNullCell(this._eraseAttrData())\n );\n this._dirtyRowTracker.markDirty(this._activeBuffer.y);\n }\n return true;\n }\n\n /**\n * CSI Ps S Scroll up Ps lines (default = 1) (SU).\n *\n * @vt: #Y CSI SU \"Scroll Up\" \"CSI Ps S\" \"Scroll `Ps` lines up (default=1).\"\n *\n *\n * FIXME: scrolled out lines at top = 1 should add to scrollback (xterm)\n */\n public scrollUp(params: IParams): boolean {\n let param = params.params[0] || 1;\n\n while (param--) {\n this._activeBuffer.lines.splice(this._activeBuffer.ybase + this._activeBuffer.scrollTop, 1);\n this._activeBuffer.lines.splice(this._activeBuffer.ybase + this._activeBuffer.scrollBottom, 0, this._activeBuffer.getBlankLine(this._eraseAttrData()));\n }\n this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom);\n return true;\n }\n\n /**\n * CSI Ps T Scroll down Ps lines (default = 1) (SD).\n *\n * @vt: #Y CSI SD \"Scroll Down\" \"CSI Ps T\" \"Scroll `Ps` lines down (default=1).\"\n */\n public scrollDown(params: IParams): boolean {\n let param = params.params[0] || 1;\n\n while (param--) {\n this._activeBuffer.lines.splice(this._activeBuffer.ybase + this._activeBuffer.scrollBottom, 1);\n this._activeBuffer.lines.splice(this._activeBuffer.ybase + this._activeBuffer.scrollTop, 0, this._activeBuffer.getBlankLine(DEFAULT_ATTR_DATA));\n }\n this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom);\n return true;\n }\n\n /**\n * CSI Ps SP @ Scroll left Ps columns (default = 1) (SL) ECMA-48\n *\n * Notation: (Pn)\n * Representation: CSI Pn 02/00 04/00\n * Parameter default value: Pn = 1\n * SL causes the data in the presentation component to be moved by n character positions\n * if the line orientation is horizontal, or by n line positions if the line orientation\n * is vertical, such that the data appear to move to the left; where n equals the value of Pn.\n * The active presentation position is not affected by this control function.\n *\n * Supported:\n * - always left shift (no line orientation setting respected)\n *\n * @vt: #Y CSI SL \"Scroll Left\" \"CSI Ps SP @\" \"Scroll viewport `Ps` times to the left.\"\n * SL moves the content of all lines within the scroll margins `Ps` times to the left.\n * SL has no effect outside of the scroll margins.\n */\n public scrollLeft(params: IParams): boolean {\n if (this._activeBuffer.y > this._activeBuffer.scrollBottom || this._activeBuffer.y < this._activeBuffer.scrollTop) {\n return true;\n }\n const param = params.params[0] || 1;\n for (let y = this._activeBuffer.scrollTop; y <= this._activeBuffer.scrollBottom; ++y) {\n const line = this._activeBuffer.lines.get(this._activeBuffer.ybase + y)!;\n line.deleteCells(0, param, this._activeBuffer.getNullCell(this._eraseAttrData()));\n line.isWrapped = false;\n }\n this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom);\n return true;\n }\n\n /**\n * CSI Ps SP A Scroll right Ps columns (default = 1) (SR) ECMA-48\n *\n * Notation: (Pn)\n * Representation: CSI Pn 02/00 04/01\n * Parameter default value: Pn = 1\n * SR causes the data in the presentation component to be moved by n character positions\n * if the line orientation is horizontal, or by n line positions if the line orientation\n * is vertical, such that the data appear to move to the right; where n equals the value of Pn.\n * The active presentation position is not affected by this control function.\n *\n * Supported:\n * - always right shift (no line orientation setting respected)\n *\n * @vt: #Y CSI SR \"Scroll Right\" \"CSI Ps SP A\" \"Scroll viewport `Ps` times to the right.\"\n * SL moves the content of all lines within the scroll margins `Ps` times to the right.\n * Content at the right margin is lost.\n * SL has no effect outside of the scroll margins.\n */\n public scrollRight(params: IParams): boolean {\n if (this._activeBuffer.y > this._activeBuffer.scrollBottom || this._activeBuffer.y < this._activeBuffer.scrollTop) {\n return true;\n }\n const param = params.params[0] || 1;\n for (let y = this._activeBuffer.scrollTop; y <= this._activeBuffer.scrollBottom; ++y) {\n const line = this._activeBuffer.lines.get(this._activeBuffer.ybase + y)!;\n line.insertCells(0, param, this._activeBuffer.getNullCell(this._eraseAttrData()));\n line.isWrapped = false;\n }\n this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom);\n return true;\n }\n\n /**\n * CSI Pm ' }\n * Insert Ps Column(s) (default = 1) (DECIC), VT420 and up.\n *\n * @vt: #Y CSI DECIC \"Insert Columns\" \"CSI Ps ' }\" \"Insert `Ps` columns at cursor position.\"\n * DECIC inserts `Ps` times blank columns at the cursor position for all lines with the scroll\n * margins, moving content to the right. Content at the right margin is lost. DECIC has no effect\n * outside the scrolling margins.\n */\n public insertColumns(params: IParams): boolean {\n if (this._activeBuffer.y > this._activeBuffer.scrollBottom || this._activeBuffer.y < this._activeBuffer.scrollTop) {\n return true;\n }\n const param = params.params[0] || 1;\n for (let y = this._activeBuffer.scrollTop; y <= this._activeBuffer.scrollBottom; ++y) {\n const line = this._activeBuffer.lines.get(this._activeBuffer.ybase + y)!;\n line.insertCells(this._activeBuffer.x, param, this._activeBuffer.getNullCell(this._eraseAttrData()));\n line.isWrapped = false;\n }\n this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom);\n return true;\n }\n\n /**\n * CSI Pm ' ~\n * Delete Ps Column(s) (default = 1) (DECDC), VT420 and up.\n *\n * @vt: #Y CSI DECDC \"Delete Columns\" \"CSI Ps ' ~\" \"Delete `Ps` columns at cursor position.\"\n * DECDC deletes `Ps` times columns at the cursor position for all lines with the scroll margins,\n * moving content to the left. Blank columns are added at the right margin.\n * DECDC has no effect outside the scrolling margins.\n */\n public deleteColumns(params: IParams): boolean {\n if (this._activeBuffer.y > this._activeBuffer.scrollBottom || this._activeBuffer.y < this._activeBuffer.scrollTop) {\n return true;\n }\n const param = params.params[0] || 1;\n for (let y = this._activeBuffer.scrollTop; y <= this._activeBuffer.scrollBottom; ++y) {\n const line = this._activeBuffer.lines.get(this._activeBuffer.ybase + y)!;\n line.deleteCells(this._activeBuffer.x, param, this._activeBuffer.getNullCell(this._eraseAttrData()));\n line.isWrapped = false;\n }\n this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom);\n return true;\n }\n\n /**\n * CSI Ps X\n * Erase Ps Character(s) (default = 1) (ECH).\n *\n * @vt: #Y CSI ECH \"Erase Character\" \"CSI Ps X\" \"Erase `Ps` characters from current cursor position to the right (default=1).\"\n * ED erases `Ps` characters from current cursor position to the right.\n * ED works inside or outside the scrolling margins.\n */\n public eraseChars(params: IParams): boolean {\n this._restrictCursor();\n const line = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y);\n if (line) {\n line.replaceCells(\n this._activeBuffer.x,\n this._activeBuffer.x + (params.params[0] || 1),\n this._activeBuffer.getNullCell(this._eraseAttrData())\n );\n this._dirtyRowTracker.markDirty(this._activeBuffer.y);\n }\n return true;\n }\n\n /**\n * CSI Ps b Repeat the preceding graphic character Ps times (REP).\n * From ECMA 48 (@see http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-048.pdf)\n * Notation: (Pn)\n * Representation: CSI Pn 06/02\n * Parameter default value: Pn = 1\n * REP is used to indicate that the preceding character in the data stream,\n * if it is a graphic character (represented by one or more bit combinations) including SPACE,\n * is to be repeated n times, where n equals the value of Pn.\n * If the character preceding REP is a control function or part of a control function,\n * the effect of REP is not defined by this Standard.\n *\n * We extend xterm's behavior to allow repeating entire grapheme clusters.\n * This isn't 100% xterm-compatible, but it seems saner and more useful.\n * - text attrs are applied normally\n * - wrap around is respected\n * - any valid sequence resets the carried forward char\n *\n * Note: To get reset on a valid sequence working correctly without much runtime penalty, the\n * preceding codepoint is stored on the parser in `this.print` and reset during `parser.parse`.\n *\n * @vt: #Y CSI REP \"Repeat Preceding Character\" \"CSI Ps b\" \"Repeat preceding character `Ps` times (default=1).\"\n * REP repeats the previous character `Ps` times advancing the cursor, also wrapping if DECAWM is\n * set. REP has no effect if the sequence does not follow a printable ASCII character\n * (NOOP for any other sequence in between or NON ASCII characters).\n */\n public repeatPrecedingCharacter(params: IParams): boolean {\n const joinState = this._parser.precedingJoinState;\n if (!joinState) {\n return true;\n }\n // call print to insert the chars and handle correct wrapping\n const length = params.params[0] || 1;\n const chWidth = UnicodeService.extractWidth(joinState);\n const x = this._activeBuffer.x - chWidth;\n const bufferRow = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y)!;\n const text = bufferRow.getString(x);\n const data = new Uint32Array(text.length * length);\n let idata = 0;\n for (let itext = 0; itext < text.length;) {\n const ch = text.codePointAt(itext) || 0;\n data[idata++] = ch;\n itext += ch > 0xffff ? 2 : 1;\n }\n let tlength = idata;\n for (let i = 1; i < length; ++i) {\n data.copyWithin(tlength, 0, idata);\n tlength += idata;\n }\n this.print(data, 0, tlength);\n return true;\n }\n\n /**\n * CSI Ps c Send Device Attributes (Primary DA).\n * Ps = 0 or omitted -> request attributes from terminal. The\n * response depends on the decTerminalID resource setting.\n * -> CSI ? 1 ; 2 c (``VT100 with Advanced Video Option'')\n * -> CSI ? 1 ; 0 c (``VT101 with No Options'')\n * -> CSI ? 6 c (``VT102'')\n * -> CSI ? 6 0 ; 1 ; 2 ; 6 ; 8 ; 9 ; 1 5 ; c (``VT220'')\n * The VT100-style response parameters do not mean anything by\n * themselves. VT220 parameters do, telling the host what fea-\n * tures the terminal supports:\n * Ps = 1 -> 132-columns.\n * Ps = 2 -> Printer.\n * Ps = 6 -> Selective erase.\n * Ps = 8 -> User-defined keys.\n * Ps = 9 -> National replacement character sets.\n * Ps = 1 5 -> Technical characters.\n * Ps = 2 2 -> ANSI color, e.g., VT525.\n * Ps = 2 9 -> ANSI text locator (i.e., DEC Locator mode).\n *\n * @vt: #Y CSI DA1 \"Primary Device Attributes\" \"CSI c\" \"Send primary device attributes.\"\n *\n *\n * TODO: fix and cleanup response\n */\n public sendDeviceAttributesPrimary(params: IParams): boolean {\n if (params.params[0] > 0) {\n return true;\n }\n if (this._is('xterm') || this._is('rxvt-unicode') || this._is('screen')) {\n this._coreService.triggerDataEvent(C0.ESC + '[?1;2c');\n } else if (this._is('linux')) {\n this._coreService.triggerDataEvent(C0.ESC + '[?6c');\n }\n return true;\n }\n\n /**\n * CSI > Ps c\n * Send Device Attributes (Secondary DA).\n * Ps = 0 or omitted -> request the terminal's identification\n * code. The response depends on the decTerminalID resource set-\n * ting. It should apply only to VT220 and up, but xterm extends\n * this to VT100.\n * -> CSI > Pp ; Pv ; Pc c\n * where Pp denotes the terminal type\n * Pp = 0 -> ``VT100''.\n * Pp = 1 -> ``VT220''.\n * and Pv is the firmware version (for xterm, this was originally\n * the XFree86 patch number, starting with 95). In a DEC termi-\n * nal, Pc indicates the ROM cartridge registration number and is\n * always zero.\n * More information:\n * xterm/charproc.c - line 2012, for more information.\n * vim responds with ^[[?0c or ^[[?1c after the terminal's response (?)\n *\n * @vt: #Y CSI DA2 \"Secondary Device Attributes\" \"CSI > c\" \"Send primary device attributes.\"\n *\n *\n * TODO: fix and cleanup response\n */\n public sendDeviceAttributesSecondary(params: IParams): boolean {\n if (params.params[0] > 0) {\n return true;\n }\n // xterm and urxvt\n // seem to spit this\n // out around ~370 times (?).\n if (this._is('xterm')) {\n this._coreService.triggerDataEvent(C0.ESC + '[>0;276;0c');\n } else if (this._is('rxvt-unicode')) {\n this._coreService.triggerDataEvent(C0.ESC + '[>85;95;0c');\n } else if (this._is('linux')) {\n // not supported by linux console.\n // linux console echoes parameters.\n this._coreService.triggerDataEvent(params.params[0] + 'c');\n } else if (this._is('screen')) {\n this._coreService.triggerDataEvent(C0.ESC + '[>83;40003;0c');\n }\n return true;\n }\n\n /**\n * Evaluate if the current terminal is the given argument.\n * @param term The terminal name to evaluate\n */\n private _is(term: string): boolean {\n return (this._optionsService.rawOptions.termName + '').indexOf(term) === 0;\n }\n\n /**\n * CSI Pm h Set Mode (SM).\n * Ps = 2 -> Keyboard Action Mode (AM).\n * Ps = 4 -> Insert Mode (IRM).\n * Ps = 1 2 -> Send/receive (SRM).\n * Ps = 2 0 -> Automatic Newline (LNM).\n *\n * @vt: #P[Only IRM is supported.] CSI SM \"Set Mode\" \"CSI Pm h\" \"Set various terminal modes.\"\n * Supported param values by SM:\n *\n * | Param | Action | Support |\n * | ----- | -------------------------------------- | ------- |\n * | 2 | Keyboard Action Mode (KAM). Always on. | #N |\n * | 4 | Insert Mode (IRM). | #Y |\n * | 12 | Send/receive (SRM). Always off. | #N |\n * | 20 | Automatic Newline (LNM). | #Y |\n */\n public setMode(params: IParams): boolean {\n for (let i = 0; i < params.length; i++) {\n switch (params.params[i]) {\n case 4:\n this._coreService.modes.insertMode = true;\n break;\n case 20:\n this._optionsService.options.convertEol = true;\n break;\n }\n }\n return true;\n }\n\n /**\n * CSI ? Pm h\n * DEC Private Mode Set (DECSET).\n * Ps = 1 -> Application Cursor Keys (DECCKM).\n * Ps = 2 -> Designate USASCII for character sets G0-G3\n * (DECANM), and set VT100 mode.\n * Ps = 3 -> 132 Column Mode (DECCOLM).\n * Ps = 4 -> Smooth (Slow) Scroll (DECSCLM).\n * Ps = 5 -> Reverse Video (DECSCNM).\n * Ps = 6 -> Origin Mode (DECOM).\n * Ps = 7 -> Wraparound Mode (DECAWM).\n * Ps = 8 -> Auto-repeat Keys (DECARM).\n * Ps = 9 -> Send Mouse X & Y on button press. See the sec-\n * tion Mouse Tracking.\n * Ps = 1 0 -> Show toolbar (rxvt).\n * Ps = 1 2 -> Start Blinking Cursor (att610).\n * Ps = 1 8 -> Print form feed (DECPFF).\n * Ps = 1 9 -> Set print extent to full screen (DECPEX).\n * Ps = 2 5 -> Show Cursor (DECTCEM).\n * Ps = 3 0 -> Show scrollbar (rxvt).\n * Ps = 3 5 -> Enable font-shifting functions (rxvt).\n * Ps = 3 8 -> Enter Tektronix Mode (DECTEK).\n * Ps = 4 0 -> Allow 80 -> 132 Mode.\n * Ps = 4 1 -> more(1) fix (see curses resource).\n * Ps = 4 2 -> Enable Nation Replacement Character sets (DECN-\n * RCM).\n * Ps = 4 4 -> Turn On Margin Bell.\n * Ps = 4 5 -> Reverse-wraparound Mode.\n * Ps = 4 6 -> Start Logging. This is normally disabled by a\n * compile-time option.\n * Ps = 4 7 -> Use Alternate Screen Buffer. (This may be dis-\n * abled by the titeInhibit resource).\n * Ps = 6 6 -> Application keypad (DECNKM).\n * Ps = 6 7 -> Backarrow key sends backspace (DECBKM).\n * Ps = 1 0 0 0 -> Send Mouse X & Y on button press and\n * release. See the section Mouse Tracking.\n * Ps = 1 0 0 1 -> Use Hilite Mouse Tracking.\n * Ps = 1 0 0 2 -> Use Cell Motion Mouse Tracking.\n * Ps = 1 0 0 3 -> Use All Motion Mouse Tracking.\n * Ps = 1 0 0 4 -> Send FocusIn/FocusOut events.\n * Ps = 1 0 0 5 -> Enable Extended Mouse Mode.\n * Ps = 1 0 1 0 -> Scroll to bottom on tty output (rxvt).\n * Ps = 1 0 1 1 -> Scroll to bottom on key press (rxvt).\n * Ps = 1 0 3 4 -> Interpret \"meta\" key, sets eighth bit.\n * (enables the eightBitInput resource).\n * Ps = 1 0 3 5 -> Enable special modifiers for Alt and Num-\n * Lock keys. (This enables the numLock resource).\n * Ps = 1 0 3 6 -> Send ESC when Meta modifies a key. (This\n * enables the metaSendsEscape resource).\n * Ps = 1 0 3 7 -> Send DEL from the editing-keypad Delete\n * key.\n * Ps = 1 0 3 9 -> Send ESC when Alt modifies a key. (This\n * enables the altSendsEscape resource).\n * Ps = 1 0 4 0 -> Keep selection even if not highlighted.\n * (This enables the keepSelection resource).\n * Ps = 1 0 4 1 -> Use the CLIPBOARD selection. (This enables\n * the selectToClipboard resource).\n * Ps = 1 0 4 2 -> Enable Urgency window manager hint when\n * Control-G is received. (This enables the bellIsUrgent\n * resource).\n * Ps = 1 0 4 3 -> Enable raising of the window when Control-G\n * is received. (enables the popOnBell resource).\n * Ps = 1 0 4 7 -> Use Alternate Screen Buffer. (This may be\n * disabled by the titeInhibit resource).\n * Ps = 1 0 4 8 -> Save cursor as in DECSC. (This may be dis-\n * abled by the titeInhibit resource).\n * Ps = 1 0 4 9 -> Save cursor as in DECSC and use Alternate\n * Screen Buffer, clearing it first. (This may be disabled by\n * the titeInhibit resource). This combines the effects of the 1\n * 0 4 7 and 1 0 4 8 modes. Use this with terminfo-based\n * applications rather than the 4 7 mode.\n * Ps = 1 0 5 0 -> Set terminfo/termcap function-key mode.\n * Ps = 1 0 5 1 -> Set Sun function-key mode.\n * Ps = 1 0 5 2 -> Set HP function-key mode.\n * Ps = 1 0 5 3 -> Set SCO function-key mode.\n * Ps = 1 0 6 0 -> Set legacy keyboard emulation (X11R6).\n * Ps = 1 0 6 1 -> Set VT220 keyboard emulation.\n * Ps = 2 0 0 4 -> Set bracketed paste mode.\n * Modes:\n * http: *vt100.net/docs/vt220-rm/chapter4.html\n *\n * @vt: #P[See below for supported modes.] CSI DECSET \"DEC Private Set Mode\" \"CSI ? Pm h\" \"Set various terminal attributes.\"\n * Supported param values by DECSET:\n *\n * | param | Action | Support |\n * | ----- | ------------------------------------------------------- | --------|\n * | 1 | Application Cursor Keys (DECCKM). | #Y |\n * | 2 | Designate US-ASCII for character sets G0-G3 (DECANM). | #Y |\n * | 3 | 132 Column Mode (DECCOLM). | #Y |\n * | 6 | Origin Mode (DECOM). | #Y |\n * | 7 | Auto-wrap Mode (DECAWM). | #Y |\n * | 8 | Auto-repeat Keys (DECARM). Always on. | #N |\n * | 9 | X10 xterm mouse protocol. | #Y |\n * | 12 | Start Blinking Cursor. | #Y |\n * | 25 | Show Cursor (DECTCEM). | #Y |\n * | 45 | Reverse wrap-around. | #Y |\n * | 47 | Use Alternate Screen Buffer. | #Y |\n * | 66 | Application keypad (DECNKM). | #Y |\n * | 1000 | X11 xterm mouse protocol. | #Y |\n * | 1002 | Use Cell Motion Mouse Tracking. | #Y |\n * | 1003 | Use All Motion Mouse Tracking. | #Y |\n * | 1004 | Send FocusIn/FocusOut events | #Y |\n * | 1005 | Enable UTF-8 Mouse Mode. | #N |\n * | 1006 | Enable SGR Mouse Mode. | #Y |\n * | 1015 | Enable urxvt Mouse Mode. | #N |\n * | 1016 | Enable SGR-Pixels Mouse Mode. | #Y |\n * | 1047 | Use Alternate Screen Buffer. | #Y |\n * | 1048 | Save cursor as in DECSC. | #Y |\n * | 1049 | Save cursor and switch to alternate buffer clearing it. | #P[Does not clear the alternate buffer.] |\n * | 2004 | Set bracketed paste mode. | #Y |\n *\n *\n * FIXME: implement DECSCNM, 1049 should clear altbuffer\n */\n public setModePrivate(params: IParams): boolean {\n for (let i = 0; i < params.length; i++) {\n switch (params.params[i]) {\n case 1:\n this._coreService.decPrivateModes.applicationCursorKeys = true;\n break;\n case 2:\n this._charsetService.setgCharset(0, DEFAULT_CHARSET);\n this._charsetService.setgCharset(1, DEFAULT_CHARSET);\n this._charsetService.setgCharset(2, DEFAULT_CHARSET);\n this._charsetService.setgCharset(3, DEFAULT_CHARSET);\n // set VT100 mode here\n break;\n case 3:\n /**\n * DECCOLM - 132 column mode.\n * This is only active if 'SetWinLines' (24) is enabled\n * through `options.windowsOptions`.\n */\n if (this._optionsService.rawOptions.windowOptions.setWinLines) {\n this._bufferService.resize(132, this._bufferService.rows);\n this._onRequestReset.fire();\n }\n break;\n case 6:\n this._coreService.decPrivateModes.origin = true;\n this._setCursor(0, 0);\n break;\n case 7:\n this._coreService.decPrivateModes.wraparound = true;\n break;\n case 12:\n this._optionsService.options.cursorBlink = true;\n break;\n case 45:\n this._coreService.decPrivateModes.reverseWraparound = true;\n break;\n case 66:\n this._logService.debug('Serial port requested application keypad.');\n this._coreService.decPrivateModes.applicationKeypad = true;\n this._onRequestSyncScrollBar.fire();\n break;\n case 9: // X10 Mouse\n // no release, no motion, no wheel, no modifiers.\n this._coreMouseService.activeProtocol = 'X10';\n break;\n case 1000: // vt200 mouse\n // no motion.\n this._coreMouseService.activeProtocol = 'VT200';\n break;\n case 1002: // button event mouse\n this._coreMouseService.activeProtocol = 'DRAG';\n break;\n case 1003: // any event mouse\n // any event - sends motion events,\n // even if there is no button held down.\n this._coreMouseService.activeProtocol = 'ANY';\n break;\n case 1004: // send focusin/focusout events\n // focusin: ^[[I\n // focusout: ^[[O\n this._coreService.decPrivateModes.sendFocus = true;\n this._onRequestSendFocus.fire();\n break;\n case 1005: // utf8 ext mode mouse - removed in #2507\n this._logService.debug('DECSET 1005 not supported (see #2507)');\n break;\n case 1006: // sgr ext mode mouse\n this._coreMouseService.activeEncoding = 'SGR';\n break;\n case 1015: // urxvt ext mode mouse - removed in #2507\n this._logService.debug('DECSET 1015 not supported (see #2507)');\n break;\n case 1016: // sgr pixels mode mouse\n this._coreMouseService.activeEncoding = 'SGR_PIXELS';\n break;\n case 25: // show cursor\n this._coreService.isCursorHidden = false;\n break;\n case 1048: // alt screen cursor\n this.saveCursor();\n break;\n case 1049: // alt screen buffer cursor\n this.saveCursor();\n // FALL-THROUGH\n case 47: // alt screen buffer\n case 1047: // alt screen buffer\n this._bufferService.buffers.activateAltBuffer(this._eraseAttrData());\n this._coreService.isCursorInitialized = true;\n this._onRequestRefreshRows.fire(undefined);\n this._onRequestSyncScrollBar.fire();\n break;\n case 2004: // bracketed paste mode (https://cirw.in/blog/bracketed-paste)\n this._coreService.decPrivateModes.bracketedPasteMode = true;\n break;\n case 2026: // synchronized output (https://github.com/contour-terminal/vt-extensions/blob/master/synchronized-output.md)\n this._coreService.decPrivateModes.synchronizedOutput = true;\n break;\n }\n }\n return true;\n }\n\n\n /**\n * CSI Pm l Reset Mode (RM).\n * Ps = 2 -> Keyboard Action Mode (AM).\n * Ps = 4 -> Replace Mode (IRM).\n * Ps = 1 2 -> Send/receive (SRM).\n * Ps = 2 0 -> Normal Linefeed (LNM).\n *\n * @vt: #P[Only IRM is supported.] CSI RM \"Reset Mode\" \"CSI Pm l\" \"Set various terminal attributes.\"\n * Supported param values by RM:\n *\n * | Param | Action | Support |\n * | ----- | -------------------------------------- | ------- |\n * | 2 | Keyboard Action Mode (KAM). Always on. | #N |\n * | 4 | Replace Mode (IRM). (default) | #Y |\n * | 12 | Send/receive (SRM). Always off. | #N |\n * | 20 | Normal Linefeed (LNM). | #Y |\n *\n *\n * FIXME: why is LNM commented out?\n */\n public resetMode(params: IParams): boolean {\n for (let i = 0; i < params.length; i++) {\n switch (params.params[i]) {\n case 4:\n this._coreService.modes.insertMode = false;\n break;\n case 20:\n this._optionsService.options.convertEol = false;\n break;\n }\n }\n return true;\n }\n\n /**\n * CSI ? Pm l\n * DEC Private Mode Reset (DECRST).\n * Ps = 1 -> Normal Cursor Keys (DECCKM).\n * Ps = 2 -> Designate VT52 mode (DECANM).\n * Ps = 3 -> 80 Column Mode (DECCOLM).\n * Ps = 4 -> Jump (Fast) Scroll (DECSCLM).\n * Ps = 5 -> Normal Video (DECSCNM).\n * Ps = 6 -> Normal Cursor Mode (DECOM).\n * Ps = 7 -> No Wraparound Mode (DECAWM).\n * Ps = 8 -> No Auto-repeat Keys (DECARM).\n * Ps = 9 -> Don't send Mouse X & Y on button press.\n * Ps = 1 0 -> Hide toolbar (rxvt).\n * Ps = 1 2 -> Stop Blinking Cursor (att610).\n * Ps = 1 8 -> Don't print form feed (DECPFF).\n * Ps = 1 9 -> Limit print to scrolling region (DECPEX).\n * Ps = 2 5 -> Hide Cursor (DECTCEM).\n * Ps = 3 0 -> Don't show scrollbar (rxvt).\n * Ps = 3 5 -> Disable font-shifting functions (rxvt).\n * Ps = 4 0 -> Disallow 80 -> 132 Mode.\n * Ps = 4 1 -> No more(1) fix (see curses resource).\n * Ps = 4 2 -> Disable Nation Replacement Character sets (DEC-\n * NRCM).\n * Ps = 4 4 -> Turn Off Margin Bell.\n * Ps = 4 5 -> No Reverse-wraparound Mode.\n * Ps = 4 6 -> Stop Logging. (This is normally disabled by a\n * compile-time option).\n * Ps = 4 7 -> Use Normal Screen Buffer.\n * Ps = 6 6 -> Numeric keypad (DECNKM).\n * Ps = 6 7 -> Backarrow key sends delete (DECBKM).\n * Ps = 1 0 0 0 -> Don't send Mouse X & Y on button press and\n * release. See the section Mouse Tracking.\n * Ps = 1 0 0 1 -> Don't use Hilite Mouse Tracking.\n * Ps = 1 0 0 2 -> Don't use Cell Motion Mouse Tracking.\n * Ps = 1 0 0 3 -> Don't use All Motion Mouse Tracking.\n * Ps = 1 0 0 4 -> Don't send FocusIn/FocusOut events.\n * Ps = 1 0 0 5 -> Disable Extended Mouse Mode.\n * Ps = 1 0 1 0 -> Don't scroll to bottom on tty output\n * (rxvt).\n * Ps = 1 0 1 1 -> Don't scroll to bottom on key press (rxvt).\n * Ps = 1 0 3 4 -> Don't interpret \"meta\" key. (This disables\n * the eightBitInput resource).\n * Ps = 1 0 3 5 -> Disable special modifiers for Alt and Num-\n * Lock keys. (This disables the numLock resource).\n * Ps = 1 0 3 6 -> Don't send ESC when Meta modifies a key.\n * (This disables the metaSendsEscape resource).\n * Ps = 1 0 3 7 -> Send VT220 Remove from the editing-keypad\n * Delete key.\n * Ps = 1 0 3 9 -> Don't send ESC when Alt modifies a key.\n * (This disables the altSendsEscape resource).\n * Ps = 1 0 4 0 -> Do not keep selection when not highlighted.\n * (This disables the keepSelection resource).\n * Ps = 1 0 4 1 -> Use the PRIMARY selection. (This disables\n * the selectToClipboard resource).\n * Ps = 1 0 4 2 -> Disable Urgency window manager hint when\n * Control-G is received. (This disables the bellIsUrgent\n * resource).\n * Ps = 1 0 4 3 -> Disable raising of the window when Control-\n * G is received. (This disables the popOnBell resource).\n * Ps = 1 0 4 7 -> Use Normal Screen Buffer, clearing screen\n * first if in the Alternate Screen. (This may be disabled by\n * the titeInhibit resource).\n * Ps = 1 0 4 8 -> Restore cursor as in DECRC. (This may be\n * disabled by the titeInhibit resource).\n * Ps = 1 0 4 9 -> Use Normal Screen Buffer and restore cursor\n * as in DECRC. (This may be disabled by the titeInhibit\n * resource). This combines the effects of the 1 0 4 7 and 1 0\n * 4 8 modes. Use this with terminfo-based applications rather\n * than the 4 7 mode.\n * Ps = 1 0 5 0 -> Reset terminfo/termcap function-key mode.\n * Ps = 1 0 5 1 -> Reset Sun function-key mode.\n * Ps = 1 0 5 2 -> Reset HP function-key mode.\n * Ps = 1 0 5 3 -> Reset SCO function-key mode.\n * Ps = 1 0 6 0 -> Reset legacy keyboard emulation (X11R6).\n * Ps = 1 0 6 1 -> Reset keyboard emulation to Sun/PC style.\n * Ps = 2 0 0 4 -> Reset bracketed paste mode.\n *\n * @vt: #P[See below for supported modes.] CSI DECRST \"DEC Private Reset Mode\" \"CSI ? Pm l\" \"Reset various terminal attributes.\"\n * Supported param values by DECRST:\n *\n * | param | Action | Support |\n * | ----- | ------------------------------------------------------- | ------- |\n * | 1 | Normal Cursor Keys (DECCKM). | #Y |\n * | 2 | Designate VT52 mode (DECANM). | #N |\n * | 3 | 80 Column Mode (DECCOLM). | #B[Switches to old column width instead of 80.] |\n * | 6 | Normal Cursor Mode (DECOM). | #Y |\n * | 7 | No Wraparound Mode (DECAWM). | #Y |\n * | 8 | No Auto-repeat Keys (DECARM). | #N |\n * | 9 | Don't send Mouse X & Y on button press. | #Y |\n * | 12 | Stop Blinking Cursor. | #Y |\n * | 25 | Hide Cursor (DECTCEM). | #Y |\n * | 45 | No reverse wrap-around. | #Y |\n * | 47 | Use Normal Screen Buffer. | #Y |\n * | 66 | Numeric keypad (DECNKM). | #Y |\n * | 1000 | Don't send Mouse reports. | #Y |\n * | 1002 | Don't use Cell Motion Mouse Tracking. | #Y |\n * | 1003 | Don't use All Motion Mouse Tracking. | #Y |\n * | 1004 | Don't send FocusIn/FocusOut events. | #Y |\n * | 1005 | Disable UTF-8 Mouse Mode. | #N |\n * | 1006 | Disable SGR Mouse Mode. | #Y |\n * | 1015 | Disable urxvt Mouse Mode. | #N |\n * | 1016 | Disable SGR-Pixels Mouse Mode. | #Y |\n * | 1047 | Use Normal Screen Buffer (clearing screen if in alt). | #Y |\n * | 1048 | Restore cursor as in DECRC. | #Y |\n * | 1049 | Use Normal Screen Buffer and restore cursor. | #Y |\n * | 2004 | Reset bracketed paste mode. | #Y |\n *\n *\n * FIXME: DECCOLM is currently broken (already fixed in window options PR)\n */\n public resetModePrivate(params: IParams): boolean {\n for (let i = 0; i < params.length; i++) {\n switch (params.params[i]) {\n case 1:\n this._coreService.decPrivateModes.applicationCursorKeys = false;\n break;\n case 3:\n /**\n * DECCOLM - 80 column mode.\n * This is only active if 'SetWinLines' (24) is enabled\n * through `options.windowsOptions`.\n */\n if (this._optionsService.rawOptions.windowOptions.setWinLines) {\n this._bufferService.resize(80, this._bufferService.rows);\n this._onRequestReset.fire();\n }\n break;\n case 6:\n this._coreService.decPrivateModes.origin = false;\n this._setCursor(0, 0);\n break;\n case 7:\n this._coreService.decPrivateModes.wraparound = false;\n break;\n case 12:\n this._optionsService.options.cursorBlink = false;\n break;\n case 45:\n this._coreService.decPrivateModes.reverseWraparound = false;\n break;\n case 66:\n this._logService.debug('Switching back to normal keypad.');\n this._coreService.decPrivateModes.applicationKeypad = false;\n this._onRequestSyncScrollBar.fire();\n break;\n case 9: // X10 Mouse\n case 1000: // vt200 mouse\n case 1002: // button event mouse\n case 1003: // any event mouse\n this._coreMouseService.activeProtocol = 'NONE';\n break;\n case 1004: // send focusin/focusout events\n this._coreService.decPrivateModes.sendFocus = false;\n break;\n case 1005: // utf8 ext mode mouse - removed in #2507\n this._logService.debug('DECRST 1005 not supported (see #2507)');\n break;\n case 1006: // sgr ext mode mouse\n this._coreMouseService.activeEncoding = 'DEFAULT';\n break;\n case 1015: // urxvt ext mode mouse - removed in #2507\n this._logService.debug('DECRST 1015 not supported (see #2507)');\n break;\n case 1016: // sgr pixels mode mouse\n this._coreMouseService.activeEncoding = 'DEFAULT';\n break;\n case 25: // hide cursor\n this._coreService.isCursorHidden = true;\n break;\n case 1048: // alt screen cursor\n this.restoreCursor();\n break;\n case 1049: // alt screen buffer cursor\n // FALL-THROUGH\n case 47: // normal screen buffer\n case 1047: // normal screen buffer - clearing it first\n // Ensure the selection manager has the correct buffer\n this._bufferService.buffers.activateNormalBuffer();\n if (params.params[i] === 1049) {\n this.restoreCursor();\n }\n this._coreService.isCursorInitialized = true;\n this._onRequestRefreshRows.fire(undefined);\n this._onRequestSyncScrollBar.fire();\n break;\n case 2004: // bracketed paste mode (https://cirw.in/blog/bracketed-paste)\n this._coreService.decPrivateModes.bracketedPasteMode = false;\n break;\n case 2026: // synchronized output (https://github.com/contour-terminal/vt-extensions/blob/master/synchronized-output.md)\n this._coreService.decPrivateModes.synchronizedOutput = false;\n this._onRequestRefreshRows.fire(undefined);\n break;\n }\n }\n return true;\n }\n\n /**\n * CSI Ps $ p Request ANSI Mode (DECRQM).\n *\n * Reports CSI Ps; Pm $ y (DECRPM), where Ps is the mode number as in SM/RM,\n * and Pm is the mode value:\n * 0 - not recognized\n * 1 - set\n * 2 - reset\n * 3 - permanently set\n * 4 - permanently reset\n *\n * @vt: #Y CSI DECRQM \"Request Mode\" \"CSI Ps $p\" \"Request mode state.\"\n * Returns a report as `CSI Ps; Pm $ y` (DECRPM), where `Ps` is the mode number as in SM/RM\n * or DECSET/DECRST, and `Pm` is the mode value:\n * - 0: not recognized\n * - 1: set\n * - 2: reset\n * - 3: permanently set\n * - 4: permanently reset\n *\n * For modes not understood xterm.js always returns `notRecognized`. In general this means,\n * that a certain operation mode is not implemented and cannot be used.\n *\n * Modes changing the active terminal buffer (47, 1047, 1049) are not subqueried\n * and only report, whether the alternate buffer is set.\n *\n * Mouse encodings and mouse protocols are handled mutual exclusive,\n * thus only one of each of those can be set at a given time.\n *\n * There is a chance, that some mode reports are not fully in line with xterm.js' behavior,\n * e.g. if the default implementation already exposes a certain behavior. If you find\n * discrepancies in the mode reports, please file a bug.\n */\n public requestMode(params: IParams, ansi: boolean): boolean {\n // return value as in DECRPM\n const enum V {\n NOT_RECOGNIZED = 0,\n SET = 1,\n RESET = 2,\n PERMANENTLY_SET = 3,\n PERMANENTLY_RESET = 4\n }\n\n // access helpers\n const dm = this._coreService.decPrivateModes;\n const { activeProtocol: mouseProtocol, activeEncoding: mouseEncoding } = this._coreMouseService;\n const cs = this._coreService;\n const { buffers, cols } = this._bufferService;\n const { active, alt } = buffers;\n const opts = this._optionsService.rawOptions;\n\n const f = (m: number, v: V): boolean => {\n cs.triggerDataEvent(`${C0.ESC}[${ansi ? '' : '?'}${m};${v}$y`);\n return true;\n };\n const b2v = (value: boolean): V => value ? V.SET : V.RESET;\n\n const p = params.params[0];\n\n if (ansi) {\n if (p === 2) return f(p, V.PERMANENTLY_RESET);\n if (p === 4) return f(p, b2v(cs.modes.insertMode));\n if (p === 12) return f(p, V.PERMANENTLY_SET);\n if (p === 20) return f(p, b2v(opts.convertEol));\n return f(p, V.NOT_RECOGNIZED);\n }\n\n if (p === 1) return f(p, b2v(dm.applicationCursorKeys));\n if (p === 3) return f(p, opts.windowOptions.setWinLines ? (cols === 80 ? V.RESET : cols === 132 ? V.SET : V.NOT_RECOGNIZED) : V.NOT_RECOGNIZED);\n if (p === 6) return f(p, b2v(dm.origin));\n if (p === 7) return f(p, b2v(dm.wraparound));\n if (p === 8) return f(p, V.PERMANENTLY_SET);\n if (p === 9) return f(p, b2v(mouseProtocol === 'X10'));\n if (p === 12) return f(p, b2v(opts.cursorBlink));\n if (p === 25) return f(p, b2v(!cs.isCursorHidden));\n if (p === 45) return f(p, b2v(dm.reverseWraparound));\n if (p === 66) return f(p, b2v(dm.applicationKeypad));\n if (p === 67) return f(p, V.PERMANENTLY_RESET);\n if (p === 1000) return f(p, b2v(mouseProtocol === 'VT200'));\n if (p === 1002) return f(p, b2v(mouseProtocol === 'DRAG'));\n if (p === 1003) return f(p, b2v(mouseProtocol === 'ANY'));\n if (p === 1004) return f(p, b2v(dm.sendFocus));\n if (p === 1005) return f(p, V.PERMANENTLY_RESET);\n if (p === 1006) return f(p, b2v(mouseEncoding === 'SGR'));\n if (p === 1015) return f(p, V.PERMANENTLY_RESET);\n if (p === 1016) return f(p, b2v(mouseEncoding === 'SGR_PIXELS'));\n if (p === 1048) return f(p, V.SET); // xterm always returns SET here\n if (p === 47 || p === 1047 || p === 1049) return f(p, b2v(active === alt));\n if (p === 2004) return f(p, b2v(dm.bracketedPasteMode));\n if (p === 2026) return f(p, b2v(dm.synchronizedOutput));\n return f(p, V.NOT_RECOGNIZED);\n }\n\n /**\n * Helper to write color information packed with color mode.\n */\n private _updateAttrColor(color: number, mode: number, c1: number, c2: number, c3: number): number {\n if (mode === 2) {\n color |= Attributes.CM_RGB;\n color &= ~Attributes.RGB_MASK;\n color |= AttributeData.fromColorRGB([c1, c2, c3]);\n } else if (mode === 5) {\n color &= ~(Attributes.CM_MASK | Attributes.PCOLOR_MASK);\n color |= Attributes.CM_P256 | (c1 & 0xff);\n }\n return color;\n }\n\n /**\n * Helper to extract and apply color params/subparams.\n * Returns advance for params index.\n */\n private _extractColor(params: IParams, pos: number, attr: IAttributeData): number {\n // normalize params\n // meaning: [target, CM, ign, val, val, val]\n // RGB : [ 38/48, 2, ign, r, g, b]\n // P256 : [ 38/48, 5, ign, v, ign, ign]\n const accu = [0, 0, -1, 0, 0, 0];\n\n // alignment placeholder for non color space sequences\n let cSpace = 0;\n\n // return advance we took in params\n let advance = 0;\n\n do {\n accu[advance + cSpace] = params.params[pos + advance];\n if (params.hasSubParams(pos + advance)) {\n const subparams = params.getSubParams(pos + advance)!;\n let i = 0;\n do {\n if (accu[1] === 5) {\n cSpace = 1;\n }\n accu[advance + i + 1 + cSpace] = subparams[i];\n } while (++i < subparams.length && i + advance + 1 + cSpace < accu.length);\n break;\n }\n // exit early if can decide color mode with semicolons\n if ((accu[1] === 5 && advance + cSpace >= 2)\n || (accu[1] === 2 && advance + cSpace >= 5)) {\n break;\n }\n // offset colorSpace slot for semicolon mode\n if (accu[1]) {\n cSpace = 1;\n }\n } while (++advance + pos < params.length && advance + cSpace < accu.length);\n\n // set default values to 0\n for (let i = 2; i < accu.length; ++i) {\n if (accu[i] === -1) {\n accu[i] = 0;\n }\n }\n\n // apply colors\n switch (accu[0]) {\n case 38:\n attr.fg = this._updateAttrColor(attr.fg, accu[1], accu[3], accu[4], accu[5]);\n break;\n case 48:\n attr.bg = this._updateAttrColor(attr.bg, accu[1], accu[3], accu[4], accu[5]);\n break;\n case 58:\n attr.extended = attr.extended.clone();\n attr.extended.underlineColor = this._updateAttrColor(attr.extended.underlineColor, accu[1], accu[3], accu[4], accu[5]);\n }\n\n return advance;\n }\n\n /**\n * SGR 4 subparams:\n * 4:0 - equal to SGR 24 (turn off all underline)\n * 4:1 - equal to SGR 4 (single underline)\n * 4:2 - equal to SGR 21 (double underline)\n * 4:3 - curly underline\n * 4:4 - dotted underline\n * 4:5 - dashed underline\n */\n private _processUnderline(style: number, attr: IAttributeData): void {\n // treat extended attrs as immutable, thus always clone from old one\n // this is needed since the buffer only holds references to it\n attr.extended = attr.extended.clone();\n\n // default to 1 == single underline\n if (!~style || style > 5) {\n style = 1;\n }\n attr.extended.underlineStyle = style;\n attr.fg |= FgFlags.UNDERLINE;\n\n // 0 deactivates underline\n if (style === 0) {\n attr.fg &= ~FgFlags.UNDERLINE;\n }\n\n // update HAS_EXTENDED in BG\n attr.updateExtended();\n }\n\n private _processSGR0(attr: IAttributeData): void {\n attr.fg = DEFAULT_ATTR_DATA.fg;\n attr.bg = DEFAULT_ATTR_DATA.bg;\n attr.extended = attr.extended.clone();\n // Reset underline style and color. Note that we don't want to reset other\n // fields such as the url id.\n attr.extended.underlineStyle = UnderlineStyle.NONE;\n attr.extended.underlineColor &= ~(Attributes.CM_MASK | Attributes.RGB_MASK);\n attr.updateExtended();\n }\n\n /**\n * CSI Pm m Character Attributes (SGR).\n *\n * @vt: #P[See below for supported attributes.] CSI SGR \"Select Graphic Rendition\" \"CSI Pm m\" \"Set/Reset various text attributes.\"\n * SGR selects one or more character attributes at the same time. Multiple params (up to 32)\n * are applied in order from left to right. The changed attributes are applied to all new\n * characters received. If you move characters in the viewport by scrolling or any other means,\n * then the attributes move with the characters.\n *\n * Supported param values by SGR:\n *\n * | Param | Meaning | Support |\n * | --------- | -------------------------------------------------------- | ------- |\n * | 0 | Normal (default). Resets any other preceding SGR. | #Y |\n * | 1 | Bold. (also see `options.drawBoldTextInBrightColors`) | #Y |\n * | 2 | Faint, decreased intensity. | #Y |\n * | 3 | Italic. | #Y |\n * | 4 | Underlined (see below for style support). | #Y |\n * | 5 | Slowly blinking. | #N |\n * | 6 | Rapidly blinking. | #N |\n * | 7 | Inverse. Flips foreground and background color. | #Y |\n * | 8 | Invisible (hidden). | #Y |\n * | 9 | Crossed-out characters (strikethrough). | #Y |\n * | 21 | Doubly underlined. | #Y |\n * | 22 | Normal (neither bold nor faint). | #Y |\n * | 23 | No italic. | #Y |\n * | 24 | Not underlined. | #Y |\n * | 25 | Steady (not blinking). | #Y |\n * | 27 | Positive (not inverse). | #Y |\n * | 28 | Visible (not hidden). | #Y |\n * | 29 | Not Crossed-out (strikethrough). | #Y |\n * | 30 | Foreground color: Black. | #Y |\n * | 31 | Foreground color: Red. | #Y |\n * | 32 | Foreground color: Green. | #Y |\n * | 33 | Foreground color: Yellow. | #Y |\n * | 34 | Foreground color: Blue. | #Y |\n * | 35 | Foreground color: Magenta. | #Y |\n * | 36 | Foreground color: Cyan. | #Y |\n * | 37 | Foreground color: White. | #Y |\n * | 38 | Foreground color: Extended color. | #P[Support for RGB and indexed colors, see below.] |\n * | 39 | Foreground color: Default (original). | #Y |\n * | 40 | Background color: Black. | #Y |\n * | 41 | Background color: Red. | #Y |\n * | 42 | Background color: Green. | #Y |\n * | 43 | Background color: Yellow. | #Y |\n * | 44 | Background color: Blue. | #Y |\n * | 45 | Background color: Magenta. | #Y |\n * | 46 | Background color: Cyan. | #Y |\n * | 47 | Background color: White. | #Y |\n * | 48 | Background color: Extended color. | #P[Support for RGB and indexed colors, see below.] |\n * | 49 | Background color: Default (original). | #Y |\n * | 53 | Overlined. | #Y |\n * | 55 | Not Overlined. | #Y |\n * | 58 | Underline color: Extended color. | #P[Support for RGB and indexed colors, see below.] |\n * | 90 - 97 | Bright foreground color (analogous to 30 - 37). | #Y |\n * | 100 - 107 | Bright background color (analogous to 40 - 47). | #Y |\n *\n * Underline supports subparams to denote the style in the form `4 : x`:\n *\n * | x | Meaning | Support |\n * | ------ | ------------------------------------------------------------- | ------- |\n * | 0 | No underline. Same as `SGR 24 m`. | #Y |\n * | 1 | Single underline. Same as `SGR 4 m`. | #Y |\n * | 2 | Double underline. | #Y |\n * | 3 | Curly underline. | #Y |\n * | 4 | Dotted underline. | #Y |\n * | 5 | Dashed underline. | #Y |\n * | other | Single underline. Same as `SGR 4 m`. | #Y |\n *\n * Extended colors are supported for foreground (Ps=38), background (Ps=48) and underline (Ps=58)\n * as follows:\n *\n * | Ps + 1 | Meaning | Support |\n * | ------ | ------------------------------------------------------------- | ------- |\n * | 0 | Implementation defined. | #N |\n * | 1 | Transparent. | #N |\n * | 2 | RGB color as `Ps ; 2 ; R ; G ; B` or `Ps : 2 : : R : G : B`. | #Y |\n * | 3 | CMY color. | #N |\n * | 4 | CMYK color. | #N |\n * | 5 | Indexed (256 colors) as `Ps ; 5 ; INDEX` or `Ps : 5 : INDEX`. | #Y |\n *\n *\n * FIXME: blinking is implemented in attrs, but not working in renderers?\n * FIXME: remove dead branch for p=100\n */\n public charAttributes(params: IParams): boolean {\n // Optimize a single SGR0.\n if (params.length === 1 && params.params[0] === 0) {\n this._processSGR0(this._curAttrData);\n return true;\n }\n\n const l = params.length;\n let p;\n const attr = this._curAttrData;\n\n for (let i = 0; i < l; i++) {\n p = params.params[i];\n if (p >= 30 && p <= 37) {\n // fg color 8\n attr.fg &= ~(Attributes.CM_MASK | Attributes.PCOLOR_MASK);\n attr.fg |= Attributes.CM_P16 | (p - 30);\n } else if (p >= 40 && p <= 47) {\n // bg color 8\n attr.bg &= ~(Attributes.CM_MASK | Attributes.PCOLOR_MASK);\n attr.bg |= Attributes.CM_P16 | (p - 40);\n } else if (p >= 90 && p <= 97) {\n // fg color 16\n attr.fg &= ~(Attributes.CM_MASK | Attributes.PCOLOR_MASK);\n attr.fg |= Attributes.CM_P16 | (p - 90) | 8;\n } else if (p >= 100 && p <= 107) {\n // bg color 16\n attr.bg &= ~(Attributes.CM_MASK | Attributes.PCOLOR_MASK);\n attr.bg |= Attributes.CM_P16 | (p - 100) | 8;\n } else if (p === 0) {\n // default\n this._processSGR0(attr);\n } else if (p === 1) {\n // bold text\n attr.fg |= FgFlags.BOLD;\n } else if (p === 3) {\n // italic text\n attr.bg |= BgFlags.ITALIC;\n } else if (p === 4) {\n // underlined text\n attr.fg |= FgFlags.UNDERLINE;\n this._processUnderline(params.hasSubParams(i) ? params.getSubParams(i)![0] : UnderlineStyle.SINGLE, attr);\n } else if (p === 5) {\n // blink\n attr.fg |= FgFlags.BLINK;\n } else if (p === 7) {\n // inverse and positive\n // test with: echo -e '\\e[31m\\e[42mhello\\e[7mworld\\e[27mhi\\e[m'\n attr.fg |= FgFlags.INVERSE;\n } else if (p === 8) {\n // invisible\n attr.fg |= FgFlags.INVISIBLE;\n } else if (p === 9) {\n // strikethrough\n attr.fg |= FgFlags.STRIKETHROUGH;\n } else if (p === 2) {\n // dimmed text\n attr.bg |= BgFlags.DIM;\n } else if (p === 21) {\n // double underline\n this._processUnderline(UnderlineStyle.DOUBLE, attr);\n } else if (p === 22) {\n // not bold nor faint\n attr.fg &= ~FgFlags.BOLD;\n attr.bg &= ~BgFlags.DIM;\n } else if (p === 23) {\n // not italic\n attr.bg &= ~BgFlags.ITALIC;\n } else if (p === 24) {\n // not underlined\n attr.fg &= ~FgFlags.UNDERLINE;\n this._processUnderline(UnderlineStyle.NONE, attr);\n } else if (p === 25) {\n // not blink\n attr.fg &= ~FgFlags.BLINK;\n } else if (p === 27) {\n // not inverse\n attr.fg &= ~FgFlags.INVERSE;\n } else if (p === 28) {\n // not invisible\n attr.fg &= ~FgFlags.INVISIBLE;\n } else if (p === 29) {\n // not strikethrough\n attr.fg &= ~FgFlags.STRIKETHROUGH;\n } else if (p === 39) {\n // reset fg\n attr.fg &= ~(Attributes.CM_MASK | Attributes.RGB_MASK);\n attr.fg |= DEFAULT_ATTR_DATA.fg & (Attributes.PCOLOR_MASK | Attributes.RGB_MASK);\n } else if (p === 49) {\n // reset bg\n attr.bg &= ~(Attributes.CM_MASK | Attributes.RGB_MASK);\n attr.bg |= DEFAULT_ATTR_DATA.bg & (Attributes.PCOLOR_MASK | Attributes.RGB_MASK);\n } else if (p === 38 || p === 48 || p === 58) {\n // fg color 256 and RGB\n i += this._extractColor(params, i, attr);\n } else if (p === 53) {\n // overline\n attr.bg |= BgFlags.OVERLINE;\n } else if (p === 55) {\n // not overline\n attr.bg &= ~BgFlags.OVERLINE;\n } else if (p === 59) {\n attr.extended = attr.extended.clone();\n attr.extended.underlineColor = -1;\n attr.updateExtended();\n } else if (p === 100) { // FIXME: dead branch, p=100 already handled above!\n // reset fg/bg\n attr.fg &= ~(Attributes.CM_MASK | Attributes.RGB_MASK);\n attr.fg |= DEFAULT_ATTR_DATA.fg & (Attributes.PCOLOR_MASK | Attributes.RGB_MASK);\n attr.bg &= ~(Attributes.CM_MASK | Attributes.RGB_MASK);\n attr.bg |= DEFAULT_ATTR_DATA.bg & (Attributes.PCOLOR_MASK | Attributes.RGB_MASK);\n } else {\n this._logService.debug('Unknown SGR attribute: %d.', p);\n }\n }\n return true;\n }\n\n /**\n * CSI Ps n Device Status Report (DSR).\n * Ps = 5 -> Status Report. Result (``OK'') is\n * CSI 0 n\n * Ps = 6 -> Report Cursor Position (CPR) [row;column].\n * Result is\n * CSI r ; c R\n * CSI ? Ps n\n * Device Status Report (DSR, DEC-specific).\n * Ps = 6 -> Report Cursor Position (CPR) [row;column] as CSI\n * ? r ; c R (assumes page is zero).\n * Ps = 1 5 -> Report Printer status as CSI ? 1 0 n (ready).\n * or CSI ? 1 1 n (not ready).\n * Ps = 2 5 -> Report UDK status as CSI ? 2 0 n (unlocked)\n * or CSI ? 2 1 n (locked).\n * Ps = 2 6 -> Report Keyboard status as\n * CSI ? 2 7 ; 1 ; 0 ; 0 n (North American).\n * The last two parameters apply to VT400 & up, and denote key-\n * board ready and LK01 respectively.\n * Ps = 5 3 -> Report Locator status as\n * CSI ? 5 3 n Locator available, if compiled-in, or\n * CSI ? 5 0 n No Locator, if not.\n *\n * @vt: #Y CSI DSR \"Device Status Report\" \"CSI Ps n\" \"Request cursor position (CPR) with `Ps` = 6.\"\n */\n public deviceStatus(params: IParams): boolean {\n switch (params.params[0]) {\n case 5:\n // status report\n this._coreService.triggerDataEvent(`${C0.ESC}[0n`);\n break;\n case 6:\n // cursor position\n const y = this._activeBuffer.y + 1;\n const x = this._activeBuffer.x + 1;\n this._coreService.triggerDataEvent(`${C0.ESC}[${y};${x}R`);\n break;\n }\n return true;\n }\n\n // @vt: #P[Only CPR is supported.] CSI DECDSR \"DEC Device Status Report\" \"CSI ? Ps n\" \"Only CPR is supported (same as DSR).\"\n public deviceStatusPrivate(params: IParams): boolean {\n // modern xterm doesnt seem to\n // respond to any of these except ?6, 6, and 5\n switch (params.params[0]) {\n case 6:\n // cursor position\n const y = this._activeBuffer.y + 1;\n const x = this._activeBuffer.x + 1;\n this._coreService.triggerDataEvent(`${C0.ESC}[?${y};${x}R`);\n break;\n case 15:\n // no printer\n // this.handler(C0.ESC + '[?11n');\n break;\n case 25:\n // dont support user defined keys\n // this.handler(C0.ESC + '[?21n');\n break;\n case 26:\n // north american keyboard\n // this.handler(C0.ESC + '[?27;1;0;0n');\n break;\n case 53:\n // no dec locator/mouse\n // this.handler(C0.ESC + '[?50n');\n break;\n }\n return true;\n }\n\n /**\n * CSI ! p Soft terminal reset (DECSTR).\n * http://vt100.net/docs/vt220-rm/table4-10.html\n *\n * @vt: #Y CSI DECSTR \"Soft Terminal Reset\" \"CSI ! p\" \"Reset several terminal attributes to initial state.\"\n * There are two terminal reset sequences - RIS and DECSTR. While RIS performs almost a full\n * terminal bootstrap, DECSTR only resets certain attributes. For most needs DECSTR should be\n * sufficient.\n *\n * The following terminal attributes are reset to default values:\n * - IRM is reset (dafault = false)\n * - scroll margins are reset (default = viewport size)\n * - erase attributes are reset to default\n * - charsets are reset\n * - DECSC data is reset to initial values\n * - DECOM is reset to absolute mode\n *\n *\n * FIXME: there are several more attributes missing (see VT520 manual)\n */\n public softReset(params: IParams): boolean {\n this._coreService.isCursorHidden = false;\n this._onRequestSyncScrollBar.fire();\n this._activeBuffer.scrollTop = 0;\n this._activeBuffer.scrollBottom = this._bufferService.rows - 1;\n this._curAttrData = DEFAULT_ATTR_DATA.clone();\n this._coreService.reset();\n this._charsetService.reset();\n\n // reset DECSC data\n this._activeBuffer.savedX = 0;\n this._activeBuffer.savedY = this._activeBuffer.ybase;\n this._activeBuffer.savedCurAttrData.fg = this._curAttrData.fg;\n this._activeBuffer.savedCurAttrData.bg = this._curAttrData.bg;\n this._activeBuffer.savedCharset = this._charsetService.charset;\n\n // reset DECOM\n this._coreService.decPrivateModes.origin = false;\n return true;\n }\n\n /**\n * CSI Ps SP q Set cursor style (DECSCUSR, VT520).\n * Ps = 0 -> reset to option.\n * Ps = 1 -> blinking block (default).\n * Ps = 2 -> steady block.\n * Ps = 3 -> blinking underline.\n * Ps = 4 -> steady underline.\n * Ps = 5 -> blinking bar (xterm).\n * Ps = 6 -> steady bar (xterm).\n *\n * @vt: #Y CSI DECSCUSR \"Set Cursor Style\" \"CSI Ps SP q\" \"Set cursor style.\"\n * Supported cursor styles:\n * - 0: reset to option\n * - empty, 1: blinking block\n * - 2: steady block\n * - 3: blinking underline\n * - 4: steady underline\n * - 5: blinking bar\n * - 6: steady bar\n */\n public setCursorStyle(params: IParams): boolean {\n const param = params.length === 0 ? 1 : params.params[0];\n if (param === 0) {\n this._coreService.decPrivateModes.cursorStyle = undefined;\n this._coreService.decPrivateModes.cursorBlink = undefined;\n } else {\n switch (param) {\n case 1:\n case 2:\n this._coreService.decPrivateModes.cursorStyle = 'block';\n break;\n case 3:\n case 4:\n this._coreService.decPrivateModes.cursorStyle = 'underline';\n break;\n case 5:\n case 6:\n this._coreService.decPrivateModes.cursorStyle = 'bar';\n break;\n }\n const isBlinking = param % 2 === 1;\n this._coreService.decPrivateModes.cursorBlink = isBlinking;\n }\n return true;\n }\n\n /**\n * CSI Ps ; Ps r\n * Set Scrolling Region [top;bottom] (default = full size of win-\n * dow) (DECSTBM).\n *\n * @vt: #Y CSI DECSTBM \"Set Top and Bottom Margin\" \"CSI Ps ; Ps r\" \"Set top and bottom margins of the viewport [top;bottom] (default = viewport size).\"\n */\n public setScrollRegion(params: IParams): boolean {\n const top = params.params[0] || 1;\n let bottom: number;\n\n if (params.length < 2 || (bottom = params.params[1]) > this._bufferService.rows || bottom === 0) {\n bottom = this._bufferService.rows;\n }\n\n if (bottom > top) {\n this._activeBuffer.scrollTop = top - 1;\n this._activeBuffer.scrollBottom = bottom - 1;\n this._setCursor(0, 0);\n }\n return true;\n }\n\n /**\n * CSI Ps ; Ps ; Ps t - Various window manipulations and reports (xterm)\n *\n * Note: Only those listed below are supported. All others are left to integrators and\n * need special treatment based on the embedding environment.\n *\n * Ps = 1 4 supported\n * Report xterm text area size in pixels.\n * Result is CSI 4 ; height ; width t\n * Ps = 14 ; 2 not implemented\n * Ps = 16 supported\n * Report xterm character cell size in pixels.\n * Result is CSI 6 ; height ; width t\n * Ps = 18 supported\n * Report the size of the text area in characters.\n * Result is CSI 8 ; height ; width t\n * Ps = 20 supported\n * Report xterm window's icon label.\n * Result is OSC L label ST\n * Ps = 21 supported\n * Report xterm window's title.\n * Result is OSC l label ST\n * Ps = 22 ; 0 -> Save xterm icon and window title on stack. supported\n * Ps = 22 ; 1 -> Save xterm icon title on stack. supported\n * Ps = 22 ; 2 -> Save xterm window title on stack. supported\n * Ps = 23 ; 0 -> Restore xterm icon and window title from stack. supported\n * Ps = 23 ; 1 -> Restore xterm icon title from stack. supported\n * Ps = 23 ; 2 -> Restore xterm window title from stack. supported\n * Ps >= 24 not implemented\n */\n public windowOptions(params: IParams): boolean {\n if (!paramToWindowOption(params.params[0], this._optionsService.rawOptions.windowOptions)) {\n return true;\n }\n const second = (params.length > 1) ? params.params[1] : 0;\n switch (params.params[0]) {\n case 14: // GetWinSizePixels, returns CSI 4 ; height ; width t\n if (second !== 2) {\n this._onRequestWindowsOptionsReport.fire(WindowsOptionsReportType.GET_WIN_SIZE_PIXELS);\n }\n break;\n case 16: // GetCellSizePixels, returns CSI 6 ; height ; width t\n this._onRequestWindowsOptionsReport.fire(WindowsOptionsReportType.GET_CELL_SIZE_PIXELS);\n break;\n case 18: // GetWinSizeChars, returns CSI 8 ; height ; width t\n if (this._bufferService) {\n this._coreService.triggerDataEvent(`${C0.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);\n }\n break;\n case 22: // PushTitle\n if (second === 0 || second === 2) {\n this._windowTitleStack.push(this._windowTitle);\n if (this._windowTitleStack.length > STACK_LIMIT) {\n this._windowTitleStack.shift();\n }\n }\n if (second === 0 || second === 1) {\n this._iconNameStack.push(this._iconName);\n if (this._iconNameStack.length > STACK_LIMIT) {\n this._iconNameStack.shift();\n }\n }\n break;\n case 23: // PopTitle\n if (second === 0 || second === 2) {\n if (this._windowTitleStack.length) {\n this.setTitle(this._windowTitleStack.pop()!);\n }\n }\n if (second === 0 || second === 1) {\n if (this._iconNameStack.length) {\n this.setIconName(this._iconNameStack.pop()!);\n }\n }\n break;\n }\n return true;\n }\n\n\n /**\n * CSI s\n * ESC 7\n * Save cursor (ANSI.SYS).\n *\n * @vt: #P[TODO...] CSI SCOSC \"Save Cursor\" \"CSI s\" \"Save cursor position, charmap and text attributes.\"\n * @vt: #Y ESC SC \"Save Cursor\" \"ESC 7\" \"Save cursor position, charmap and text attributes.\"\n */\n public saveCursor(params?: IParams): boolean {\n this._activeBuffer.savedX = this._activeBuffer.x;\n this._activeBuffer.savedY = this._activeBuffer.ybase + this._activeBuffer.y;\n this._activeBuffer.savedCurAttrData.fg = this._curAttrData.fg;\n this._activeBuffer.savedCurAttrData.bg = this._curAttrData.bg;\n this._activeBuffer.savedCharset = this._charsetService.charset;\n return true;\n }\n\n\n /**\n * CSI u\n * ESC 8\n * Restore cursor (ANSI.SYS).\n *\n * @vt: #P[TODO...] CSI SCORC \"Restore Cursor\" \"CSI u\" \"Restore cursor position, charmap and text attributes.\"\n * @vt: #Y ESC RC \"Restore Cursor\" \"ESC 8\" \"Restore cursor position, charmap and text attributes.\"\n */\n public restoreCursor(params?: IParams): boolean {\n this._activeBuffer.x = this._activeBuffer.savedX || 0;\n this._activeBuffer.y = Math.max(this._activeBuffer.savedY - this._activeBuffer.ybase, 0);\n this._curAttrData.fg = this._activeBuffer.savedCurAttrData.fg;\n this._curAttrData.bg = this._activeBuffer.savedCurAttrData.bg;\n this._charsetService.charset = (this as any)._savedCharset;\n if (this._activeBuffer.savedCharset) {\n this._charsetService.charset = this._activeBuffer.savedCharset;\n }\n this._restrictCursor();\n return true;\n }\n\n\n /**\n * OSC 2; ST (set window title)\n * Proxy to set window title.\n *\n * @vt: #P[Icon name is not exposed.] OSC 0 \"Set Windows Title and Icon Name\" \"OSC 0 ; Pt BEL\" \"Set window title and icon name.\"\n * Icon name is not supported. For Window Title see below.\n *\n * @vt: #Y OSC 2 \"Set Windows Title\" \"OSC 2 ; Pt BEL\" \"Set window title.\"\n * xterm.js does not manipulate the title directly, instead exposes changes via the event\n * `Terminal.onTitleChange`.\n */\n public setTitle(data: string): boolean {\n this._windowTitle = data;\n this._onTitleChange.fire(data);\n return true;\n }\n\n /**\n * OSC 1; ST\n * Note: Icon name is not exposed.\n */\n public setIconName(data: string): boolean {\n this._iconName = data;\n return true;\n }\n\n /**\n * OSC 4; ; ST (set ANSI color to )\n *\n * @vt: #Y OSC 4 \"Set ANSI color\" \"OSC 4 ; c ; spec BEL\" \"Change color number `c` to the color specified by `spec`.\"\n * `c` is the color index between 0 and 255. The color format of `spec` is derived from\n * `XParseColor` (see OSC 10 for supported formats). There may be multipe `c ; spec` pairs present\n * in the same instruction. If `spec` contains `?` the terminal returns a sequence with the\n * currently set color.\n */\n public setOrReportIndexedColor(data: string): boolean {\n const event: IColorEvent = [];\n const slots = data.split(';');\n while (slots.length > 1) {\n const idx = slots.shift() as string;\n const spec = slots.shift() as string;\n if (/^\\d+$/.exec(idx)) {\n const index = parseInt(idx);\n if (isValidColorIndex(index)) {\n if (spec === '?') {\n event.push({ type: ColorRequestType.REPORT, index });\n } else {\n const color = parseColor(spec);\n if (color) {\n event.push({ type: ColorRequestType.SET, index, color });\n }\n }\n }\n }\n }\n if (event.length) {\n this._onColor.fire(event);\n }\n return true;\n }\n\n /**\n * OSC 8 ; ; ST - create hyperlink\n * OSC 8 ; ; ST - finish hyperlink\n *\n * Test case:\n *\n * ```sh\n * printf '\\e]8;;http://example.com\\e\\\\This is a link\\e]8;;\\e\\\\\\n'\n * ```\n *\n * @vt: #Y OSC 8 \"Create hyperlink\" \"OSC 8 ; params ; uri BEL\" \"Create a hyperlink to `uri` using `params`.\"\n * `uri` is a hyperlink starting with `http://`, `https://`, `ftp://`, `file://` or `mailto://`. `params` is an\n * optional list of key=value assignments, separated by the : character.\n * Example: `id=xyz123:foo=bar:baz=quux`.\n * Currently only the id key is defined. Cells that share the same ID and URI share hover\n * feedback. Use `OSC 8 ; ; BEL` to finish the current hyperlink.\n */\n public setHyperlink(data: string): boolean {\n // Arg parsing is special cases to support unencoded semi-colons in the URIs (#4944)\n const idx = data.indexOf(';');\n if (idx === -1) {\n // malformed sequence, just return as handled\n return true;\n }\n const id = data.slice(0, idx).trim();\n const uri = data.slice(idx + 1);\n if (uri) {\n return this._createHyperlink(id, uri);\n }\n if (id.trim()) {\n return false;\n }\n return this._finishHyperlink();\n }\n\n private _createHyperlink(params: string, uri: string): boolean {\n // It's legal to open a new hyperlink without explicitly finishing the previous one\n if (this._getCurrentLinkId()) {\n this._finishHyperlink();\n }\n const parsedParams = params.split(':');\n let id: string | undefined;\n const idParamIndex = parsedParams.findIndex(e => e.startsWith('id='));\n if (idParamIndex !== -1) {\n id = parsedParams[idParamIndex].slice(3) || undefined;\n }\n this._curAttrData.extended = this._curAttrData.extended.clone();\n this._curAttrData.extended.urlId = this._oscLinkService.registerLink({ id, uri });\n this._curAttrData.updateExtended();\n return true;\n }\n\n private _finishHyperlink(): boolean {\n this._curAttrData.extended = this._curAttrData.extended.clone();\n this._curAttrData.extended.urlId = 0;\n this._curAttrData.updateExtended();\n return true;\n }\n\n // special colors - OSC 10 | 11 | 12\n private _specialColors = [SpecialColorIndex.FOREGROUND, SpecialColorIndex.BACKGROUND, SpecialColorIndex.CURSOR];\n\n /**\n * Apply colors requests for special colors in OSC 10 | 11 | 12.\n * Since these commands are stacking from multiple parameters,\n * we handle them in a loop with an entry offset to `_specialColors`.\n */\n private _setOrReportSpecialColor(data: string, offset: number): boolean {\n const slots = data.split(';');\n for (let i = 0; i < slots.length; ++i, ++offset) {\n if (offset >= this._specialColors.length) break;\n if (slots[i] === '?') {\n this._onColor.fire([{ type: ColorRequestType.REPORT, index: this._specialColors[offset] }]);\n } else {\n const color = parseColor(slots[i]);\n if (color) {\n this._onColor.fire([{ type: ColorRequestType.SET, index: this._specialColors[offset], color }]);\n }\n }\n }\n return true;\n }\n\n /**\n * OSC 10 ; | ST - set or query default foreground color\n *\n * @vt: #Y OSC 10 \"Set or query default foreground color\" \"OSC 10 ; Pt BEL\" \"Set or query default foreground color.\"\n * To set the color, the following color specification formats are supported:\n * - `rgb://` for `, , ` in `h | hh | hhh | hhhh`, where\n * `h` is a single hexadecimal digit (case insignificant). The different widths scale\n * from 4 bit (`h`) to 16 bit (`hhhh`) and get converted to 8 bit (`hh`).\n * - `#RGB` - 4 bits per channel, expanded to `#R0G0B0`\n * - `#RRGGBB` - 8 bits per channel\n * - `#RRRGGGBBB` - 12 bits per channel, truncated to `#RRGGBB`\n * - `#RRRRGGGGBBBB` - 16 bits per channel, truncated to `#RRGGBB`\n *\n * **Note:** X11 named colors are currently unsupported.\n *\n * If `Pt` contains `?` instead of a color specification, the terminal\n * returns a sequence with the current default foreground color\n * (use that sequence to restore the color after changes).\n *\n * **Note:** Other than xterm, xterm.js does not support OSC 12 - 19.\n * Therefore stacking multiple `Pt` separated by `;` only works for the first two entries.\n */\n public setOrReportFgColor(data: string): boolean {\n return this._setOrReportSpecialColor(data, 0);\n }\n\n /**\n * OSC 11 ; | ST - set or query default background color\n *\n * @vt: #Y OSC 11 \"Set or query default background color\" \"OSC 11 ; Pt BEL\" \"Same as OSC 10, but for default background.\"\n */\n public setOrReportBgColor(data: string): boolean {\n return this._setOrReportSpecialColor(data, 1);\n }\n\n /**\n * OSC 12 ; | ST - set or query default cursor color\n *\n * @vt: #Y OSC 12 \"Set or query default cursor color\" \"OSC 12 ; Pt BEL\" \"Same as OSC 10, but for default cursor color.\"\n */\n public setOrReportCursorColor(data: string): boolean {\n return this._setOrReportSpecialColor(data, 2);\n }\n\n /**\n * OSC 104 ; ST - restore ANSI color \n *\n * @vt: #Y OSC 104 \"Reset ANSI color\" \"OSC 104 ; c BEL\" \"Reset color number `c` to themed color.\"\n * `c` is the color index between 0 and 255. This function restores the default color for `c` as\n * specified by the loaded theme. Any number of `c` parameters may be given.\n * If no parameters are given, the entire indexed color table will be reset.\n */\n public restoreIndexedColor(data: string): boolean {\n if (!data) {\n this._onColor.fire([{ type: ColorRequestType.RESTORE }]);\n return true;\n }\n const event: IColorEvent = [];\n const slots = data.split(';');\n for (let i = 0; i < slots.length; ++i) {\n if (/^\\d+$/.exec(slots[i])) {\n const index = parseInt(slots[i]);\n if (isValidColorIndex(index)) {\n event.push({ type: ColorRequestType.RESTORE, index });\n }\n }\n }\n if (event.length) {\n this._onColor.fire(event);\n }\n return true;\n }\n\n /**\n * OSC 110 ST - restore default foreground color\n *\n * @vt: #Y OSC 110 \"Restore default foreground color\" \"OSC 110 BEL\" \"Restore default foreground to themed color.\"\n */\n public restoreFgColor(data: string): boolean {\n this._onColor.fire([{ type: ColorRequestType.RESTORE, index: SpecialColorIndex.FOREGROUND }]);\n return true;\n }\n\n /**\n * OSC 111 ST - restore default background color\n *\n * @vt: #Y OSC 111 \"Restore default background color\" \"OSC 111 BEL\" \"Restore default background to themed color.\"\n */\n public restoreBgColor(data: string): boolean {\n this._onColor.fire([{ type: ColorRequestType.RESTORE, index: SpecialColorIndex.BACKGROUND }]);\n return true;\n }\n\n /**\n * OSC 112 ST - restore default cursor color\n *\n * @vt: #Y OSC 112 \"Restore default cursor color\" \"OSC 112 BEL\" \"Restore default cursor to themed color.\"\n */\n public restoreCursorColor(data: string): boolean {\n this._onColor.fire([{ type: ColorRequestType.RESTORE, index: SpecialColorIndex.CURSOR }]);\n return true;\n }\n\n /**\n * ESC E\n * C1.NEL\n * DEC mnemonic: NEL (https://vt100.net/docs/vt510-rm/NEL)\n * Moves cursor to first position on next line.\n *\n * @vt: #Y C1 NEL \"Next Line\" \"\\x85\" \"Move the cursor to the beginning of the next row.\"\n * @vt: #Y ESC NEL \"Next Line\" \"ESC E\" \"Move the cursor to the beginning of the next row.\"\n */\n public nextLine(): boolean {\n this._activeBuffer.x = 0;\n this.index();\n return true;\n }\n\n /**\n * ESC =\n * DEC mnemonic: DECKPAM (https://vt100.net/docs/vt510-rm/DECKPAM.html)\n * Enables the numeric keypad to send application sequences to the host.\n */\n public keypadApplicationMode(): boolean {\n this._logService.debug('Serial port requested application keypad.');\n this._coreService.decPrivateModes.applicationKeypad = true;\n this._onRequestSyncScrollBar.fire();\n return true;\n }\n\n /**\n * ESC >\n * DEC mnemonic: DECKPNM (https://vt100.net/docs/vt510-rm/DECKPNM.html)\n * Enables the keypad to send numeric characters to the host.\n */\n public keypadNumericMode(): boolean {\n this._logService.debug('Switching back to normal keypad.');\n this._coreService.decPrivateModes.applicationKeypad = false;\n this._onRequestSyncScrollBar.fire();\n return true;\n }\n\n /**\n * ESC % @\n * ESC % G\n * Select default character set. UTF-8 is not supported (string are unicode anyways)\n * therefore ESC % G does the same.\n */\n public selectDefaultCharset(): boolean {\n this._charsetService.setgLevel(0);\n this._charsetService.setgCharset(0, DEFAULT_CHARSET); // US (default)\n return true;\n }\n\n /**\n * ESC ( C\n * Designate G0 Character Set, VT100, ISO 2022.\n * ESC ) C\n * Designate G1 Character Set (ISO 2022, VT100).\n * ESC * C\n * Designate G2 Character Set (ISO 2022, VT220).\n * ESC + C\n * Designate G3 Character Set (ISO 2022, VT220).\n * ESC - C\n * Designate G1 Character Set (VT300).\n * ESC . C\n * Designate G2 Character Set (VT300).\n * ESC / C\n * Designate G3 Character Set (VT300). C = A -> ISO Latin-1 Supplemental. - Supported?\n */\n public selectCharset(collectAndFlag: string): boolean {\n if (collectAndFlag.length !== 2) {\n this.selectDefaultCharset();\n return true;\n }\n if (collectAndFlag[0] === '/') {\n return true; // TODO: Is this supported?\n }\n this._charsetService.setgCharset(GLEVEL[collectAndFlag[0]], CHARSETS[collectAndFlag[1]] || DEFAULT_CHARSET);\n return true;\n }\n\n /**\n * ESC D\n * C1.IND\n * DEC mnemonic: IND (https://vt100.net/docs/vt510-rm/IND.html)\n * Moves the cursor down one line in the same column.\n *\n * @vt: #Y C1 IND \"Index\" \"\\x84\" \"Move the cursor one line down scrolling if needed.\"\n * @vt: #Y ESC IND \"Index\" \"ESC D\" \"Move the cursor one line down scrolling if needed.\"\n */\n public index(): boolean {\n this._restrictCursor();\n this._activeBuffer.y++;\n if (this._activeBuffer.y === this._activeBuffer.scrollBottom + 1) {\n this._activeBuffer.y--;\n this._bufferService.scroll(this._eraseAttrData());\n } else if (this._activeBuffer.y >= this._bufferService.rows) {\n this._activeBuffer.y = this._bufferService.rows - 1;\n }\n this._restrictCursor();\n return true;\n }\n\n /**\n * ESC H\n * C1.HTS\n * DEC mnemonic: HTS (https://vt100.net/docs/vt510-rm/HTS.html)\n * Sets a horizontal tab stop at the column position indicated by\n * the value of the active column when the terminal receives an HTS.\n *\n * @vt: #Y C1 HTS \"Horizontal Tabulation Set\" \"\\x88\" \"Places a tab stop at the current cursor position.\"\n * @vt: #Y ESC HTS \"Horizontal Tabulation Set\" \"ESC H\" \"Places a tab stop at the current cursor position.\"\n */\n public tabSet(): boolean {\n this._activeBuffer.tabs[this._activeBuffer.x] = true;\n return true;\n }\n\n /**\n * ESC M\n * C1.RI\n * DEC mnemonic: HTS\n * Moves the cursor up one line in the same column. If the cursor is at the top margin,\n * the page scrolls down.\n *\n * @vt: #Y ESC IR \"Reverse Index\" \"ESC M\" \"Move the cursor one line up scrolling if needed.\"\n */\n public reverseIndex(): boolean {\n this._restrictCursor();\n if (this._activeBuffer.y === this._activeBuffer.scrollTop) {\n // possibly move the code below to term.reverseScroll();\n // test: echo -ne '\\e[1;1H\\e[44m\\eM\\e[0m'\n // blankLine(true) is xterm/linux behavior\n const scrollRegionHeight = this._activeBuffer.scrollBottom - this._activeBuffer.scrollTop;\n this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase + this._activeBuffer.y, scrollRegionHeight, 1);\n this._activeBuffer.lines.set(this._activeBuffer.ybase + this._activeBuffer.y, this._activeBuffer.getBlankLine(this._eraseAttrData()));\n this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom);\n } else {\n this._activeBuffer.y--;\n this._restrictCursor(); // quickfix to not run out of bounds\n }\n return true;\n }\n\n /**\n * ESC c\n * DEC mnemonic: RIS (https://vt100.net/docs/vt510-rm/RIS.html)\n * Reset to initial state.\n */\n public fullReset(): boolean {\n this._parser.reset();\n this._onRequestReset.fire();\n return true;\n }\n\n public reset(): void {\n this._curAttrData = DEFAULT_ATTR_DATA.clone();\n this._eraseAttrDataInternal = DEFAULT_ATTR_DATA.clone();\n }\n\n /**\n * back_color_erase feature for xterm.\n */\n private _eraseAttrData(): IAttributeData {\n this._eraseAttrDataInternal.bg &= ~(Attributes.CM_MASK | 0xFFFFFF);\n this._eraseAttrDataInternal.bg |= this._curAttrData.bg & ~0xFC000000;\n return this._eraseAttrDataInternal;\n }\n\n /**\n * ESC n\n * ESC o\n * ESC |\n * ESC }\n * ESC ~\n * DEC mnemonic: LS (https://vt100.net/docs/vt510-rm/LS.html)\n * When you use a locking shift, the character set remains in GL or GR until\n * you use another locking shift. (partly supported)\n */\n public setgLevel(level: number): boolean {\n this._charsetService.setgLevel(level);\n return true;\n }\n\n /**\n * ESC # 8\n * DEC mnemonic: DECALN (https://vt100.net/docs/vt510-rm/DECALN.html)\n * This control function fills the complete screen area with\n * a test pattern (E) used for adjusting screen alignment.\n *\n * @vt: #Y ESC DECALN \"Screen Alignment Pattern\" \"ESC # 8\" \"Fill viewport with a test pattern (E).\"\n */\n public screenAlignmentPattern(): boolean {\n // prepare cell data\n const cell = new CellData();\n cell.content = 1 << Content.WIDTH_SHIFT | 'E'.charCodeAt(0);\n cell.fg = this._curAttrData.fg;\n cell.bg = this._curAttrData.bg;\n\n\n this._setCursor(0, 0);\n for (let yOffset = 0; yOffset < this._bufferService.rows; ++yOffset) {\n const row = this._activeBuffer.ybase + this._activeBuffer.y + yOffset;\n const line = this._activeBuffer.lines.get(row);\n if (line) {\n line.fill(cell);\n line.isWrapped = false;\n }\n }\n this._dirtyRowTracker.markAllDirty();\n this._setCursor(0, 0);\n return true;\n }\n\n\n /**\n * DCS $ q Pt ST\n * DECRQSS (https://vt100.net/docs/vt510-rm/DECRQSS.html)\n * Request Status String (DECRQSS), VT420 and up.\n * Response: DECRPSS (https://vt100.net/docs/vt510-rm/DECRPSS.html)\n *\n * @vt: #P[Limited support, see below.] DCS DECRQSS \"Request Selection or Setting\" \"DCS $ q Pt ST\" \"Request several terminal settings.\"\n * Response is in the form `ESC P 1 $ r Pt ST` for valid requests, where `Pt` contains the\n * corresponding CSI string, `ESC P 0 ST` for invalid requests.\n *\n * Supported requests and responses:\n *\n * | Type | Request | Response (`Pt`) |\n * | -------------------------------- | ----------------- | ----------------------------------------------------- |\n * | Graphic Rendition (SGR) | `DCS $ q m ST` | always reporting `0m` (currently broken) |\n * | Top and Bottom Margins (DECSTBM) | `DCS $ q r ST` | `Ps ; Ps r` |\n * | Cursor Style (DECSCUSR) | `DCS $ q SP q ST` | `Ps SP q` |\n * | Protection Attribute (DECSCA) | `DCS $ q \" q ST` | `Ps \" q` (DECSCA 2 is reported as Ps = 0) |\n * | Conformance Level (DECSCL) | `DCS $ q \" p ST` | always reporting `61 ; 1 \" p` (DECSCL is unsupported) |\n *\n *\n * TODO:\n * - fix SGR report\n * - either check which conformance is better suited or remove the report completely\n * --> we are currently a mixture of all up to VT400 but dont follow anyone strictly\n */\n public requestStatusString(data: string, params: IParams): boolean {\n const f = (s: string): boolean => {\n this._coreService.triggerDataEvent(`${C0.ESC}${s}${C0.ESC}\\\\`);\n return true;\n };\n\n // access helpers\n const b = this._bufferService.buffer;\n const opts = this._optionsService.rawOptions;\n const STYLES: { [key: string]: number } = { 'block': 2, 'underline': 4, 'bar': 6 };\n\n if (data === '\"q') return f(`P1$r${this._curAttrData.isProtected() ? 1 : 0}\"q`);\n if (data === '\"p') return f(`P1$r61;1\"p`);\n if (data === 'r') return f(`P1$r${b.scrollTop + 1};${b.scrollBottom + 1}r`);\n // FIXME: report real SGR settings instead of 0m\n if (data === 'm') return f(`P1$r0m`);\n if (data === ' q') return f(`P1$r${STYLES[opts.cursorStyle] - (opts.cursorBlink ? 1 : 0)} q`);\n return f(`P0$r`);\n }\n\n public markRangeDirty(y1: number, y2: number): void {\n this._dirtyRowTracker.markRangeDirty(y1, y2);\n }\n}\n\nexport interface IDirtyRowTracker {\n readonly start: number;\n readonly end: number;\n\n clearRange(): void;\n markDirty(y: number): void;\n markRangeDirty(y1: number, y2: number): void;\n markAllDirty(): void;\n}\n\nclass DirtyRowTracker implements IDirtyRowTracker {\n public start!: number;\n public end!: number;\n\n constructor(\n @IBufferService private readonly _bufferService: IBufferService\n ) {\n this.clearRange();\n }\n\n public clearRange(): void {\n this.start = this._bufferService.buffer.y;\n this.end = this._bufferService.buffer.y;\n }\n\n public markDirty(y: number): void {\n if (y < this.start) {\n this.start = y;\n } else if (y > this.end) {\n this.end = y;\n }\n }\n\n public markRangeDirty(y1: number, y2: number): void {\n if (y1 > y2) {\n $temp = y1;\n y1 = y2;\n y2 = $temp;\n }\n if (y1 < this.start) {\n this.start = y1;\n }\n if (y2 > this.end) {\n this.end = y2;\n }\n }\n\n public markAllDirty(): void {\n this.markRangeDirty(0, this._bufferService.rows - 1);\n }\n}\n\nexport function isValidColorIndex(value: number): value is ColorIndex {\n return 0 <= value && value < 256;\n}\n", "\n/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { Disposable } from 'vs/base/common/lifecycle';\nimport { Emitter } from 'vs/base/common/event';\n\ndeclare const setTimeout: (handler: () => void, timeout?: number) => void;\n\n/**\n * Safety watermark to avoid memory exhaustion and browser engine crash on fast data input.\n * Enable flow control to avoid this limit and make sure that your backend correctly\n * propagates this to the underlying pty. (see docs for further instructions)\n * Since this limit is meant as a safety parachute to prevent browser crashs,\n * it is set to a very high number. Typically xterm.js gets unresponsive with\n * a 100 times lower number (>500 kB).\n */\nconst DISCARD_WATERMARK = 50000000; // ~50 MB\n\n/**\n * The max number of ms to spend on writes before allowing the renderer to\n * catch up with a 0ms setTimeout. A value of < 33 to keep us close to\n * 30fps, and a value of < 16 to try to run at 60fps. Of course, the real FPS\n * depends on the time it takes for the renderer to draw the frame.\n */\nconst WRITE_TIMEOUT_MS = 12;\n\n/**\n * Threshold of max held chunks in the write buffer, that were already processed.\n * This is a tradeoff between extensive write buffer shifts (bad runtime) and high\n * memory consumption by data thats not used anymore.\n */\nconst WRITE_BUFFER_LENGTH_THRESHOLD = 50;\n\nexport class WriteBuffer extends Disposable {\n private _writeBuffer: (string | Uint8Array)[] = [];\n private _callbacks: ((() => void) | undefined)[] = [];\n private _pendingData = 0;\n private _bufferOffset = 0;\n private _isSyncWriting = false;\n private _syncCalls = 0;\n private _didUserInput = false;\n\n private readonly _onWriteParsed = this._register(new Emitter());\n public readonly onWriteParsed = this._onWriteParsed.event;\n\n constructor(private _action: (data: string | Uint8Array, promiseResult?: boolean) => void | Promise) {\n super();\n }\n\n public handleUserInput(): void {\n this._didUserInput = true;\n }\n\n /**\n * @deprecated Unreliable, to be removed soon.\n */\n public writeSync(data: string | Uint8Array, maxSubsequentCalls?: number): void {\n // stop writeSync recursions with maxSubsequentCalls argument\n // This is dangerous to use as it will lose the current data chunk\n // and return immediately.\n if (maxSubsequentCalls !== undefined && this._syncCalls > maxSubsequentCalls) {\n // comment next line if a whole loop block should only contain x `writeSync` calls\n // (total flat vs. deep nested limit)\n this._syncCalls = 0;\n return;\n }\n // append chunk to buffer\n this._pendingData += data.length;\n this._writeBuffer.push(data);\n this._callbacks.push(undefined);\n\n // increase recursion counter\n this._syncCalls++;\n // exit early if another writeSync loop is active\n if (this._isSyncWriting) {\n return;\n }\n this._isSyncWriting = true;\n\n // force sync processing on pending data chunks to avoid in-band data scrambling\n // does the same as innerWrite but without event loop\n // we have to do it here as single loop steps to not corrupt loop subject\n // by another writeSync call triggered from _action\n let chunk: string | Uint8Array | undefined;\n while (chunk = this._writeBuffer.shift()) {\n this._action(chunk);\n const cb = this._callbacks.shift();\n if (cb) cb();\n }\n // reset to avoid reprocessing of chunks with scheduled innerWrite call\n // stopping scheduled innerWrite by offset > length condition\n this._pendingData = 0;\n this._bufferOffset = 0x7FFFFFFF;\n\n // allow another writeSync to loop\n this._isSyncWriting = false;\n this._syncCalls = 0;\n }\n\n public write(data: string | Uint8Array, callback?: () => void): void {\n if (this._pendingData > DISCARD_WATERMARK) {\n throw new Error('write data discarded, use flow control to avoid losing data');\n }\n\n // schedule chunk processing for next event loop run\n if (!this._writeBuffer.length) {\n this._bufferOffset = 0;\n\n // If this is the first write call after the user has done some input,\n // parse it immediately to minimize input latency,\n // otherwise schedule for the next event\n if (this._didUserInput) {\n this._didUserInput = false;\n this._pendingData += data.length;\n this._writeBuffer.push(data);\n this._callbacks.push(callback);\n this._innerWrite();\n return;\n }\n\n setTimeout(() => this._innerWrite());\n }\n\n this._pendingData += data.length;\n this._writeBuffer.push(data);\n this._callbacks.push(callback);\n }\n\n /**\n * Inner write call, that enters the sliced chunk processing by timing.\n *\n * `lastTime` indicates, when the last _innerWrite call had started.\n * It is used to aggregate async handler execution under a timeout constraint\n * effectively lowering the redrawing needs, schematically:\n *\n * macroTask _innerWrite:\n * if (performance.now() - (lastTime | 0) < WRITE_TIMEOUT_MS):\n * schedule microTask _innerWrite(lastTime)\n * else:\n * schedule macroTask _innerWrite(0)\n *\n * overall execution order on task queues:\n *\n * macrotasks: [...] --> _innerWrite(0) --> [...] --> screenUpdate --> [...]\n * m t: |\n * i a: [...]\n * c s: |\n * r k: while < timeout:\n * o s: _innerWrite(timeout)\n *\n * `promiseResult` depicts the promise resolve value of an async handler.\n * This value gets carried forward through all saved stack states of the\n * paused parser for proper continuation.\n *\n * Note, for pure sync code `lastTime` and `promiseResult` have no meaning.\n */\n protected _innerWrite(lastTime: number = 0, promiseResult: boolean = true): void {\n const startTime = lastTime || performance.now();\n while (this._writeBuffer.length > this._bufferOffset) {\n const data = this._writeBuffer[this._bufferOffset];\n const result = this._action(data, promiseResult);\n if (result) {\n /**\n * If we get a promise as return value, we re-schedule the continuation\n * as thenable on the promise and exit right away.\n *\n * The exit here means, that we block input processing at the current active chunk,\n * the exact execution position within the chunk is preserved by the saved\n * stack content in InputHandler and EscapeSequenceParser.\n *\n * Resuming happens automatically from that saved stack state.\n * Also the resolved promise value is passed along the callstack to\n * `EscapeSequenceParser.parse` to correctly resume the stopped handler loop.\n *\n * Exceptions on async handlers will be logged to console async, but do not interrupt\n * the input processing (continues with next handler at the current input position).\n */\n\n /**\n * If a promise takes long to resolve, we should schedule continuation behind setTimeout.\n * This might already be too late, if our .then enters really late (executor + prev thens\n * took very long). This cannot be solved here for the handler itself (it is the handlers\n * responsibility to slice hard work), but we can at least schedule a screen update as we\n * gain control.\n */\n const continuation: (r: boolean) => void = (r: boolean) => performance.now() - startTime >= WRITE_TIMEOUT_MS\n ? setTimeout(() => this._innerWrite(0, r))\n : this._innerWrite(startTime, r);\n\n /**\n * Optimization considerations:\n * The continuation above favors FPS over throughput by eval'ing `startTime` on resolve.\n * This might schedule too many screen updates with bad throughput drops (in case a slow\n * resolving handler sliced its work properly behind setTimeout calls). We cannot spot\n * this condition here, also the renderer has no way to spot nonsense updates either.\n * FIXME: A proper fix for this would track the FPS at the renderer entry level separately.\n *\n * If favoring of FPS shows bad throughtput impact, use the following instead. It favors\n * throughput by eval'ing `startTime` upfront pulling at least one more chunk into the\n * current microtask queue (executed before setTimeout).\n */\n // const continuation: (r: boolean) => void = performance.now() - startTime >=\n // WRITE_TIMEOUT_MS\n // ? r => setTimeout(() => this._innerWrite(0, r))\n // : r => this._innerWrite(startTime, r);\n\n // Handle exceptions synchronously to current band position, idea:\n // 1. spawn a single microtask which we allow to throw hard\n // 2. spawn a promise immediately resolving to `true`\n // (executed on the same queue, thus properly aligned before continuation happens)\n result.catch(err => {\n queueMicrotask(() => {throw err;});\n return Promise.resolve(false);\n }).then(continuation);\n return;\n }\n\n const cb = this._callbacks[this._bufferOffset];\n if (cb) cb();\n this._bufferOffset++;\n this._pendingData -= data.length;\n\n if (performance.now() - startTime >= WRITE_TIMEOUT_MS) {\n break;\n }\n }\n if (this._writeBuffer.length > this._bufferOffset) {\n // Allow renderer to catch up before processing the next batch\n // trim already processed chunks if we are above threshold\n if (this._bufferOffset > WRITE_BUFFER_LENGTH_THRESHOLD) {\n this._writeBuffer = this._writeBuffer.slice(this._bufferOffset);\n this._callbacks = this._callbacks.slice(this._bufferOffset);\n this._bufferOffset = 0;\n }\n setTimeout(() => this._innerWrite());\n } else {\n this._writeBuffer.length = 0;\n this._callbacks.length = 0;\n this._pendingData = 0;\n this._bufferOffset = 0;\n }\n this._onWriteParsed.fire();\n }\n}\n", "/**\n * Copyright (c) 2022 The xterm.js authors. All rights reserved.\n * @license MIT\n */\nimport { IBufferService, IOscLinkService } from 'common/services/Services';\nimport { IMarker, IOscLinkData } from 'common/Types';\n\nexport class OscLinkService implements IOscLinkService {\n public serviceBrand: any;\n\n private _nextId = 1;\n\n /**\n * A map of the link key to link entry. This is used to add additional lines to links with ids.\n */\n private _entriesWithId: Map = new Map();\n\n /**\n * A map of the link id to the link entry. The \"link id\" (number) which is the numberic\n * representation of a unique link should not be confused with \"id\" (string) which comes in with\n * `id=` in the OSC link's properties.\n */\n private _dataByLinkId: Map = new Map();\n\n constructor(\n @IBufferService private readonly _bufferService: IBufferService\n ) {\n }\n\n public registerLink(data: IOscLinkData): number {\n const buffer = this._bufferService.buffer;\n\n // Links with no id will only ever be registered a single time\n if (data.id === undefined) {\n const marker = buffer.addMarker(buffer.ybase + buffer.y);\n const entry: IOscLinkEntryNoId = {\n data,\n id: this._nextId++,\n lines: [marker]\n };\n marker.onDispose(() => this._removeMarkerFromLink(entry, marker));\n this._dataByLinkId.set(entry.id, entry);\n return entry.id;\n }\n\n // Add the line to the link if it already exists\n const castData = data as Required;\n const key = this._getEntryIdKey(castData);\n const match = this._entriesWithId.get(key);\n if (match) {\n this.addLineToLink(match.id, buffer.ybase + buffer.y);\n return match.id;\n }\n\n // Create the link\n const marker = buffer.addMarker(buffer.ybase + buffer.y);\n const entry: IOscLinkEntryWithId = {\n id: this._nextId++,\n key: this._getEntryIdKey(castData),\n data: castData,\n lines: [marker]\n };\n marker.onDispose(() => this._removeMarkerFromLink(entry, marker));\n this._entriesWithId.set(entry.key, entry);\n this._dataByLinkId.set(entry.id, entry);\n return entry.id;\n }\n\n public addLineToLink(linkId: number, y: number): void {\n const entry = this._dataByLinkId.get(linkId);\n if (!entry) {\n return;\n }\n if (entry.lines.every(e => e.line !== y)) {\n const marker = this._bufferService.buffer.addMarker(y);\n entry.lines.push(marker);\n marker.onDispose(() => this._removeMarkerFromLink(entry, marker));\n }\n }\n\n public getLinkData(linkId: number): IOscLinkData | undefined {\n return this._dataByLinkId.get(linkId)?.data;\n }\n\n private _getEntryIdKey(linkData: Required): string {\n return `${linkData.id};;${linkData.uri}`;\n }\n\n private _removeMarkerFromLink(entry: IOscLinkEntryNoId | IOscLinkEntryWithId, marker: IMarker): void {\n const index = entry.lines.indexOf(marker);\n if (index === -1) {\n return;\n }\n entry.lines.splice(index, 1);\n if (entry.lines.length === 0) {\n if (entry.data.id !== undefined) {\n this._entriesWithId.delete((entry as IOscLinkEntryWithId).key);\n }\n this._dataByLinkId.delete(entry.id);\n }\n }\n}\n\ninterface IOscLinkEntry {\n data: T;\n id: number;\n lines: IMarker[];\n}\n\ninterface IOscLinkEntryNoId extends IOscLinkEntry {\n}\n\ninterface IOscLinkEntryWithId extends IOscLinkEntry> {\n key: string;\n}\n", "/**\n * Copyright (c) 2014-2020 The xterm.js authors. All rights reserved.\n * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)\n * @license MIT\n *\n * Originally forked from (with the author's permission):\n * Fabrice Bellard's javascript vt100 for jslinux:\n * http://bellard.org/jslinux/\n * Copyright (c) 2011 Fabrice Bellard\n * The original design remains. The terminal itself\n * has been extended to include xterm CSI codes, among\n * other features.\n *\n * Terminal Emulation References:\n * http://vt100.net/\n * http://invisible-island.net/xterm/ctlseqs/ctlseqs.txt\n * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html\n * http://invisible-island.net/vttest/\n * http://www.inwap.com/pdp10/ansicode.txt\n * http://linux.die.net/man/4/console_codes\n * http://linux.die.net/man/7/urxvt\n */\n\nimport { IInstantiationService, IOptionsService, IBufferService, ILogService, ICharsetService, ICoreService, ICoreMouseService, IUnicodeService, LogLevelEnum, ITerminalOptions, IOscLinkService } from 'common/services/Services';\nimport { InstantiationService } from 'common/services/InstantiationService';\nimport { LogService } from 'common/services/LogService';\nimport { BufferService, MINIMUM_COLS, MINIMUM_ROWS } from 'common/services/BufferService';\nimport { OptionsService } from 'common/services/OptionsService';\nimport { IDisposable, IAttributeData, ICoreTerminal, IScrollEvent } from 'common/Types';\nimport { CoreService } from 'common/services/CoreService';\nimport { CoreMouseService } from 'common/services/CoreMouseService';\nimport { UnicodeService } from 'common/services/UnicodeService';\nimport { CharsetService } from 'common/services/CharsetService';\nimport { updateWindowsModeWrappedState } from 'common/WindowsMode';\nimport { IFunctionIdentifier, IParams } from 'common/parser/Types';\nimport { IBufferSet } from 'common/buffer/Types';\nimport { InputHandler } from 'common/InputHandler';\nimport { WriteBuffer } from 'common/input/WriteBuffer';\nimport { OscLinkService } from 'common/services/OscLinkService';\nimport { Emitter, Event } from 'vs/base/common/event';\nimport { Disposable, MutableDisposable, toDisposable } from 'vs/base/common/lifecycle';\n\n// Only trigger this warning a single time per session\nlet hasWriteSyncWarnHappened = false;\n\nexport abstract class CoreTerminal extends Disposable implements ICoreTerminal {\n protected readonly _instantiationService: IInstantiationService;\n protected readonly _bufferService: IBufferService;\n protected readonly _logService: ILogService;\n protected readonly _charsetService: ICharsetService;\n protected readonly _oscLinkService: IOscLinkService;\n\n public readonly coreMouseService: ICoreMouseService;\n public readonly coreService: ICoreService;\n public readonly unicodeService: IUnicodeService;\n public readonly optionsService: IOptionsService;\n\n protected _inputHandler: InputHandler;\n private _writeBuffer: WriteBuffer;\n private _windowsWrappingHeuristics = this._register(new MutableDisposable());\n\n private readonly _onBinary = this._register(new Emitter());\n public readonly onBinary = this._onBinary.event;\n private readonly _onData = this._register(new Emitter());\n public readonly onData = this._onData.event;\n protected _onLineFeed = this._register(new Emitter());\n public readonly onLineFeed = this._onLineFeed.event;\n private readonly _onResize = this._register(new Emitter<{ cols: number, rows: number }>());\n public readonly onResize = this._onResize.event;\n protected readonly _onWriteParsed = this._register(new Emitter());\n public readonly onWriteParsed = this._onWriteParsed.event;\n\n /**\n * Internally we track the source of the scroll but this is meaningless outside the library so\n * it's filtered out.\n */\n protected _onScrollApi?: Emitter;\n protected _onScroll = this._register(new Emitter());\n public get onScroll(): Event {\n if (!this._onScrollApi) {\n this._onScrollApi = this._register(new Emitter());\n this._onScroll.event(ev => {\n this._onScrollApi?.fire(ev.position);\n });\n }\n return this._onScrollApi.event;\n }\n\n public get cols(): number { return this._bufferService.cols; }\n public get rows(): number { return this._bufferService.rows; }\n public get buffers(): IBufferSet { return this._bufferService.buffers; }\n public get options(): Required { return this.optionsService.options; }\n public set options(options: ITerminalOptions) {\n for (const key in options) {\n this.optionsService.options[key] = options[key];\n }\n }\n\n constructor(\n options: Partial\n ) {\n super();\n\n // Setup and initialize services\n this._instantiationService = new InstantiationService();\n this.optionsService = this._register(new OptionsService(options));\n this._instantiationService.setService(IOptionsService, this.optionsService);\n this._bufferService = this._register(this._instantiationService.createInstance(BufferService));\n this._instantiationService.setService(IBufferService, this._bufferService);\n this._logService = this._register(this._instantiationService.createInstance(LogService));\n this._instantiationService.setService(ILogService, this._logService);\n this.coreService = this._register(this._instantiationService.createInstance(CoreService));\n this._instantiationService.setService(ICoreService, this.coreService);\n this.coreMouseService = this._register(this._instantiationService.createInstance(CoreMouseService));\n this._instantiationService.setService(ICoreMouseService, this.coreMouseService);\n this.unicodeService = this._register(this._instantiationService.createInstance(UnicodeService));\n this._instantiationService.setService(IUnicodeService, this.unicodeService);\n this._charsetService = this._instantiationService.createInstance(CharsetService);\n this._instantiationService.setService(ICharsetService, this._charsetService);\n this._oscLinkService = this._instantiationService.createInstance(OscLinkService);\n this._instantiationService.setService(IOscLinkService, this._oscLinkService);\n\n\n // Register input handler and handle/forward events\n this._inputHandler = this._register(new InputHandler(this._bufferService, this._charsetService, this.coreService, this._logService, this.optionsService, this._oscLinkService, this.coreMouseService, this.unicodeService));\n this._register(Event.forward(this._inputHandler.onLineFeed, this._onLineFeed));\n this._register(this._inputHandler);\n\n // Setup listeners\n this._register(Event.forward(this._bufferService.onResize, this._onResize));\n this._register(Event.forward(this.coreService.onData, this._onData));\n this._register(Event.forward(this.coreService.onBinary, this._onBinary));\n this._register(this.coreService.onRequestScrollToBottom(() => this.scrollToBottom(true)));\n this._register(this.coreService.onUserInput(() => this._writeBuffer.handleUserInput()));\n this._register(this.optionsService.onMultipleOptionChange(['windowsMode', 'windowsPty'], () => this._handleWindowsPtyOptionChange()));\n this._register(this._bufferService.onScroll(() => {\n this._onScroll.fire({ position: this._bufferService.buffer.ydisp });\n this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop, this._bufferService.buffer.scrollBottom);\n }));\n // Setup WriteBuffer\n this._writeBuffer = this._register(new WriteBuffer((data, promiseResult) => this._inputHandler.parse(data, promiseResult)));\n this._register(Event.forward(this._writeBuffer.onWriteParsed, this._onWriteParsed));\n }\n\n public write(data: string | Uint8Array, callback?: () => void): void {\n this._writeBuffer.write(data, callback);\n }\n\n /**\n * Write data to terminal synchonously.\n *\n * This method is unreliable with async parser handlers, thus should not\n * be used anymore. If you need blocking semantics on data input consider\n * `write` with a callback instead.\n *\n * @deprecated Unreliable, will be removed soon.\n */\n public writeSync(data: string | Uint8Array, maxSubsequentCalls?: number): void {\n if (this._logService.logLevel <= LogLevelEnum.WARN && !hasWriteSyncWarnHappened) {\n this._logService.warn('writeSync is unreliable and will be removed soon.');\n hasWriteSyncWarnHappened = true;\n }\n this._writeBuffer.writeSync(data, maxSubsequentCalls);\n }\n\n public input(data: string, wasUserInput: boolean = true): void {\n this.coreService.triggerDataEvent(data, wasUserInput);\n }\n\n public resize(x: number, y: number): void {\n if (isNaN(x) || isNaN(y)) {\n return;\n }\n\n x = Math.max(x, MINIMUM_COLS);\n y = Math.max(y, MINIMUM_ROWS);\n\n this._bufferService.resize(x, y);\n }\n\n /**\n * Scroll the terminal down 1 row, creating a blank line.\n * @param eraseAttr The attribute data to use the for blank line.\n * @param isWrapped Whether the new line is wrapped from the previous line.\n */\n public scroll(eraseAttr: IAttributeData, isWrapped: boolean = false): void {\n this._bufferService.scroll(eraseAttr, isWrapped);\n }\n\n /**\n * Scroll the display of the terminal\n * @param disp The number of lines to scroll down (negative scroll up).\n * @param suppressScrollEvent Don't emit the scroll event as scrollLines. This is used to avoid\n * unwanted events being handled by the viewport when the event was triggered from the viewport\n * originally.\n */\n public scrollLines(disp: number, suppressScrollEvent?: boolean): void {\n this._bufferService.scrollLines(disp, suppressScrollEvent);\n }\n\n public scrollPages(pageCount: number): void {\n this.scrollLines(pageCount * (this.rows - 1));\n }\n\n public scrollToTop(): void {\n this.scrollLines(-this._bufferService.buffer.ydisp);\n }\n\n public scrollToBottom(disableSmoothScroll?: boolean): void {\n this.scrollLines(this._bufferService.buffer.ybase - this._bufferService.buffer.ydisp);\n }\n\n public scrollToLine(line: number): void {\n const scrollAmount = line - this._bufferService.buffer.ydisp;\n if (scrollAmount !== 0) {\n this.scrollLines(scrollAmount);\n }\n }\n\n /** Add handler for ESC escape sequence. See xterm.d.ts for details. */\n public registerEscHandler(id: IFunctionIdentifier, callback: () => boolean | Promise): IDisposable {\n return this._inputHandler.registerEscHandler(id, callback);\n }\n\n /** Add handler for DCS escape sequence. See xterm.d.ts for details. */\n public registerDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: IParams) => boolean | Promise): IDisposable {\n return this._inputHandler.registerDcsHandler(id, callback);\n }\n\n /** Add handler for CSI escape sequence. See xterm.d.ts for details. */\n public registerCsiHandler(id: IFunctionIdentifier, callback: (params: IParams) => boolean | Promise): IDisposable {\n return this._inputHandler.registerCsiHandler(id, callback);\n }\n\n /** Add handler for OSC escape sequence. See xterm.d.ts for details. */\n public registerOscHandler(ident: number, callback: (data: string) => boolean | Promise): IDisposable {\n return this._inputHandler.registerOscHandler(ident, callback);\n }\n\n protected _setup(): void {\n this._handleWindowsPtyOptionChange();\n }\n\n public reset(): void {\n this._inputHandler.reset();\n this._bufferService.reset();\n this._charsetService.reset();\n this.coreService.reset();\n this.coreMouseService.reset();\n }\n\n\n private _handleWindowsPtyOptionChange(): void {\n let value = false;\n const windowsPty = this.optionsService.rawOptions.windowsPty;\n if (windowsPty && windowsPty.buildNumber !== undefined && windowsPty.buildNumber !== undefined) {\n value = !!(windowsPty.backend === 'conpty' && windowsPty.buildNumber < 21376);\n } else if (this.optionsService.rawOptions.windowsMode) {\n value = true;\n }\n if (value) {\n this._enableWindowsWrappingHeuristics();\n } else {\n this._windowsWrappingHeuristics.clear();\n }\n }\n\n protected _enableWindowsWrappingHeuristics(): void {\n if (!this._windowsWrappingHeuristics.value) {\n const disposables: IDisposable[] = [];\n disposables.push(this.onLineFeed(updateWindowsModeWrappedState.bind(null, this._bufferService)));\n disposables.push(this.registerCsiHandler({ final: 'H' }, () => {\n updateWindowsModeWrappedState(this._bufferService);\n return false;\n }));\n this._windowsWrappingHeuristics.value = toDisposable(() => {\n for (const d of disposables) {\n d.dispose();\n }\n });\n }\n }\n}\n", "/**\n * Copyright (c) 2014 The xterm.js authors. All rights reserved.\n * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)\n * @license MIT\n */\n\nimport { IKeyboardEvent, IKeyboardResult, KeyboardResultType } from 'common/Types';\nimport { C0 } from 'common/data/EscapeSequences';\n\n// reg + shift key mappings for digits and special chars\nconst KEYCODE_KEY_MAPPINGS: { [key: number]: [string, string]} = {\n // digits 0-9\n 48: ['0', ')'],\n 49: ['1', '!'],\n 50: ['2', '@'],\n 51: ['3', '#'],\n 52: ['4', '$'],\n 53: ['5', '%'],\n 54: ['6', '^'],\n 55: ['7', '&'],\n 56: ['8', '*'],\n 57: ['9', '('],\n\n // special chars\n 186: [';', ':'],\n 187: ['=', '+'],\n 188: [',', '<'],\n 189: ['-', '_'],\n 190: ['.', '>'],\n 191: ['/', '?'],\n 192: ['`', '~'],\n 219: ['[', '{'],\n 220: ['\\\\', '|'],\n 221: [']', '}'],\n 222: ['\\'', '\"']\n};\n\nexport function evaluateKeyboardEvent(\n ev: IKeyboardEvent,\n applicationCursorMode: boolean,\n isMac: boolean,\n macOptionIsMeta: boolean\n): IKeyboardResult {\n const result: IKeyboardResult = {\n type: KeyboardResultType.SEND_KEY,\n // Whether to cancel event propagation (NOTE: this may not be needed since the event is\n // canceled at the end of keyDown\n cancel: false,\n // The new key even to emit\n key: undefined\n };\n const modifiers = (ev.shiftKey ? 1 : 0) | (ev.altKey ? 2 : 0) | (ev.ctrlKey ? 4 : 0) | (ev.metaKey ? 8 : 0);\n switch (ev.keyCode) {\n case 0:\n if (ev.key === 'UIKeyInputUpArrow') {\n if (applicationCursorMode) {\n result.key = C0.ESC + 'OA';\n } else {\n result.key = C0.ESC + '[A';\n }\n }\n else if (ev.key === 'UIKeyInputLeftArrow') {\n if (applicationCursorMode) {\n result.key = C0.ESC + 'OD';\n } else {\n result.key = C0.ESC + '[D';\n }\n }\n else if (ev.key === 'UIKeyInputRightArrow') {\n if (applicationCursorMode) {\n result.key = C0.ESC + 'OC';\n } else {\n result.key = C0.ESC + '[C';\n }\n }\n else if (ev.key === 'UIKeyInputDownArrow') {\n if (applicationCursorMode) {\n result.key = C0.ESC + 'OB';\n } else {\n result.key = C0.ESC + '[B';\n }\n }\n break;\n case 8:\n // backspace\n result.key = ev.ctrlKey ? '\\b' : C0.DEL; // ^H or ^?\n if (ev.altKey) {\n result.key = C0.ESC + result.key;\n }\n break;\n case 9:\n // tab\n if (ev.shiftKey) {\n result.key = C0.ESC + '[Z';\n break;\n }\n result.key = C0.HT;\n result.cancel = true;\n break;\n case 13:\n // return/enter\n result.key = ev.altKey ? C0.ESC + C0.CR : C0.CR;\n result.cancel = true;\n break;\n case 27:\n // escape\n result.key = C0.ESC;\n if (ev.altKey) {\n result.key = C0.ESC + C0.ESC;\n }\n result.cancel = true;\n break;\n case 37:\n // left-arrow\n if (ev.metaKey) {\n break;\n }\n if (modifiers) {\n result.key = C0.ESC + '[1;' + (modifiers + 1) + 'D';\n } else if (applicationCursorMode) {\n result.key = C0.ESC + 'OD';\n } else {\n result.key = C0.ESC + '[D';\n }\n break;\n case 39:\n // right-arrow\n if (ev.metaKey) {\n break;\n }\n if (modifiers) {\n result.key = C0.ESC + '[1;' + (modifiers + 1) + 'C';\n } else if (applicationCursorMode) {\n result.key = C0.ESC + 'OC';\n } else {\n result.key = C0.ESC + '[C';\n }\n break;\n case 38:\n // up-arrow\n if (ev.metaKey) {\n break;\n }\n if (modifiers) {\n result.key = C0.ESC + '[1;' + (modifiers + 1) + 'A';\n } else if (applicationCursorMode) {\n result.key = C0.ESC + 'OA';\n } else {\n result.key = C0.ESC + '[A';\n }\n break;\n case 40:\n // down-arrow\n if (ev.metaKey) {\n break;\n }\n if (modifiers) {\n result.key = C0.ESC + '[1;' + (modifiers + 1) + 'B';\n } else if (applicationCursorMode) {\n result.key = C0.ESC + 'OB';\n } else {\n result.key = C0.ESC + '[B';\n }\n break;\n case 45:\n // insert\n if (!ev.shiftKey && !ev.ctrlKey) {\n // or + are used to\n // copy-paste on some systems.\n result.key = C0.ESC + '[2~';\n }\n break;\n case 46:\n // delete\n if (modifiers) {\n result.key = C0.ESC + '[3;' + (modifiers + 1) + '~';\n } else {\n result.key = C0.ESC + '[3~';\n }\n break;\n case 36:\n // home\n if (modifiers) {\n result.key = C0.ESC + '[1;' + (modifiers + 1) + 'H';\n } else if (applicationCursorMode) {\n result.key = C0.ESC + 'OH';\n } else {\n result.key = C0.ESC + '[H';\n }\n break;\n case 35:\n // end\n if (modifiers) {\n result.key = C0.ESC + '[1;' + (modifiers + 1) + 'F';\n } else if (applicationCursorMode) {\n result.key = C0.ESC + 'OF';\n } else {\n result.key = C0.ESC + '[F';\n }\n break;\n case 33:\n // page up\n if (ev.shiftKey) {\n result.type = KeyboardResultType.PAGE_UP;\n } else if (ev.ctrlKey) {\n result.key = C0.ESC + '[5;' + (modifiers + 1) + '~';\n } else {\n result.key = C0.ESC + '[5~';\n }\n break;\n case 34:\n // page down\n if (ev.shiftKey) {\n result.type = KeyboardResultType.PAGE_DOWN;\n } else if (ev.ctrlKey) {\n result.key = C0.ESC + '[6;' + (modifiers + 1) + '~';\n } else {\n result.key = C0.ESC + '[6~';\n }\n break;\n case 112:\n // F1-F12\n if (modifiers) {\n result.key = C0.ESC + '[1;' + (modifiers + 1) + 'P';\n } else {\n result.key = C0.ESC + 'OP';\n }\n break;\n case 113:\n if (modifiers) {\n result.key = C0.ESC + '[1;' + (modifiers + 1) + 'Q';\n } else {\n result.key = C0.ESC + 'OQ';\n }\n break;\n case 114:\n if (modifiers) {\n result.key = C0.ESC + '[1;' + (modifiers + 1) + 'R';\n } else {\n result.key = C0.ESC + 'OR';\n }\n break;\n case 115:\n if (modifiers) {\n result.key = C0.ESC + '[1;' + (modifiers + 1) + 'S';\n } else {\n result.key = C0.ESC + 'OS';\n }\n break;\n case 116:\n if (modifiers) {\n result.key = C0.ESC + '[15;' + (modifiers + 1) + '~';\n } else {\n result.key = C0.ESC + '[15~';\n }\n break;\n case 117:\n if (modifiers) {\n result.key = C0.ESC + '[17;' + (modifiers + 1) + '~';\n } else {\n result.key = C0.ESC + '[17~';\n }\n break;\n case 118:\n if (modifiers) {\n result.key = C0.ESC + '[18;' + (modifiers + 1) + '~';\n } else {\n result.key = C0.ESC + '[18~';\n }\n break;\n case 119:\n if (modifiers) {\n result.key = C0.ESC + '[19;' + (modifiers + 1) + '~';\n } else {\n result.key = C0.ESC + '[19~';\n }\n break;\n case 120:\n if (modifiers) {\n result.key = C0.ESC + '[20;' + (modifiers + 1) + '~';\n } else {\n result.key = C0.ESC + '[20~';\n }\n break;\n case 121:\n if (modifiers) {\n result.key = C0.ESC + '[21;' + (modifiers + 1) + '~';\n } else {\n result.key = C0.ESC + '[21~';\n }\n break;\n case 122:\n if (modifiers) {\n result.key = C0.ESC + '[23;' + (modifiers + 1) + '~';\n } else {\n result.key = C0.ESC + '[23~';\n }\n break;\n case 123:\n if (modifiers) {\n result.key = C0.ESC + '[24;' + (modifiers + 1) + '~';\n } else {\n result.key = C0.ESC + '[24~';\n }\n break;\n default:\n // a-z and space\n if (ev.ctrlKey && !ev.shiftKey && !ev.altKey && !ev.metaKey) {\n if (ev.keyCode >= 65 && ev.keyCode <= 90) {\n result.key = String.fromCharCode(ev.keyCode - 64);\n } else if (ev.keyCode === 32) {\n result.key = C0.NUL;\n } else if (ev.keyCode >= 51 && ev.keyCode <= 55) {\n // escape, file sep, group sep, record sep, unit sep\n result.key = String.fromCharCode(ev.keyCode - 51 + 27);\n } else if (ev.keyCode === 56) {\n result.key = C0.DEL;\n } else if (ev.keyCode === 219) {\n result.key = C0.ESC;\n } else if (ev.keyCode === 220) {\n result.key = C0.FS;\n } else if (ev.keyCode === 221) {\n result.key = C0.GS;\n }\n } else if ((!isMac || macOptionIsMeta) && ev.altKey && !ev.metaKey) {\n // On macOS this is a third level shift when !macOptionIsMeta. Use instead.\n const keyMapping = KEYCODE_KEY_MAPPINGS[ev.keyCode];\n const key = keyMapping?.[!ev.shiftKey ? 0 : 1];\n if (key) {\n result.key = C0.ESC + key;\n } else if (ev.keyCode >= 65 && ev.keyCode <= 90) {\n const keyCode = ev.ctrlKey ? ev.keyCode - 64 : ev.keyCode + 32;\n let keyString = String.fromCharCode(keyCode);\n if (ev.shiftKey) {\n keyString = keyString.toUpperCase();\n }\n result.key = C0.ESC + keyString;\n } else if (ev.keyCode === 32) {\n result.key = C0.ESC + (ev.ctrlKey ? C0.NUL : ' ');\n } else if (ev.key === 'Dead' && ev.code.startsWith('Key')) {\n // Reference: https://github.com/xtermjs/xterm.js/issues/3725\n // Alt will produce a \"dead key\" (initate composition) with some\n // of the letters in US layout (e.g. N/E/U).\n // It's safe to match against Key* since no other `code` values begin with \"Key\".\n // https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code/code_values#code_values_on_mac\n let keyString = ev.code.slice(3, 4);\n if (!ev.shiftKey) {\n keyString = keyString.toLowerCase();\n }\n result.key = C0.ESC + keyString;\n result.cancel = true;\n }\n } else if (isMac && !ev.altKey && !ev.ctrlKey && !ev.shiftKey && ev.metaKey) {\n if (ev.keyCode === 65) { // cmd + a\n result.type = KeyboardResultType.SELECT_ALL;\n }\n } else if (ev.key && !ev.ctrlKey && !ev.altKey && !ev.metaKey && ev.keyCode >= 48 && ev.key.length === 1) {\n // Include only keys that that result in a _single_ character; don't include num lock,\n // volume up, etc.\n result.key = ev.key;\n } else if (ev.key && ev.ctrlKey) {\n if (ev.key === '_') { // ^_\n result.key = C0.US;\n }\n if (ev.key === '@') { // ^ + shift + 2 = ^ + @\n result.key = C0.NUL;\n }\n }\n break;\n }\n\n return result;\n}\n", "/**\n * Copyright (c) 2022 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IdleTaskQueue } from 'common/TaskQueue';\n\n// Work variables to avoid garbage collection.\nlet i = 0;\n\n/**\n * A generic list that is maintained in sorted order and allows values with duplicate keys. Deferred\n * batch insertion and deletion is used to significantly reduce the time it takes to insert and\n * delete a large amount of items in succession. This list is based on binary search and as such\n * locating a key will take O(log n) amortized, this includes the by key iterator.\n */\nexport class SortedList {\n private _array: T[] = [];\n\n private readonly _insertedValues: T[] = [];\n private readonly _flushInsertedTask = new IdleTaskQueue();\n private _isFlushingInserted = false;\n\n private readonly _deletedIndices: number[] = [];\n private readonly _flushDeletedTask = new IdleTaskQueue();\n private _isFlushingDeleted = false;\n\n constructor(\n private readonly _getKey: (value: T) => number\n ) {\n }\n\n public clear(): void {\n this._array.length = 0;\n this._insertedValues.length = 0;\n this._flushInsertedTask.clear();\n this._isFlushingInserted = false;\n this._deletedIndices.length = 0;\n this._flushDeletedTask.clear();\n this._isFlushingDeleted = false;\n }\n\n public insert(value: T): void {\n this._flushCleanupDeleted();\n if (this._insertedValues.length === 0) {\n this._flushInsertedTask.enqueue(() => this._flushInserted());\n }\n this._insertedValues.push(value);\n }\n\n private _flushInserted(): void {\n const sortedAddedValues = this._insertedValues.sort((a, b) => this._getKey(a) - this._getKey(b));\n let sortedAddedValuesIndex = 0;\n let arrayIndex = 0;\n\n const newArray = new Array(this._array.length + this._insertedValues.length);\n\n for (let newArrayIndex = 0; newArrayIndex < newArray.length; newArrayIndex++) {\n if (arrayIndex >= this._array.length || this._getKey(sortedAddedValues[sortedAddedValuesIndex]) <= this._getKey(this._array[arrayIndex])) {\n newArray[newArrayIndex] = sortedAddedValues[sortedAddedValuesIndex];\n sortedAddedValuesIndex++;\n } else {\n newArray[newArrayIndex] = this._array[arrayIndex++];\n }\n }\n\n this._array = newArray;\n this._insertedValues.length = 0;\n }\n\n private _flushCleanupInserted(): void {\n if (!this._isFlushingInserted && this._insertedValues.length > 0) {\n this._flushInsertedTask.flush();\n }\n }\n\n public delete(value: T): boolean {\n this._flushCleanupInserted();\n if (this._array.length === 0) {\n return false;\n }\n const key = this._getKey(value);\n if (key === undefined) {\n return false;\n }\n i = this._search(key);\n if (i === -1) {\n return false;\n }\n if (this._getKey(this._array[i]) !== key) {\n return false;\n }\n do {\n if (this._array[i] === value) {\n if (this._deletedIndices.length === 0) {\n this._flushDeletedTask.enqueue(() => this._flushDeleted());\n }\n this._deletedIndices.push(i);\n return true;\n }\n } while (++i < this._array.length && this._getKey(this._array[i]) === key);\n return false;\n }\n\n private _flushDeleted(): void {\n this._isFlushingDeleted = true;\n const sortedDeletedIndices = this._deletedIndices.sort((a, b) => a - b);\n let sortedDeletedIndicesIndex = 0;\n const newArray = new Array(this._array.length - sortedDeletedIndices.length);\n let newArrayIndex = 0;\n for (let i = 0; i < this._array.length; i++) {\n if (sortedDeletedIndices[sortedDeletedIndicesIndex] === i) {\n sortedDeletedIndicesIndex++;\n } else {\n newArray[newArrayIndex++] = this._array[i];\n }\n }\n this._array = newArray;\n this._deletedIndices.length = 0;\n this._isFlushingDeleted = false;\n }\n\n private _flushCleanupDeleted(): void {\n if (!this._isFlushingDeleted && this._deletedIndices.length > 0) {\n this._flushDeletedTask.flush();\n }\n }\n\n public *getKeyIterator(key: number): IterableIterator {\n this._flushCleanupInserted();\n this._flushCleanupDeleted();\n if (this._array.length === 0) {\n return;\n }\n i = this._search(key);\n if (i < 0 || i >= this._array.length) {\n return;\n }\n if (this._getKey(this._array[i]) !== key) {\n return;\n }\n do {\n yield this._array[i];\n } while (++i < this._array.length && this._getKey(this._array[i]) === key);\n }\n\n public forEachByKey(key: number, callback: (value: T) => void): void {\n this._flushCleanupInserted();\n this._flushCleanupDeleted();\n if (this._array.length === 0) {\n return;\n }\n i = this._search(key);\n if (i < 0 || i >= this._array.length) {\n return;\n }\n if (this._getKey(this._array[i]) !== key) {\n return;\n }\n do {\n callback(this._array[i]);\n } while (++i < this._array.length && this._getKey(this._array[i]) === key);\n }\n\n public values(): IterableIterator {\n this._flushCleanupInserted();\n this._flushCleanupDeleted();\n // Duplicate the array to avoid issues when _array changes while iterating\n return [...this._array].values();\n }\n\n private _search(key: number): number {\n let min = 0;\n let max = this._array.length - 1;\n while (max >= min) {\n let mid = (min + max) >> 1;\n const midKey = this._getKey(this._array[mid]);\n if (midKey > key) {\n max = mid - 1;\n } else if (midKey < key) {\n min = mid + 1;\n } else {\n // key in list, walk to lowest duplicate\n while (mid > 0 && this._getKey(this._array[mid - 1]) === key) {\n mid--;\n }\n return mid;\n }\n }\n // key not in list\n // still return closest min (also used as insert position)\n return min;\n }\n}\n", "/**\n * Copyright (c) 2022 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { css } from 'common/Color';\nimport { Disposable, DisposableStore, toDisposable } from 'vs/base/common/lifecycle';\nimport { IDecorationService, IInternalDecoration } from 'common/services/Services';\nimport { SortedList } from 'common/SortedList';\nimport { IColor } from 'common/Types';\nimport { IDecoration, IDecorationOptions, IMarker } from '@xterm/xterm';\nimport { Emitter } from 'vs/base/common/event';\n\n// Work variables to avoid garbage collection\nlet $xmin = 0;\nlet $xmax = 0;\n\nexport class DecorationService extends Disposable implements IDecorationService {\n public serviceBrand: any;\n\n /**\n * A list of all decorations, sorted by the marker's line value. This relies on the fact that\n * while marker line values do change, they should all change by the same amount so this should\n * never become out of order.\n */\n private readonly _decorations: SortedList = new SortedList(e => e?.marker.line);\n\n private readonly _onDecorationRegistered = this._register(new Emitter());\n public readonly onDecorationRegistered = this._onDecorationRegistered.event;\n private readonly _onDecorationRemoved = this._register(new Emitter());\n public readonly onDecorationRemoved = this._onDecorationRemoved.event;\n\n public get decorations(): IterableIterator { return this._decorations.values(); }\n\n constructor() {\n super();\n\n this._register(toDisposable(() => this.reset()));\n }\n\n public registerDecoration(options: IDecorationOptions): IDecoration | undefined {\n if (options.marker.isDisposed) {\n return undefined;\n }\n const decoration = new Decoration(options);\n if (decoration) {\n const markerDispose = decoration.marker.onDispose(() => decoration.dispose());\n const listener = decoration.onDispose(() => {\n listener.dispose();\n if (decoration) {\n if (this._decorations.delete(decoration)) {\n this._onDecorationRemoved.fire(decoration);\n }\n markerDispose.dispose();\n }\n });\n this._decorations.insert(decoration);\n this._onDecorationRegistered.fire(decoration);\n }\n return decoration;\n }\n\n public reset(): void {\n for (const d of this._decorations.values()) {\n d.dispose();\n }\n this._decorations.clear();\n }\n\n public *getDecorationsAtCell(x: number, line: number, layer?: 'bottom' | 'top'): IterableIterator {\n let xmin = 0;\n let xmax = 0;\n for (const d of this._decorations.getKeyIterator(line)) {\n xmin = d.options.x ?? 0;\n xmax = xmin + (d.options.width ?? 1);\n if (x >= xmin && x < xmax && (!layer || (d.options.layer ?? 'bottom') === layer)) {\n yield d;\n }\n }\n }\n\n public forEachDecorationAtCell(x: number, line: number, layer: 'bottom' | 'top' | undefined, callback: (decoration: IInternalDecoration) => void): void {\n this._decorations.forEachByKey(line, d => {\n $xmin = d.options.x ?? 0;\n $xmax = $xmin + (d.options.width ?? 1);\n if (x >= $xmin && x < $xmax && (!layer || (d.options.layer ?? 'bottom') === layer)) {\n callback(d);\n }\n });\n }\n}\n\nclass Decoration extends DisposableStore implements IInternalDecoration {\n public readonly marker: IMarker;\n public element: HTMLElement | undefined;\n\n public readonly onRenderEmitter = this.add(new Emitter());\n public readonly onRender = this.onRenderEmitter.event;\n private readonly _onDispose = this.add(new Emitter());\n public readonly onDispose = this._onDispose.event;\n\n private _cachedBg: IColor | undefined | null = null;\n public get backgroundColorRGB(): IColor | undefined {\n if (this._cachedBg === null) {\n if (this.options.backgroundColor) {\n this._cachedBg = css.toColor(this.options.backgroundColor);\n } else {\n this._cachedBg = undefined;\n }\n }\n return this._cachedBg;\n }\n\n private _cachedFg: IColor | undefined | null = null;\n public get foregroundColorRGB(): IColor | undefined {\n if (this._cachedFg === null) {\n if (this.options.foregroundColor) {\n this._cachedFg = css.toColor(this.options.foregroundColor);\n } else {\n this._cachedFg = undefined;\n }\n }\n return this._cachedFg;\n }\n\n constructor(\n public readonly options: IDecorationOptions\n ) {\n super();\n this.marker = options.marker;\n if (this.options.overviewRulerOptions && !this.options.overviewRulerOptions.position) {\n this.options.overviewRulerOptions.position = 'full';\n }\n }\n\n public override dispose(): void {\n this._onDispose.fire();\n super.dispose();\n }\n}\n", "/**\n * Copyright (c) 2018 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nconst RENDER_DEBOUNCE_THRESHOLD_MS = 1000; // 1 Second\n\nimport { IRenderDebouncer } from 'browser/Types';\n\n/**\n * Debounces calls to update screen readers to update at most once configurable interval of time.\n */\nexport class TimeBasedDebouncer implements IRenderDebouncer {\n private _rowStart: number | undefined;\n private _rowEnd: number | undefined;\n private _rowCount: number | undefined;\n\n // The last moment that the Terminal was refreshed at\n private _lastRefreshMs = 0;\n // Whether a trailing refresh should be triggered due to a refresh request that was throttled\n private _additionalRefreshRequested = false;\n\n private _refreshTimeoutID: number | undefined;\n\n constructor(\n private _renderCallback: (start: number, end: number) => void,\n private readonly _debounceThresholdMS = RENDER_DEBOUNCE_THRESHOLD_MS\n ) {\n }\n\n public dispose(): void {\n if (this._refreshTimeoutID) {\n clearTimeout(this._refreshTimeoutID);\n }\n }\n\n public refresh(rowStart: number | undefined, rowEnd: number | undefined, rowCount: number): void {\n this._rowCount = rowCount;\n // Get the min/max row start/end for the arg values\n rowStart = rowStart !== undefined ? rowStart : 0;\n rowEnd = rowEnd !== undefined ? rowEnd : this._rowCount - 1;\n // Set the properties to the updated values\n this._rowStart = this._rowStart !== undefined ? Math.min(this._rowStart, rowStart) : rowStart;\n this._rowEnd = this._rowEnd !== undefined ? Math.max(this._rowEnd, rowEnd) : rowEnd;\n\n // Only refresh if the time since last refresh is above a threshold, otherwise wait for\n // enough time to pass before refreshing again.\n const refreshRequestTime: number = performance.now();\n if (refreshRequestTime - this._lastRefreshMs >= this._debounceThresholdMS) {\n // Enough time has lapsed since the last refresh; refresh immediately\n this._lastRefreshMs = refreshRequestTime;\n this._innerRefresh();\n } else if (!this._additionalRefreshRequested) {\n // This is the first additional request throttled; set up trailing refresh\n const elapsed = refreshRequestTime - this._lastRefreshMs;\n const waitPeriodBeforeTrailingRefresh = this._debounceThresholdMS - elapsed;\n this._additionalRefreshRequested = true;\n\n this._refreshTimeoutID = window.setTimeout(() => {\n this._lastRefreshMs = performance.now();\n this._innerRefresh();\n this._additionalRefreshRequested = false;\n this._refreshTimeoutID = undefined; // No longer need to clear the timeout\n }, waitPeriodBeforeTrailingRefresh);\n }\n }\n\n private _innerRefresh(): void {\n // Make sure values are set\n if (this._rowStart === undefined || this._rowEnd === undefined || this._rowCount === undefined) {\n return;\n }\n\n // Clamp values\n const start = Math.max(this._rowStart, 0);\n const end = Math.min(this._rowEnd, this._rowCount - 1);\n\n // Reset debouncer (this happens before render callback as the render could trigger it again)\n this._rowStart = undefined;\n this._rowEnd = undefined;\n\n // Run render callback\n this._renderCallback(start, end);\n }\n}\n\n", "/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport * as Strings from 'browser/LocalizableStrings';\nimport { ITerminal, IRenderDebouncer } from 'browser/Types';\nimport { TimeBasedDebouncer } from 'browser/TimeBasedDebouncer';\nimport { Disposable, toDisposable } from 'vs/base/common/lifecycle';\nimport { ICoreBrowserService, IRenderService } from 'browser/services/Services';\nimport { IBuffer } from 'common/buffer/Types';\nimport { IInstantiationService } from 'common/services/Services';\nimport { addDisposableListener } from 'vs/base/browser/dom';\n\nconst MAX_ROWS_TO_READ = 20;\n\nconst enum BoundaryPosition {\n TOP,\n BOTTOM\n}\n\n// Turn this on to unhide the accessibility tree and display it under\n// (instead of overlapping with) the terminal.\nconst DEBUG = false;\n\nexport class AccessibilityManager extends Disposable {\n private _debugRootContainer: HTMLElement | undefined;\n private _accessibilityContainer: HTMLElement;\n\n private _rowContainer: HTMLElement;\n private _rowElements: HTMLElement[];\n private _rowColumns: WeakMap = new WeakMap();\n\n private _liveRegion: HTMLElement;\n private _liveRegionLineCount: number = 0;\n private _liveRegionDebouncer: IRenderDebouncer;\n\n private _topBoundaryFocusListener: (e: FocusEvent) => void;\n private _bottomBoundaryFocusListener: (e: FocusEvent) => void;\n\n /**\n * This queue has a character pushed to it for keys that are pressed, if the\n * next character added to the terminal is equal to the key char then it is\n * not announced (added to live region) because it has already been announced\n * by the textarea event (which cannot be canceled). There are some race\n * condition cases if there is typing while data is streaming, but this covers\n * the main case of typing into the prompt and inputting the answer to a\n * question (Y/N, etc.).\n */\n private _charsToConsume: string[] = [];\n\n private _charsToAnnounce: string = '';\n\n constructor(\n private readonly _terminal: ITerminal,\n @IInstantiationService instantiationService: IInstantiationService,\n @ICoreBrowserService private readonly _coreBrowserService: ICoreBrowserService,\n @IRenderService private readonly _renderService: IRenderService\n ) {\n super();\n const doc = this._coreBrowserService.mainDocument;\n this._accessibilityContainer = doc.createElement('div');\n this._accessibilityContainer.classList.add('xterm-accessibility');\n\n this._rowContainer = doc.createElement('div');\n this._rowContainer.setAttribute('role', 'list');\n this._rowContainer.classList.add('xterm-accessibility-tree');\n this._rowElements = [];\n for (let i = 0; i < this._terminal.rows; i++) {\n this._rowElements[i] = this._createAccessibilityTreeNode();\n this._rowContainer.appendChild(this._rowElements[i]);\n }\n\n this._topBoundaryFocusListener = e => this._handleBoundaryFocus(e, BoundaryPosition.TOP);\n this._bottomBoundaryFocusListener = e => this._handleBoundaryFocus(e, BoundaryPosition.BOTTOM);\n this._rowElements[0].addEventListener('focus', this._topBoundaryFocusListener);\n this._rowElements[this._rowElements.length - 1].addEventListener('focus', this._bottomBoundaryFocusListener);\n\n this._accessibilityContainer.appendChild(this._rowContainer);\n\n this._liveRegion = doc.createElement('div');\n this._liveRegion.classList.add('live-region');\n this._liveRegion.setAttribute('aria-live', 'assertive');\n this._accessibilityContainer.appendChild(this._liveRegion);\n this._liveRegionDebouncer = this._register(new TimeBasedDebouncer(this._renderRows.bind(this)));\n\n if (!this._terminal.element) {\n throw new Error('Cannot enable accessibility before Terminal.open');\n }\n\n if (DEBUG) {\n this._accessibilityContainer.classList.add('debug');\n this._rowContainer.classList.add('debug');\n\n // Use a `
` container so that the css will still apply.\n this._debugRootContainer = doc.createElement('div');\n this._debugRootContainer.classList.add('xterm');\n\n this._debugRootContainer.appendChild(doc.createTextNode('------start a11y------'));\n this._debugRootContainer.appendChild(this._accessibilityContainer);\n this._debugRootContainer.appendChild(doc.createTextNode('------end a11y------'));\n\n this._terminal.element.insertAdjacentElement('afterend', this._debugRootContainer);\n } else {\n this._terminal.element.insertAdjacentElement('afterbegin', this._accessibilityContainer);\n }\n\n this._register(this._terminal.onResize(e => this._handleResize(e.rows)));\n this._register(this._terminal.onRender(e => this._refreshRows(e.start, e.end)));\n this._register(this._terminal.onScroll(() => this._refreshRows()));\n // Line feed is an issue as the prompt won't be read out after a command is run\n this._register(this._terminal.onA11yChar(char => this._handleChar(char)));\n this._register(this._terminal.onLineFeed(() => this._handleChar('\\n')));\n this._register(this._terminal.onA11yTab(spaceCount => this._handleTab(spaceCount)));\n this._register(this._terminal.onKey(e => this._handleKey(e.key)));\n this._register(this._terminal.onBlur(() => this._clearLiveRegion()));\n this._register(this._renderService.onDimensionsChange(() => this._refreshRowsDimensions()));\n this._register(addDisposableListener(doc, 'selectionchange', () => this._handleSelectionChange()));\n this._register(this._coreBrowserService.onDprChange(() => this._refreshRowsDimensions()));\n\n this._refreshRowsDimensions();\n this._refreshRows();\n this._register(toDisposable(() => {\n if (DEBUG) {\n this._debugRootContainer!.remove();\n } else {\n this._accessibilityContainer.remove();\n }\n this._rowElements.length = 0;\n }));\n }\n\n private _handleTab(spaceCount: number): void {\n for (let i = 0; i < spaceCount; i++) {\n this._handleChar(' ');\n }\n }\n\n private _handleChar(char: string): void {\n if (this._liveRegionLineCount < MAX_ROWS_TO_READ + 1) {\n if (this._charsToConsume.length > 0) {\n // Have the screen reader ignore the char if it was just input\n const shiftedChar = this._charsToConsume.shift();\n if (shiftedChar !== char) {\n this._charsToAnnounce += char;\n }\n } else {\n this._charsToAnnounce += char;\n }\n\n if (char === '\\n') {\n this._liveRegionLineCount++;\n if (this._liveRegionLineCount === MAX_ROWS_TO_READ + 1) {\n this._liveRegion.textContent += Strings.tooMuchOutput.get();\n }\n }\n }\n }\n\n private _clearLiveRegion(): void {\n this._liveRegion.textContent = '';\n this._liveRegionLineCount = 0;\n }\n\n private _handleKey(keyChar: string): void {\n this._clearLiveRegion();\n // Only add the char if there is no control character.\n if (!/\\p{Control}/u.test(keyChar)) {\n this._charsToConsume.push(keyChar);\n }\n }\n\n private _refreshRows(start?: number, end?: number): void {\n this._liveRegionDebouncer.refresh(start, end, this._terminal.rows);\n }\n\n private _renderRows(start: number, end: number): void {\n const buffer: IBuffer = this._terminal.buffer;\n const setSize = buffer.lines.length.toString();\n for (let i = start; i <= end; i++) {\n const line = buffer.lines.get(buffer.ydisp + i);\n const columns: number[] = [];\n const lineData = line?.translateToString(true, undefined, undefined, columns) || '';\n const posInSet = (buffer.ydisp + i + 1).toString();\n const element = this._rowElements[i];\n if (element) {\n if (lineData.length === 0) {\n element.textContent = '\\u00a0';\n this._rowColumns.set(element, [0, 1]);\n } else {\n element.textContent = lineData;\n this._rowColumns.set(element, columns);\n }\n element.setAttribute('aria-posinset', posInSet);\n element.setAttribute('aria-setsize', setSize);\n this._alignRowWidth(element);\n }\n }\n this._announceCharacters();\n }\n\n private _announceCharacters(): void {\n if (this._charsToAnnounce.length === 0) {\n return;\n }\n this._liveRegion.textContent += this._charsToAnnounce;\n this._charsToAnnounce = '';\n }\n\n private _handleBoundaryFocus(e: FocusEvent, position: BoundaryPosition): void {\n const boundaryElement = e.target as HTMLElement;\n const beforeBoundaryElement = this._rowElements[position === BoundaryPosition.TOP ? 1 : this._rowElements.length - 2];\n\n // Don't scroll if the buffer top has reached the end in that direction\n const posInSet = boundaryElement.getAttribute('aria-posinset');\n const lastRowPos = position === BoundaryPosition.TOP ? '1' : `${this._terminal.buffer.lines.length}`;\n if (posInSet === lastRowPos) {\n return;\n }\n\n // Don't scroll when the last focused item was not the second row (focus is going the other\n // direction)\n if (e.relatedTarget !== beforeBoundaryElement) {\n return;\n }\n\n // Remove old boundary element from array\n let topBoundaryElement: HTMLElement;\n let bottomBoundaryElement: HTMLElement;\n if (position === BoundaryPosition.TOP) {\n topBoundaryElement = boundaryElement;\n bottomBoundaryElement = this._rowElements.pop()!;\n this._rowContainer.removeChild(bottomBoundaryElement);\n } else {\n topBoundaryElement = this._rowElements.shift()!;\n bottomBoundaryElement = boundaryElement;\n this._rowContainer.removeChild(topBoundaryElement);\n }\n\n // Remove listeners from old boundary elements\n topBoundaryElement.removeEventListener('focus', this._topBoundaryFocusListener);\n bottomBoundaryElement.removeEventListener('focus', this._bottomBoundaryFocusListener);\n\n // Add new element to array/DOM\n if (position === BoundaryPosition.TOP) {\n const newElement = this._createAccessibilityTreeNode();\n this._rowElements.unshift(newElement);\n this._rowContainer.insertAdjacentElement('afterbegin', newElement);\n } else {\n const newElement = this._createAccessibilityTreeNode();\n this._rowElements.push(newElement);\n this._rowContainer.appendChild(newElement);\n }\n\n // Add listeners to new boundary elements\n this._rowElements[0].addEventListener('focus', this._topBoundaryFocusListener);\n this._rowElements[this._rowElements.length - 1].addEventListener('focus', this._bottomBoundaryFocusListener);\n\n // Scroll up\n this._terminal.scrollLines(position === BoundaryPosition.TOP ? -1 : 1);\n\n // Focus new boundary before element\n this._rowElements[position === BoundaryPosition.TOP ? 1 : this._rowElements.length - 2].focus();\n\n // Prevent the standard behavior\n e.preventDefault();\n e.stopImmediatePropagation();\n }\n\n private _handleSelectionChange(): void {\n if (this._rowElements.length === 0) {\n return;\n }\n\n const selection = this._coreBrowserService.mainDocument.getSelection();\n if (!selection) {\n return;\n }\n\n if (selection.isCollapsed) {\n // Only do something when the anchorNode is inside the row container. This\n // behavior mirrors what we do with mouse --- if the mouse clicks\n // somewhere outside of the terminal, we don't clear the selection.\n if (this._rowContainer.contains(selection.anchorNode)) {\n this._terminal.clearSelection();\n }\n return;\n }\n\n if (!selection.anchorNode || !selection.focusNode) {\n console.error('anchorNode and/or focusNode are null');\n return;\n }\n\n // Sort the two selection points in document order.\n let begin = { node: selection.anchorNode, offset: selection.anchorOffset };\n let end = { node: selection.focusNode, offset: selection.focusOffset };\n if ((begin.node.compareDocumentPosition(end.node) & Node.DOCUMENT_POSITION_PRECEDING) || (begin.node === end.node && begin.offset > end.offset) ) {\n [begin, end] = [end, begin];\n }\n\n // Clamp begin/end to the inside of the row container.\n if (begin.node.compareDocumentPosition(this._rowElements[0]) & (Node.DOCUMENT_POSITION_CONTAINED_BY | Node.DOCUMENT_POSITION_FOLLOWING)) {\n begin = { node: this._rowElements[0].childNodes[0], offset: 0 };\n }\n if (!this._rowContainer.contains(begin.node)) {\n // This happens when `begin` is below the last row.\n return;\n }\n const lastRowElement = this._rowElements.slice(-1)[0];\n if (end.node.compareDocumentPosition(lastRowElement) & (Node.DOCUMENT_POSITION_CONTAINED_BY | Node.DOCUMENT_POSITION_PRECEDING)) {\n end = {\n node: lastRowElement,\n offset: lastRowElement.textContent?.length ?? 0\n };\n }\n if (!this._rowContainer.contains(end.node)) {\n // This happens when `end` is above the first row.\n return;\n }\n\n const toRowColumn = ({ node, offset }: typeof begin): {row: number, column: number} | null => {\n // `node` is either the row element or the Text node inside it.\n const rowElement: any = node instanceof Text ? node.parentNode : node;\n let row = parseInt(rowElement?.getAttribute('aria-posinset'), 10) - 1;\n if (isNaN(row)) {\n console.warn('row is invalid. Race condition?');\n return null;\n }\n\n const columns = this._rowColumns.get(rowElement);\n if (!columns) {\n console.warn('columns is null. Race condition?');\n return null;\n }\n\n let column = offset < columns.length ? columns[offset] : columns.slice(-1)[0] + 1;\n if (column >= this._terminal.cols) {\n ++row;\n column = 0;\n }\n return {\n row,\n column\n };\n };\n\n const beginRowColumn = toRowColumn(begin);\n const endRowColumn = toRowColumn(end);\n\n if (!beginRowColumn || !endRowColumn) {\n return;\n }\n\n if (beginRowColumn.row > endRowColumn.row || (beginRowColumn.row === endRowColumn.row && beginRowColumn.column >= endRowColumn.column)) {\n // This should not happen unless we have some bugs.\n throw new Error('invalid range');\n }\n\n this._terminal.select(\n beginRowColumn.column,\n beginRowColumn.row,\n (endRowColumn.row - beginRowColumn.row) * this._terminal.cols - beginRowColumn.column + endRowColumn.column\n );\n }\n\n private _handleResize(rows: number): void {\n // Remove bottom boundary listener\n this._rowElements[this._rowElements.length - 1].removeEventListener('focus', this._bottomBoundaryFocusListener);\n\n // Grow rows as required\n for (let i = this._rowContainer.children.length; i < this._terminal.rows; i++) {\n this._rowElements[i] = this._createAccessibilityTreeNode();\n this._rowContainer.appendChild(this._rowElements[i]);\n }\n // Shrink rows as required\n while (this._rowElements.length > rows) {\n this._rowContainer.removeChild(this._rowElements.pop()!);\n }\n\n // Add bottom boundary listener\n this._rowElements[this._rowElements.length - 1].addEventListener('focus', this._bottomBoundaryFocusListener);\n\n this._refreshRowsDimensions();\n }\n\n private _createAccessibilityTreeNode(): HTMLElement {\n const element = this._coreBrowserService.mainDocument.createElement('div');\n element.setAttribute('role', 'listitem');\n element.tabIndex = -1;\n this._refreshRowDimensions(element);\n return element;\n }\n\n private _refreshRowsDimensions(): void {\n if (!this._renderService.dimensions.css.cell.height) {\n return;\n }\n Object.assign(this._accessibilityContainer.style, {\n width: `${this._renderService.dimensions.css.canvas.width}px`,\n fontSize: `${this._terminal.options.fontSize}px`\n });\n if (this._rowElements.length !== this._terminal.rows) {\n this._handleResize(this._terminal.rows);\n }\n for (let i = 0; i < this._terminal.rows; i++) {\n this._refreshRowDimensions(this._rowElements[i]);\n this._alignRowWidth(this._rowElements[i]);\n }\n }\n\n private _refreshRowDimensions(element: HTMLElement): void {\n element.style.height = `${this._renderService.dimensions.css.cell.height}px`;\n }\n\n /**\n * Scale the width of a row so that each of the character is (mostly) aligned\n * with the actual rendering. This will allow the screen reader to draw\n * selection outline at the correct position.\n *\n * On top of using the \"monospace\" font and correct font size, the scaling\n * here is necessary to handle characters that are not covered by the font\n * (e.g. CJK).\n */\n private _alignRowWidth(element: HTMLElement): void {\n element.style.transform = '';\n const width = element.getBoundingClientRect().width;\n const lastColumn = this._rowColumns.get(element)?.slice(-1)?.[0];\n if (!lastColumn) {\n return;\n }\n const targetWidth = lastColumn * this._renderService.dimensions.css.cell.width;\n element.style.transform = `scaleX(${targetWidth / width})`;\n }\n}\n", "/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IBufferCellPosition, ILink, ILinkDecorations, ILinkWithState, ILinkifier2, ILinkifierEvent } from 'browser/Types';\nimport { Disposable, dispose, toDisposable } from 'vs/base/common/lifecycle';\nimport { IDisposable } from 'common/Types';\nimport { IBufferService } from 'common/services/Services';\nimport { ILinkProviderService, IMouseService, IRenderService } from './services/Services';\nimport { Emitter } from 'vs/base/common/event';\nimport { addDisposableListener } from 'vs/base/browser/dom';\n\nexport class Linkifier extends Disposable implements ILinkifier2 {\n public get currentLink(): ILinkWithState | undefined { return this._currentLink; }\n protected _currentLink: ILinkWithState | undefined;\n private _mouseDownLink: ILinkWithState | undefined;\n private _lastMouseEvent: MouseEvent | undefined;\n private _linkCacheDisposables: IDisposable[] = [];\n private _lastBufferCell: IBufferCellPosition | undefined;\n private _isMouseOut: boolean = true;\n private _wasResized: boolean = false;\n private _activeProviderReplies: Map | undefined;\n private _activeLine: number = -1;\n\n private readonly _onShowLinkUnderline = this._register(new Emitter());\n public readonly onShowLinkUnderline = this._onShowLinkUnderline.event;\n private readonly _onHideLinkUnderline = this._register(new Emitter());\n public readonly onHideLinkUnderline = this._onHideLinkUnderline.event;\n\n constructor(\n private readonly _element: HTMLElement,\n @IMouseService private readonly _mouseService: IMouseService,\n @IRenderService private readonly _renderService: IRenderService,\n @IBufferService private readonly _bufferService: IBufferService,\n @ILinkProviderService private readonly _linkProviderService: ILinkProviderService\n ) {\n super();\n this._register(toDisposable(() => {\n dispose(this._linkCacheDisposables);\n this._linkCacheDisposables.length = 0;\n this._lastMouseEvent = undefined;\n // Clear out link providers as they could easily cause an embedder memory leak\n this._activeProviderReplies?.clear();\n }));\n // Listen to resize to catch the case where it's resized and the cursor is out of the viewport.\n this._register(this._bufferService.onResize(() => {\n this._clearCurrentLink();\n this._wasResized = true;\n }));\n this._register(addDisposableListener(this._element, 'mouseleave', () => {\n this._isMouseOut = true;\n this._clearCurrentLink();\n }));\n this._register(addDisposableListener(this._element, 'mousemove', this._handleMouseMove.bind(this)));\n this._register(addDisposableListener(this._element, 'mousedown', this._handleMouseDown.bind(this)));\n this._register(addDisposableListener(this._element, 'mouseup', this._handleMouseUp.bind(this)));\n }\n\n private _handleMouseMove(event: MouseEvent): void {\n this._lastMouseEvent = event;\n\n const position = this._positionFromMouseEvent(event, this._element, this._mouseService);\n if (!position) {\n return;\n }\n this._isMouseOut = false;\n\n // Ignore the event if it's an embedder created hover widget\n const composedPath = event.composedPath() as HTMLElement[];\n for (let i = 0; i < composedPath.length; i++) {\n const target = composedPath[i];\n // Hit Terminal.element, break and continue\n if (target.classList.contains('xterm')) {\n break;\n }\n // It's a hover, don't respect hover event\n if (target.classList.contains('xterm-hover')) {\n return;\n }\n }\n\n if (!this._lastBufferCell || (position.x !== this._lastBufferCell.x || position.y !== this._lastBufferCell.y)) {\n this._handleHover(position);\n this._lastBufferCell = position;\n }\n }\n\n private _handleHover(position: IBufferCellPosition): void {\n // TODO: This currently does not cache link provider results across wrapped lines, activeLine\n // should be something like `activeRange: {startY, endY}`\n // Check if we need to clear the link\n if (this._activeLine !== position.y || this._wasResized) {\n this._clearCurrentLink();\n this._askForLink(position, false);\n this._wasResized = false;\n return;\n }\n\n // Check the if the link is in the mouse position\n const isCurrentLinkInPosition = this._currentLink && this._linkAtPosition(this._currentLink.link, position);\n if (!isCurrentLinkInPosition) {\n this._clearCurrentLink();\n this._askForLink(position, true);\n }\n }\n\n private _askForLink(position: IBufferCellPosition, useLineCache: boolean): void {\n if (!this._activeProviderReplies || !useLineCache) {\n this._activeProviderReplies?.forEach(reply => {\n reply?.forEach(linkWithState => {\n if (linkWithState.link.dispose) {\n linkWithState.link.dispose();\n }\n });\n });\n this._activeProviderReplies = new Map();\n this._activeLine = position.y;\n }\n let linkProvided = false;\n\n // There is no link cached, so ask for one\n for (const [i, linkProvider] of this._linkProviderService.linkProviders.entries()) {\n if (useLineCache) {\n const existingReply = this._activeProviderReplies?.get(i);\n // If there isn't a reply, the provider hasn't responded yet.\n\n // TODO: If there isn't a reply yet it means that the provider is still resolving. Ensuring\n // provideLinks isn't triggered again saves ILink.hover firing twice though. This probably\n // needs promises to get fixed\n if (existingReply) {\n linkProvided = this._checkLinkProviderResult(i, position, linkProvided);\n }\n } else {\n linkProvider.provideLinks(position.y, (links: ILink[] | undefined) => {\n if (this._isMouseOut) {\n return;\n }\n const linksWithState: ILinkWithState[] | undefined = links?.map(link => ({ link }));\n this._activeProviderReplies?.set(i, linksWithState);\n linkProvided = this._checkLinkProviderResult(i, position, linkProvided);\n\n // If all providers have responded, remove lower priority links that intersect ranges of\n // higher priority links\n if (this._activeProviderReplies?.size === this._linkProviderService.linkProviders.length) {\n this._removeIntersectingLinks(position.y, this._activeProviderReplies);\n }\n });\n }\n }\n }\n\n private _removeIntersectingLinks(y: number, replies: Map): void {\n const occupiedCells = new Set();\n for (let i = 0; i < replies.size; i++) {\n const providerReply = replies.get(i);\n if (!providerReply) {\n continue;\n }\n for (let i = 0; i < providerReply.length; i++) {\n const linkWithState = providerReply[i];\n const startX = linkWithState.link.range.start.y < y ? 0 : linkWithState.link.range.start.x;\n const endX = linkWithState.link.range.end.y > y ? this._bufferService.cols : linkWithState.link.range.end.x;\n for (let x = startX; x <= endX; x++) {\n if (occupiedCells.has(x)) {\n providerReply.splice(i--, 1);\n break;\n }\n occupiedCells.add(x);\n }\n }\n }\n }\n\n private _checkLinkProviderResult(index: number, position: IBufferCellPosition, linkProvided: boolean): boolean {\n if (!this._activeProviderReplies) {\n return linkProvided;\n }\n\n const links = this._activeProviderReplies.get(index);\n\n // Check if every provider before this one has come back undefined\n let hasLinkBefore = false;\n for (let j = 0; j < index; j++) {\n if (!this._activeProviderReplies.has(j) || this._activeProviderReplies.get(j)) {\n hasLinkBefore = true;\n }\n }\n\n // If all providers with higher priority came back undefined, then this provider's link for\n // the position should be used\n if (!hasLinkBefore && links) {\n const linkAtPosition = links.find(link => this._linkAtPosition(link.link, position));\n if (linkAtPosition) {\n linkProvided = true;\n this._handleNewLink(linkAtPosition);\n }\n }\n\n // Check if all the providers have responded\n if (this._activeProviderReplies.size === this._linkProviderService.linkProviders.length && !linkProvided) {\n // Respect the order of the link providers\n for (let j = 0; j < this._activeProviderReplies.size; j++) {\n const currentLink = this._activeProviderReplies.get(j)?.find(link => this._linkAtPosition(link.link, position));\n if (currentLink) {\n linkProvided = true;\n this._handleNewLink(currentLink);\n break;\n }\n }\n }\n\n return linkProvided;\n }\n\n private _handleMouseDown(): void {\n this._mouseDownLink = this._currentLink;\n }\n\n private _handleMouseUp(event: MouseEvent): void {\n if (!this._currentLink) {\n return;\n }\n\n const position = this._positionFromMouseEvent(event, this._element, this._mouseService);\n if (!position) {\n return;\n }\n\n if (this._mouseDownLink && linkEquals(this._mouseDownLink.link, this._currentLink.link) && this._linkAtPosition(this._currentLink.link, position)) {\n this._currentLink.link.activate(event, this._currentLink.link.text);\n }\n }\n\n private _clearCurrentLink(startRow?: number, endRow?: number): void {\n if (!this._currentLink || !this._lastMouseEvent) {\n return;\n }\n\n // If we have a start and end row, check that the link is within it\n if (!startRow || !endRow || (this._currentLink.link.range.start.y >= startRow && this._currentLink.link.range.end.y <= endRow)) {\n this._linkLeave(this._element, this._currentLink.link, this._lastMouseEvent);\n this._currentLink = undefined;\n dispose(this._linkCacheDisposables);\n this._linkCacheDisposables.length = 0;\n }\n }\n\n private _handleNewLink(linkWithState: ILinkWithState): void {\n if (!this._lastMouseEvent) {\n return;\n }\n\n const position = this._positionFromMouseEvent(this._lastMouseEvent, this._element, this._mouseService);\n\n if (!position) {\n return;\n }\n\n // Trigger hover if the we have a link at the position\n if (this._linkAtPosition(linkWithState.link, position)) {\n this._currentLink = linkWithState;\n this._currentLink.state = {\n decorations: {\n underline: linkWithState.link.decorations === undefined ? true : linkWithState.link.decorations.underline,\n pointerCursor: linkWithState.link.decorations === undefined ? true : linkWithState.link.decorations.pointerCursor\n },\n isHovered: true\n };\n this._linkHover(this._element, linkWithState.link, this._lastMouseEvent);\n\n // Add listener for tracking decorations changes\n linkWithState.link.decorations = {} as ILinkDecorations;\n Object.defineProperties(linkWithState.link.decorations, {\n pointerCursor: {\n get: () => this._currentLink?.state?.decorations.pointerCursor,\n set: v => {\n if (this._currentLink?.state && this._currentLink.state.decorations.pointerCursor !== v) {\n this._currentLink.state.decorations.pointerCursor = v;\n if (this._currentLink.state.isHovered) {\n this._element.classList.toggle('xterm-cursor-pointer', v);\n }\n }\n }\n },\n underline: {\n get: () => this._currentLink?.state?.decorations.underline,\n set: v => {\n if (this._currentLink?.state && this._currentLink?.state?.decorations.underline !== v) {\n this._currentLink.state.decorations.underline = v;\n if (this._currentLink.state.isHovered) {\n this._fireUnderlineEvent(linkWithState.link, v);\n }\n }\n }\n }\n });\n\n // Listen to viewport changes to re-render the link under the cursor (only when the line the\n // link is on changes)\n this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(e => {\n // Sanity check, this shouldn't happen in practice as this listener would be disposed\n if (!this._currentLink) {\n return;\n }\n // When start is 0 a scroll most likely occurred, make sure links above the fold also get\n // cleared.\n const start = e.start === 0 ? 0 : e.start + 1 + this._bufferService.buffer.ydisp;\n const end = this._bufferService.buffer.ydisp + 1 + e.end;\n // Only clear the link if the viewport change happened on this line\n if (this._currentLink.link.range.start.y >= start && this._currentLink.link.range.end.y <= end) {\n this._clearCurrentLink(start, end);\n if (this._lastMouseEvent) {\n // re-eval previously active link after changes\n const position = this._positionFromMouseEvent(this._lastMouseEvent, this._element, this._mouseService!);\n if (position) {\n this._askForLink(position, false);\n }\n }\n }\n }));\n }\n }\n\n protected _linkHover(element: HTMLElement, link: ILink, event: MouseEvent): void {\n if (this._currentLink?.state) {\n this._currentLink.state.isHovered = true;\n if (this._currentLink.state.decorations.underline) {\n this._fireUnderlineEvent(link, true);\n }\n if (this._currentLink.state.decorations.pointerCursor) {\n element.classList.add('xterm-cursor-pointer');\n }\n }\n\n if (link.hover) {\n link.hover(event, link.text);\n }\n }\n\n private _fireUnderlineEvent(link: ILink, showEvent: boolean): void {\n const range = link.range;\n const scrollOffset = this._bufferService.buffer.ydisp;\n const event = this._createLinkUnderlineEvent(range.start.x - 1, range.start.y - scrollOffset - 1, range.end.x, range.end.y - scrollOffset - 1, undefined);\n const emitter = showEvent ? this._onShowLinkUnderline : this._onHideLinkUnderline;\n emitter.fire(event);\n }\n\n protected _linkLeave(element: HTMLElement, link: ILink, event: MouseEvent): void {\n if (this._currentLink?.state) {\n this._currentLink.state.isHovered = false;\n if (this._currentLink.state.decorations.underline) {\n this._fireUnderlineEvent(link, false);\n }\n if (this._currentLink.state.decorations.pointerCursor) {\n element.classList.remove('xterm-cursor-pointer');\n }\n }\n\n if (link.leave) {\n link.leave(event, link.text);\n }\n }\n\n /**\n * Check if the buffer position is within the link\n * @param link\n * @param position\n */\n private _linkAtPosition(link: ILink, position: IBufferCellPosition): boolean {\n const lower = link.range.start.y * this._bufferService.cols + link.range.start.x;\n const upper = link.range.end.y * this._bufferService.cols + link.range.end.x;\n const current = position.y * this._bufferService.cols + position.x;\n return (lower <= current && current <= upper);\n }\n\n /**\n * Get the buffer position from a mouse event\n * @param event\n */\n private _positionFromMouseEvent(event: MouseEvent, element: HTMLElement, mouseService: IMouseService): IBufferCellPosition | undefined {\n const coords = mouseService.getCoords(event, element, this._bufferService.cols, this._bufferService.rows);\n if (!coords) {\n return;\n }\n\n return { x: coords[0], y: coords[1] + this._bufferService.buffer.ydisp };\n }\n\n private _createLinkUnderlineEvent(x1: number, y1: number, x2: number, y2: number, fg: number | undefined): ILinkifierEvent {\n return { x1, y1, x2, y2, cols: this._bufferService.cols, fg };\n }\n}\n\nfunction linkEquals(a: ILink, b: ILink): boolean {\n return (\n a.text === b.text &&\n a.range.start.x === b.range.start.x &&\n a.range.start.y === b.range.start.y &&\n a.range.end.x === b.range.end.x &&\n a.range.end.y === b.range.end.y\n );\n}\n", "/**\n * Copyright (c) 2014 The xterm.js authors. All rights reserved.\n * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)\n * @license MIT\n *\n * Originally forked from (with the author's permission):\n * Fabrice Bellard's javascript vt100 for jslinux:\n * http://bellard.org/jslinux/\n * Copyright (c) 2011 Fabrice Bellard\n * The original design remains. The terminal itself\n * has been extended to include xterm CSI codes, among\n * other features.\n *\n * Terminal Emulation References:\n * http://vt100.net/\n * http://invisible-island.net/xterm/ctlseqs/ctlseqs.txt\n * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html\n * http://invisible-island.net/vttest/\n * http://www.inwap.com/pdp10/ansicode.txt\n * http://linux.die.net/man/4/console_codes\n * http://linux.die.net/man/7/urxvt\n */\n\nimport { IDecoration, IDecorationOptions, IDisposable, ILinkProvider, IMarker } from '@xterm/xterm';\nimport { copyHandler, handlePasteEvent, moveTextAreaUnderMouseCursor, paste, rightClickHandler } from 'browser/Clipboard';\nimport * as Strings from 'browser/LocalizableStrings';\nimport { OscLinkProvider } from 'browser/OscLinkProvider';\nimport { CharacterJoinerHandler, CustomKeyEventHandler, CustomWheelEventHandler, IBrowser, IBufferRange, ICompositionHelper, ILinkifier2, ITerminal } from 'browser/Types';\nimport { Viewport } from 'browser/Viewport';\nimport { BufferDecorationRenderer } from 'browser/decorations/BufferDecorationRenderer';\nimport { OverviewRulerRenderer } from 'browser/decorations/OverviewRulerRenderer';\nimport { CompositionHelper } from 'browser/input/CompositionHelper';\nimport { DomRenderer } from 'browser/renderer/dom/DomRenderer';\nimport { IRenderer } from 'browser/renderer/shared/Types';\nimport { CharSizeService } from 'browser/services/CharSizeService';\nimport { CharacterJoinerService } from 'browser/services/CharacterJoinerService';\nimport { CoreBrowserService } from 'browser/services/CoreBrowserService';\nimport { LinkProviderService } from 'browser/services/LinkProviderService';\nimport { MouseService } from 'browser/services/MouseService';\nimport { RenderService } from 'browser/services/RenderService';\nimport { SelectionService } from 'browser/services/SelectionService';\nimport { ICharSizeService, ICharacterJoinerService, ICoreBrowserService, ILinkProviderService, IMouseService, IRenderService, ISelectionService, IThemeService } from 'browser/services/Services';\nimport { ThemeService } from 'browser/services/ThemeService';\nimport { channels, color } from 'common/Color';\nimport { CoreTerminal } from 'common/CoreTerminal';\nimport * as Browser from 'common/Platform';\nimport { ColorRequestType, CoreMouseAction, CoreMouseButton, CoreMouseEventType, IColorEvent, ITerminalOptions, KeyboardResultType, SpecialColorIndex } from 'common/Types';\nimport { DEFAULT_ATTR_DATA } from 'common/buffer/BufferLine';\nimport { IBuffer } from 'common/buffer/Types';\nimport { C0, C1_ESCAPED } from 'common/data/EscapeSequences';\nimport { evaluateKeyboardEvent } from 'common/input/Keyboard';\nimport { toRgbString } from 'common/input/XParseColor';\nimport { DecorationService } from 'common/services/DecorationService';\nimport { IDecorationService } from 'common/services/Services';\nimport { WindowsOptionsReportType } from '../common/InputHandler';\nimport { AccessibilityManager } from './AccessibilityManager';\nimport { Linkifier } from './Linkifier';\nimport { Emitter, Event } from 'vs/base/common/event';\nimport { addDisposableListener } from 'vs/base/browser/dom';\nimport { MutableDisposable, toDisposable } from 'vs/base/common/lifecycle';\n\nexport class CoreBrowserTerminal extends CoreTerminal implements ITerminal {\n public textarea: HTMLTextAreaElement | undefined;\n public element: HTMLElement | undefined;\n public screenElement: HTMLElement | undefined;\n\n private _document: Document | undefined;\n private _viewportElement: HTMLElement | undefined;\n private _helperContainer: HTMLElement | undefined;\n private _compositionView: HTMLElement | undefined;\n\n private readonly _linkifier: MutableDisposable = this._register(new MutableDisposable());\n public get linkifier(): ILinkifier2 | undefined { return this._linkifier.value; }\n private _overviewRulerRenderer: OverviewRulerRenderer | undefined;\n private _viewport: Viewport | undefined;\n\n public browser: IBrowser = Browser as any;\n\n private _customKeyEventHandler: CustomKeyEventHandler | undefined;\n private _customWheelEventHandler: CustomWheelEventHandler | undefined;\n\n // Browser services\n private _decorationService: DecorationService;\n private _linkProviderService: ILinkProviderService;\n\n // Optional browser services\n private _charSizeService: ICharSizeService | undefined;\n private _coreBrowserService: ICoreBrowserService | undefined;\n private _mouseService: IMouseService | undefined;\n private _renderService: IRenderService | undefined;\n private _themeService: IThemeService | undefined;\n private _characterJoinerService: ICharacterJoinerService | undefined;\n private _selectionService: ISelectionService | undefined;\n\n /**\n * Records whether the keydown event has already been handled and triggered a data event, if so\n * the keypress event should not trigger a data event but should still print to the textarea so\n * screen readers will announce it.\n */\n private _keyDownHandled: boolean = false;\n\n /**\n * Records whether a keydown event has occured since the last keyup event, i.e. whether a key\n * is currently \"pressed\".\n */\n private _keyDownSeen: boolean = false;\n\n /**\n * Records whether the keypress event has already been handled and triggered a data event, if so\n * the input event should not trigger a data event but should still print to the textarea so\n * screen readers will announce it.\n */\n private _keyPressHandled: boolean = false;\n\n /**\n * Records whether there has been a keydown event for a dead key without a corresponding keydown\n * event for the composed/alternative character. If we cancel the keydown event for the dead key,\n * no events will be emitted for the final character.\n */\n private _unprocessedDeadKey: boolean = false;\n\n private _compositionHelper: ICompositionHelper | undefined;\n private _accessibilityManager: MutableDisposable = this._register(new MutableDisposable());\n\n private readonly _onCursorMove = this._register(new Emitter());\n public readonly onCursorMove = this._onCursorMove.event;\n private readonly _onKey = this._register(new Emitter<{ key: string, domEvent: KeyboardEvent }>());\n public readonly onKey = this._onKey.event;\n private readonly _onRender = this._register(new Emitter<{ start: number, end: number }>());\n public readonly onRender = this._onRender.event;\n private readonly _onSelectionChange = this._register(new Emitter());\n public readonly onSelectionChange = this._onSelectionChange.event;\n private readonly _onTitleChange = this._register(new Emitter());\n public readonly onTitleChange = this._onTitleChange.event;\n private readonly _onBell = this._register(new Emitter());\n public readonly onBell = this._onBell.event;\n\n private _onFocus = this._register(new Emitter());\n public get onFocus(): Event { return this._onFocus.event; }\n private _onBlur = this._register(new Emitter());\n public get onBlur(): Event { return this._onBlur.event; }\n private _onA11yCharEmitter = this._register(new Emitter());\n public get onA11yChar(): Event { return this._onA11yCharEmitter.event; }\n private _onA11yTabEmitter = this._register(new Emitter());\n public get onA11yTab(): Event { return this._onA11yTabEmitter.event; }\n private _onWillOpen = this._register(new Emitter());\n public get onWillOpen(): Event { return this._onWillOpen.event; }\n\n constructor(\n options: Partial = {}\n ) {\n super(options);\n\n this._setup();\n\n this._decorationService = this._instantiationService.createInstance(DecorationService);\n this._instantiationService.setService(IDecorationService, this._decorationService);\n this._linkProviderService = this._instantiationService.createInstance(LinkProviderService);\n this._instantiationService.setService(ILinkProviderService, this._linkProviderService);\n this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(OscLinkProvider));\n\n // Setup InputHandler listeners\n this._register(this._inputHandler.onRequestBell(() => this._onBell.fire()));\n this._register(this._inputHandler.onRequestRefreshRows((e) => this.refresh(e?.start ?? 0, e?.end ?? (this.rows - 1))));\n this._register(this._inputHandler.onRequestSendFocus(() => this._reportFocus()));\n this._register(this._inputHandler.onRequestReset(() => this.reset()));\n this._register(this._inputHandler.onRequestWindowsOptionsReport(type => this._reportWindowsOptions(type)));\n this._register(this._inputHandler.onColor((event) => this._handleColorEvent(event)));\n this._register(Event.forward(this._inputHandler.onCursorMove, this._onCursorMove));\n this._register(Event.forward(this._inputHandler.onTitleChange, this._onTitleChange));\n this._register(Event.forward(this._inputHandler.onA11yChar, this._onA11yCharEmitter));\n this._register(Event.forward(this._inputHandler.onA11yTab, this._onA11yTabEmitter));\n\n // Setup listeners\n this._register(this._bufferService.onResize(e => this._afterResize(e.cols, e.rows)));\n\n this._register(toDisposable(() => {\n this._customKeyEventHandler = undefined;\n this.element?.parentNode?.removeChild(this.element);\n }));\n }\n\n /**\n * Handle color event from inputhandler for OSC 4|104 | 10|110 | 11|111 | 12|112.\n * An event from OSC 4|104 may contain multiple set or report requests, and multiple\n * or none restore requests (resetting all),\n * while an event from OSC 10|110 | 11|111 | 12|112 always contains a single request.\n */\n private _handleColorEvent(event: IColorEvent): void {\n if (!this._themeService) return;\n for (const req of event) {\n let acc: 'foreground' | 'background' | 'cursor' | 'ansi';\n let ident = '';\n switch (req.index) {\n case SpecialColorIndex.FOREGROUND: // OSC 10 | 110\n acc = 'foreground';\n ident = '10';\n break;\n case SpecialColorIndex.BACKGROUND: // OSC 11 | 111\n acc = 'background';\n ident = '11';\n break;\n case SpecialColorIndex.CURSOR: // OSC 12 | 112\n acc = 'cursor';\n ident = '12';\n break;\n default: // OSC 4 | 104\n // we can skip the [0..255] range check here (already done in inputhandler)\n acc = 'ansi';\n ident = '4;' + req.index;\n }\n switch (req.type) {\n case ColorRequestType.REPORT:\n const colorRgb = color.toColorRGB(acc === 'ansi'\n ? this._themeService.colors.ansi[req.index]\n : this._themeService.colors[acc]);\n this.coreService.triggerDataEvent(`${C0.ESC}]${ident};${toRgbString(colorRgb)}${C1_ESCAPED.ST}`);\n break;\n case ColorRequestType.SET:\n if (acc === 'ansi') {\n this._themeService.modifyColors(colors => colors.ansi[req.index] = channels.toColor(...req.color));\n } else {\n const narrowedAcc = acc;\n this._themeService.modifyColors(colors => colors[narrowedAcc] = channels.toColor(...req.color));\n }\n break;\n case ColorRequestType.RESTORE:\n this._themeService.restoreColor(req.index);\n break;\n }\n }\n }\n\n protected _setup(): void {\n super._setup();\n\n this._customKeyEventHandler = undefined;\n }\n\n /**\n * Convenience property to active buffer.\n */\n public get buffer(): IBuffer {\n return this.buffers.active;\n }\n\n /**\n * Focus the terminal. Delegates focus handling to the terminal's DOM element.\n */\n public focus(): void {\n if (this.textarea) {\n this.textarea.focus({ preventScroll: true });\n }\n }\n\n private _handleScreenReaderModeOptionChange(value: boolean): void {\n if (value) {\n if (!this._accessibilityManager.value && this._renderService) {\n this._accessibilityManager.value = this._instantiationService.createInstance(AccessibilityManager, this);\n }\n } else {\n this._accessibilityManager.clear();\n }\n }\n\n /**\n * Binds the desired focus behavior on a given terminal object.\n */\n private _handleTextAreaFocus(ev: FocusEvent): void {\n if (this.coreService.decPrivateModes.sendFocus) {\n this.coreService.triggerDataEvent(C0.ESC + '[I');\n }\n this.element!.classList.add('focus');\n this._showCursor();\n this._onFocus.fire();\n }\n\n /**\n * Blur the terminal, calling the blur function on the terminal's underlying\n * textarea.\n */\n public blur(): void {\n return this.textarea?.blur();\n }\n\n /**\n * Binds the desired blur behavior on a given terminal object.\n */\n private _handleTextAreaBlur(): void {\n // Text can safely be removed on blur. Doing it earlier could interfere with\n // screen readers reading it out.\n this.textarea!.value = '';\n this.refresh(this.buffer.y, this.buffer.y);\n if (this.coreService.decPrivateModes.sendFocus) {\n this.coreService.triggerDataEvent(C0.ESC + '[O');\n }\n this.element!.classList.remove('focus');\n this._onBlur.fire();\n }\n\n private _syncTextArea(): void {\n if (!this.textarea || !this.buffer.isCursorInViewport || this._compositionHelper!.isComposing || !this._renderService) {\n return;\n }\n const cursorY = this.buffer.ybase + this.buffer.y;\n const bufferLine = this.buffer.lines.get(cursorY);\n if (!bufferLine) {\n return;\n }\n const cursorX = Math.min(this.buffer.x, this.cols - 1);\n const cellHeight = this._renderService.dimensions.css.cell.height;\n const width = bufferLine.getWidth(cursorX);\n const cellWidth = this._renderService.dimensions.css.cell.width * width;\n const cursorTop = this.buffer.y * this._renderService.dimensions.css.cell.height;\n const cursorLeft = cursorX * this._renderService.dimensions.css.cell.width;\n\n // Sync the textarea to the exact position of the composition view so the IME knows where the\n // text is.\n this.textarea.style.left = cursorLeft + 'px';\n this.textarea.style.top = cursorTop + 'px';\n this.textarea.style.width = cellWidth + 'px';\n this.textarea.style.height = cellHeight + 'px';\n this.textarea.style.lineHeight = cellHeight + 'px';\n this.textarea.style.zIndex = '-5';\n }\n\n /**\n * Initialize default behavior\n */\n private _initGlobal(): void {\n this._bindKeys();\n\n // Bind clipboard functionality\n this._register(addDisposableListener(this.element!, 'copy', (event: ClipboardEvent) => {\n // If mouse events are active it means the selection manager is disabled and\n // copy should be handled by the host program.\n if (!this.hasSelection()) {\n return;\n }\n copyHandler(event, this._selectionService!);\n }));\n const pasteHandlerWrapper = (event: ClipboardEvent): void => handlePasteEvent(event, this.textarea!, this.coreService, this.optionsService);\n this._register(addDisposableListener(this.textarea!, 'paste', pasteHandlerWrapper));\n this._register(addDisposableListener(this.element!, 'paste', pasteHandlerWrapper));\n\n // Handle right click context menus\n if (Browser.isFirefox) {\n // Firefox doesn't appear to fire the contextmenu event on right click\n this._register(addDisposableListener(this.element!, 'mousedown', (event: MouseEvent) => {\n if (event.button === 2) {\n rightClickHandler(event, this.textarea!, this.screenElement!, this._selectionService!, this.options.rightClickSelectsWord);\n }\n }));\n } else {\n this._register(addDisposableListener(this.element!, 'contextmenu', (event: MouseEvent) => {\n rightClickHandler(event, this.textarea!, this.screenElement!, this._selectionService!, this.options.rightClickSelectsWord);\n }));\n }\n\n // Move the textarea under the cursor when middle clicking on Linux to ensure\n // middle click to paste selection works. This only appears to work in Chrome\n // at the time is writing.\n if (Browser.isLinux) {\n // Use auxclick event over mousedown the latter doesn't seem to work. Note\n // that the regular click event doesn't fire for the middle mouse button.\n this._register(addDisposableListener(this.element!, 'auxclick', (event: MouseEvent) => {\n if (event.button === 1) {\n moveTextAreaUnderMouseCursor(event, this.textarea!, this.screenElement!);\n }\n }));\n }\n }\n\n /**\n * Apply key handling to the terminal\n */\n private _bindKeys(): void {\n this._register(addDisposableListener(this.textarea!, 'keyup', (ev: KeyboardEvent) => this._keyUp(ev), true));\n this._register(addDisposableListener(this.textarea!, 'keydown', (ev: KeyboardEvent) => this._keyDown(ev), true));\n this._register(addDisposableListener(this.textarea!, 'keypress', (ev: KeyboardEvent) => this._keyPress(ev), true));\n this._register(addDisposableListener(this.textarea!, 'compositionstart', () => this._compositionHelper!.compositionstart()));\n this._register(addDisposableListener(this.textarea!, 'compositionupdate', (e: CompositionEvent) => this._compositionHelper!.compositionupdate(e)));\n this._register(addDisposableListener(this.textarea!, 'compositionend', () => this._compositionHelper!.compositionend()));\n this._register(addDisposableListener(this.textarea!, 'input', (ev: InputEvent) => this._inputEvent(ev), true));\n this._register(this.onRender(() => this._compositionHelper!.updateCompositionElements()));\n }\n\n /**\n * Opens the terminal within an element.\n *\n * @param parent The element to create the terminal within.\n */\n public open(parent: HTMLElement): void {\n if (!parent) {\n throw new Error('Terminal requires a parent element.');\n }\n\n if (!parent.isConnected) {\n this._logService.debug('Terminal.open was called on an element that was not attached to the DOM');\n }\n\n // If the terminal is already opened\n if (this.element?.ownerDocument.defaultView && this._coreBrowserService) {\n // Adjust the window if needed\n if (this.element.ownerDocument.defaultView !== this._coreBrowserService.window) {\n this._coreBrowserService.window = this.element.ownerDocument.defaultView;\n }\n return;\n }\n\n this._document = parent.ownerDocument;\n if (this.options.documentOverride && this.options.documentOverride instanceof Document) {\n this._document = this.optionsService.rawOptions.documentOverride as Document;\n }\n\n // Create main element container\n this.element = this._document.createElement('div');\n this.element.dir = 'ltr'; // xterm.css assumes LTR\n this.element.classList.add('terminal');\n this.element.classList.add('xterm');\n parent.appendChild(this.element);\n\n // Performance: Use a document fragment to build the terminal\n // viewport and helper elements detached from the DOM\n const fragment = this._document.createDocumentFragment();\n this._viewportElement = this._document.createElement('div');\n this._viewportElement.classList.add('xterm-viewport');\n fragment.appendChild(this._viewportElement);\n\n this.screenElement = this._document.createElement('div');\n this.screenElement.classList.add('xterm-screen');\n this._register(addDisposableListener(this.screenElement, 'mousemove', (ev: MouseEvent) => this.updateCursorStyle(ev)));\n // Create the container that will hold helpers like the textarea for\n // capturing DOM Events. Then produce the helpers.\n this._helperContainer = this._document.createElement('div');\n this._helperContainer.classList.add('xterm-helpers');\n this.screenElement.appendChild(this._helperContainer);\n fragment.appendChild(this.screenElement);\n\n const textarea = this.textarea = this._document.createElement('textarea');\n this.textarea.classList.add('xterm-helper-textarea');\n this.textarea.setAttribute('aria-label', Strings.promptLabel.get());\n if (!Browser.isChromeOS) {\n // ChromeVox on ChromeOS does not like this. See\n // https://issuetracker.google.com/issues/260170397\n this.textarea.setAttribute('aria-multiline', 'false');\n }\n this.textarea.setAttribute('autocorrect', 'off');\n this.textarea.setAttribute('autocapitalize', 'off');\n this.textarea.setAttribute('spellcheck', 'false');\n this.textarea.tabIndex = 0;\n this._register(this.optionsService.onSpecificOptionChange('disableStdin', () => textarea.readOnly = this.optionsService.rawOptions.disableStdin));\n this.textarea.readOnly = this.optionsService.rawOptions.disableStdin;\n\n // Register the core browser service before the generic textarea handlers are registered so it\n // handles them first. Otherwise the renderers may use the wrong focus state.\n this._coreBrowserService = this._register(this._instantiationService.createInstance(CoreBrowserService,\n this.textarea,\n parent.ownerDocument.defaultView ?? window,\n // Force unsafe null in node.js environment for tests\n this._document ?? (typeof window !== 'undefined') ? window.document : null as any\n ));\n this._instantiationService.setService(ICoreBrowserService, this._coreBrowserService);\n\n this._register(addDisposableListener(this.textarea, 'focus', (ev: FocusEvent) => this._handleTextAreaFocus(ev)));\n this._register(addDisposableListener(this.textarea, 'blur', () => this._handleTextAreaBlur()));\n this._helperContainer.appendChild(this.textarea);\n\n this._charSizeService = this._instantiationService.createInstance(CharSizeService, this._document, this._helperContainer);\n this._instantiationService.setService(ICharSizeService, this._charSizeService);\n\n this._themeService = this._instantiationService.createInstance(ThemeService);\n this._instantiationService.setService(IThemeService, this._themeService);\n\n this._characterJoinerService = this._instantiationService.createInstance(CharacterJoinerService);\n this._instantiationService.setService(ICharacterJoinerService, this._characterJoinerService);\n\n this._renderService = this._register(this._instantiationService.createInstance(RenderService, this.rows, this.screenElement));\n this._instantiationService.setService(IRenderService, this._renderService);\n this._register(this._renderService.onRenderedViewportChange(e => this._onRender.fire(e)));\n this.onResize(e => this._renderService!.resize(e.cols, e.rows));\n\n this._compositionView = this._document.createElement('div');\n this._compositionView.classList.add('composition-view');\n this._compositionHelper = this._instantiationService.createInstance(CompositionHelper, this.textarea, this._compositionView);\n this._helperContainer.appendChild(this._compositionView);\n\n this._mouseService = this._instantiationService.createInstance(MouseService);\n this._instantiationService.setService(IMouseService, this._mouseService);\n\n const linkifier = this._linkifier.value = this._register(this._instantiationService.createInstance(Linkifier, this.screenElement));\n\n // Performance: Add viewport and helper elements from the fragment\n this.element.appendChild(fragment);\n\n try {\n this._onWillOpen.fire(this.element);\n }\n catch { /* fails to load addon for some reason */ }\n if (!this._renderService.hasRenderer()) {\n this._renderService.setRenderer(this._createRenderer());\n }\n\n this._register(this.onCursorMove(() => {\n this._renderService!.handleCursorMove();\n this._syncTextArea();\n }));\n this._register(this.onResize(() => this._renderService!.handleResize(this.cols, this.rows)));\n this._register(this.onBlur(() => this._renderService!.handleBlur()));\n this._register(this.onFocus(() => this._renderService!.handleFocus()));\n\n this._viewport = this._register(this._instantiationService.createInstance(Viewport, this.element, this.screenElement));\n this._register(this._viewport.onRequestScrollLines(e => {\n super.scrollLines(e, false);\n this.refresh(0, this.rows - 1);\n }));\n\n this._selectionService = this._register(this._instantiationService.createInstance(SelectionService,\n this.element,\n this.screenElement,\n linkifier\n ));\n this._instantiationService.setService(ISelectionService, this._selectionService);\n this._register(this._selectionService.onRequestScrollLines(e => this.scrollLines(e.amount, e.suppressScrollEvent)));\n this._register(this._selectionService.onSelectionChange(() => this._onSelectionChange.fire()));\n this._register(this._selectionService.onRequestRedraw(e => this._renderService!.handleSelectionChanged(e.start, e.end, e.columnSelectMode)));\n this._register(this._selectionService.onLinuxMouseSelection(text => {\n // If there's a new selection, put it into the textarea, focus and select it\n // in order to register it as a selection on the OS. This event is fired\n // only on Linux to enable middle click to paste selection.\n this.textarea!.value = text;\n this.textarea!.focus();\n this.textarea!.select();\n }));\n this._register(Event.any(\n this._onScroll.event,\n this._inputHandler.onScroll\n )(() => {\n this._selectionService!.refresh();\n this._viewport?.queueSync();\n }));\n\n this._register(this._instantiationService.createInstance(BufferDecorationRenderer, this.screenElement));\n this._register(addDisposableListener(this.element, 'mousedown', (e: MouseEvent) => this._selectionService!.handleMouseDown(e)));\n\n // apply mouse event classes set by escape codes before terminal was attached\n if (this.coreMouseService.areMouseEventsActive) {\n this._selectionService.disable();\n this.element.classList.add('enable-mouse-events');\n } else {\n this._selectionService.enable();\n }\n\n if (this.options.screenReaderMode) {\n // Note that this must be done *after* the renderer is created in order to\n // ensure the correct order of the dprchange event\n this._accessibilityManager.value = this._instantiationService.createInstance(AccessibilityManager, this);\n }\n this._register(this.optionsService.onSpecificOptionChange('screenReaderMode', e => this._handleScreenReaderModeOptionChange(e)));\n\n if (this.options.overviewRuler.width) {\n this._overviewRulerRenderer = this._register(this._instantiationService.createInstance(OverviewRulerRenderer, this._viewportElement, this.screenElement));\n }\n this.optionsService.onSpecificOptionChange('overviewRuler', value => {\n if (!this._overviewRulerRenderer && value && this._viewportElement && this.screenElement) {\n this._overviewRulerRenderer = this._register(this._instantiationService.createInstance(OverviewRulerRenderer, this._viewportElement, this.screenElement));\n }\n });\n // Measure the character size\n this._charSizeService.measure();\n\n // Setup loop that draws to screen\n this.refresh(0, this.rows - 1);\n\n // Initialize global actions that need to be taken on the document.\n this._initGlobal();\n\n // Listen for mouse events and translate\n // them into terminal mouse protocols.\n this.bindMouse();\n }\n\n private _createRenderer(): IRenderer {\n return this._instantiationService.createInstance(DomRenderer, this, this._document!, this.element!, this.screenElement!, this._viewportElement!, this._helperContainer!, this.linkifier!);\n }\n\n /**\n * Bind certain mouse events to the terminal.\n * By default only 3 button + wheel up/down is ativated. For higher buttons\n * no mouse report will be created. Typically the standard actions will be active.\n *\n * There are several reasons not to enable support for higher buttons/wheel:\n * - Button 4 and 5 are typically used for history back and forward navigation,\n * there is no straight forward way to supress/intercept those standard actions.\n * - Support for higher buttons does not work in some platform/browser combinations.\n * - Left/right wheel was not tested.\n * - Emulators vary in mouse button support, typically only 3 buttons and\n * wheel up/down work reliable.\n *\n * TODO: Move mouse event code into its own file.\n */\n public bindMouse(): void {\n const self = this;\n const el = this.element!;\n\n // send event to CoreMouseService\n function sendEvent(ev: MouseEvent | WheelEvent): boolean {\n // get mouse coordinates\n const pos = self._mouseService!.getMouseReportCoords(ev, self.screenElement!);\n if (!pos) {\n return false;\n }\n\n let but: CoreMouseButton;\n let action: CoreMouseAction | undefined;\n switch ((ev as any).overrideType || ev.type) {\n case 'mousemove':\n action = CoreMouseAction.MOVE;\n if (ev.buttons === undefined) {\n // buttons is not supported on macOS, try to get a value from button instead\n but = CoreMouseButton.NONE;\n if (ev.button !== undefined) {\n but = ev.button < 3 ? ev.button : CoreMouseButton.NONE;\n }\n } else {\n // according to MDN buttons only reports up to button 5 (AUX2)\n but = ev.buttons & 1 ? CoreMouseButton.LEFT :\n ev.buttons & 4 ? CoreMouseButton.MIDDLE :\n ev.buttons & 2 ? CoreMouseButton.RIGHT :\n CoreMouseButton.NONE; // fallback to NONE\n }\n break;\n case 'mouseup':\n action = CoreMouseAction.UP;\n but = ev.button < 3 ? ev.button : CoreMouseButton.NONE;\n break;\n case 'mousedown':\n action = CoreMouseAction.DOWN;\n but = ev.button < 3 ? ev.button : CoreMouseButton.NONE;\n break;\n case 'wheel':\n if (self._customWheelEventHandler && self._customWheelEventHandler(ev as WheelEvent) === false) {\n return false;\n }\n const deltaY = (ev as WheelEvent).deltaY;\n if (deltaY === 0) {\n return false;\n }\n const lines = self.coreMouseService.consumeWheelEvent(\n ev as WheelEvent,\n self._renderService?.dimensions?.device?.cell?.height,\n self._coreBrowserService?.dpr\n );\n if (lines === 0) {\n return false;\n }\n action = deltaY < 0 ? CoreMouseAction.UP : CoreMouseAction.DOWN;\n but = CoreMouseButton.WHEEL;\n break;\n default:\n // dont handle other event types by accident\n return false;\n }\n\n // exit if we cannot determine valid button/action values\n // do nothing for higher buttons than wheel\n if (action === undefined || but === undefined || but > CoreMouseButton.WHEEL) {\n return false;\n }\n\n return self.coreMouseService.triggerMouseEvent({\n col: pos.col,\n row: pos.row,\n x: pos.x,\n y: pos.y,\n button: but,\n action,\n ctrl: ev.ctrlKey,\n alt: ev.altKey,\n shift: ev.shiftKey\n });\n }\n\n /**\n * Event listener state handling.\n * We listen to the onProtocolChange event of CoreMouseService and put\n * requested listeners in `requestedEvents`. With this the listeners\n * have all bits to do the event listener juggling.\n * Note: 'mousedown' currently is \"always on\" and not managed\n * by onProtocolChange.\n */\n const requestedEvents: { [key: string]: ((ev: MouseEvent | WheelEvent) => void) | null } = {\n mouseup: null,\n wheel: null,\n mousedrag: null,\n mousemove: null\n };\n const eventListeners: { [key: string]: (ev: any) => void | boolean } = {\n mouseup: (ev: MouseEvent) => {\n sendEvent(ev);\n if (!ev.buttons) {\n // if no other button is held remove global handlers\n this._document!.removeEventListener('mouseup', requestedEvents.mouseup!);\n if (requestedEvents.mousedrag) {\n this._document!.removeEventListener('mousemove', requestedEvents.mousedrag);\n }\n }\n return this.cancel(ev);\n },\n wheel: (ev: WheelEvent) => {\n sendEvent(ev);\n return this.cancel(ev, true);\n },\n mousedrag: (ev: MouseEvent) => {\n // deal only with move while a button is held\n if (ev.buttons) {\n sendEvent(ev);\n }\n },\n mousemove: (ev: MouseEvent) => {\n // deal only with move without any button\n if (!ev.buttons) {\n sendEvent(ev);\n }\n }\n };\n this._register(this.coreMouseService.onProtocolChange(events => {\n // apply global changes on events\n if (events) {\n if (this.optionsService.rawOptions.logLevel === 'debug') {\n this._logService.debug('Binding to mouse events:', this.coreMouseService.explainEvents(events));\n }\n this.element!.classList.add('enable-mouse-events');\n this._selectionService!.disable();\n } else {\n this._logService.debug('Unbinding from mouse events.');\n this.element!.classList.remove('enable-mouse-events');\n this._selectionService!.enable();\n }\n\n // add/remove handlers from requestedEvents\n\n if (!(events & CoreMouseEventType.MOVE)) {\n el.removeEventListener('mousemove', requestedEvents.mousemove!);\n requestedEvents.mousemove = null;\n } else if (!requestedEvents.mousemove) {\n el.addEventListener('mousemove', eventListeners.mousemove);\n requestedEvents.mousemove = eventListeners.mousemove;\n }\n\n if (!(events & CoreMouseEventType.WHEEL)) {\n el.removeEventListener('wheel', requestedEvents.wheel!);\n requestedEvents.wheel = null;\n } else if (!requestedEvents.wheel) {\n el.addEventListener('wheel', eventListeners.wheel, { passive: false });\n requestedEvents.wheel = eventListeners.wheel;\n }\n\n if (!(events & CoreMouseEventType.UP)) {\n this._document!.removeEventListener('mouseup', requestedEvents.mouseup!);\n requestedEvents.mouseup = null;\n } else if (!requestedEvents.mouseup) {\n requestedEvents.mouseup = eventListeners.mouseup;\n }\n\n if (!(events & CoreMouseEventType.DRAG)) {\n this._document!.removeEventListener('mousemove', requestedEvents.mousedrag!);\n requestedEvents.mousedrag = null;\n } else if (!requestedEvents.mousedrag) {\n requestedEvents.mousedrag = eventListeners.mousedrag;\n }\n }));\n // force initial onProtocolChange so we dont miss early mouse requests\n this.coreMouseService.activeProtocol = this.coreMouseService.activeProtocol;\n\n /**\n * \"Always on\" event listeners.\n */\n this._register(addDisposableListener(el, 'mousedown', (ev: MouseEvent) => {\n ev.preventDefault();\n this.focus();\n\n // Don't send the mouse button to the pty if mouse events are disabled or\n // if the selection manager is having selection forced (ie. a modifier is\n // held).\n if (!this.coreMouseService.areMouseEventsActive || this._selectionService!.shouldForceSelection(ev)) {\n return;\n }\n\n sendEvent(ev);\n\n // Register additional global handlers which should keep reporting outside\n // of the terminal element.\n // Note: Other emulators also do this for 'mousedown' while a button\n // is held, we currently limit 'mousedown' to the terminal only.\n if (requestedEvents.mouseup) {\n this._document!.addEventListener('mouseup', requestedEvents.mouseup);\n }\n if (requestedEvents.mousedrag) {\n this._document!.addEventListener('mousemove', requestedEvents.mousedrag);\n }\n\n return this.cancel(ev);\n }));\n\n this._register(addDisposableListener(el, 'wheel', (ev: WheelEvent) => {\n // do nothing, if app side handles wheel itself\n if (requestedEvents.wheel) return;\n\n if (this._customWheelEventHandler && this._customWheelEventHandler(ev) === false) {\n return false;\n }\n\n if (!this.buffer.hasScrollback) {\n // Convert wheel events into up/down events when the buffer does not have scrollback, this\n // enables scrolling in apps hosted in the alt buffer such as vim or tmux even when mouse\n // events are not enabled.\n // This used implementation used get the actual lines/partial lines scrolled from the\n // viewport but since moving to the new viewport implementation has been simplified to\n // simply send a single up or down sequence.\n\n // Do nothing if there's no vertical scroll\n const deltaY = (ev as WheelEvent).deltaY;\n if (deltaY === 0) {\n return false;\n }\n\n const lines = self.coreMouseService.consumeWheelEvent(\n ev as WheelEvent,\n self._renderService?.dimensions?.device?.cell?.height,\n self._coreBrowserService?.dpr\n );\n if (lines === 0) {\n return this.cancel(ev, true);\n }\n\n // Construct and send sequences\n const sequence = C0.ESC + (this.coreService.decPrivateModes.applicationCursorKeys ? 'O' : '[') + (ev.deltaY < 0 ? 'A' : 'B');\n this.coreService.triggerDataEvent(sequence, true);\n return this.cancel(ev, true);\n }\n }, { passive: false }));\n }\n\n\n /**\n * Tells the renderer to refresh terminal content between two rows (inclusive) at the next\n * opportunity.\n * @param start The row to start from (between 0 and this.rows - 1).\n * @param end The row to end at (between start and this.rows - 1).\n */\n public refresh(start: number, end: number): void {\n this._renderService?.refreshRows(start, end);\n }\n\n /**\n * Change the cursor style for different selection modes\n */\n public updateCursorStyle(ev: KeyboardEvent | MouseEvent): void {\n if (this._selectionService?.shouldColumnSelect(ev)) {\n this.element!.classList.add('column-select');\n } else {\n this.element!.classList.remove('column-select');\n }\n }\n\n /**\n * Display the cursor element\n */\n private _showCursor(): void {\n if (!this.coreService.isCursorInitialized) {\n this.coreService.isCursorInitialized = true;\n this.refresh(this.buffer.y, this.buffer.y);\n }\n }\n\n public scrollLines(disp: number, suppressScrollEvent?: boolean): void {\n // All scrollLines methods need to go via the viewport in order to support smooth scroll\n if (this._viewport) {\n this._viewport.scrollLines(disp);\n } else {\n super.scrollLines(disp, suppressScrollEvent);\n }\n this.refresh(0, this.rows - 1);\n }\n\n public scrollPages(pageCount: number): void {\n this.scrollLines(pageCount * (this.rows - 1));\n }\n\n public scrollToTop(): void {\n this.scrollLines(-this._bufferService.buffer.ydisp);\n }\n\n public scrollToBottom(disableSmoothScroll?: boolean): void {\n if (disableSmoothScroll && this._viewport) {\n this._viewport.scrollToLine(this.buffer.ybase, true);\n } else {\n this.scrollLines(this._bufferService.buffer.ybase - this._bufferService.buffer.ydisp);\n }\n }\n\n public scrollToLine(line: number): void {\n const scrollAmount = line - this._bufferService.buffer.ydisp;\n if (scrollAmount !== 0) {\n this.scrollLines(scrollAmount);\n }\n }\n\n public paste(data: string): void {\n paste(data, this.textarea!, this.coreService, this.optionsService);\n }\n\n public attachCustomKeyEventHandler(customKeyEventHandler: CustomKeyEventHandler): void {\n this._customKeyEventHandler = customKeyEventHandler;\n }\n\n public attachCustomWheelEventHandler(customWheelEventHandler: CustomWheelEventHandler): void {\n this._customWheelEventHandler = customWheelEventHandler;\n }\n\n public registerLinkProvider(linkProvider: ILinkProvider): IDisposable {\n return this._linkProviderService.registerLinkProvider(linkProvider);\n }\n\n public registerCharacterJoiner(handler: CharacterJoinerHandler): number {\n if (!this._characterJoinerService) {\n throw new Error('Terminal must be opened first');\n }\n const joinerId = this._characterJoinerService.register(handler);\n this.refresh(0, this.rows - 1);\n return joinerId;\n }\n\n public deregisterCharacterJoiner(joinerId: number): void {\n if (!this._characterJoinerService) {\n throw new Error('Terminal must be opened first');\n }\n if (this._characterJoinerService.deregister(joinerId)) {\n this.refresh(0, this.rows - 1);\n }\n }\n\n public get markers(): IMarker[] {\n return this.buffer.markers;\n }\n\n public registerMarker(cursorYOffset: number): IMarker {\n return this.buffer.addMarker(this.buffer.ybase + this.buffer.y + cursorYOffset);\n }\n\n public registerDecoration(decorationOptions: IDecorationOptions): IDecoration | undefined {\n return this._decorationService.registerDecoration(decorationOptions);\n }\n\n /**\n * Gets whether the terminal has an active selection.\n */\n public hasSelection(): boolean {\n return this._selectionService ? this._selectionService.hasSelection : false;\n }\n\n /**\n * Selects text within the terminal.\n * @param column The column the selection starts at..\n * @param row The row the selection starts at.\n * @param length The length of the selection.\n */\n public select(column: number, row: number, length: number): void {\n this._selectionService!.setSelection(column, row, length);\n }\n\n /**\n * Gets the terminal's current selection, this is useful for implementing copy\n * behavior outside of xterm.js.\n */\n public getSelection(): string {\n return this._selectionService ? this._selectionService.selectionText : '';\n }\n\n public getSelectionPosition(): IBufferRange | undefined {\n if (!this._selectionService || !this._selectionService.hasSelection) {\n return undefined;\n }\n\n return {\n start: {\n x: this._selectionService.selectionStart![0],\n y: this._selectionService.selectionStart![1]\n },\n end: {\n x: this._selectionService.selectionEnd![0],\n y: this._selectionService.selectionEnd![1]\n }\n };\n }\n\n /**\n * Clears the current terminal selection.\n */\n public clearSelection(): void {\n this._selectionService?.clearSelection();\n }\n\n /**\n * Selects all text within the terminal.\n */\n public selectAll(): void {\n this._selectionService?.selectAll();\n }\n\n public selectLines(start: number, end: number): void {\n this._selectionService?.selectLines(start, end);\n }\n\n /**\n * Handle a keydown [KeyboardEvent].\n *\n * [KeyboardEvent]: https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent\n */\n protected _keyDown(event: KeyboardEvent): boolean | undefined {\n this._keyDownHandled = false;\n this._keyDownSeen = true;\n\n if (this._customKeyEventHandler && this._customKeyEventHandler(event) === false) {\n return false;\n }\n\n // Ignore composing with Alt key on Mac when macOptionIsMeta is enabled\n const shouldIgnoreComposition = this.browser.isMac && this.options.macOptionIsMeta && event.altKey;\n\n if (!shouldIgnoreComposition && !this._compositionHelper!.keydown(event)) {\n if (this.options.scrollOnUserInput && this.buffer.ybase !== this.buffer.ydisp) {\n this.scrollToBottom(true);\n }\n return false;\n }\n\n if (!shouldIgnoreComposition && (event.key === 'Dead' || event.key === 'AltGraph')) {\n this._unprocessedDeadKey = true;\n }\n\n const result = evaluateKeyboardEvent(event, this.coreService.decPrivateModes.applicationCursorKeys, this.browser.isMac, this.options.macOptionIsMeta);\n\n this.updateCursorStyle(event);\n\n if (result.type === KeyboardResultType.PAGE_DOWN || result.type === KeyboardResultType.PAGE_UP) {\n const scrollCount = this.rows - 1;\n this.scrollLines(result.type === KeyboardResultType.PAGE_UP ? -scrollCount : scrollCount);\n return this.cancel(event, true);\n }\n\n if (result.type === KeyboardResultType.SELECT_ALL) {\n this.selectAll();\n }\n\n if (this._isThirdLevelShift(this.browser, event)) {\n return true;\n }\n\n if (result.cancel) {\n // The event is canceled at the end already, is this necessary?\n this.cancel(event, true);\n }\n\n if (!result.key) {\n return true;\n }\n\n // HACK: Process A-Z in the keypress event to fix an issue with macOS IMEs where lower case\n // letters cannot be input while caps lock is on.\n if (event.key && !event.ctrlKey && !event.altKey && !event.metaKey && event.key.length === 1) {\n if (event.key.charCodeAt(0) >= 65 && event.key.charCodeAt(0) <= 90) {\n return true;\n }\n }\n\n if (this._unprocessedDeadKey) {\n this._unprocessedDeadKey = false;\n return true;\n }\n\n // If ctrl+c or enter is being sent, clear out the textarea. This is done so that screen readers\n // will announce deleted characters. This will not work 100% of the time but it should cover\n // most scenarios.\n if (result.key === C0.ETX || result.key === C0.CR) {\n this.textarea!.value = '';\n }\n\n this._onKey.fire({ key: result.key, domEvent: event });\n this._showCursor();\n this.coreService.triggerDataEvent(result.key, true);\n\n // Cancel events when not in screen reader mode so events don't get bubbled up and handled by\n // other listeners. When screen reader mode is enabled, we don't cancel them (unless ctrl or alt\n // is also depressed) so that the cursor textarea can be updated, which triggers the screen\n // reader to read it.\n if (!this.optionsService.rawOptions.screenReaderMode || event.altKey || event.ctrlKey) {\n return this.cancel(event, true);\n }\n\n this._keyDownHandled = true;\n }\n\n private _isThirdLevelShift(browser: IBrowser, ev: KeyboardEvent): boolean {\n const thirdLevelKey =\n (browser.isMac && !this.options.macOptionIsMeta && ev.altKey && !ev.ctrlKey && !ev.metaKey) ||\n (browser.isWindows && ev.altKey && ev.ctrlKey && !ev.metaKey) ||\n (browser.isWindows && ev.getModifierState('AltGraph'));\n\n if (ev.type === 'keypress') {\n return thirdLevelKey;\n }\n\n // Don't invoke for arrows, pageDown, home, backspace, etc. (on non-keypress events)\n return thirdLevelKey && (!ev.keyCode || ev.keyCode > 47);\n }\n\n protected _keyUp(ev: KeyboardEvent): void {\n this._keyDownSeen = false;\n\n if (this._customKeyEventHandler && this._customKeyEventHandler(ev) === false) {\n return;\n }\n\n if (!wasModifierKeyOnlyEvent(ev)) {\n this.focus();\n }\n\n this.updateCursorStyle(ev);\n this._keyPressHandled = false;\n }\n\n /**\n * Handle a keypress event.\n * Key Resources:\n * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent\n * @param ev The keypress event to be handled.\n */\n protected _keyPress(ev: KeyboardEvent): boolean {\n let key;\n\n this._keyPressHandled = false;\n\n if (this._keyDownHandled) {\n return false;\n }\n\n if (this._customKeyEventHandler && this._customKeyEventHandler(ev) === false) {\n return false;\n }\n\n this.cancel(ev);\n\n if (ev.charCode) {\n key = ev.charCode;\n } else if (ev.which === null || ev.which === undefined) {\n key = ev.keyCode;\n } else if (ev.which !== 0 && ev.charCode !== 0) {\n key = ev.which;\n } else {\n return false;\n }\n\n if (!key || (\n (ev.altKey || ev.ctrlKey || ev.metaKey) && !this._isThirdLevelShift(this.browser, ev)\n )) {\n return false;\n }\n\n key = String.fromCharCode(key);\n\n this._onKey.fire({ key, domEvent: ev });\n this._showCursor();\n this.coreService.triggerDataEvent(key, true);\n\n this._keyPressHandled = true;\n\n // The key was handled so clear the dead key state, otherwise certain keystrokes like arrow\n // keys could be ignored\n this._unprocessedDeadKey = false;\n\n return true;\n }\n\n /**\n * Handle an input event.\n * Key Resources:\n * - https://developer.mozilla.org/en-US/docs/Web/API/InputEvent\n * @param ev The input event to be handled.\n */\n protected _inputEvent(ev: InputEvent): boolean {\n // Only support emoji IMEs when screen reader mode is disabled as the event must bubble up to\n // support reading out character input which can doubling up input characters\n // Based on these event traces: https://github.com/xtermjs/xterm.js/issues/3679\n if (ev.data && ev.inputType === 'insertText' && (!ev.composed || !this._keyDownSeen) && !this.optionsService.rawOptions.screenReaderMode) {\n if (this._keyPressHandled) {\n return false;\n }\n\n // The key was handled so clear the dead key state, otherwise certain keystrokes like arrow\n // keys could be ignored\n this._unprocessedDeadKey = false;\n\n const text = ev.data;\n this.coreService.triggerDataEvent(text, true);\n\n this.cancel(ev);\n return true;\n }\n\n return false;\n }\n\n /**\n * Resizes the terminal.\n *\n * @param x The number of columns to resize to.\n * @param y The number of rows to resize to.\n */\n public resize(x: number, y: number): void {\n if (x === this.cols && y === this.rows) {\n // Check if we still need to measure the char size (fixes #785).\n if (this._charSizeService && !this._charSizeService.hasValidSize) {\n this._charSizeService.measure();\n }\n return;\n }\n\n super.resize(x, y);\n }\n\n private _afterResize(x: number, y: number): void {\n this._charSizeService?.measure();\n }\n\n /**\n * Clear the entire buffer, making the prompt line the new first line.\n */\n public clear(): void {\n if (this.buffer.ybase === 0 && this.buffer.y === 0) {\n // Don't clear if it's already clear\n return;\n }\n this.buffer.clearAllMarkers();\n this.buffer.lines.set(0, this.buffer.lines.get(this.buffer.ybase + this.buffer.y)!);\n this.buffer.lines.length = 1;\n this.buffer.ydisp = 0;\n this.buffer.ybase = 0;\n this.buffer.y = 0;\n for (let i = 1; i < this.rows; i++) {\n this.buffer.lines.push(this.buffer.getBlankLine(DEFAULT_ATTR_DATA));\n }\n // IMPORTANT: Fire scroll event before viewport is reset. This ensures embedders get the clear\n // scroll event and that the viewport's state will be valid for immediate writes.\n this._onScroll.fire({ position: this.buffer.ydisp });\n this.refresh(0, this.rows - 1);\n }\n\n /**\n * Reset terminal.\n * Note: Calling this directly from JS is synchronous but does not clear\n * input buffers and does not reset the parser, thus the terminal will\n * continue to apply pending input data.\n * If you need in band reset (synchronous with input data) consider\n * using DECSTR (soft reset, CSI ! p) or RIS instead (hard reset, ESC c).\n */\n public reset(): void {\n /**\n * Since _setup handles a full terminal creation, we have to carry forward\n * a few things that should not reset.\n */\n this.options.rows = this.rows;\n this.options.cols = this.cols;\n const customKeyEventHandler = this._customKeyEventHandler;\n\n this._setup();\n super.reset();\n this._selectionService?.reset();\n this._decorationService.reset();\n\n // reattach\n this._customKeyEventHandler = customKeyEventHandler;\n\n // do a full screen refresh\n this.refresh(0, this.rows - 1);\n }\n\n public clearTextureAtlas(): void {\n this._renderService?.clearTextureAtlas();\n }\n\n private _reportFocus(): void {\n if (this.element?.classList.contains('focus')) {\n this.coreService.triggerDataEvent(C0.ESC + '[I');\n } else {\n this.coreService.triggerDataEvent(C0.ESC + '[O');\n }\n }\n\n private _reportWindowsOptions(type: WindowsOptionsReportType): void {\n if (!this._renderService) {\n return;\n }\n\n switch (type) {\n case WindowsOptionsReportType.GET_WIN_SIZE_PIXELS:\n const canvasWidth = this._renderService.dimensions.css.canvas.width.toFixed(0);\n const canvasHeight = this._renderService.dimensions.css.canvas.height.toFixed(0);\n this.coreService.triggerDataEvent(`${C0.ESC}[4;${canvasHeight};${canvasWidth}t`);\n break;\n case WindowsOptionsReportType.GET_CELL_SIZE_PIXELS:\n const cellWidth = this._renderService.dimensions.css.cell.width.toFixed(0);\n const cellHeight = this._renderService.dimensions.css.cell.height.toFixed(0);\n this.coreService.triggerDataEvent(`${C0.ESC}[6;${cellHeight};${cellWidth}t`);\n break;\n }\n }\n\n // TODO: Remove cancel function and cancelEvents option\n public cancel(ev: MouseEvent | WheelEvent | KeyboardEvent | InputEvent, force?: boolean): boolean | undefined {\n if (!this.options.cancelEvents && !force) {\n return;\n }\n ev.preventDefault();\n ev.stopPropagation();\n return false;\n }\n}\n\n/**\n * Helpers\n */\n\nfunction wasModifierKeyOnlyEvent(ev: KeyboardEvent): boolean {\n return ev.keyCode === 16 || // Shift\n ev.keyCode === 17 || // Ctrl\n ev.keyCode === 18; // Alt\n}\n", "/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { ITerminalAddon, IDisposable, Terminal } from '@xterm/xterm';\n\nexport interface ILoadedAddon {\n instance: ITerminalAddon;\n dispose: () => void;\n isDisposed: boolean;\n}\n\nexport class AddonManager implements IDisposable {\n protected _addons: ILoadedAddon[] = [];\n\n public dispose(): void {\n for (let i = this._addons.length - 1; i >= 0; i--) {\n this._addons[i].instance.dispose();\n }\n }\n\n public loadAddon(terminal: Terminal, instance: ITerminalAddon): void {\n const loadedAddon: ILoadedAddon = {\n instance,\n dispose: instance.dispose,\n isDisposed: false\n };\n this._addons.push(loadedAddon);\n instance.dispose = () => this._wrappedAddonDispose(loadedAddon);\n instance.activate(terminal as any);\n }\n\n private _wrappedAddonDispose(loadedAddon: ILoadedAddon): void {\n if (loadedAddon.isDisposed) {\n // Do nothing if already disposed\n return;\n }\n let index = -1;\n for (let i = 0; i < this._addons.length; i++) {\n if (this._addons[i] === loadedAddon) {\n index = i;\n break;\n }\n }\n if (index === -1) {\n throw new Error('Could not dispose an addon that has not been loaded');\n }\n loadedAddon.isDisposed = true;\n loadedAddon.dispose.apply(loadedAddon.instance);\n this._addons.splice(index, 1);\n }\n}\n", "/**\n * Copyright (c) 2021 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { CellData } from 'common/buffer/CellData';\nimport { IBufferLine, ICellData } from 'common/Types';\nimport { IBufferCell as IBufferCellApi, IBufferLine as IBufferLineApi } from '@xterm/xterm';\n\nexport class BufferLineApiView implements IBufferLineApi {\n constructor(private _line: IBufferLine) { }\n\n public get isWrapped(): boolean { return this._line.isWrapped; }\n public get length(): number { return this._line.length; }\n public getCell(x: number, cell?: IBufferCellApi): IBufferCellApi | undefined {\n if (x < 0 || x >= this._line.length) {\n return undefined;\n }\n\n if (cell) {\n this._line.loadCell(x, cell as ICellData);\n return cell;\n }\n return this._line.loadCell(x, new CellData());\n }\n public translateToString(trimRight?: boolean, startColumn?: number, endColumn?: number): string {\n return this._line.translateToString(trimRight, startColumn, endColumn);\n }\n}\n", "/**\n * Copyright (c) 2021 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IBuffer as IBufferApi, IBufferLine as IBufferLineApi, IBufferCell as IBufferCellApi } from '@xterm/xterm';\nimport { IBuffer } from 'common/buffer/Types';\nimport { BufferLineApiView } from 'common/public/BufferLineApiView';\nimport { CellData } from 'common/buffer/CellData';\n\nexport class BufferApiView implements IBufferApi {\n constructor(\n private _buffer: IBuffer,\n public readonly type: 'normal' | 'alternate'\n ) { }\n\n public init(buffer: IBuffer): BufferApiView {\n this._buffer = buffer;\n return this;\n }\n\n public get cursorY(): number { return this._buffer.y; }\n public get cursorX(): number { return this._buffer.x; }\n public get viewportY(): number { return this._buffer.ydisp; }\n public get baseY(): number { return this._buffer.ybase; }\n public get length(): number { return this._buffer.lines.length; }\n public getLine(y: number): IBufferLineApi | undefined {\n const line = this._buffer.lines.get(y);\n if (!line) {\n return undefined;\n }\n return new BufferLineApiView(line);\n }\n public getNullCell(): IBufferCellApi { return new CellData(); }\n}\n", "/**\n * Copyright (c) 2021 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IBuffer as IBufferApi, IBufferNamespace as IBufferNamespaceApi } from '@xterm/xterm';\nimport { BufferApiView } from 'common/public/BufferApiView';\nimport { ICoreTerminal } from 'common/Types';\nimport { Disposable } from 'vs/base/common/lifecycle';\nimport { Emitter } from 'vs/base/common/event';\n\nexport class BufferNamespaceApi extends Disposable implements IBufferNamespaceApi {\n private _normal: BufferApiView;\n private _alternate: BufferApiView;\n\n private readonly _onBufferChange = this._register(new Emitter());\n public readonly onBufferChange = this._onBufferChange.event;\n\n constructor(private _core: ICoreTerminal) {\n super();\n this._normal = new BufferApiView(this._core.buffers.normal, 'normal');\n this._alternate = new BufferApiView(this._core.buffers.alt, 'alternate');\n this._core.buffers.onBufferActivate(() => this._onBufferChange.fire(this.active));\n }\n public get active(): IBufferApi {\n if (this._core.buffers.active === this._core.buffers.normal) { return this.normal; }\n if (this._core.buffers.active === this._core.buffers.alt) { return this.alternate; }\n throw new Error('Active buffer is neither normal nor alternate');\n }\n public get normal(): IBufferApi {\n return this._normal.init(this._core.buffers.normal);\n }\n public get alternate(): IBufferApi {\n return this._alternate.init(this._core.buffers.alt);\n }\n}\n", "/**\n * Copyright (c) 2021 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IParams } from 'common/parser/Types';\nimport { IDisposable, IFunctionIdentifier, IParser } from '@xterm/xterm';\nimport { ICoreTerminal } from 'common/Types';\n\nexport class ParserApi implements IParser {\n constructor(private _core: ICoreTerminal) { }\n\n public registerCsiHandler(id: IFunctionIdentifier, callback: (params: (number | number[])[]) => boolean | Promise): IDisposable {\n return this._core.registerCsiHandler(id, (params: IParams) => callback(params.toArray()));\n }\n public addCsiHandler(id: IFunctionIdentifier, callback: (params: (number | number[])[]) => boolean | Promise): IDisposable {\n return this.registerCsiHandler(id, callback);\n }\n public registerDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: (number | number[])[]) => boolean | Promise): IDisposable {\n return this._core.registerDcsHandler(id, (data: string, params: IParams) => callback(data, params.toArray()));\n }\n public addDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: (number | number[])[]) => boolean | Promise): IDisposable {\n return this.registerDcsHandler(id, callback);\n }\n public registerEscHandler(id: IFunctionIdentifier, handler: () => boolean | Promise): IDisposable {\n return this._core.registerEscHandler(id, handler);\n }\n public addEscHandler(id: IFunctionIdentifier, handler: () => boolean | Promise): IDisposable {\n return this.registerEscHandler(id, handler);\n }\n public registerOscHandler(ident: number, callback: (data: string) => boolean | Promise): IDisposable {\n return this._core.registerOscHandler(ident, callback);\n }\n public addOscHandler(ident: number, callback: (data: string) => boolean | Promise): IDisposable {\n return this.registerOscHandler(ident, callback);\n }\n}\n", "/**\n * Copyright (c) 2021 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { ICoreTerminal } from 'common/Types';\nimport { IUnicodeHandling, IUnicodeVersionProvider } from '@xterm/xterm';\n\nexport class UnicodeApi implements IUnicodeHandling {\n constructor(private _core: ICoreTerminal) { }\n\n public register(provider: IUnicodeVersionProvider): void {\n this._core.unicodeService.register(provider);\n }\n\n public get versions(): string[] {\n return this._core.unicodeService.versions;\n }\n\n public get activeVersion(): string {\n return this._core.unicodeService.activeVersion;\n }\n\n public set activeVersion(version: string) {\n this._core.unicodeService.activeVersion = version;\n }\n}\n", "/**\n * Copyright (c) 2018 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport * as Strings from 'browser/LocalizableStrings';\nimport { CoreBrowserTerminal as TerminalCore } from 'browser/CoreBrowserTerminal';\nimport { IBufferRange, ITerminal } from 'browser/Types';\nimport { Disposable } from 'vs/base/common/lifecycle';\nimport { ITerminalOptions } from 'common/Types';\nimport { AddonManager } from 'common/public/AddonManager';\nimport { BufferNamespaceApi } from 'common/public/BufferNamespaceApi';\nimport { ParserApi } from 'common/public/ParserApi';\nimport { UnicodeApi } from 'common/public/UnicodeApi';\nimport { IBufferNamespace as IBufferNamespaceApi, IDecoration, IDecorationOptions, IDisposable, ILinkProvider, ILocalizableStrings, IMarker, IModes, IParser, ITerminalAddon, Terminal as ITerminalApi, ITerminalInitOnlyOptions, IUnicodeHandling } from '@xterm/xterm';\nimport type { Event } from 'vs/base/common/event';\n\n/**\n * The set of options that only have an effect when set in the Terminal constructor.\n */\nconst CONSTRUCTOR_ONLY_OPTIONS = ['cols', 'rows'];\n\nlet $value = 0;\n\nexport class Terminal extends Disposable implements ITerminalApi {\n private _core: ITerminal;\n private _addonManager: AddonManager;\n private _parser: IParser | undefined;\n private _buffer: BufferNamespaceApi | undefined;\n private _publicOptions: Required;\n\n constructor(options?: ITerminalOptions & ITerminalInitOnlyOptions) {\n super();\n\n this._core = this._register(new TerminalCore(options));\n this._addonManager = this._register(new AddonManager());\n\n this._publicOptions = { ... this._core.options };\n const getter = (propName: string): any => {\n return this._core.options[propName];\n };\n const setter = (propName: string, value: any): void => {\n this._checkReadonlyOptions(propName);\n this._core.options[propName] = value;\n };\n\n for (const propName in this._core.options) {\n const desc = {\n get: getter.bind(this, propName),\n set: setter.bind(this, propName)\n };\n Object.defineProperty(this._publicOptions, propName, desc);\n }\n }\n\n private _checkReadonlyOptions(propName: string): void {\n // Throw an error if any constructor only option is modified\n // from terminal.options\n // Modifications from anywhere else are allowed\n if (CONSTRUCTOR_ONLY_OPTIONS.includes(propName)) {\n throw new Error(`Option \"${propName}\" can only be set in the constructor`);\n }\n }\n\n private _checkProposedApi(): void {\n if (!this._core.optionsService.rawOptions.allowProposedApi) {\n throw new Error('You must set the allowProposedApi option to true to use proposed API');\n }\n }\n\n public get onBell(): Event { return this._core.onBell; }\n public get onBinary(): Event { return this._core.onBinary; }\n public get onCursorMove(): Event { return this._core.onCursorMove; }\n public get onData(): Event { return this._core.onData; }\n public get onKey(): Event<{ key: string, domEvent: KeyboardEvent }> { return this._core.onKey; }\n public get onLineFeed(): Event { return this._core.onLineFeed; }\n public get onRender(): Event<{ start: number, end: number }> { return this._core.onRender; }\n public get onResize(): Event<{ cols: number, rows: number }> { return this._core.onResize; }\n public get onScroll(): Event { return this._core.onScroll; }\n public get onSelectionChange(): Event { return this._core.onSelectionChange; }\n public get onTitleChange(): Event { return this._core.onTitleChange; }\n public get onWriteParsed(): Event { return this._core.onWriteParsed; }\n\n public get element(): HTMLElement | undefined { return this._core.element; }\n public get parser(): IParser {\n if (!this._parser) {\n this._parser = new ParserApi(this._core);\n }\n return this._parser;\n }\n public get unicode(): IUnicodeHandling {\n this._checkProposedApi();\n return new UnicodeApi(this._core);\n }\n public get textarea(): HTMLTextAreaElement | undefined { return this._core.textarea; }\n public get rows(): number { return this._core.rows; }\n public get cols(): number { return this._core.cols; }\n public get buffer(): IBufferNamespaceApi {\n if (!this._buffer) {\n this._buffer = this._register(new BufferNamespaceApi(this._core));\n }\n return this._buffer;\n }\n public get markers(): ReadonlyArray {\n this._checkProposedApi();\n return this._core.markers;\n }\n public get modes(): IModes {\n const m = this._core.coreService.decPrivateModes;\n let mouseTrackingMode: 'none' | 'x10' | 'vt200' | 'drag' | 'any' = 'none';\n switch (this._core.coreMouseService.activeProtocol) {\n case 'X10': mouseTrackingMode = 'x10'; break;\n case 'VT200': mouseTrackingMode = 'vt200'; break;\n case 'DRAG': mouseTrackingMode = 'drag'; break;\n case 'ANY': mouseTrackingMode = 'any'; break;\n }\n return {\n applicationCursorKeysMode: m.applicationCursorKeys,\n applicationKeypadMode: m.applicationKeypad,\n bracketedPasteMode: m.bracketedPasteMode,\n insertMode: this._core.coreService.modes.insertMode,\n mouseTrackingMode: mouseTrackingMode,\n originMode: m.origin,\n reverseWraparoundMode: m.reverseWraparound,\n sendFocusMode: m.sendFocus,\n synchronizedOutputMode: m.synchronizedOutput,\n wraparoundMode: m.wraparound\n };\n }\n public get options(): Required {\n return this._publicOptions;\n }\n public set options(options: ITerminalOptions) {\n for (const propName in options) {\n this._publicOptions[propName] = options[propName];\n }\n }\n public blur(): void {\n this._core.blur();\n }\n public focus(): void {\n this._core.focus();\n }\n public input(data: string, wasUserInput: boolean = true): void {\n this._core.input(data, wasUserInput);\n }\n public resize(columns: number, rows: number): void {\n this._verifyIntegers(columns, rows);\n this._core.resize(columns, rows);\n }\n public open(parent: HTMLElement): void {\n this._core.open(parent);\n }\n public attachCustomKeyEventHandler(customKeyEventHandler: (event: KeyboardEvent) => boolean): void {\n this._core.attachCustomKeyEventHandler(customKeyEventHandler);\n }\n public attachCustomWheelEventHandler(customWheelEventHandler: (event: WheelEvent) => boolean): void {\n this._core.attachCustomWheelEventHandler(customWheelEventHandler);\n }\n public registerLinkProvider(linkProvider: ILinkProvider): IDisposable {\n return this._core.registerLinkProvider(linkProvider);\n }\n public registerCharacterJoiner(handler: (text: string) => [number, number][]): number {\n this._checkProposedApi();\n return this._core.registerCharacterJoiner(handler);\n }\n public deregisterCharacterJoiner(joinerId: number): void {\n this._checkProposedApi();\n this._core.deregisterCharacterJoiner(joinerId);\n }\n public registerMarker(cursorYOffset: number = 0): IMarker {\n this._verifyIntegers(cursorYOffset);\n return this._core.registerMarker(cursorYOffset);\n }\n public registerDecoration(decorationOptions: IDecorationOptions): IDecoration | undefined {\n this._checkProposedApi();\n this._verifyPositiveIntegers(decorationOptions.x ?? 0, decorationOptions.width ?? 0, decorationOptions.height ?? 0);\n return this._core.registerDecoration(decorationOptions);\n }\n public hasSelection(): boolean {\n return this._core.hasSelection();\n }\n public select(column: number, row: number, length: number): void {\n this._verifyIntegers(column, row, length);\n this._core.select(column, row, length);\n }\n public getSelection(): string {\n return this._core.getSelection();\n }\n public getSelectionPosition(): IBufferRange | undefined {\n return this._core.getSelectionPosition();\n }\n public clearSelection(): void {\n this._core.clearSelection();\n }\n public selectAll(): void {\n this._core.selectAll();\n }\n public selectLines(start: number, end: number): void {\n this._verifyIntegers(start, end);\n this._core.selectLines(start, end);\n }\n public dispose(): void {\n super.dispose();\n }\n public scrollLines(amount: number): void {\n this._verifyIntegers(amount);\n this._core.scrollLines(amount);\n }\n public scrollPages(pageCount: number): void {\n this._verifyIntegers(pageCount);\n this._core.scrollPages(pageCount);\n }\n public scrollToTop(): void {\n this._core.scrollToTop();\n }\n public scrollToBottom(): void {\n this._core.scrollToBottom();\n }\n public scrollToLine(line: number): void {\n this._verifyIntegers(line);\n this._core.scrollToLine(line);\n }\n public clear(): void {\n this._core.clear();\n }\n public write(data: string | Uint8Array, callback?: () => void): void {\n this._core.write(data, callback);\n }\n public writeln(data: string | Uint8Array, callback?: () => void): void {\n this._core.write(data);\n this._core.write('\\r\\n', callback);\n }\n public paste(data: string): void {\n this._core.paste(data);\n }\n public refresh(start: number, end: number): void {\n this._verifyIntegers(start, end);\n this._core.refresh(start, end);\n }\n public reset(): void {\n this._core.reset();\n }\n public clearTextureAtlas(): void {\n this._core.clearTextureAtlas();\n }\n public loadAddon(addon: ITerminalAddon): void {\n this._addonManager.loadAddon(this, addon);\n }\n public static get strings(): ILocalizableStrings {\n // A wrapper is required here because esbuild prevents setting an `export let`\n return {\n get promptLabel(): string { return Strings.promptLabel.get(); },\n set promptLabel(value: string) { Strings.promptLabel.set(value); },\n get tooMuchOutput(): string { return Strings.tooMuchOutput.get(); },\n set tooMuchOutput(value: string) { Strings.tooMuchOutput.set(value); }\n };\n }\n\n private _verifyIntegers(...values: number[]): void {\n for ($value of values) {\n if ($value === Infinity || isNaN($value) || $value % 1 !== 0) {\n throw new Error('This API only accepts integers');\n }\n }\n }\n\n private _verifyPositiveIntegers(...values: number[]): void {\n for ($value of values) {\n if ($value && ($value === Infinity || isNaN($value) || $value % 1 !== 0 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,EACb,GAAIxC,KAAW,KAAY,MAAMA,EAAM,GAAKA,GAAS,IAAM,EACzD,MAAM,IAAI,MAAM,gCAAgC,CAGtD,CAEQ,2BAA2BwC,EAAwB,CACzD,IAAKxC,MAAUwC,EACb,GAAIxC,KAAWA,KAAW,KAAY,MAAMA,EAAM,GAAKA,GAAS,IAAM,GAAKA,GAAS,GAClF,MAAM,IAAI,MAAM,yCAAyC,CAG/D,CACF", + "names": ["promptLabelInternal", "promptLabel", "value", "tooMuchOutputInternal", "tooMuchOutput", "prepareTextForTerminal", "text", "bracketTextForPaste", "bracketedPasteMode", "copyHandler", "ev", "selectionService", "handlePasteEvent", "textarea", "coreService", "optionsService", "paste", "moveTextAreaUnderMouseCursor", "screenElement", "pos", "left", "top", "rightClickHandler", "shouldSelectWord", "stringFromCodePoint", "codePoint", "utf32ToString", "data", "start", "end", "result", "i", "codepoint", "StringToUtf32", "input", "target", "length", "size", "startPos", "second", "code", "Utf8ToUtf32", "byte1", "byte2", "byte3", "byte4", "discardInterim", "cp", "pos", "tmp", "type", "missing", "fourStop", "NULL_CELL_CHAR", "WHITESPACE_CELL_CHAR", "AttributeData", "_AttributeData", "ExtendedAttrs", "value", "newObj", "_ExtendedAttrs", "ext", "urlId", "val", "CellData", "_CellData", "AttributeData", "ExtendedAttrs", "value", "obj", "stringFromCodePoint", "combined", "code", "second", "DI_TARGET", "DI_DEPENDENCIES", "serviceRegistry", "getServiceDependencies", "ctor", "createDecorator", "id", "decorator", "target", "key", "index", "storeServiceDependency", "IBufferService", "createDecorator", "ICoreMouseService", "ICoreService", "ICharsetService", "IInstantiationService", "ILogService", "createDecorator", "IOptionsService", "IOscLinkService", "IUnicodeService", "IDecorationService", "OscLinkProvider", "_bufferService", "_optionsService", "_oscLinkService", "y", "callback", "line", "result", "linkHandler", "cell", "CellData", "lineLength", "currentLinkId", "currentStart", "finishLink", "x", "text", "range", "ignoreLink", "parsed", "e", "defaultActivate", "__decorateClass", "__decorateParam", "IBufferService", "IOptionsService", "IOscLinkService", "uri", "newWindow", "ICharSizeService", "createDecorator", "ICoreBrowserService", "IMouseService", "IRenderService", "ISelectionService", "ICharacterJoinerService", "IThemeService", "ILinkProviderService", "ErrorHandler", "e", "ErrorNoTelemetry", "listener", "newUnexpectedErrorHandler", "errorHandler", "onUnexpectedError", "e", "isCancellationError", "errorHandler", "canceledName", "isCancellationError", "error", "CancellationError", "illegalArgument", "name", "ErrorNoTelemetry", "_ErrorNoTelemetry", "msg", "err", "result", "BugIndicatingError", "_BugIndicatingError", "message", "findLastIdxMonotonous", "array", "predicate", "startIdx", "endIdxEx", "i", "j", "k", "_MonotonousArray", "_array", "predicate", "item", "idx", "findLastIdxMonotonous", "MonotonousArray", "tail", "array", "n", "CompareResult", "isLessThan", "result", "isLessThanOrEqual", "isGreaterThan", "isNeitherLessOrGreaterThan", "compareBy", "selector", "comparator", "a", "b", "numberComparator", "a", "b", "_CallbackIterable", "iterate", "handler", "item", "result", "predicate", "cb", "mapFn", "comparator", "first", "CompareResult", "_callback", "CallbackIterable", "groupBy", "data", "groupFn", "result", "element", "key", "target", "_a", "_b", "SetWithKey", "values", "toKey", "value", "key", "entry", "callbackfn", "thisArg", "SetMap", "key", "value", "values", "fn", "createSingleCallFunction", "fn", "fnDidRunCallback", "_this", "didCall", "result", "Iterable", "is", "thing", "_empty", "empty", "single", "element", "wrap", "iterableOrElement", "from", "iterable", "reverse", "array", "i", "isEmpty", "first", "some", "predicate", "find", "filter", "map", "fn", "index", "flatMap", "concat", "iterables", "reduce", "reducer", "initialValue", "value", "slice", "arr", "to", "consume", "atMost", "consumed", "iterator", "next", "asyncToArray", "result", "item", "TRACK_DISPOSABLES", "disposableTracker", "_DisposableTracker", "d", "val", "data", "child", "parent", "x", "disposable", "cache", "cacheValue", "result", "rootParentCache", "v", "k", "maxReported", "preComputedLeaks", "uncoveredLeakingObjs", "leakingObjects", "info", "leakingObjsSet", "o", "l", "getStackTracePath", "leaking", "removePrefix", "array", "linesToRemove", "regexp", "lines", "p", "stackTraceStarts", "SetMap", "stackTracePath", "i", "compareBy", "numberComparator", "message", "stackTraceFormattedLines", "line", "prevStarts", "continuations", "groupBy", "cont", "set", "DisposableTracker", "setDisposableTracker", "tracker", "__is_disposable_tracked__", "stack", "Disposable", "trackDisposable", "markAsDisposed", "setParentOfDisposable", "setParentOfDisposables", "children", "markAsSingleton", "singleton", "dispose", "arg", "Iterable", "errors", "d", "e", "combinedDisposable", "disposables", "parent", "toDisposable", "dispose", "setParentOfDisposables", "fn", "self", "trackDisposable", "createSingleCallFunction", "markAsDisposed", "_DisposableStore", "o", "setParentOfDisposable", "DisposableStore", "Disposable", "MutableDisposable", "value", "oldValue", "mainWindow", "_Node", "element", "Node", "LinkedList", "node", "next", "atTheEnd", "newNode", "oldLast", "oldFirst", "didRemove", "res", "anchor", "hasPerformanceNow", "StopWatch", "_StopWatch", "highResolution", "_enableListenerGCedWarning", "_enableDisposeWithListenerWarning", "_enableSnapshotPotentialLeakWarning", "Event", "Disposable", "_addLeakageTraceLogic", "options", "origListenerDidAdd", "stack", "Stacktrace", "count", "defer", "event", "disposable", "debounce", "once", "listener", "thisArgs", "disposables", "didFire", "result", "e", "map", "snapshot", "i", "forEach", "each", "filter", "signal", "any", "events", "combinedDisposable", "addAndReturnDisposable", "reduce", "merge", "initial", "output", "emitter", "Emitter", "d", "store", "delay", "leading", "flushOnListenerRemove", "leakWarningThreshold", "subscription", "handle", "numDebouncedCalls", "doFire", "cur", "_output", "accumulate", "last", "latch", "equals", "a", "b", "firstCall", "cache", "value", "shouldEmit", "split", "isT", "buffer", "flushAfterTimeout", "_buffer", "flush", "chain", "sythensize", "cs", "ChainableSynthesis", "HaltChainable", "fn", "v", "step", "fromNodeEventEmitter", "eventName", "id", "args", "onFirstListenerAdd", "onLastListenerRemove", "fromDOMEventEmitter", "toPromise", "resolve", "fromPromise", "promise", "res", "forward", "from", "to", "runAndSubscribe", "handler", "EmitterObserver", "_observable", "_change", "fromObservable", "obs", "fromObservableLight", "observable", "didChange", "observer", "DisposableStore", "_EventProfiling", "name", "listenerCount", "StopWatch", "elapsed", "EventProfiling", "_globalLeakWarningThreshold", "_LeakageMonitor", "_errorHandler", "threshold", "name", "stack", "listenerCount", "count", "topStack", "topCount", "message", "error", "ListenerLeakError", "LeakageMonitor", "Stacktrace", "_Stacktrace", "value", "err", "ListenerRefusalError", "id", "UniqueContainer", "compactionThreshold", "forEachListener", "listeners", "fn", "i", "l", "_listenerFinalizers", "_enableListenerGCedWarning", "leaks", "heldValue", "Emitter", "options", "_globalLeakWarningThreshold", "onUnexpectedError", "EventProfiling", "_enableDisposeWithListenerWarning", "callback", "thisArgs", "disposables", "tuple", "Disposable", "contained", "removeMonitor", "EventDeliveryQueuePrivate", "result", "toDisposable", "DisposableStore", "match", "listener", "index", "adjustDeliveryQueue", "errorHandler", "e", "dq", "event", "EventDeliveryQueuePrivate", "emitter", "value", "end", "_WindowManager", "Emitter", "targetWindow", "zoomLevel", "targetWindowId", "zoomFactor", "fullscreen", "windowId", "WindowManager", "addMatchMediaChangeListener", "query", "callback", "onDidChangeZoomLevel", "WindowManager", "getZoomFactor", "targetWindow", "onDidChangeFullscreen", "WindowManager", "userAgent", "isFirefox", "isWebKit", "isChrome", "isSafari", "isElectron", "userAgent", "isAndroid", "standalone", "mainWindow", "standaloneMatchMedia", "fullScreenMatchMedia", "addMatchMediaChangeListener", "matches", "isStandalone", "LANGUAGE_DEFAULT", "_isWindows", "_isMacintosh", "_isLinux", "_isLinuxSnap", "_isNative", "_isWeb", "_isElectron", "_isIOS", "_isCI", "_isMobile", "_locale", "_language", "_platformLocale", "_translationsConfigFile", "_userAgent", "$globalThis", "nodeProcess", "isElectronProcess", "isElectronRenderer", "rawNlsConfig", "nlsConfig", "_platform", "_isMacintosh", "_isWindows", "_isLinux", "isWindows", "isMacintosh", "isLinux", "isNative", "_isNative", "isWebWorker", "_isWeb", "$globalThis", "webWorkerOrigin", "userAgent", "_userAgent", "language", "_language", "Language", "value", "isDefaultVariant", "isDefault", "setTimeout0IsFaster", "$globalThis", "setTimeout0", "pending", "len", "candidate", "lastId", "callback", "myId", "isChrome", "userAgent", "isFirefox", "isSafari", "isEdge", "isAndroid", "safeNavigator", "BrowserFeatures", "isNative", "isStandalone", "isSafari", "mainWindow", "KeyCodeStrMap", "keyCode", "str", "uiMap", "userSettingsUSMap", "userSettingsGeneralMap", "EVENT_KEY_CODE_MAP", "KeyCodeUtils", "toString", "keyCode", "uiMap", "fromString", "key", "toUserSettingsUS", "userSettingsUSMap", "toUserSettingsGeneral", "userSettingsGeneralMap", "fromUserSettings", "toElectronAccelerator", "KeyCodeChord", "_KeyCodeChord", "ctrlKey", "shiftKey", "altKey", "metaKey", "keyCode", "other", "ctrl", "shift", "alt", "meta", "Keybinding", "Keybinding", "chords", "illegalArgument", "result", "i", "len", "other", "extractKeyCode", "e", "char", "KeyCodeUtils", "keyCode", "isFirefox", "isLinux", "isMacintosh", "isWebKit", "EVENT_KEY_CODE_MAP", "ctrlKeyMod", "altKeyMod", "shiftKeyMod", "metaKeyMod", "StandardKeyboardEvent", "source", "extractKeyCode", "other", "key", "result", "ctrlKeyMod", "altKeyMod", "shiftKeyMod", "metaKeyMod", "KeyCodeChord", "sameOriginWindowChainCache", "getParentWindowIfSameOrigin", "w", "location", "parentLocation", "IframeUtils", "targetWindow", "windowChainCache", "parent", "childWindow", "ancestorWindow", "top", "left", "windowChain", "windowChainEl", "windowInChain", "boundingRect", "StandardMouseEvent", "targetWindow", "iframeOffsets", "IframeUtils", "StandardWheelEvent", "e", "deltaX", "deltaY", "shouldFactorDPR", "isChrome", "chromeVersionMatch", "e1", "e2", "devicePixelRatio", "ev", "isFirefox", "isMacintosh", "isSafari", "isWindows", "shortcutEvent", "callback", "context", "handle", "CancellationToken", "isCancellationToken", "thing", "MutableToken", "Event", "Emitter", "MicrotaskDelay", "TimeoutTimer", "runner", "timeout", "BugIndicatingError", "IntervalTimer", "interval", "context", "handle", "toDisposable", "runWhenGlobalIdle", "_runWhenIdle", "_targetWindow", "runner", "setTimeout0", "disposed", "end", "targetWindow", "timeout", "handle", "Promises", "settled", "promises", "firstError", "result", "promise", "value", "error", "withAsyncBody", "bodyFn", "resolve", "reject", "_AsyncIterableObject", "items", "writer", "promise", "emitter", "promises", "p", "iterables", "iterable", "item", "executor", "onReturn", "Emitter", "error", "err", "i", "Event", "mapFn", "filterFn", "result", "value", "values", "AsyncIterableObject", "isHighSurrogate", "charCode", "isLowSurrogate", "computeCodePoint", "highSurrogate", "lowSurrogate", "hash", "obj", "doHash", "hashVal", "numberHash", "arrayHash", "objectHash", "stringHash", "booleanHash", "val", "initialHashVal", "b", "i", "length", "arr", "item", "key", "leftRotate", "value", "bits", "totalBits", "delta", "mask", "fill", "dest", "index", "count", "i", "leftPad", "length", "char", "toHexString", "bufferOrValue", "bitsize", "b", "_StringSHA1", "str", "strLen", "buff", "buffLen", "leftoverHighSurrogate", "charCode", "offset", "codePoint", "isHighSurrogate", "nextCharCode", "isLowSurrogate", "computeCodePoint", "ml", "bigBlock32", "data", "j", "a", "c", "d", "e", "f", "k", "temp", "StringSHA1", "registerWindow", "getWindow", "getDocument", "getWindows", "getWindowsCount", "getWindowId", "getWindowById", "hasWindow", "onDidRegisterWindow", "onWillUnregisterWindow", "onDidUnregisterWindow", "windows", "mainWindow", "mainWindowRegistration", "DisposableStore", "Emitter", "windowId", "fallbackToMain", "window", "Disposable", "disposables", "registeredWindow", "toDisposable", "addDisposableListener", "EventType", "targetWindow", "e", "candidateNode", "candidateEvent", "DomListener", "node", "type", "handler", "options", "addDisposableListener", "useCaptureOrOptions", "_wrapAsStandardMouseEvent", "targetWindow", "StandardMouseEvent", "_wrapAsStandardKeyboardEvent", "e", "StandardKeyboardEvent", "addStandardDisposableListener", "useCapture", "wrapHandler", "getWindow", "runAtThisOrScheduleAtNextAnimationFrame", "scheduleAtNextAnimationFrame", "WindowIntervalTimer", "IntervalTimer", "node", "getWindow", "runner", "interval", "targetWindow", "AnimationFrameQueueItem", "priority", "e", "onUnexpectedError", "a", "b", "NEXT_QUEUE", "CURRENT_QUEUE", "animFrameRequested", "inAnimationFrameRunner", "animationFrameRunner", "targetWindowId", "currentQueue", "scheduleAtNextAnimationFrame", "getWindowId", "item", "nextQueue", "runAtThisOrScheduleAtNextAnimationFrame", "_Dimension", "width", "height", "obj", "a", "b", "Dimension", "getDomNodePagePosition", "domNode", "bb", "window", "getWindow", "sharedMutationObserver", "target", "disposables", "options", "mutationObserversPerTarget", "optionsHash", "hash", "mutationObserverPerOptions", "onDidMutate", "Emitter", "observer", "mutations", "resolvedMutationObserverPerOptions", "toDisposable", "EventType", "isWebKit", "SELECTOR_REGEX", "_$", "namespace", "description", "attrs", "children", "match", "SELECTOR_REGEX", "tagName", "result", "name", "value", "$", "FastDomNode", "domNode", "_maxWidth", "maxWidth", "numberAsPixels", "_width", "width", "_height", "height", "_top", "top", "_left", "left", "_bottom", "bottom", "_right", "right", "_paddingTop", "paddingTop", "_paddingLeft", "paddingLeft", "_paddingBottom", "paddingBottom", "_paddingRight", "paddingRight", "fontFamily", "fontWeight", "_fontSize", "fontSize", "fontStyle", "fontFeatureSettings", "fontVariationSettings", "textDecoration", "_lineHeight", "lineHeight", "_letterSpacing", "letterSpacing", "className", "shouldHaveIt", "display", "position", "visibility", "color", "backgroundColor", "layerHint", "boxShadow", "contain", "name", "value", "child", "createFastDomNode", "GlobalPointerMoveMonitor", "DisposableStore", "invokeStopCallback", "browserEvent", "onStopCallback", "initialElement", "pointerId", "initialButtons", "pointerMoveCallback", "eventSource", "toDisposable", "getWindow", "addDisposableListener", "EventType", "e", "memoize", "_target", "key", "descriptor", "fnKey", "fn", "memoizeKey", "args", "EventType", "_Gesture", "Disposable", "LinkedList", "Event", "onDidRegisterWindow", "window", "disposables", "addDisposableListener", "e", "mainWindow", "element", "markAsSingleton", "remove", "toDisposable", "timestamp", "i", "len", "touch", "evt", "targetWindow", "activeTouchCount", "data", "holdTime", "tail", "finalX", "finalY", "deltaT", "deltaX", "deltaY", "dispatchTo", "t", "type", "initialTarget", "event", "currentTime", "setTapCount", "ignoreTarget", "targets", "target", "depth", "now", "a", "b", "_", "t1", "vX", "dirX", "x", "vY", "dirY", "y", "scheduleAtNextAnimationFrame", "delta_pos_x", "delta_pos_y", "stopped", "d", "__decorateClass", "memoize", "Gesture", "Widget", "Disposable", "domNode", "listener", "addDisposableListener", "EventType", "e", "StandardMouseEvent", "getWindow", "StandardKeyboardEvent", "Gesture", "ARROW_IMG_SIZE", "ScrollbarArrow", "Widget", "opts", "GlobalPointerMoveMonitor", "addStandardDisposableListener", "EventType", "WindowIntervalTimer", "TimeoutTimer", "e", "scheduleRepeater", "getWindow", "pointerMoveData", "ScrollState", "_ScrollState", "_forceIntegerValues", "width", "scrollWidth", "scrollLeft", "height", "scrollHeight", "scrollTop", "other", "update", "useRawScrollPositions", "previous", "inSmoothScrolling", "widthChanged", "scrollWidthChanged", "scrollLeftChanged", "heightChanged", "scrollHeightChanged", "scrollTopChanged", "Scrollable", "Disposable", "options", "Emitter", "smoothScrollDuration", "scrollPosition", "dimensions", "newState", "reuseAnimation", "validTarget", "newSmoothScrolling", "SmoothScrollingOperation", "oldState", "SmoothScrollingUpdate", "isDone", "createEaseOutCubic", "from", "to", "delta", "completion", "easeOutCubic", "createComposed", "a", "b", "cut", "_SmoothScrollingOperation", "startTime", "duration", "viewportSize", "stop1", "stop2", "state", "now", "newScrollLeft", "newScrollTop", "easeInCubic", "t", "ScrollbarVisibilityController", "Disposable", "visibility", "visibleClassName", "invisibleClassName", "TimeoutTimer", "rawShouldBeVisible", "shouldBeVisible", "isNeeded", "domNode", "withFadeAway", "POINTER_DRAG_RESET_DISTANCE", "AbstractScrollbar", "Widget", "opts", "ScrollbarVisibilityController", "GlobalPointerMoveMonitor", "createFastDomNode", "addDisposableListener", "EventType", "arrow", "ScrollbarArrow", "top", "left", "width", "height", "e", "visibleSize", "elementScrollSize", "elementScrollPosition", "domTop", "sliderStart", "sliderStop", "pointerPos", "offsetX", "offsetY", "domNodePosition", "getDomNodePagePosition", "offset", "initialPointerPosition", "initialPointerOrthogonalPosition", "initialScrollbarState", "pointerMoveData", "pointerOrthogonalPosition", "pointerOrthogonalDelta", "isWindows", "pointerDelta", "_desiredScrollPosition", "desiredScrollPosition", "scrollbarSize", "ScrollbarState", "_ScrollbarState", "arrowSize", "scrollbarSize", "oppositeScrollbarSize", "visibleSize", "scrollSize", "scrollPosition", "iVisibleSize", "iScrollSize", "iScrollPosition", "computedAvailableSize", "computedRepresentableSize", "computedIsNeeded", "computedSliderSize", "computedSliderRatio", "computedSliderPosition", "r", "offset", "desiredSliderPosition", "correctedOffset", "desiredScrollPosition", "delta", "HorizontalScrollbar", "AbstractScrollbar", "scrollable", "options", "host", "scrollDimensions", "scrollPosition", "ScrollbarState", "sliderSize", "sliderPosition", "largeSize", "smallSize", "e", "offsetX", "offsetY", "size", "target", "VerticalScrollbar", "AbstractScrollbar", "scrollable", "options", "host", "scrollDimensions", "scrollPosition", "ScrollbarState", "sliderSize", "sliderPosition", "largeSize", "smallSize", "e", "offsetX", "offsetY", "size", "target", "HIDE_TIMEOUT", "SCROLL_WHEEL_SENSITIVITY", "SCROLL_WHEEL_SMOOTH_SCROLL_ENABLED", "MouseWheelClassifierItem", "timestamp", "deltaX", "deltaY", "_MouseWheelClassifier", "remainingInfluence", "score", "iteration", "index", "influence", "e", "isChrome", "targetWindow", "getWindow", "pageZoomFactor", "getZoomFactor", "previousItem", "item", "absDeltaX", "absDeltaY", "absPreviousDeltaX", "absPreviousDeltaY", "minDeltaX", "minDeltaY", "maxDeltaX", "maxDeltaY", "value", "MouseWheelClassifier", "AbstractScrollableElement", "Widget", "element", "options", "scrollable", "Emitter", "resolveOptions", "scrollbarHost", "mouseWheelEvent", "VerticalScrollbar", "HorizontalScrollbar", "createFastDomNode", "TimeoutTimer", "dispose", "browserEvent", "dimensions", "newClassName", "isMacintosh", "newOptions", "StandardWheelEvent", "shouldListen", "onMouseWheel", "addDisposableListener", "EventType", "classifier", "didScroll", "shiftConvert", "futureScrollPosition", "desiredScrollPosition", "deltaScrollTop", "desiredScrollTop", "deltaScrollLeft", "desiredScrollLeft", "consumeMouseWheel", "scrollState", "enableTop", "enableLeft", "leftClassName", "topClassName", "topLeftClassName", "SmoothScrollableElement", "AbstractScrollableElement", "element", "options", "scrollable", "update", "resolveOptions", "opts", "result", "isMacintosh", "Viewport", "Disposable", "element", "screenElement", "_bufferService", "coreBrowserService", "coreMouseService", "themeService", "_optionsService", "_renderService", "Emitter", "scrollable", "Scrollable", "cb", "scheduleAtNextAnimationFrame", "SmoothScrollableElement", "type", "Event", "toDisposable", "e", "disp", "pos", "line", "disableSmoothScroll", "ydisp", "newRow", "diff", "__decorateClass", "__decorateParam", "IBufferService", "ICoreBrowserService", "ICoreMouseService", "IThemeService", "IOptionsService", "IRenderService", "BufferDecorationRenderer", "Disposable", "_screenElement", "_bufferService", "_coreBrowserService", "_decorationService", "_renderService", "decoration", "toDisposable", "element", "x", "line", "__decorateClass", "__decorateParam", "IBufferService", "ICoreBrowserService", "IDecorationService", "IRenderService", "ColorZoneStore", "decoration", "z", "padding", "zone", "line", "position", "drawHeight", "drawWidth", "drawX", "OverviewRulerRenderer", "Disposable", "_viewportElement", "_screenElement", "_bufferService", "_decorationService", "_renderService", "_optionsService", "_themeService", "_coreBrowserService", "ColorZoneStore", "toDisposable", "ctx", "outerWidth", "innerWidth", "pixelsPerLine", "nonFullHeight", "decoration", "zones", "zone", "updateCanvasDimensions", "updateAnchor", "__decorateClass", "__decorateParam", "IBufferService", "IDecorationService", "IRenderService", "IOptionsService", "IThemeService", "ICoreBrowserService", "C0", "C1", "C1_ESCAPED", "CompositionHelper", "_textarea", "_compositionView", "_bufferService", "_optionsService", "_coreService", "_renderService", "ev", "waitForPropagation", "currentCompositionPosition", "input", "oldValue", "newValue", "diff", "C0", "dontRecurse", "cursorX", "cellHeight", "cursorTop", "cursorLeft", "compositionViewBounds", "__decorateClass", "__decorateParam", "IBufferService", "IOptionsService", "ICoreService", "IRenderService", "$r", "$g", "$b", "$a", "NULL_COLOR", "channels", "toCss", "g", "b", "a", "toPaddedHex", "toRgba", "toColor", "color", "blend", "bg", "fg", "fgR", "fgG", "fgB", "bgR", "bgG", "bgB", "css", "rgba", "isOpaque", "ensureContrastRatio", "ratio", "result", "opaque", "rgbaColor", "opacity", "multiplyOpacity", "factor", "toColorRGB", "$ctx", "$litmusColor", "canvas", "ctx", "rgbaMatch", "rgb", "relativeLuminance", "relativeLuminance2", "r", "rs", "gs", "bs", "rr", "rg", "rb", "bgRgba", "fgRgba", "bgL", "fgL", "contrastRatio", "resultA", "reduceLuminance", "resultARatio", "resultB", "increaseLuminance", "resultBRatio", "cr", "toChannels", "value", "c", "s", "l1", "l2", "JoinedCellData", "AttributeData", "firstCell", "chars", "width", "value", "CharacterJoinerService", "_bufferService", "CellData", "handler", "joiner", "joinerId", "i", "row", "line", "ranges", "lineStr", "rangeStartColumn", "currentStringIndex", "rangeStartStringIndex", "rangeAttrFG", "rangeAttrBG", "x", "joinedRanges", "WHITESPACE_CELL_CHAR", "startIndex", "endIndex", "lineData", "startCol", "text", "allJoinedRanges", "error", "joinerRanges", "j", "currentRangeIndex", "currentRangeStarted", "currentRange", "length", "newRange", "inRange", "range", "__decorateClass", "__decorateParam", "IBufferService", "isPowerlineGlyph", "codepoint", "isBoxOrBlockGlyph", "codepoint", "treatGlyphAsBackgroundColor", "codepoint", "isPowerlineGlyph", "isBoxOrBlockGlyph", "createRenderDimensions", "createDimension", "DomRendererRowFactory", "_document", "_characterJoinerService", "_optionsService", "_coreBrowserService", "_coreService", "_decorationService", "_themeService", "CellData", "start", "end", "columnSelectMode", "lineData", "row", "isCursorRow", "cursorStyle", "cursorInactiveStyle", "cursorX", "cursorBlink", "cellWidth", "widthCache", "linkStart", "linkEnd", "elements", "joinedRanges", "colors", "lineLength", "charElement", "cellAmount", "text", "i", "oldBg", "oldFg", "oldExt", "oldLinkHover", "oldSpacing", "oldIsInSelection", "spacing", "skipJoinedCheckUntilX", "classes", "hasHover", "x", "width", "isJoined", "isValidJoinRange", "lastCharX", "cell", "range", "firstSelectionState", "JoinedCellData", "isInSelection", "isCursorCell", "isLinkHover", "isDecorated", "d", "chars", "WHITESPACE_CELL_CHAR", "AttributeData", "fg", "fgColorMode", "bg", "bgColorMode", "isInverse", "temp", "temp2", "bgOverride", "fgOverride", "isTop", "resolvedBg", "channels", "padStart", "color", "element", "treatGlyphAsBackgroundColor", "cache", "adjustedColor", "ratio", "style", "y", "__decorateClass", "__decorateParam", "ICharacterJoinerService", "IOptionsService", "ICoreBrowserService", "ICoreService", "IDecorationService", "IThemeService", "padChar", "length", "WidthCache", "_document", "_helperContainer", "regular", "bold", "italic", "boldItalic", "font", "fontSize", "weight", "weightBold", "c", "cp", "width", "key", "variant", "el", "SelectionRenderModel", "terminal", "start", "end", "columnSelectMode", "viewportY", "viewportStartRow", "viewportEndRow", "viewportCappedStartRow", "viewportCappedEndRow", "x", "y", "createSelectionRenderModel", "TERMINAL_CLASS_PREFIX", "ROW_CONTAINER_CLASS", "FG_CLASS_PREFIX", "BG_CLASS_PREFIX", "FOCUS_CLASS", "SELECTION_CLASS", "nextTerminalId", "DomRenderer", "Disposable", "_terminal", "_document", "_element", "_screenElement", "_viewportElement", "_helperContainer", "_linkifier2", "instantiationService", "_charSizeService", "_optionsService", "_bufferService", "_coreService", "_coreBrowserService", "_themeService", "createSelectionRenderModel", "Emitter", "createRenderDimensions", "e", "DomRendererRowFactory", "toDisposable", "WidthCache", "dpr", "element", "styles", "colors", "color", "blinkAnimationUnderlineId", "blinkAnimationBarId", "blinkAnimationBlockId", "i", "c", "spacing", "cols", "rows", "row", "start", "end", "columnSelectMode", "viewportStartRow", "viewportEndRow", "viewportCappedStartRow", "viewportCappedEndRow", "documentFragment", "isXFlipped", "startCol", "endCol", "middleRowsCount", "colStart", "colEnd", "rowCount", "left", "width", "buffer", "cursorAbsoluteY", "cursorX", "cursorBlink", "cursorStyle", "cursorInactiveStyle", "y", "rowElement", "lineData", "x", "x2", "y2", "enabled", "maxY", "bufferline", "__decorateClass", "__decorateParam", "IInstantiationService", "ICharSizeService", "IOptionsService", "IBufferService", "ICoreService", "ICoreBrowserService", "IThemeService", "CharSizeService", "Disposable", "document", "parentElement", "_optionsService", "Emitter", "TextMetricsMeasureStrategy", "DomMeasureStrategy", "result", "__decorateClass", "__decorateParam", "IOptionsService", "BaseMeasureStategy", "Disposable", "width", "height", "DomMeasureStrategy", "_document", "_parentElement", "_optionsService", "TextMetricsMeasureStrategy", "a", "metrics", "CoreBrowserService", "Disposable", "_textarea", "_window", "mainDocument", "ScreenDprMonitor", "Emitter", "w", "Event", "addDisposableListener", "value", "_parentWindow", "MutableDisposable", "toDisposable", "parentWindow", "LinkProviderService", "Disposable", "toDisposable", "linkProvider", "providerIndex", "getCoordsRelativeToElement", "window", "event", "element", "rect", "elementStyle", "leftPadding", "topPadding", "getCoords", "colCount", "rowCount", "hasValidCharSize", "cssCellWidth", "cssCellHeight", "isSelection", "coords", "MouseService", "_renderService", "_charSizeService", "event", "element", "colCount", "rowCount", "isSelection", "getCoords", "coords", "getCoordsRelativeToElement", "__decorateClass", "__decorateParam", "IRenderService", "ICharSizeService", "RenderDebouncer", "_renderCallback", "_coreBrowserService", "callback", "rowStart", "rowEnd", "rowCount", "start", "end", "Platform_exports", "__export", "getSafariVersion", "isChromeOS", "isFirefox", "isIpad", "isIphone", "isLegacyEdge", "isLinux", "isMac", "isNode", "isSafari", "isWindows", "userAgent", "platform", "majorVersion", "TaskQueue", "task", "deadline", "taskDuration", "longestTask", "lastDeadlineRemaining", "deadlineRemaining", "PriorityTaskQueue", "callback", "identifier", "duration", "end", "IdleTaskQueueInternal", "IdleTaskQueue", "isNode", "DebouncedIdleTask", "RenderService", "Disposable", "_rowCount", "screenElement", "_optionsService", "_charSizeService", "_coreService", "decorationService", "bufferService", "_coreBrowserService", "themeService", "MutableDisposable", "DebouncedIdleTask", "Emitter", "RenderDebouncer", "start", "end", "SynchronizedOutputHandler", "toDisposable", "w", "observer", "e", "entry", "isRedrawOnly", "buffered", "cols", "rows", "renderer", "callback", "columnSelectMode", "__decorateClass", "__decorateParam", "IOptionsService", "ICharSizeService", "ICoreService", "IDecorationService", "IBufferService", "ICoreBrowserService", "IThemeService", "_onTimeout", "result", "moveToCellSequence", "targetX", "targetY", "bufferService", "applicationCursor", "startX", "startY", "resetStartingRow", "moveToRequestedRow", "moveToRequestedCol", "direction", "repeat", "sequence", "rowDifference", "cellsToMove", "colsFromRowEnd", "colsFromRowBeginning", "currX", "bufferLine", "wrappedRowsForRow", "startRow", "endRow", "rowsToMove", "wrappedRowsCount", "verticalDirection", "horizontalDirection", "wrappedRows", "i", "currentRow", "rowCount", "line", "lineWraps", "startCol", "endCol", "forward", "currentCol", "bufferStr", "mod", "C0", "count", "str", "rpt", "SelectionModel", "_bufferService", "startPlusLength", "start", "end", "amount", "getRangeLength", "range", "bufferCols", "DRAG_SCROLL_MAX_THRESHOLD", "DRAG_SCROLL_MAX_SPEED", "DRAG_SCROLL_INTERVAL", "ALT_CLICK_MOVE_CURSOR_TIME", "NON_BREAKING_SPACE_CHAR", "ALL_NON_BREAKING_SPACE_REGEX", "SelectionService", "Disposable", "_element", "_screenElement", "_linkifier", "_bufferService", "_coreService", "_mouseService", "_optionsService", "_renderService", "_coreBrowserService", "CellData", "Emitter", "event", "amount", "e", "SelectionModel", "toDisposable", "start", "end", "buffer", "result", "startCol", "endCol", "i", "lineText", "startRowEndCol", "bufferLine", "line", "ALL_NON_BREAKING_SPACE_REGEX", "isWindows", "isLinuxMouseSelection", "isLinux", "coords", "x", "y", "allowWhitespaceOnlySelection", "range", "getRangeLength", "offset", "getCoordsRelativeToElement", "terminalHeight", "DRAG_SCROLL_MAX_THRESHOLD", "DRAG_SCROLL_MAX_SPEED", "isMac", "DRAG_SCROLL_INTERVAL", "previousSelectionEnd", "timeElapsed", "ALT_CLICK_MOVE_CURSOR_TIME", "coordinates", "sequence", "moveToCellSequence", "hasSelection", "charIndex", "length", "col", "row", "ev", "followWrappedLinesAbove", "followWrappedLinesBelow", "startIndex", "endIndex", "charOffset", "leftWideCharCount", "rightWideCharCount", "leftLongCharOffset", "rightLongCharOffset", "previousBufferLine", "previousLineWordPosition", "nextBufferLine", "nextLineWordPosition", "wordPosition", "endRow", "cell", "wrappedRange", "__decorateClass", "__decorateParam", "IBufferService", "ICoreService", "IMouseService", "IOptionsService", "IRenderService", "ICoreBrowserService", "TwoKeyMap", "first", "second", "value", "ColorContrastCache", "TwoKeyMap", "bg", "fg", "value", "DEFAULT_ANSI_COLORS", "colors", "css", "v", "i", "r", "g", "b", "channels", "c", "DEFAULT_FOREGROUND", "css", "DEFAULT_BACKGROUND", "DEFAULT_CURSOR", "DEFAULT_CURSOR_ACCENT", "DEFAULT_SELECTION", "DEFAULT_OVERVIEW_RULER_BORDER", "ThemeService", "Disposable", "_optionsService", "ColorContrastCache", "Emitter", "color", "DEFAULT_ANSI_COLORS", "theme", "colors", "parseColor", "NULL_COLOR", "colorCount", "i", "slot", "callback", "__decorateClass", "__decorateParam", "IOptionsService", "cssString", "fallback", "ServiceCollection", "entries", "id", "service", "instance", "result", "callback", "key", "value", "InstantiationService", "IInstantiationService", "ctor", "args", "serviceDependencies", "getServiceDependencies", "a", "b", "serviceArgs", "dependency", "firstServiceArgPos", "optionsKeyToLogLevel", "LOG_PREFIX", "LogService", "Disposable", "_optionsService", "traceLogger", "optionalParams", "type", "message", "__decorateClass", "__decorateParam", "IOptionsService", "CircularList", "Disposable", "_maxLength", "Emitter", "newMaxLength", "newArray", "i", "newLength", "index", "value", "start", "deleteCount", "items", "countToTrim", "count", "offset", "expandListBy", "CELL_SIZE", "DEFAULT_ATTR_DATA", "AttributeData", "$startIndex", "CLEANUP_THRESHOLD", "BufferLine", "_BufferLine", "cols", "fillCellData", "isWrapped", "CELL_SIZE", "cell", "CellData", "NULL_CELL_CHAR", "i", "index", "content", "cp", "stringFromCodePoint", "value", "codePoint", "width", "attrs", "pos", "n", "start", "end", "respectProtect", "uint32Cells", "data", "keys", "key", "extKeys", "line", "el", "newLine", "src", "srcCol", "destCol", "length", "applyInReverse", "srcData", "srcCombinedKeys", "trimRight", "startCol", "endCol", "outColumns", "result", "chars", "WHITESPACE_CELL_CHAR", "reflowLargerGetLinesToRemove", "lines", "oldCols", "newCols", "bufferAbsoluteY", "nullCell", "reflowCursorLine", "toRemove", "y", "i", "nextLine", "wrappedLines", "destLineIndex", "destCol", "getWrappedLineTrimmedLength", "srcLineIndex", "srcCol", "srcTrimmedTineLength", "srcRemainingCells", "destRemainingCells", "cellsToCopy", "countToRemove", "reflowLargerCreateNewLayout", "layout", "nextToRemoveIndex", "nextToRemoveStart", "countRemovedSoFar", "reflowLargerApplyNewLayout", "newLayout", "newLayoutLines", "reflowSmallerGetNewLineLengths", "newLineLengths", "cellsNeeded", "l", "p", "c", "srcLine", "cellsAvailable", "oldTrimmedLength", "endsWithWide", "lineLength", "cols", "endsInNull", "followingLineStartsWithWide", "_Marker", "line", "Emitter", "dispose", "disposable", "Marker", "CHARSETS", "DEFAULT_CHARSET", "MAX_BUFFER_SIZE", "Buffer", "_hasScrollback", "_optionsService", "_bufferService", "DEFAULT_ATTR_DATA", "DEFAULT_CHARSET", "CellData", "NULL_CELL_CHAR", "WHITESPACE_CELL_CHAR", "IdleTaskQueue", "CircularList", "attr", "ExtendedAttrs", "isWrapped", "BufferLine", "relativeY", "rows", "correctBufferLength", "fillAttr", "i", "newCols", "newRows", "nullCell", "dirtyMemoryLines", "newMaxLength", "addToY", "y", "amountToTrim", "normalRun", "counted", "windowsPty", "reflowCursorLine", "toRemove", "reflowLargerGetLinesToRemove", "newLayoutResult", "reflowLargerCreateNewLayout", "reflowLargerApplyNewLayout", "countRemoved", "viewportAdjustments", "toInsert", "countToInsert", "nextLine", "wrappedLines", "absoluteY", "lastLineLength", "destLineLengths", "reflowSmallerGetNewLineLengths", "linesToAdd", "trimmedLines", "newLines", "newLine", "destLineIndex", "destCol", "srcLineIndex", "srcCol", "cellsToCopy", "wrappedLinesIndex", "getWrappedLineTrimmedLength", "insertEvents", "originalLines", "originalLinesLength", "originalLineIndex", "nextToInsertIndex", "nextToInsert", "countInsertedSoFar", "nextI", "insertCountEmitted", "lineIndex", "trimRight", "startCol", "endCol", "line", "first", "last", "x", "marker", "Marker", "amount", "event", "BufferSet", "Disposable", "_optionsService", "_bufferService", "Emitter", "Buffer", "fillAttr", "newCols", "newRows", "i", "MINIMUM_COLS", "MINIMUM_ROWS", "BufferService", "Disposable", "optionsService", "Emitter", "BufferSet", "e", "cols", "rows", "colsChanged", "rowsChanged", "eraseAttr", "isWrapped", "buffer", "newLine", "topRow", "bottomRow", "willBufferBeTrimmed", "scrollRegionHeight", "disp", "suppressScrollEvent", "oldYdisp", "__decorateClass", "__decorateParam", "IOptionsService", "DEFAULT_OPTIONS", "isMac", "FONT_WEIGHT_OPTIONS", "OptionsService", "Disposable", "options", "Emitter", "defaultOptions", "key", "newValue", "e", "toDisposable", "listener", "eventKey", "keys", "getter", "propName", "setter", "value", "desc", "isCursorStyle", "clone", "val", "depth", "clonedObject", "key", "DEFAULT_MODES", "DEFAULT_DEC_PRIVATE_MODES", "CoreService", "Disposable", "_bufferService", "_logService", "_optionsService", "Emitter", "clone", "data", "wasUserInput", "buffer", "e", "__decorateClass", "__decorateParam", "IBufferService", "ILogService", "IOptionsService", "DEFAULT_PROTOCOLS", "e", "eventCode", "e", "isSGR", "code", "S", "DEFAULT_ENCODINGS", "params", "final", "CoreMouseService", "Disposable", "_bufferService", "_coreService", "_optionsService", "Emitter", "name", "DEFAULT_PROTOCOLS", "protocol", "encoding", "ev", "cellHeight", "dpr", "targetWheelEventPixels", "amount", "report", "events", "e1", "e2", "pixels", "__decorateClass", "__decorateParam", "IBufferService", "ICoreService", "IOptionsService", "BMP_COMBINING", "HIGH_COMBINING", "table", "bisearch", "ucs", "data", "min", "max", "mid", "UnicodeV6", "r", "num", "codepoint", "preceding", "width", "shouldJoin", "oldWidth", "UnicodeService", "UnicodeService", "_UnicodeService", "Emitter", "defaultProvider", "UnicodeV6", "value", "state", "width", "shouldJoin", "version", "provider", "num", "s", "result", "precedingInfo", "length", "i", "code", "second", "currentInfo", "chWidth", "codepoint", "preceding", "CharsetService", "g", "charset", "updateWindowsModeWrappedState", "bufferService", "lastChar", "nextLine", "MAX_VALUE", "MAX_SUBPARAMS", "Params", "_Params", "maxLength", "maxSubParamsLength", "values", "params", "value", "k", "newParams", "res", "i", "start", "end", "idx", "result", "length", "store", "cur", "EMPTY_HANDLERS", "OscParser", "ident", "handler", "handlerList", "handlerIndex", "j", "data", "start", "end", "utf32ToString", "code", "success", "promiseResult", "handlerResult", "fallThrough", "OscHandler", "_handler", "ret", "res", "EMPTY_HANDLERS", "DcsParser", "ident", "handler", "handlerList", "handlerIndex", "j", "params", "data", "start", "end", "utf32ToString", "success", "promiseResult", "handlerResult", "fallThrough", "EMPTY_PARAMS", "Params", "DcsHandler", "_handler", "ret", "res", "TransitionTable", "length", "action", "next", "code", "state", "codes", "i", "NON_ASCII_PRINTABLE", "VT500_TRANSITION_TABLE", "table", "blueprint", "unused", "r", "start", "end", "PRINTABLES", "EXECUTABLES", "states", "EscapeSequenceParser", "Disposable", "_transitions", "Params", "data", "ident", "params", "toDisposable", "OscParser", "DcsParser", "id", "finalRange", "res", "intermediate", "finalCode", "handler", "handlerList", "handlerIndex", "flag", "callback", "handlers", "handlerPos", "transition", "chunkPos", "promiseResult", "handlerResult", "j", "handlersEsc", "jj", "RGB_REX", "HASH_REX", "parseColor", "data", "low", "m", "base", "adv", "result", "i", "c", "pad", "n", "bits", "s", "s2", "toRgbString", "color", "r", "g", "b", "GLEVEL", "MAX_PARSEBUFFER_LENGTH", "STACK_LIMIT", "paramToWindowOption", "n", "opts", "SLOW_ASYNC_LIMIT", "$temp", "InputHandler", "Disposable", "_bufferService", "_charsetService", "_coreService", "_logService", "_optionsService", "_oscLinkService", "_coreMouseService", "_unicodeService", "_parser", "EscapeSequenceParser", "StringToUtf32", "Utf8ToUtf32", "DEFAULT_ATTR_DATA", "Emitter", "DirtyRowTracker", "e", "ident", "params", "code", "identifier", "action", "data", "payload", "start", "end", "C0", "C1", "OscHandler", "flag", "CHARSETS", "state", "DcsHandler", "cursorStartX", "cursorStartY", "decodedLength", "position", "p", "res", "rej", "err", "promiseResult", "result", "wasPaused", "MAX_PARSEBUFFER_LENGTH", "i", "len", "viewportEnd", "viewportStart", "chWidth", "charset", "screenReaderMode", "cols", "wraparoundMode", "insertMode", "curAttr", "bufferRow", "precedingJoinState", "pos", "ch", "currentInfo", "UnicodeService", "shouldJoin", "oldWidth", "stringFromCodePoint", "oldRow", "oldCol", "BufferLine", "offset", "delta", "id", "callback", "paramToWindowOption", "line", "originalX", "maxCol", "x", "y", "diffToTop", "diffToBottom", "param", "clearWrap", "respectProtect", "j", "scrollBackSize", "row", "scrollBottomRowsOffset", "scrollBottomAbsolute", "joinState", "length", "text", "idata", "itext", "tlength", "term", "DEFAULT_CHARSET", "ansi", "V", "dm", "mouseProtocol", "mouseEncoding", "cs", "buffers", "active", "alt", "opts", "f", "m", "v", "b2v", "value", "color", "mode", "c1", "c2", "c3", "AttributeData", "attr", "accu", "cSpace", "advance", "subparams", "style", "l", "isBlinking", "top", "bottom", "second", "STACK_LIMIT", "event", "slots", "idx", "spec", "index", "isValidColorIndex", "parseColor", "uri", "parsedParams", "idParamIndex", "collectAndFlag", "GLEVEL", "scrollRegionHeight", "level", "cell", "CellData", "yOffset", "s", "b", "STYLES", "y1", "y2", "__decorateClass", "__decorateParam", "IBufferService", "DISCARD_WATERMARK", "WRITE_TIMEOUT_MS", "WRITE_BUFFER_LENGTH_THRESHOLD", "WriteBuffer", "Disposable", "_action", "Emitter", "data", "maxSubsequentCalls", "chunk", "cb", "callback", "lastTime", "promiseResult", "startTime", "result", "continuation", "r", "err", "OscLinkService", "_bufferService", "data", "buffer", "marker", "entry", "castData", "key", "match", "linkId", "y", "e", "linkData", "index", "__decorateClass", "__decorateParam", "IBufferService", "hasWriteSyncWarnHappened", "CoreTerminal", "Disposable", "options", "MutableDisposable", "Emitter", "InstantiationService", "OptionsService", "IOptionsService", "BufferService", "IBufferService", "LogService", "ILogService", "CoreService", "ICoreService", "CoreMouseService", "ICoreMouseService", "UnicodeService", "IUnicodeService", "CharsetService", "ICharsetService", "OscLinkService", "IOscLinkService", "InputHandler", "Event", "WriteBuffer", "data", "promiseResult", "ev", "key", "callback", "maxSubsequentCalls", "wasUserInput", "x", "y", "MINIMUM_COLS", "MINIMUM_ROWS", "eraseAttr", "isWrapped", "disp", "suppressScrollEvent", "pageCount", "disableSmoothScroll", "line", "scrollAmount", "id", "ident", "value", "windowsPty", "disposables", "updateWindowsModeWrappedState", "toDisposable", "d", "KEYCODE_KEY_MAPPINGS", "evaluateKeyboardEvent", "ev", "applicationCursorMode", "isMac", "macOptionIsMeta", "result", "modifiers", "C0", "key", "keyCode", "keyString", "i", "SortedList", "_getKey", "IdleTaskQueue", "value", "sortedAddedValues", "a", "b", "sortedAddedValuesIndex", "arrayIndex", "newArray", "newArrayIndex", "key", "sortedDeletedIndices", "sortedDeletedIndicesIndex", "callback", "min", "max", "mid", "midKey", "$xmin", "$xmax", "DecorationService", "Disposable", "SortedList", "Emitter", "toDisposable", "options", "decoration", "Decoration", "markerDispose", "listener", "d", "x", "line", "layer", "xmin", "xmax", "callback", "DisposableStore", "css", "RENDER_DEBOUNCE_THRESHOLD_MS", "TimeBasedDebouncer", "_renderCallback", "_debounceThresholdMS", "rowStart", "rowEnd", "rowCount", "refreshRequestTime", "elapsed", "waitPeriodBeforeTrailingRefresh", "start", "end", "MAX_ROWS_TO_READ", "DEBUG", "AccessibilityManager", "Disposable", "_terminal", "instantiationService", "_coreBrowserService", "_renderService", "doc", "i", "e", "TimeBasedDebouncer", "char", "spaceCount", "addDisposableListener", "toDisposable", "MAX_ROWS_TO_READ", "tooMuchOutput", "keyChar", "start", "end", "buffer", "setSize", "line", "columns", "lineData", "posInSet", "element", "position", "boundaryElement", "beforeBoundaryElement", "lastRowPos", "topBoundaryElement", "bottomBoundaryElement", "newElement", "selection", "begin", "lastRowElement", "toRowColumn", "node", "offset", "rowElement", "row", "column", "beginRowColumn", "endRowColumn", "rows", "width", "lastColumn", "targetWidth", "__decorateClass", "__decorateParam", "IInstantiationService", "ICoreBrowserService", "IRenderService", "Linkifier", "Disposable", "_element", "_mouseService", "_renderService", "_bufferService", "_linkProviderService", "Emitter", "toDisposable", "dispose", "addDisposableListener", "event", "position", "composedPath", "i", "target", "useLineCache", "reply", "linkWithState", "linkProvided", "linkProvider", "links", "linksWithState", "link", "y", "replies", "occupiedCells", "providerReply", "startX", "endX", "x", "index", "hasLinkBefore", "j", "linkAtPosition", "currentLink", "linkEquals", "startRow", "endRow", "v", "e", "start", "end", "element", "showEvent", "range", "scrollOffset", "lower", "upper", "current", "mouseService", "coords", "x1", "y1", "x2", "y2", "fg", "__decorateClass", "__decorateParam", "IMouseService", "IRenderService", "IBufferService", "ILinkProviderService", "a", "b", "CoreBrowserTerminal", "CoreTerminal", "options", "MutableDisposable", "Platform_exports", "Emitter", "DecorationService", "IDecorationService", "LinkProviderService", "ILinkProviderService", "OscLinkProvider", "e", "type", "event", "Event", "toDisposable", "req", "acc", "ident", "colorRgb", "color", "C0", "toRgbString", "C1_ESCAPED", "colors", "channels", "narrowedAcc", "value", "AccessibilityManager", "ev", "cursorY", "bufferLine", "cursorX", "cellHeight", "width", "cellWidth", "cursorTop", "cursorLeft", "addDisposableListener", "copyHandler", "pasteHandlerWrapper", "handlePasteEvent", "isFirefox", "rightClickHandler", "isLinux", "moveTextAreaUnderMouseCursor", "parent", "fragment", "textarea", "promptLabel", "isChromeOS", "CoreBrowserService", "ICoreBrowserService", "CharSizeService", "ICharSizeService", "ThemeService", "IThemeService", "CharacterJoinerService", "ICharacterJoinerService", "RenderService", "IRenderService", "CompositionHelper", "MouseService", "IMouseService", "linkifier", "Linkifier", "Viewport", "SelectionService", "ISelectionService", "text", "BufferDecorationRenderer", "OverviewRulerRenderer", "DomRenderer", "self", "el", "sendEvent", "pos", "but", "action", "deltaY", "requestedEvents", "eventListeners", "events", "sequence", "start", "end", "disp", "suppressScrollEvent", "pageCount", "disableSmoothScroll", "line", "scrollAmount", "data", "paste", "customKeyEventHandler", "customWheelEventHandler", "linkProvider", "handler", "joinerId", "cursorYOffset", "decorationOptions", "column", "row", "length", "shouldIgnoreComposition", "result", "evaluateKeyboardEvent", "scrollCount", "browser", "thirdLevelKey", "wasModifierKeyOnlyEvent", "key", "x", "y", "i", "DEFAULT_ATTR_DATA", "canvasWidth", "canvasHeight", "force", "AddonManager", "i", "terminal", "instance", "loadedAddon", "index", "BufferLineApiView", "_line", "x", "cell", "CellData", "trimRight", "startColumn", "endColumn", "BufferApiView", "_buffer", "type", "buffer", "y", "line", "BufferLineApiView", "CellData", "BufferNamespaceApi", "Disposable", "_core", "Emitter", "BufferApiView", "ParserApi", "_core", "id", "callback", "params", "data", "handler", "ident", "UnicodeApi", "_core", "provider", "version", "CONSTRUCTOR_ONLY_OPTIONS", "$value", "Terminal", "Disposable", "options", "CoreBrowserTerminal", "AddonManager", "getter", "propName", "setter", "value", "desc", "ParserApi", "UnicodeApi", "BufferNamespaceApi", "m", "mouseTrackingMode", "data", "wasUserInput", "columns", "rows", "parent", "customKeyEventHandler", "customWheelEventHandler", "linkProvider", "handler", "joinerId", "cursorYOffset", "decorationOptions", "column", "row", "length", "start", "end", "amount", "pageCount", "line", "callback", "addon", "promptLabel", "tooMuchOutput", "values"] +} diff --git a/node_modules/@xterm/xterm/package.json b/node_modules/@xterm/xterm/package.json new file mode 100644 index 0000000..e55987d --- /dev/null +++ b/node_modules/@xterm/xterm/package.json @@ -0,0 +1,111 @@ +{ + "name": "@xterm/xterm", + "description": "Full xterm terminal, in your browser", + "version": "6.0.0", + "main": "lib/xterm.js", + "module": "lib/xterm.mjs", + "style": "css/xterm.css", + "types": "typings/xterm.d.ts", + "repository": "https://github.com/xtermjs/xterm.js", + "license": "MIT", + "workspaces": [ + "addons/*" + ], + "keywords": [ + "cli", + "command-line", + "console", + "pty", + "shell", + "ssh", + "styles", + "terminal-emulator", + "terminal", + "tty", + "vt100", + "webgl", + "xterm" + ], + "scripts": { + "setup": "npm run build", + "start": "node demo/start", + "build": "npm run tsc", + "watch": "npm run tsc-watch", + "tsc": "tsc -b ./tsconfig.all.json", + "tsc-watch": "tsc -b -w ./tsconfig.all.json --preserveWatchOutput", + "esbuild": "node bin/esbuild_all.mjs", + "esbuild-watch": "node bin/esbuild_all.mjs --watch", + "esbuild-package": "node bin/esbuild_all.mjs --prod", + "esbuild-package-watch": "node bin/esbuild_all.mjs --prod --watch", + "esbuild-package-headless-only": "node bin/esbuild.mjs --prod --headless", + "esbuild-demo": "node bin/esbuild.mjs --demo-client", + "esbuild-demo-watch": "node bin/esbuild.mjs --demo-client --watch", + "test": "npm run test-unit", + "posttest": "npm run lint", + "lint": "eslint -c .eslintrc.json --max-warnings 0 --ext .ts src/ addons/", + "lint-fix": "eslint -c .eslintrc.json --fix --ext .ts src/ addons/", + "lint-api": "eslint --no-eslintrc -c .eslintrc.json.typings --max-warnings 0 --no-ignore --ext .d.ts typings/", + "test-unit": "node ./bin/test_unit.js", + "test-unit-coverage": "node ./bin/test_unit.js --coverage", + "test-unit-dev": "cross-env NODE_PATH='./out' mocha", + "test-integration": "node ./bin/test_integration.js --workers=75%", + "test-integration-chromium": "node ./bin/test_integration.js --workers=75% \"--project=ChromeStable\"", + "test-integration-firefox": "node ./bin/test_integration.js --workers=75% \"--project=FirefoxStable\"", + "test-integration-webkit": "node ./bin/test_integration.js --workers=75% \"--project=WebKit\"", + "test-integration-debug": "node ./bin/test_integration.js --workers=1 --headed --timeout=30000", + "benchmark": "NODE_PATH=./out xterm-benchmark -r 5 -c test/benchmark/benchmark.json", + "benchmark-baseline": "NODE_PATH=./out xterm-benchmark -r 5 -c test/benchmark/benchmark.json --baseline out-test/benchmark/*benchmark.js", + "benchmark-eval": "NODE_PATH=./out xterm-benchmark -r 5 -c test/benchmark/benchmark.json --eval out-test/benchmark/*benchmark.js", + "clean": "rm -rf lib out addons/*/lib addons/*/out", + "vtfeatures": "node bin/extract_vtfeatures.js src/**/*.ts src/*.ts", + "prepackage": "npm run build", + "package": "webpack", + "postpackage": "npm run esbuild-package", + "prepackage-headless": "npm run esbuild-package-headless-only", + "package-headless": "webpack --config ./webpack.config.headless.js", + "postpackage-headless": "node ./bin/package_headless.js", + "prepublishOnly": "npm run package" + }, + "devDependencies": { + "@lunapaint/png-codec": "^0.2.0", + "@playwright/test": "^1.37.1", + "@stylistic/eslint-plugin": "^2.3.0", + "@types/chai": "^4.2.22", + "@types/debug": "^4.1.7", + "@types/deep-equal": "^1.0.1", + "@types/express": "4", + "@types/express-ws": "^3.0.1", + "@types/jsdom": "^16.2.13", + "@types/mocha": "^9.0.0", + "@types/node": "^18.16.0", + "@types/trusted-types": "^1.0.6", + "@types/utf8": "^3.0.0", + "@types/webpack": "^5.28.0", + "@types/ws": "^8.2.0", + "@typescript-eslint/eslint-plugin": "^6.2.00", + "@typescript-eslint/parser": "^6.2.00", + "chai": "^4.3.4", + "cross-env": "^7.0.3", + "deep-equal": "^2.0.5", + "esbuild": "~0.25.2", + "eslint": "^8.56.0", + "eslint-plugin-jsdoc": "^46.9.1", + "express": "^4.19.2", + "express-ws": "^5.0.2", + "jsdom": "^18.0.1", + "mocha": "^10.1.0", + "mustache": "^4.2.0", + "node-pty": "1.1.0-beta19", + "nyc": "^15.1.0", + "source-map-loader": "^3.0.0", + "source-map-support": "^0.5.20", + "ts-loader": "^9.3.1", + "typescript": "5.5", + "utf8": "^3.0.0", + "webpack": "^5.61.0", + "webpack-cli": "^4.9.1", + "ws": "^8.2.3", + "xterm-benchmark": "^0.3.1" + }, + "commit": "f447274f430fd22513f6adbf9862d19524471c04" +} \ No newline at end of file diff --git a/node_modules/@xterm/xterm/src/browser/AccessibilityManager.ts b/node_modules/@xterm/xterm/src/browser/AccessibilityManager.ts new file mode 100644 index 0000000..746a5a7 --- /dev/null +++ b/node_modules/@xterm/xterm/src/browser/AccessibilityManager.ts @@ -0,0 +1,435 @@ +/** + * Copyright (c) 2017 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import * as Strings from 'browser/LocalizableStrings'; +import { ITerminal, IRenderDebouncer } from 'browser/Types'; +import { TimeBasedDebouncer } from 'browser/TimeBasedDebouncer'; +import { Disposable, toDisposable } from 'vs/base/common/lifecycle'; +import { ICoreBrowserService, IRenderService } from 'browser/services/Services'; +import { IBuffer } from 'common/buffer/Types'; +import { IInstantiationService } from 'common/services/Services'; +import { addDisposableListener } from 'vs/base/browser/dom'; + +const MAX_ROWS_TO_READ = 20; + +const enum BoundaryPosition { + TOP, + BOTTOM +} + +// Turn this on to unhide the accessibility tree and display it under +// (instead of overlapping with) the terminal. +const DEBUG = false; + +export class AccessibilityManager extends Disposable { + private _debugRootContainer: HTMLElement | undefined; + private _accessibilityContainer: HTMLElement; + + private _rowContainer: HTMLElement; + private _rowElements: HTMLElement[]; + private _rowColumns: WeakMap = new WeakMap(); + + private _liveRegion: HTMLElement; + private _liveRegionLineCount: number = 0; + private _liveRegionDebouncer: IRenderDebouncer; + + private _topBoundaryFocusListener: (e: FocusEvent) => void; + private _bottomBoundaryFocusListener: (e: FocusEvent) => void; + + /** + * This queue has a character pushed to it for keys that are pressed, if the + * next character added to the terminal is equal to the key char then it is + * not announced (added to live region) because it has already been announced + * by the textarea event (which cannot be canceled). There are some race + * condition cases if there is typing while data is streaming, but this covers + * the main case of typing into the prompt and inputting the answer to a + * question (Y/N, etc.). + */ + private _charsToConsume: string[] = []; + + private _charsToAnnounce: string = ''; + + constructor( + private readonly _terminal: ITerminal, + @IInstantiationService instantiationService: IInstantiationService, + @ICoreBrowserService private readonly _coreBrowserService: ICoreBrowserService, + @IRenderService private readonly _renderService: IRenderService + ) { + super(); + const doc = this._coreBrowserService.mainDocument; + this._accessibilityContainer = doc.createElement('div'); + this._accessibilityContainer.classList.add('xterm-accessibility'); + + this._rowContainer = doc.createElement('div'); + this._rowContainer.setAttribute('role', 'list'); + this._rowContainer.classList.add('xterm-accessibility-tree'); + this._rowElements = []; + for (let i = 0; i < this._terminal.rows; i++) { + this._rowElements[i] = this._createAccessibilityTreeNode(); + this._rowContainer.appendChild(this._rowElements[i]); + } + + this._topBoundaryFocusListener = e => this._handleBoundaryFocus(e, BoundaryPosition.TOP); + this._bottomBoundaryFocusListener = e => this._handleBoundaryFocus(e, BoundaryPosition.BOTTOM); + this._rowElements[0].addEventListener('focus', this._topBoundaryFocusListener); + this._rowElements[this._rowElements.length - 1].addEventListener('focus', this._bottomBoundaryFocusListener); + + this._accessibilityContainer.appendChild(this._rowContainer); + + this._liveRegion = doc.createElement('div'); + this._liveRegion.classList.add('live-region'); + this._liveRegion.setAttribute('aria-live', 'assertive'); + this._accessibilityContainer.appendChild(this._liveRegion); + this._liveRegionDebouncer = this._register(new TimeBasedDebouncer(this._renderRows.bind(this))); + + if (!this._terminal.element) { + throw new Error('Cannot enable accessibility before Terminal.open'); + } + + if (DEBUG) { + this._accessibilityContainer.classList.add('debug'); + this._rowContainer.classList.add('debug'); + + // Use a `
` container so that the css will still apply. + this._debugRootContainer = doc.createElement('div'); + this._debugRootContainer.classList.add('xterm'); + + this._debugRootContainer.appendChild(doc.createTextNode('------start a11y------')); + this._debugRootContainer.appendChild(this._accessibilityContainer); + this._debugRootContainer.appendChild(doc.createTextNode('------end a11y------')); + + this._terminal.element.insertAdjacentElement('afterend', this._debugRootContainer); + } else { + this._terminal.element.insertAdjacentElement('afterbegin', this._accessibilityContainer); + } + + this._register(this._terminal.onResize(e => this._handleResize(e.rows))); + this._register(this._terminal.onRender(e => this._refreshRows(e.start, e.end))); + this._register(this._terminal.onScroll(() => this._refreshRows())); + // Line feed is an issue as the prompt won't be read out after a command is run + this._register(this._terminal.onA11yChar(char => this._handleChar(char))); + this._register(this._terminal.onLineFeed(() => this._handleChar('\n'))); + this._register(this._terminal.onA11yTab(spaceCount => this._handleTab(spaceCount))); + this._register(this._terminal.onKey(e => this._handleKey(e.key))); + this._register(this._terminal.onBlur(() => this._clearLiveRegion())); + this._register(this._renderService.onDimensionsChange(() => this._refreshRowsDimensions())); + this._register(addDisposableListener(doc, 'selectionchange', () => this._handleSelectionChange())); + this._register(this._coreBrowserService.onDprChange(() => this._refreshRowsDimensions())); + + this._refreshRowsDimensions(); + this._refreshRows(); + this._register(toDisposable(() => { + if (DEBUG) { + this._debugRootContainer!.remove(); + } else { + this._accessibilityContainer.remove(); + } + this._rowElements.length = 0; + })); + } + + private _handleTab(spaceCount: number): void { + for (let i = 0; i < spaceCount; i++) { + this._handleChar(' '); + } + } + + private _handleChar(char: string): void { + if (this._liveRegionLineCount < MAX_ROWS_TO_READ + 1) { + if (this._charsToConsume.length > 0) { + // Have the screen reader ignore the char if it was just input + const shiftedChar = this._charsToConsume.shift(); + if (shiftedChar !== char) { + this._charsToAnnounce += char; + } + } else { + this._charsToAnnounce += char; + } + + if (char === '\n') { + this._liveRegionLineCount++; + if (this._liveRegionLineCount === MAX_ROWS_TO_READ + 1) { + this._liveRegion.textContent += Strings.tooMuchOutput.get(); + } + } + } + } + + private _clearLiveRegion(): void { + this._liveRegion.textContent = ''; + this._liveRegionLineCount = 0; + } + + private _handleKey(keyChar: string): void { + this._clearLiveRegion(); + // Only add the char if there is no control character. + if (!/\p{Control}/u.test(keyChar)) { + this._charsToConsume.push(keyChar); + } + } + + private _refreshRows(start?: number, end?: number): void { + this._liveRegionDebouncer.refresh(start, end, this._terminal.rows); + } + + private _renderRows(start: number, end: number): void { + const buffer: IBuffer = this._terminal.buffer; + const setSize = buffer.lines.length.toString(); + for (let i = start; i <= end; i++) { + const line = buffer.lines.get(buffer.ydisp + i); + const columns: number[] = []; + const lineData = line?.translateToString(true, undefined, undefined, columns) || ''; + const posInSet = (buffer.ydisp + i + 1).toString(); + const element = this._rowElements[i]; + if (element) { + if (lineData.length === 0) { + element.textContent = '\u00a0'; + this._rowColumns.set(element, [0, 1]); + } else { + element.textContent = lineData; + this._rowColumns.set(element, columns); + } + element.setAttribute('aria-posinset', posInSet); + element.setAttribute('aria-setsize', setSize); + this._alignRowWidth(element); + } + } + this._announceCharacters(); + } + + private _announceCharacters(): void { + if (this._charsToAnnounce.length === 0) { + return; + } + this._liveRegion.textContent += this._charsToAnnounce; + this._charsToAnnounce = ''; + } + + private _handleBoundaryFocus(e: FocusEvent, position: BoundaryPosition): void { + const boundaryElement = e.target as HTMLElement; + const beforeBoundaryElement = this._rowElements[position === BoundaryPosition.TOP ? 1 : this._rowElements.length - 2]; + + // Don't scroll if the buffer top has reached the end in that direction + const posInSet = boundaryElement.getAttribute('aria-posinset'); + const lastRowPos = position === BoundaryPosition.TOP ? '1' : `${this._terminal.buffer.lines.length}`; + if (posInSet === lastRowPos) { + return; + } + + // Don't scroll when the last focused item was not the second row (focus is going the other + // direction) + if (e.relatedTarget !== beforeBoundaryElement) { + return; + } + + // Remove old boundary element from array + let topBoundaryElement: HTMLElement; + let bottomBoundaryElement: HTMLElement; + if (position === BoundaryPosition.TOP) { + topBoundaryElement = boundaryElement; + bottomBoundaryElement = this._rowElements.pop()!; + this._rowContainer.removeChild(bottomBoundaryElement); + } else { + topBoundaryElement = this._rowElements.shift()!; + bottomBoundaryElement = boundaryElement; + this._rowContainer.removeChild(topBoundaryElement); + } + + // Remove listeners from old boundary elements + topBoundaryElement.removeEventListener('focus', this._topBoundaryFocusListener); + bottomBoundaryElement.removeEventListener('focus', this._bottomBoundaryFocusListener); + + // Add new element to array/DOM + if (position === BoundaryPosition.TOP) { + const newElement = this._createAccessibilityTreeNode(); + this._rowElements.unshift(newElement); + this._rowContainer.insertAdjacentElement('afterbegin', newElement); + } else { + const newElement = this._createAccessibilityTreeNode(); + this._rowElements.push(newElement); + this._rowContainer.appendChild(newElement); + } + + // Add listeners to new boundary elements + this._rowElements[0].addEventListener('focus', this._topBoundaryFocusListener); + this._rowElements[this._rowElements.length - 1].addEventListener('focus', this._bottomBoundaryFocusListener); + + // Scroll up + this._terminal.scrollLines(position === BoundaryPosition.TOP ? -1 : 1); + + // Focus new boundary before element + this._rowElements[position === BoundaryPosition.TOP ? 1 : this._rowElements.length - 2].focus(); + + // Prevent the standard behavior + e.preventDefault(); + e.stopImmediatePropagation(); + } + + private _handleSelectionChange(): void { + if (this._rowElements.length === 0) { + return; + } + + const selection = this._coreBrowserService.mainDocument.getSelection(); + if (!selection) { + return; + } + + if (selection.isCollapsed) { + // Only do something when the anchorNode is inside the row container. This + // behavior mirrors what we do with mouse --- if the mouse clicks + // somewhere outside of the terminal, we don't clear the selection. + if (this._rowContainer.contains(selection.anchorNode)) { + this._terminal.clearSelection(); + } + return; + } + + if (!selection.anchorNode || !selection.focusNode) { + console.error('anchorNode and/or focusNode are null'); + return; + } + + // Sort the two selection points in document order. + let begin = { node: selection.anchorNode, offset: selection.anchorOffset }; + let end = { node: selection.focusNode, offset: selection.focusOffset }; + if ((begin.node.compareDocumentPosition(end.node) & Node.DOCUMENT_POSITION_PRECEDING) || (begin.node === end.node && begin.offset > end.offset) ) { + [begin, end] = [end, begin]; + } + + // Clamp begin/end to the inside of the row container. + if (begin.node.compareDocumentPosition(this._rowElements[0]) & (Node.DOCUMENT_POSITION_CONTAINED_BY | Node.DOCUMENT_POSITION_FOLLOWING)) { + begin = { node: this._rowElements[0].childNodes[0], offset: 0 }; + } + if (!this._rowContainer.contains(begin.node)) { + // This happens when `begin` is below the last row. + return; + } + const lastRowElement = this._rowElements.slice(-1)[0]; + if (end.node.compareDocumentPosition(lastRowElement) & (Node.DOCUMENT_POSITION_CONTAINED_BY | Node.DOCUMENT_POSITION_PRECEDING)) { + end = { + node: lastRowElement, + offset: lastRowElement.textContent?.length ?? 0 + }; + } + if (!this._rowContainer.contains(end.node)) { + // This happens when `end` is above the first row. + return; + } + + const toRowColumn = ({ node, offset }: typeof begin): {row: number, column: number} | null => { + // `node` is either the row element or the Text node inside it. + const rowElement: any = node instanceof Text ? node.parentNode : node; + let row = parseInt(rowElement?.getAttribute('aria-posinset'), 10) - 1; + if (isNaN(row)) { + console.warn('row is invalid. Race condition?'); + return null; + } + + const columns = this._rowColumns.get(rowElement); + if (!columns) { + console.warn('columns is null. Race condition?'); + return null; + } + + let column = offset < columns.length ? columns[offset] : columns.slice(-1)[0] + 1; + if (column >= this._terminal.cols) { + ++row; + column = 0; + } + return { + row, + column + }; + }; + + const beginRowColumn = toRowColumn(begin); + const endRowColumn = toRowColumn(end); + + if (!beginRowColumn || !endRowColumn) { + return; + } + + if (beginRowColumn.row > endRowColumn.row || (beginRowColumn.row === endRowColumn.row && beginRowColumn.column >= endRowColumn.column)) { + // This should not happen unless we have some bugs. + throw new Error('invalid range'); + } + + this._terminal.select( + beginRowColumn.column, + beginRowColumn.row, + (endRowColumn.row - beginRowColumn.row) * this._terminal.cols - beginRowColumn.column + endRowColumn.column + ); + } + + private _handleResize(rows: number): void { + // Remove bottom boundary listener + this._rowElements[this._rowElements.length - 1].removeEventListener('focus', this._bottomBoundaryFocusListener); + + // Grow rows as required + for (let i = this._rowContainer.children.length; i < this._terminal.rows; i++) { + this._rowElements[i] = this._createAccessibilityTreeNode(); + this._rowContainer.appendChild(this._rowElements[i]); + } + // Shrink rows as required + while (this._rowElements.length > rows) { + this._rowContainer.removeChild(this._rowElements.pop()!); + } + + // Add bottom boundary listener + this._rowElements[this._rowElements.length - 1].addEventListener('focus', this._bottomBoundaryFocusListener); + + this._refreshRowsDimensions(); + } + + private _createAccessibilityTreeNode(): HTMLElement { + const element = this._coreBrowserService.mainDocument.createElement('div'); + element.setAttribute('role', 'listitem'); + element.tabIndex = -1; + this._refreshRowDimensions(element); + return element; + } + + private _refreshRowsDimensions(): void { + if (!this._renderService.dimensions.css.cell.height) { + return; + } + Object.assign(this._accessibilityContainer.style, { + width: `${this._renderService.dimensions.css.canvas.width}px`, + fontSize: `${this._terminal.options.fontSize}px` + }); + if (this._rowElements.length !== this._terminal.rows) { + this._handleResize(this._terminal.rows); + } + for (let i = 0; i < this._terminal.rows; i++) { + this._refreshRowDimensions(this._rowElements[i]); + this._alignRowWidth(this._rowElements[i]); + } + } + + private _refreshRowDimensions(element: HTMLElement): void { + element.style.height = `${this._renderService.dimensions.css.cell.height}px`; + } + + /** + * Scale the width of a row so that each of the character is (mostly) aligned + * with the actual rendering. This will allow the screen reader to draw + * selection outline at the correct position. + * + * On top of using the "monospace" font and correct font size, the scaling + * here is necessary to handle characters that are not covered by the font + * (e.g. CJK). + */ + private _alignRowWidth(element: HTMLElement): void { + element.style.transform = ''; + const width = element.getBoundingClientRect().width; + const lastColumn = this._rowColumns.get(element)?.slice(-1)?.[0]; + if (!lastColumn) { + return; + } + const targetWidth = lastColumn * this._renderService.dimensions.css.cell.width; + element.style.transform = `scaleX(${targetWidth / width})`; + } +} diff --git a/node_modules/@xterm/xterm/src/browser/Clipboard.ts b/node_modules/@xterm/xterm/src/browser/Clipboard.ts new file mode 100644 index 0000000..ec85b58 --- /dev/null +++ b/node_modules/@xterm/xterm/src/browser/Clipboard.ts @@ -0,0 +1,93 @@ +/** + * Copyright (c) 2016 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { ISelectionService } from 'browser/services/Services'; +import { ICoreService, IOptionsService } from 'common/services/Services'; + +/** + * Prepares text to be pasted into the terminal by normalizing the line endings + * @param text The pasted text that needs processing before inserting into the terminal + */ +export function prepareTextForTerminal(text: string): string { + return text.replace(/\r?\n/g, '\r'); +} + +/** + * Bracket text for paste, if necessary, as per https://cirw.in/blog/bracketed-paste + * @param text The pasted text to bracket + */ +export function bracketTextForPaste(text: string, bracketedPasteMode: boolean): string { + if (bracketedPasteMode) { + return '\x1b[200~' + text + '\x1b[201~'; + } + return text; +} + +/** + * Binds copy functionality to the given terminal. + * @param ev The original copy event to be handled + */ +export function copyHandler(ev: ClipboardEvent, selectionService: ISelectionService): void { + if (ev.clipboardData) { + ev.clipboardData.setData('text/plain', selectionService.selectionText); + } + // Prevent or the original text will be copied. + ev.preventDefault(); +} + +/** + * Redirect the clipboard's data to the terminal's input handler. + */ +export function handlePasteEvent(ev: ClipboardEvent, textarea: HTMLTextAreaElement, coreService: ICoreService, optionsService: IOptionsService): void { + ev.stopPropagation(); + if (ev.clipboardData) { + const text = ev.clipboardData.getData('text/plain'); + paste(text, textarea, coreService, optionsService); + } +} + +export function paste(text: string, textarea: HTMLTextAreaElement, coreService: ICoreService, optionsService: IOptionsService): void { + text = prepareTextForTerminal(text); + text = bracketTextForPaste(text, coreService.decPrivateModes.bracketedPasteMode && optionsService.rawOptions.ignoreBracketedPasteMode !== true); + coreService.triggerDataEvent(text, true); + textarea.value = ''; +} + +/** + * Moves the textarea under the mouse cursor and focuses it. + * @param ev The original right click event to be handled. + * @param textarea The terminal's textarea. + */ +export function moveTextAreaUnderMouseCursor(ev: MouseEvent, textarea: HTMLTextAreaElement, screenElement: HTMLElement): void { + + // Calculate textarea position relative to the screen element + const pos = screenElement.getBoundingClientRect(); + const left = ev.clientX - pos.left - 10; + const top = ev.clientY - pos.top - 10; + + // Bring textarea at the cursor position + textarea.style.width = '20px'; + textarea.style.height = '20px'; + textarea.style.left = `${left}px`; + textarea.style.top = `${top}px`; + textarea.style.zIndex = '1000'; + + textarea.focus(); +} + +/** + * Bind to right-click event and allow right-click copy and paste. + */ +export function rightClickHandler(ev: MouseEvent, textarea: HTMLTextAreaElement, screenElement: HTMLElement, selectionService: ISelectionService, shouldSelectWord: boolean): void { + moveTextAreaUnderMouseCursor(ev, textarea, screenElement); + + if (shouldSelectWord) { + selectionService.rightClickSelect(ev); + } + + // Get textarea ready to copy from the context menu + textarea.value = selectionService.selectionText; + textarea.select(); +} diff --git a/node_modules/@xterm/xterm/src/browser/ColorContrastCache.ts b/node_modules/@xterm/xterm/src/browser/ColorContrastCache.ts new file mode 100644 index 0000000..0c60e8d --- /dev/null +++ b/node_modules/@xterm/xterm/src/browser/ColorContrastCache.ts @@ -0,0 +1,34 @@ +/** + * Copyright (c) 2017 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { IColorContrastCache } from 'browser/Types'; +import { IColor } from 'common/Types'; +import { TwoKeyMap } from 'common/MultiKeyMap'; + +export class ColorContrastCache implements IColorContrastCache { + private _color: TwoKeyMap = new TwoKeyMap(); + private _css: TwoKeyMap = new TwoKeyMap(); + + public setCss(bg: number, fg: number, value: string | null): void { + this._css.set(bg, fg, value); + } + + public getCss(bg: number, fg: number): string | null | undefined { + return this._css.get(bg, fg); + } + + public setColor(bg: number, fg: number, value: IColor | null): void { + this._color.set(bg, fg, value); + } + + public getColor(bg: number, fg: number): IColor | null | undefined { + return this._color.get(bg, fg); + } + + public clear(): void { + this._color.clear(); + this._css.clear(); + } +} diff --git a/node_modules/@xterm/xterm/src/browser/CoreBrowserTerminal.ts b/node_modules/@xterm/xterm/src/browser/CoreBrowserTerminal.ts new file mode 100644 index 0000000..38ad467 --- /dev/null +++ b/node_modules/@xterm/xterm/src/browser/CoreBrowserTerminal.ts @@ -0,0 +1,1339 @@ +/** + * Copyright (c) 2014 The xterm.js authors. All rights reserved. + * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License) + * @license MIT + * + * Originally forked from (with the author's permission): + * Fabrice Bellard's javascript vt100 for jslinux: + * http://bellard.org/jslinux/ + * Copyright (c) 2011 Fabrice Bellard + * The original design remains. The terminal itself + * has been extended to include xterm CSI codes, among + * other features. + * + * Terminal Emulation References: + * http://vt100.net/ + * http://invisible-island.net/xterm/ctlseqs/ctlseqs.txt + * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html + * http://invisible-island.net/vttest/ + * http://www.inwap.com/pdp10/ansicode.txt + * http://linux.die.net/man/4/console_codes + * http://linux.die.net/man/7/urxvt + */ + +import { IDecoration, IDecorationOptions, IDisposable, ILinkProvider, IMarker } from '@xterm/xterm'; +import { copyHandler, handlePasteEvent, moveTextAreaUnderMouseCursor, paste, rightClickHandler } from 'browser/Clipboard'; +import * as Strings from 'browser/LocalizableStrings'; +import { OscLinkProvider } from 'browser/OscLinkProvider'; +import { CharacterJoinerHandler, CustomKeyEventHandler, CustomWheelEventHandler, IBrowser, IBufferRange, ICompositionHelper, ILinkifier2, ITerminal } from 'browser/Types'; +import { Viewport } from 'browser/Viewport'; +import { BufferDecorationRenderer } from 'browser/decorations/BufferDecorationRenderer'; +import { OverviewRulerRenderer } from 'browser/decorations/OverviewRulerRenderer'; +import { CompositionHelper } from 'browser/input/CompositionHelper'; +import { DomRenderer } from 'browser/renderer/dom/DomRenderer'; +import { IRenderer } from 'browser/renderer/shared/Types'; +import { CharSizeService } from 'browser/services/CharSizeService'; +import { CharacterJoinerService } from 'browser/services/CharacterJoinerService'; +import { CoreBrowserService } from 'browser/services/CoreBrowserService'; +import { LinkProviderService } from 'browser/services/LinkProviderService'; +import { MouseService } from 'browser/services/MouseService'; +import { RenderService } from 'browser/services/RenderService'; +import { SelectionService } from 'browser/services/SelectionService'; +import { ICharSizeService, ICharacterJoinerService, ICoreBrowserService, ILinkProviderService, IMouseService, IRenderService, ISelectionService, IThemeService } from 'browser/services/Services'; +import { ThemeService } from 'browser/services/ThemeService'; +import { channels, color } from 'common/Color'; +import { CoreTerminal } from 'common/CoreTerminal'; +import * as Browser from 'common/Platform'; +import { ColorRequestType, CoreMouseAction, CoreMouseButton, CoreMouseEventType, IColorEvent, ITerminalOptions, KeyboardResultType, SpecialColorIndex } from 'common/Types'; +import { DEFAULT_ATTR_DATA } from 'common/buffer/BufferLine'; +import { IBuffer } from 'common/buffer/Types'; +import { C0, C1_ESCAPED } from 'common/data/EscapeSequences'; +import { evaluateKeyboardEvent } from 'common/input/Keyboard'; +import { toRgbString } from 'common/input/XParseColor'; +import { DecorationService } from 'common/services/DecorationService'; +import { IDecorationService } from 'common/services/Services'; +import { WindowsOptionsReportType } from '../common/InputHandler'; +import { AccessibilityManager } from './AccessibilityManager'; +import { Linkifier } from './Linkifier'; +import { Emitter, Event } from 'vs/base/common/event'; +import { addDisposableListener } from 'vs/base/browser/dom'; +import { MutableDisposable, toDisposable } from 'vs/base/common/lifecycle'; + +export class CoreBrowserTerminal extends CoreTerminal implements ITerminal { + public textarea: HTMLTextAreaElement | undefined; + public element: HTMLElement | undefined; + public screenElement: HTMLElement | undefined; + + private _document: Document | undefined; + private _viewportElement: HTMLElement | undefined; + private _helperContainer: HTMLElement | undefined; + private _compositionView: HTMLElement | undefined; + + private readonly _linkifier: MutableDisposable = this._register(new MutableDisposable()); + public get linkifier(): ILinkifier2 | undefined { return this._linkifier.value; } + private _overviewRulerRenderer: OverviewRulerRenderer | undefined; + private _viewport: Viewport | undefined; + + public browser: IBrowser = Browser as any; + + private _customKeyEventHandler: CustomKeyEventHandler | undefined; + private _customWheelEventHandler: CustomWheelEventHandler | undefined; + + // Browser services + private _decorationService: DecorationService; + private _linkProviderService: ILinkProviderService; + + // Optional browser services + private _charSizeService: ICharSizeService | undefined; + private _coreBrowserService: ICoreBrowserService | undefined; + private _mouseService: IMouseService | undefined; + private _renderService: IRenderService | undefined; + private _themeService: IThemeService | undefined; + private _characterJoinerService: ICharacterJoinerService | undefined; + private _selectionService: ISelectionService | undefined; + + /** + * Records whether the keydown event has already been handled and triggered a data event, if so + * the keypress event should not trigger a data event but should still print to the textarea so + * screen readers will announce it. + */ + private _keyDownHandled: boolean = false; + + /** + * Records whether a keydown event has occured since the last keyup event, i.e. whether a key + * is currently "pressed". + */ + private _keyDownSeen: boolean = false; + + /** + * Records whether the keypress event has already been handled and triggered a data event, if so + * the input event should not trigger a data event but should still print to the textarea so + * screen readers will announce it. + */ + private _keyPressHandled: boolean = false; + + /** + * Records whether there has been a keydown event for a dead key without a corresponding keydown + * event for the composed/alternative character. If we cancel the keydown event for the dead key, + * no events will be emitted for the final character. + */ + private _unprocessedDeadKey: boolean = false; + + private _compositionHelper: ICompositionHelper | undefined; + private _accessibilityManager: MutableDisposable = this._register(new MutableDisposable()); + + private readonly _onCursorMove = this._register(new Emitter()); + public readonly onCursorMove = this._onCursorMove.event; + private readonly _onKey = this._register(new Emitter<{ key: string, domEvent: KeyboardEvent }>()); + public readonly onKey = this._onKey.event; + private readonly _onRender = this._register(new Emitter<{ start: number, end: number }>()); + public readonly onRender = this._onRender.event; + private readonly _onSelectionChange = this._register(new Emitter()); + public readonly onSelectionChange = this._onSelectionChange.event; + private readonly _onTitleChange = this._register(new Emitter()); + public readonly onTitleChange = this._onTitleChange.event; + private readonly _onBell = this._register(new Emitter()); + public readonly onBell = this._onBell.event; + + private _onFocus = this._register(new Emitter()); + public get onFocus(): Event { return this._onFocus.event; } + private _onBlur = this._register(new Emitter()); + public get onBlur(): Event { return this._onBlur.event; } + private _onA11yCharEmitter = this._register(new Emitter()); + public get onA11yChar(): Event { return this._onA11yCharEmitter.event; } + private _onA11yTabEmitter = this._register(new Emitter()); + public get onA11yTab(): Event { return this._onA11yTabEmitter.event; } + private _onWillOpen = this._register(new Emitter()); + public get onWillOpen(): Event { return this._onWillOpen.event; } + + constructor( + options: Partial = {} + ) { + super(options); + + this._setup(); + + this._decorationService = this._instantiationService.createInstance(DecorationService); + this._instantiationService.setService(IDecorationService, this._decorationService); + this._linkProviderService = this._instantiationService.createInstance(LinkProviderService); + this._instantiationService.setService(ILinkProviderService, this._linkProviderService); + this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(OscLinkProvider)); + + // Setup InputHandler listeners + this._register(this._inputHandler.onRequestBell(() => this._onBell.fire())); + this._register(this._inputHandler.onRequestRefreshRows((e) => this.refresh(e?.start ?? 0, e?.end ?? (this.rows - 1)))); + this._register(this._inputHandler.onRequestSendFocus(() => this._reportFocus())); + this._register(this._inputHandler.onRequestReset(() => this.reset())); + this._register(this._inputHandler.onRequestWindowsOptionsReport(type => this._reportWindowsOptions(type))); + this._register(this._inputHandler.onColor((event) => this._handleColorEvent(event))); + this._register(Event.forward(this._inputHandler.onCursorMove, this._onCursorMove)); + this._register(Event.forward(this._inputHandler.onTitleChange, this._onTitleChange)); + this._register(Event.forward(this._inputHandler.onA11yChar, this._onA11yCharEmitter)); + this._register(Event.forward(this._inputHandler.onA11yTab, this._onA11yTabEmitter)); + + // Setup listeners + this._register(this._bufferService.onResize(e => this._afterResize(e.cols, e.rows))); + + this._register(toDisposable(() => { + this._customKeyEventHandler = undefined; + this.element?.parentNode?.removeChild(this.element); + })); + } + + /** + * Handle color event from inputhandler for OSC 4|104 | 10|110 | 11|111 | 12|112. + * An event from OSC 4|104 may contain multiple set or report requests, and multiple + * or none restore requests (resetting all), + * while an event from OSC 10|110 | 11|111 | 12|112 always contains a single request. + */ + private _handleColorEvent(event: IColorEvent): void { + if (!this._themeService) return; + for (const req of event) { + let acc: 'foreground' | 'background' | 'cursor' | 'ansi'; + let ident = ''; + switch (req.index) { + case SpecialColorIndex.FOREGROUND: // OSC 10 | 110 + acc = 'foreground'; + ident = '10'; + break; + case SpecialColorIndex.BACKGROUND: // OSC 11 | 111 + acc = 'background'; + ident = '11'; + break; + case SpecialColorIndex.CURSOR: // OSC 12 | 112 + acc = 'cursor'; + ident = '12'; + break; + default: // OSC 4 | 104 + // we can skip the [0..255] range check here (already done in inputhandler) + acc = 'ansi'; + ident = '4;' + req.index; + } + switch (req.type) { + case ColorRequestType.REPORT: + const colorRgb = color.toColorRGB(acc === 'ansi' + ? this._themeService.colors.ansi[req.index] + : this._themeService.colors[acc]); + this.coreService.triggerDataEvent(`${C0.ESC}]${ident};${toRgbString(colorRgb)}${C1_ESCAPED.ST}`); + break; + case ColorRequestType.SET: + if (acc === 'ansi') { + this._themeService.modifyColors(colors => colors.ansi[req.index] = channels.toColor(...req.color)); + } else { + const narrowedAcc = acc; + this._themeService.modifyColors(colors => colors[narrowedAcc] = channels.toColor(...req.color)); + } + break; + case ColorRequestType.RESTORE: + this._themeService.restoreColor(req.index); + break; + } + } + } + + protected _setup(): void { + super._setup(); + + this._customKeyEventHandler = undefined; + } + + /** + * Convenience property to active buffer. + */ + public get buffer(): IBuffer { + return this.buffers.active; + } + + /** + * Focus the terminal. Delegates focus handling to the terminal's DOM element. + */ + public focus(): void { + if (this.textarea) { + this.textarea.focus({ preventScroll: true }); + } + } + + private _handleScreenReaderModeOptionChange(value: boolean): void { + if (value) { + if (!this._accessibilityManager.value && this._renderService) { + this._accessibilityManager.value = this._instantiationService.createInstance(AccessibilityManager, this); + } + } else { + this._accessibilityManager.clear(); + } + } + + /** + * Binds the desired focus behavior on a given terminal object. + */ + private _handleTextAreaFocus(ev: FocusEvent): void { + if (this.coreService.decPrivateModes.sendFocus) { + this.coreService.triggerDataEvent(C0.ESC + '[I'); + } + this.element!.classList.add('focus'); + this._showCursor(); + this._onFocus.fire(); + } + + /** + * Blur the terminal, calling the blur function on the terminal's underlying + * textarea. + */ + public blur(): void { + return this.textarea?.blur(); + } + + /** + * Binds the desired blur behavior on a given terminal object. + */ + private _handleTextAreaBlur(): void { + // Text can safely be removed on blur. Doing it earlier could interfere with + // screen readers reading it out. + this.textarea!.value = ''; + this.refresh(this.buffer.y, this.buffer.y); + if (this.coreService.decPrivateModes.sendFocus) { + this.coreService.triggerDataEvent(C0.ESC + '[O'); + } + this.element!.classList.remove('focus'); + this._onBlur.fire(); + } + + private _syncTextArea(): void { + if (!this.textarea || !this.buffer.isCursorInViewport || this._compositionHelper!.isComposing || !this._renderService) { + return; + } + const cursorY = this.buffer.ybase + this.buffer.y; + const bufferLine = this.buffer.lines.get(cursorY); + if (!bufferLine) { + return; + } + const cursorX = Math.min(this.buffer.x, this.cols - 1); + const cellHeight = this._renderService.dimensions.css.cell.height; + const width = bufferLine.getWidth(cursorX); + const cellWidth = this._renderService.dimensions.css.cell.width * width; + const cursorTop = this.buffer.y * this._renderService.dimensions.css.cell.height; + const cursorLeft = cursorX * this._renderService.dimensions.css.cell.width; + + // Sync the textarea to the exact position of the composition view so the IME knows where the + // text is. + this.textarea.style.left = cursorLeft + 'px'; + this.textarea.style.top = cursorTop + 'px'; + this.textarea.style.width = cellWidth + 'px'; + this.textarea.style.height = cellHeight + 'px'; + this.textarea.style.lineHeight = cellHeight + 'px'; + this.textarea.style.zIndex = '-5'; + } + + /** + * Initialize default behavior + */ + private _initGlobal(): void { + this._bindKeys(); + + // Bind clipboard functionality + this._register(addDisposableListener(this.element!, 'copy', (event: ClipboardEvent) => { + // If mouse events are active it means the selection manager is disabled and + // copy should be handled by the host program. + if (!this.hasSelection()) { + return; + } + copyHandler(event, this._selectionService!); + })); + const pasteHandlerWrapper = (event: ClipboardEvent): void => handlePasteEvent(event, this.textarea!, this.coreService, this.optionsService); + this._register(addDisposableListener(this.textarea!, 'paste', pasteHandlerWrapper)); + this._register(addDisposableListener(this.element!, 'paste', pasteHandlerWrapper)); + + // Handle right click context menus + if (Browser.isFirefox) { + // Firefox doesn't appear to fire the contextmenu event on right click + this._register(addDisposableListener(this.element!, 'mousedown', (event: MouseEvent) => { + if (event.button === 2) { + rightClickHandler(event, this.textarea!, this.screenElement!, this._selectionService!, this.options.rightClickSelectsWord); + } + })); + } else { + this._register(addDisposableListener(this.element!, 'contextmenu', (event: MouseEvent) => { + rightClickHandler(event, this.textarea!, this.screenElement!, this._selectionService!, this.options.rightClickSelectsWord); + })); + } + + // Move the textarea under the cursor when middle clicking on Linux to ensure + // middle click to paste selection works. This only appears to work in Chrome + // at the time is writing. + if (Browser.isLinux) { + // Use auxclick event over mousedown the latter doesn't seem to work. Note + // that the regular click event doesn't fire for the middle mouse button. + this._register(addDisposableListener(this.element!, 'auxclick', (event: MouseEvent) => { + if (event.button === 1) { + moveTextAreaUnderMouseCursor(event, this.textarea!, this.screenElement!); + } + })); + } + } + + /** + * Apply key handling to the terminal + */ + private _bindKeys(): void { + this._register(addDisposableListener(this.textarea!, 'keyup', (ev: KeyboardEvent) => this._keyUp(ev), true)); + this._register(addDisposableListener(this.textarea!, 'keydown', (ev: KeyboardEvent) => this._keyDown(ev), true)); + this._register(addDisposableListener(this.textarea!, 'keypress', (ev: KeyboardEvent) => this._keyPress(ev), true)); + this._register(addDisposableListener(this.textarea!, 'compositionstart', () => this._compositionHelper!.compositionstart())); + this._register(addDisposableListener(this.textarea!, 'compositionupdate', (e: CompositionEvent) => this._compositionHelper!.compositionupdate(e))); + this._register(addDisposableListener(this.textarea!, 'compositionend', () => this._compositionHelper!.compositionend())); + this._register(addDisposableListener(this.textarea!, 'input', (ev: InputEvent) => this._inputEvent(ev), true)); + this._register(this.onRender(() => this._compositionHelper!.updateCompositionElements())); + } + + /** + * Opens the terminal within an element. + * + * @param parent The element to create the terminal within. + */ + public open(parent: HTMLElement): void { + if (!parent) { + throw new Error('Terminal requires a parent element.'); + } + + if (!parent.isConnected) { + this._logService.debug('Terminal.open was called on an element that was not attached to the DOM'); + } + + // If the terminal is already opened + if (this.element?.ownerDocument.defaultView && this._coreBrowserService) { + // Adjust the window if needed + if (this.element.ownerDocument.defaultView !== this._coreBrowserService.window) { + this._coreBrowserService.window = this.element.ownerDocument.defaultView; + } + return; + } + + this._document = parent.ownerDocument; + if (this.options.documentOverride && this.options.documentOverride instanceof Document) { + this._document = this.optionsService.rawOptions.documentOverride as Document; + } + + // Create main element container + this.element = this._document.createElement('div'); + this.element.dir = 'ltr'; // xterm.css assumes LTR + this.element.classList.add('terminal'); + this.element.classList.add('xterm'); + parent.appendChild(this.element); + + // Performance: Use a document fragment to build the terminal + // viewport and helper elements detached from the DOM + const fragment = this._document.createDocumentFragment(); + this._viewportElement = this._document.createElement('div'); + this._viewportElement.classList.add('xterm-viewport'); + fragment.appendChild(this._viewportElement); + + this.screenElement = this._document.createElement('div'); + this.screenElement.classList.add('xterm-screen'); + this._register(addDisposableListener(this.screenElement, 'mousemove', (ev: MouseEvent) => this.updateCursorStyle(ev))); + // Create the container that will hold helpers like the textarea for + // capturing DOM Events. Then produce the helpers. + this._helperContainer = this._document.createElement('div'); + this._helperContainer.classList.add('xterm-helpers'); + this.screenElement.appendChild(this._helperContainer); + fragment.appendChild(this.screenElement); + + const textarea = this.textarea = this._document.createElement('textarea'); + this.textarea.classList.add('xterm-helper-textarea'); + this.textarea.setAttribute('aria-label', Strings.promptLabel.get()); + if (!Browser.isChromeOS) { + // ChromeVox on ChromeOS does not like this. See + // https://issuetracker.google.com/issues/260170397 + this.textarea.setAttribute('aria-multiline', 'false'); + } + this.textarea.setAttribute('autocorrect', 'off'); + this.textarea.setAttribute('autocapitalize', 'off'); + this.textarea.setAttribute('spellcheck', 'false'); + this.textarea.tabIndex = 0; + this._register(this.optionsService.onSpecificOptionChange('disableStdin', () => textarea.readOnly = this.optionsService.rawOptions.disableStdin)); + this.textarea.readOnly = this.optionsService.rawOptions.disableStdin; + + // Register the core browser service before the generic textarea handlers are registered so it + // handles them first. Otherwise the renderers may use the wrong focus state. + this._coreBrowserService = this._register(this._instantiationService.createInstance(CoreBrowserService, + this.textarea, + parent.ownerDocument.defaultView ?? window, + // Force unsafe null in node.js environment for tests + this._document ?? (typeof window !== 'undefined') ? window.document : null as any + )); + this._instantiationService.setService(ICoreBrowserService, this._coreBrowserService); + + this._register(addDisposableListener(this.textarea, 'focus', (ev: FocusEvent) => this._handleTextAreaFocus(ev))); + this._register(addDisposableListener(this.textarea, 'blur', () => this._handleTextAreaBlur())); + this._helperContainer.appendChild(this.textarea); + + this._charSizeService = this._instantiationService.createInstance(CharSizeService, this._document, this._helperContainer); + this._instantiationService.setService(ICharSizeService, this._charSizeService); + + this._themeService = this._instantiationService.createInstance(ThemeService); + this._instantiationService.setService(IThemeService, this._themeService); + + this._characterJoinerService = this._instantiationService.createInstance(CharacterJoinerService); + this._instantiationService.setService(ICharacterJoinerService, this._characterJoinerService); + + this._renderService = this._register(this._instantiationService.createInstance(RenderService, this.rows, this.screenElement)); + this._instantiationService.setService(IRenderService, this._renderService); + this._register(this._renderService.onRenderedViewportChange(e => this._onRender.fire(e))); + this.onResize(e => this._renderService!.resize(e.cols, e.rows)); + + this._compositionView = this._document.createElement('div'); + this._compositionView.classList.add('composition-view'); + this._compositionHelper = this._instantiationService.createInstance(CompositionHelper, this.textarea, this._compositionView); + this._helperContainer.appendChild(this._compositionView); + + this._mouseService = this._instantiationService.createInstance(MouseService); + this._instantiationService.setService(IMouseService, this._mouseService); + + const linkifier = this._linkifier.value = this._register(this._instantiationService.createInstance(Linkifier, this.screenElement)); + + // Performance: Add viewport and helper elements from the fragment + this.element.appendChild(fragment); + + try { + this._onWillOpen.fire(this.element); + } + catch { /* fails to load addon for some reason */ } + if (!this._renderService.hasRenderer()) { + this._renderService.setRenderer(this._createRenderer()); + } + + this._register(this.onCursorMove(() => { + this._renderService!.handleCursorMove(); + this._syncTextArea(); + })); + this._register(this.onResize(() => this._renderService!.handleResize(this.cols, this.rows))); + this._register(this.onBlur(() => this._renderService!.handleBlur())); + this._register(this.onFocus(() => this._renderService!.handleFocus())); + + this._viewport = this._register(this._instantiationService.createInstance(Viewport, this.element, this.screenElement)); + this._register(this._viewport.onRequestScrollLines(e => { + super.scrollLines(e, false); + this.refresh(0, this.rows - 1); + })); + + this._selectionService = this._register(this._instantiationService.createInstance(SelectionService, + this.element, + this.screenElement, + linkifier + )); + this._instantiationService.setService(ISelectionService, this._selectionService); + this._register(this._selectionService.onRequestScrollLines(e => this.scrollLines(e.amount, e.suppressScrollEvent))); + this._register(this._selectionService.onSelectionChange(() => this._onSelectionChange.fire())); + this._register(this._selectionService.onRequestRedraw(e => this._renderService!.handleSelectionChanged(e.start, e.end, e.columnSelectMode))); + this._register(this._selectionService.onLinuxMouseSelection(text => { + // If there's a new selection, put it into the textarea, focus and select it + // in order to register it as a selection on the OS. This event is fired + // only on Linux to enable middle click to paste selection. + this.textarea!.value = text; + this.textarea!.focus(); + this.textarea!.select(); + })); + this._register(Event.any( + this._onScroll.event, + this._inputHandler.onScroll + )(() => { + this._selectionService!.refresh(); + this._viewport?.queueSync(); + })); + + this._register(this._instantiationService.createInstance(BufferDecorationRenderer, this.screenElement)); + this._register(addDisposableListener(this.element, 'mousedown', (e: MouseEvent) => this._selectionService!.handleMouseDown(e))); + + // apply mouse event classes set by escape codes before terminal was attached + if (this.coreMouseService.areMouseEventsActive) { + this._selectionService.disable(); + this.element.classList.add('enable-mouse-events'); + } else { + this._selectionService.enable(); + } + + if (this.options.screenReaderMode) { + // Note that this must be done *after* the renderer is created in order to + // ensure the correct order of the dprchange event + this._accessibilityManager.value = this._instantiationService.createInstance(AccessibilityManager, this); + } + this._register(this.optionsService.onSpecificOptionChange('screenReaderMode', e => this._handleScreenReaderModeOptionChange(e))); + + if (this.options.overviewRuler.width) { + this._overviewRulerRenderer = this._register(this._instantiationService.createInstance(OverviewRulerRenderer, this._viewportElement, this.screenElement)); + } + this.optionsService.onSpecificOptionChange('overviewRuler', value => { + if (!this._overviewRulerRenderer && value && this._viewportElement && this.screenElement) { + this._overviewRulerRenderer = this._register(this._instantiationService.createInstance(OverviewRulerRenderer, this._viewportElement, this.screenElement)); + } + }); + // Measure the character size + this._charSizeService.measure(); + + // Setup loop that draws to screen + this.refresh(0, this.rows - 1); + + // Initialize global actions that need to be taken on the document. + this._initGlobal(); + + // Listen for mouse events and translate + // them into terminal mouse protocols. + this.bindMouse(); + } + + private _createRenderer(): IRenderer { + return this._instantiationService.createInstance(DomRenderer, this, this._document!, this.element!, this.screenElement!, this._viewportElement!, this._helperContainer!, this.linkifier!); + } + + /** + * Bind certain mouse events to the terminal. + * By default only 3 button + wheel up/down is ativated. For higher buttons + * no mouse report will be created. Typically the standard actions will be active. + * + * There are several reasons not to enable support for higher buttons/wheel: + * - Button 4 and 5 are typically used for history back and forward navigation, + * there is no straight forward way to supress/intercept those standard actions. + * - Support for higher buttons does not work in some platform/browser combinations. + * - Left/right wheel was not tested. + * - Emulators vary in mouse button support, typically only 3 buttons and + * wheel up/down work reliable. + * + * TODO: Move mouse event code into its own file. + */ + public bindMouse(): void { + const self = this; + const el = this.element!; + + // send event to CoreMouseService + function sendEvent(ev: MouseEvent | WheelEvent): boolean { + // get mouse coordinates + const pos = self._mouseService!.getMouseReportCoords(ev, self.screenElement!); + if (!pos) { + return false; + } + + let but: CoreMouseButton; + let action: CoreMouseAction | undefined; + switch ((ev as any).overrideType || ev.type) { + case 'mousemove': + action = CoreMouseAction.MOVE; + if (ev.buttons === undefined) { + // buttons is not supported on macOS, try to get a value from button instead + but = CoreMouseButton.NONE; + if (ev.button !== undefined) { + but = ev.button < 3 ? ev.button : CoreMouseButton.NONE; + } + } else { + // according to MDN buttons only reports up to button 5 (AUX2) + but = ev.buttons & 1 ? CoreMouseButton.LEFT : + ev.buttons & 4 ? CoreMouseButton.MIDDLE : + ev.buttons & 2 ? CoreMouseButton.RIGHT : + CoreMouseButton.NONE; // fallback to NONE + } + break; + case 'mouseup': + action = CoreMouseAction.UP; + but = ev.button < 3 ? ev.button : CoreMouseButton.NONE; + break; + case 'mousedown': + action = CoreMouseAction.DOWN; + but = ev.button < 3 ? ev.button : CoreMouseButton.NONE; + break; + case 'wheel': + if (self._customWheelEventHandler && self._customWheelEventHandler(ev as WheelEvent) === false) { + return false; + } + const deltaY = (ev as WheelEvent).deltaY; + if (deltaY === 0) { + return false; + } + const lines = self.coreMouseService.consumeWheelEvent( + ev as WheelEvent, + self._renderService?.dimensions?.device?.cell?.height, + self._coreBrowserService?.dpr + ); + if (lines === 0) { + return false; + } + action = deltaY < 0 ? CoreMouseAction.UP : CoreMouseAction.DOWN; + but = CoreMouseButton.WHEEL; + break; + default: + // dont handle other event types by accident + return false; + } + + // exit if we cannot determine valid button/action values + // do nothing for higher buttons than wheel + if (action === undefined || but === undefined || but > CoreMouseButton.WHEEL) { + return false; + } + + return self.coreMouseService.triggerMouseEvent({ + col: pos.col, + row: pos.row, + x: pos.x, + y: pos.y, + button: but, + action, + ctrl: ev.ctrlKey, + alt: ev.altKey, + shift: ev.shiftKey + }); + } + + /** + * Event listener state handling. + * We listen to the onProtocolChange event of CoreMouseService and put + * requested listeners in `requestedEvents`. With this the listeners + * have all bits to do the event listener juggling. + * Note: 'mousedown' currently is "always on" and not managed + * by onProtocolChange. + */ + const requestedEvents: { [key: string]: ((ev: MouseEvent | WheelEvent) => void) | null } = { + mouseup: null, + wheel: null, + mousedrag: null, + mousemove: null + }; + const eventListeners: { [key: string]: (ev: any) => void | boolean } = { + mouseup: (ev: MouseEvent) => { + sendEvent(ev); + if (!ev.buttons) { + // if no other button is held remove global handlers + this._document!.removeEventListener('mouseup', requestedEvents.mouseup!); + if (requestedEvents.mousedrag) { + this._document!.removeEventListener('mousemove', requestedEvents.mousedrag); + } + } + return this.cancel(ev); + }, + wheel: (ev: WheelEvent) => { + sendEvent(ev); + return this.cancel(ev, true); + }, + mousedrag: (ev: MouseEvent) => { + // deal only with move while a button is held + if (ev.buttons) { + sendEvent(ev); + } + }, + mousemove: (ev: MouseEvent) => { + // deal only with move without any button + if (!ev.buttons) { + sendEvent(ev); + } + } + }; + this._register(this.coreMouseService.onProtocolChange(events => { + // apply global changes on events + if (events) { + if (this.optionsService.rawOptions.logLevel === 'debug') { + this._logService.debug('Binding to mouse events:', this.coreMouseService.explainEvents(events)); + } + this.element!.classList.add('enable-mouse-events'); + this._selectionService!.disable(); + } else { + this._logService.debug('Unbinding from mouse events.'); + this.element!.classList.remove('enable-mouse-events'); + this._selectionService!.enable(); + } + + // add/remove handlers from requestedEvents + + if (!(events & CoreMouseEventType.MOVE)) { + el.removeEventListener('mousemove', requestedEvents.mousemove!); + requestedEvents.mousemove = null; + } else if (!requestedEvents.mousemove) { + el.addEventListener('mousemove', eventListeners.mousemove); + requestedEvents.mousemove = eventListeners.mousemove; + } + + if (!(events & CoreMouseEventType.WHEEL)) { + el.removeEventListener('wheel', requestedEvents.wheel!); + requestedEvents.wheel = null; + } else if (!requestedEvents.wheel) { + el.addEventListener('wheel', eventListeners.wheel, { passive: false }); + requestedEvents.wheel = eventListeners.wheel; + } + + if (!(events & CoreMouseEventType.UP)) { + this._document!.removeEventListener('mouseup', requestedEvents.mouseup!); + requestedEvents.mouseup = null; + } else if (!requestedEvents.mouseup) { + requestedEvents.mouseup = eventListeners.mouseup; + } + + if (!(events & CoreMouseEventType.DRAG)) { + this._document!.removeEventListener('mousemove', requestedEvents.mousedrag!); + requestedEvents.mousedrag = null; + } else if (!requestedEvents.mousedrag) { + requestedEvents.mousedrag = eventListeners.mousedrag; + } + })); + // force initial onProtocolChange so we dont miss early mouse requests + this.coreMouseService.activeProtocol = this.coreMouseService.activeProtocol; + + /** + * "Always on" event listeners. + */ + this._register(addDisposableListener(el, 'mousedown', (ev: MouseEvent) => { + ev.preventDefault(); + this.focus(); + + // Don't send the mouse button to the pty if mouse events are disabled or + // if the selection manager is having selection forced (ie. a modifier is + // held). + if (!this.coreMouseService.areMouseEventsActive || this._selectionService!.shouldForceSelection(ev)) { + return; + } + + sendEvent(ev); + + // Register additional global handlers which should keep reporting outside + // of the terminal element. + // Note: Other emulators also do this for 'mousedown' while a button + // is held, we currently limit 'mousedown' to the terminal only. + if (requestedEvents.mouseup) { + this._document!.addEventListener('mouseup', requestedEvents.mouseup); + } + if (requestedEvents.mousedrag) { + this._document!.addEventListener('mousemove', requestedEvents.mousedrag); + } + + return this.cancel(ev); + })); + + this._register(addDisposableListener(el, 'wheel', (ev: WheelEvent) => { + // do nothing, if app side handles wheel itself + if (requestedEvents.wheel) return; + + if (this._customWheelEventHandler && this._customWheelEventHandler(ev) === false) { + return false; + } + + if (!this.buffer.hasScrollback) { + // Convert wheel events into up/down events when the buffer does not have scrollback, this + // enables scrolling in apps hosted in the alt buffer such as vim or tmux even when mouse + // events are not enabled. + // This used implementation used get the actual lines/partial lines scrolled from the + // viewport but since moving to the new viewport implementation has been simplified to + // simply send a single up or down sequence. + + // Do nothing if there's no vertical scroll + const deltaY = (ev as WheelEvent).deltaY; + if (deltaY === 0) { + return false; + } + + const lines = self.coreMouseService.consumeWheelEvent( + ev as WheelEvent, + self._renderService?.dimensions?.device?.cell?.height, + self._coreBrowserService?.dpr + ); + if (lines === 0) { + return this.cancel(ev, true); + } + + // Construct and send sequences + const sequence = C0.ESC + (this.coreService.decPrivateModes.applicationCursorKeys ? 'O' : '[') + (ev.deltaY < 0 ? 'A' : 'B'); + this.coreService.triggerDataEvent(sequence, true); + return this.cancel(ev, true); + } + }, { passive: false })); + } + + + /** + * Tells the renderer to refresh terminal content between two rows (inclusive) at the next + * opportunity. + * @param start The row to start from (between 0 and this.rows - 1). + * @param end The row to end at (between start and this.rows - 1). + */ + public refresh(start: number, end: number): void { + this._renderService?.refreshRows(start, end); + } + + /** + * Change the cursor style for different selection modes + */ + public updateCursorStyle(ev: KeyboardEvent | MouseEvent): void { + if (this._selectionService?.shouldColumnSelect(ev)) { + this.element!.classList.add('column-select'); + } else { + this.element!.classList.remove('column-select'); + } + } + + /** + * Display the cursor element + */ + private _showCursor(): void { + if (!this.coreService.isCursorInitialized) { + this.coreService.isCursorInitialized = true; + this.refresh(this.buffer.y, this.buffer.y); + } + } + + public scrollLines(disp: number, suppressScrollEvent?: boolean): void { + // All scrollLines methods need to go via the viewport in order to support smooth scroll + if (this._viewport) { + this._viewport.scrollLines(disp); + } else { + super.scrollLines(disp, suppressScrollEvent); + } + this.refresh(0, this.rows - 1); + } + + public scrollPages(pageCount: number): void { + this.scrollLines(pageCount * (this.rows - 1)); + } + + public scrollToTop(): void { + this.scrollLines(-this._bufferService.buffer.ydisp); + } + + public scrollToBottom(disableSmoothScroll?: boolean): void { + if (disableSmoothScroll && this._viewport) { + this._viewport.scrollToLine(this.buffer.ybase, true); + } else { + this.scrollLines(this._bufferService.buffer.ybase - this._bufferService.buffer.ydisp); + } + } + + public scrollToLine(line: number): void { + const scrollAmount = line - this._bufferService.buffer.ydisp; + if (scrollAmount !== 0) { + this.scrollLines(scrollAmount); + } + } + + public paste(data: string): void { + paste(data, this.textarea!, this.coreService, this.optionsService); + } + + public attachCustomKeyEventHandler(customKeyEventHandler: CustomKeyEventHandler): void { + this._customKeyEventHandler = customKeyEventHandler; + } + + public attachCustomWheelEventHandler(customWheelEventHandler: CustomWheelEventHandler): void { + this._customWheelEventHandler = customWheelEventHandler; + } + + public registerLinkProvider(linkProvider: ILinkProvider): IDisposable { + return this._linkProviderService.registerLinkProvider(linkProvider); + } + + public registerCharacterJoiner(handler: CharacterJoinerHandler): number { + if (!this._characterJoinerService) { + throw new Error('Terminal must be opened first'); + } + const joinerId = this._characterJoinerService.register(handler); + this.refresh(0, this.rows - 1); + return joinerId; + } + + public deregisterCharacterJoiner(joinerId: number): void { + if (!this._characterJoinerService) { + throw new Error('Terminal must be opened first'); + } + if (this._characterJoinerService.deregister(joinerId)) { + this.refresh(0, this.rows - 1); + } + } + + public get markers(): IMarker[] { + return this.buffer.markers; + } + + public registerMarker(cursorYOffset: number): IMarker { + return this.buffer.addMarker(this.buffer.ybase + this.buffer.y + cursorYOffset); + } + + public registerDecoration(decorationOptions: IDecorationOptions): IDecoration | undefined { + return this._decorationService.registerDecoration(decorationOptions); + } + + /** + * Gets whether the terminal has an active selection. + */ + public hasSelection(): boolean { + return this._selectionService ? this._selectionService.hasSelection : false; + } + + /** + * Selects text within the terminal. + * @param column The column the selection starts at.. + * @param row The row the selection starts at. + * @param length The length of the selection. + */ + public select(column: number, row: number, length: number): void { + this._selectionService!.setSelection(column, row, length); + } + + /** + * Gets the terminal's current selection, this is useful for implementing copy + * behavior outside of xterm.js. + */ + public getSelection(): string { + return this._selectionService ? this._selectionService.selectionText : ''; + } + + public getSelectionPosition(): IBufferRange | undefined { + if (!this._selectionService || !this._selectionService.hasSelection) { + return undefined; + } + + return { + start: { + x: this._selectionService.selectionStart![0], + y: this._selectionService.selectionStart![1] + }, + end: { + x: this._selectionService.selectionEnd![0], + y: this._selectionService.selectionEnd![1] + } + }; + } + + /** + * Clears the current terminal selection. + */ + public clearSelection(): void { + this._selectionService?.clearSelection(); + } + + /** + * Selects all text within the terminal. + */ + public selectAll(): void { + this._selectionService?.selectAll(); + } + + public selectLines(start: number, end: number): void { + this._selectionService?.selectLines(start, end); + } + + /** + * Handle a keydown [KeyboardEvent]. + * + * [KeyboardEvent]: https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent + */ + protected _keyDown(event: KeyboardEvent): boolean | undefined { + this._keyDownHandled = false; + this._keyDownSeen = true; + + if (this._customKeyEventHandler && this._customKeyEventHandler(event) === false) { + return false; + } + + // Ignore composing with Alt key on Mac when macOptionIsMeta is enabled + const shouldIgnoreComposition = this.browser.isMac && this.options.macOptionIsMeta && event.altKey; + + if (!shouldIgnoreComposition && !this._compositionHelper!.keydown(event)) { + if (this.options.scrollOnUserInput && this.buffer.ybase !== this.buffer.ydisp) { + this.scrollToBottom(true); + } + return false; + } + + if (!shouldIgnoreComposition && (event.key === 'Dead' || event.key === 'AltGraph')) { + this._unprocessedDeadKey = true; + } + + const result = evaluateKeyboardEvent(event, this.coreService.decPrivateModes.applicationCursorKeys, this.browser.isMac, this.options.macOptionIsMeta); + + this.updateCursorStyle(event); + + if (result.type === KeyboardResultType.PAGE_DOWN || result.type === KeyboardResultType.PAGE_UP) { + const scrollCount = this.rows - 1; + this.scrollLines(result.type === KeyboardResultType.PAGE_UP ? -scrollCount : scrollCount); + return this.cancel(event, true); + } + + if (result.type === KeyboardResultType.SELECT_ALL) { + this.selectAll(); + } + + if (this._isThirdLevelShift(this.browser, event)) { + return true; + } + + if (result.cancel) { + // The event is canceled at the end already, is this necessary? + this.cancel(event, true); + } + + if (!result.key) { + return true; + } + + // HACK: Process A-Z in the keypress event to fix an issue with macOS IMEs where lower case + // letters cannot be input while caps lock is on. + if (event.key && !event.ctrlKey && !event.altKey && !event.metaKey && event.key.length === 1) { + if (event.key.charCodeAt(0) >= 65 && event.key.charCodeAt(0) <= 90) { + return true; + } + } + + if (this._unprocessedDeadKey) { + this._unprocessedDeadKey = false; + return true; + } + + // If ctrl+c or enter is being sent, clear out the textarea. This is done so that screen readers + // will announce deleted characters. This will not work 100% of the time but it should cover + // most scenarios. + if (result.key === C0.ETX || result.key === C0.CR) { + this.textarea!.value = ''; + } + + this._onKey.fire({ key: result.key, domEvent: event }); + this._showCursor(); + this.coreService.triggerDataEvent(result.key, true); + + // Cancel events when not in screen reader mode so events don't get bubbled up and handled by + // other listeners. When screen reader mode is enabled, we don't cancel them (unless ctrl or alt + // is also depressed) so that the cursor textarea can be updated, which triggers the screen + // reader to read it. + if (!this.optionsService.rawOptions.screenReaderMode || event.altKey || event.ctrlKey) { + return this.cancel(event, true); + } + + this._keyDownHandled = true; + } + + private _isThirdLevelShift(browser: IBrowser, ev: KeyboardEvent): boolean { + const thirdLevelKey = + (browser.isMac && !this.options.macOptionIsMeta && ev.altKey && !ev.ctrlKey && !ev.metaKey) || + (browser.isWindows && ev.altKey && ev.ctrlKey && !ev.metaKey) || + (browser.isWindows && ev.getModifierState('AltGraph')); + + if (ev.type === 'keypress') { + return thirdLevelKey; + } + + // Don't invoke for arrows, pageDown, home, backspace, etc. (on non-keypress events) + return thirdLevelKey && (!ev.keyCode || ev.keyCode > 47); + } + + protected _keyUp(ev: KeyboardEvent): void { + this._keyDownSeen = false; + + if (this._customKeyEventHandler && this._customKeyEventHandler(ev) === false) { + return; + } + + if (!wasModifierKeyOnlyEvent(ev)) { + this.focus(); + } + + this.updateCursorStyle(ev); + this._keyPressHandled = false; + } + + /** + * Handle a keypress event. + * Key Resources: + * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent + * @param ev The keypress event to be handled. + */ + protected _keyPress(ev: KeyboardEvent): boolean { + let key; + + this._keyPressHandled = false; + + if (this._keyDownHandled) { + return false; + } + + if (this._customKeyEventHandler && this._customKeyEventHandler(ev) === false) { + return false; + } + + this.cancel(ev); + + if (ev.charCode) { + key = ev.charCode; + } else if (ev.which === null || ev.which === undefined) { + key = ev.keyCode; + } else if (ev.which !== 0 && ev.charCode !== 0) { + key = ev.which; + } else { + return false; + } + + if (!key || ( + (ev.altKey || ev.ctrlKey || ev.metaKey) && !this._isThirdLevelShift(this.browser, ev) + )) { + return false; + } + + key = String.fromCharCode(key); + + this._onKey.fire({ key, domEvent: ev }); + this._showCursor(); + this.coreService.triggerDataEvent(key, true); + + this._keyPressHandled = true; + + // The key was handled so clear the dead key state, otherwise certain keystrokes like arrow + // keys could be ignored + this._unprocessedDeadKey = false; + + return true; + } + + /** + * Handle an input event. + * Key Resources: + * - https://developer.mozilla.org/en-US/docs/Web/API/InputEvent + * @param ev The input event to be handled. + */ + protected _inputEvent(ev: InputEvent): boolean { + // Only support emoji IMEs when screen reader mode is disabled as the event must bubble up to + // support reading out character input which can doubling up input characters + // Based on these event traces: https://github.com/xtermjs/xterm.js/issues/3679 + if (ev.data && ev.inputType === 'insertText' && (!ev.composed || !this._keyDownSeen) && !this.optionsService.rawOptions.screenReaderMode) { + if (this._keyPressHandled) { + return false; + } + + // The key was handled so clear the dead key state, otherwise certain keystrokes like arrow + // keys could be ignored + this._unprocessedDeadKey = false; + + const text = ev.data; + this.coreService.triggerDataEvent(text, true); + + this.cancel(ev); + return true; + } + + return false; + } + + /** + * Resizes the terminal. + * + * @param x The number of columns to resize to. + * @param y The number of rows to resize to. + */ + public resize(x: number, y: number): void { + if (x === this.cols && y === this.rows) { + // Check if we still need to measure the char size (fixes #785). + if (this._charSizeService && !this._charSizeService.hasValidSize) { + this._charSizeService.measure(); + } + return; + } + + super.resize(x, y); + } + + private _afterResize(x: number, y: number): void { + this._charSizeService?.measure(); + } + + /** + * Clear the entire buffer, making the prompt line the new first line. + */ + public clear(): void { + if (this.buffer.ybase === 0 && this.buffer.y === 0) { + // Don't clear if it's already clear + return; + } + this.buffer.clearAllMarkers(); + this.buffer.lines.set(0, this.buffer.lines.get(this.buffer.ybase + this.buffer.y)!); + this.buffer.lines.length = 1; + this.buffer.ydisp = 0; + this.buffer.ybase = 0; + this.buffer.y = 0; + for (let i = 1; i < this.rows; i++) { + this.buffer.lines.push(this.buffer.getBlankLine(DEFAULT_ATTR_DATA)); + } + // IMPORTANT: Fire scroll event before viewport is reset. This ensures embedders get the clear + // scroll event and that the viewport's state will be valid for immediate writes. + this._onScroll.fire({ position: this.buffer.ydisp }); + this.refresh(0, this.rows - 1); + } + + /** + * Reset terminal. + * Note: Calling this directly from JS is synchronous but does not clear + * input buffers and does not reset the parser, thus the terminal will + * continue to apply pending input data. + * If you need in band reset (synchronous with input data) consider + * using DECSTR (soft reset, CSI ! p) or RIS instead (hard reset, ESC c). + */ + public reset(): void { + /** + * Since _setup handles a full terminal creation, we have to carry forward + * a few things that should not reset. + */ + this.options.rows = this.rows; + this.options.cols = this.cols; + const customKeyEventHandler = this._customKeyEventHandler; + + this._setup(); + super.reset(); + this._selectionService?.reset(); + this._decorationService.reset(); + + // reattach + this._customKeyEventHandler = customKeyEventHandler; + + // do a full screen refresh + this.refresh(0, this.rows - 1); + } + + public clearTextureAtlas(): void { + this._renderService?.clearTextureAtlas(); + } + + private _reportFocus(): void { + if (this.element?.classList.contains('focus')) { + this.coreService.triggerDataEvent(C0.ESC + '[I'); + } else { + this.coreService.triggerDataEvent(C0.ESC + '[O'); + } + } + + private _reportWindowsOptions(type: WindowsOptionsReportType): void { + if (!this._renderService) { + return; + } + + switch (type) { + case WindowsOptionsReportType.GET_WIN_SIZE_PIXELS: + const canvasWidth = this._renderService.dimensions.css.canvas.width.toFixed(0); + const canvasHeight = this._renderService.dimensions.css.canvas.height.toFixed(0); + this.coreService.triggerDataEvent(`${C0.ESC}[4;${canvasHeight};${canvasWidth}t`); + break; + case WindowsOptionsReportType.GET_CELL_SIZE_PIXELS: + const cellWidth = this._renderService.dimensions.css.cell.width.toFixed(0); + const cellHeight = this._renderService.dimensions.css.cell.height.toFixed(0); + this.coreService.triggerDataEvent(`${C0.ESC}[6;${cellHeight};${cellWidth}t`); + break; + } + } + + // TODO: Remove cancel function and cancelEvents option + public cancel(ev: MouseEvent | WheelEvent | KeyboardEvent | InputEvent, force?: boolean): boolean | undefined { + if (!this.options.cancelEvents && !force) { + return; + } + ev.preventDefault(); + ev.stopPropagation(); + return false; + } +} + +/** + * Helpers + */ + +function wasModifierKeyOnlyEvent(ev: KeyboardEvent): boolean { + return ev.keyCode === 16 || // Shift + ev.keyCode === 17 || // Ctrl + ev.keyCode === 18; // Alt +} diff --git a/node_modules/@xterm/xterm/src/browser/Linkifier.ts b/node_modules/@xterm/xterm/src/browser/Linkifier.ts new file mode 100644 index 0000000..c5c31d6 --- /dev/null +++ b/node_modules/@xterm/xterm/src/browser/Linkifier.ts @@ -0,0 +1,403 @@ +/** + * Copyright (c) 2019 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { IBufferCellPosition, ILink, ILinkDecorations, ILinkWithState, ILinkifier2, ILinkifierEvent } from 'browser/Types'; +import { Disposable, dispose, toDisposable } from 'vs/base/common/lifecycle'; +import { IDisposable } from 'common/Types'; +import { IBufferService } from 'common/services/Services'; +import { ILinkProviderService, IMouseService, IRenderService } from './services/Services'; +import { Emitter } from 'vs/base/common/event'; +import { addDisposableListener } from 'vs/base/browser/dom'; + +export class Linkifier extends Disposable implements ILinkifier2 { + public get currentLink(): ILinkWithState | undefined { return this._currentLink; } + protected _currentLink: ILinkWithState | undefined; + private _mouseDownLink: ILinkWithState | undefined; + private _lastMouseEvent: MouseEvent | undefined; + private _linkCacheDisposables: IDisposable[] = []; + private _lastBufferCell: IBufferCellPosition | undefined; + private _isMouseOut: boolean = true; + private _wasResized: boolean = false; + private _activeProviderReplies: Map | undefined; + private _activeLine: number = -1; + + private readonly _onShowLinkUnderline = this._register(new Emitter()); + public readonly onShowLinkUnderline = this._onShowLinkUnderline.event; + private readonly _onHideLinkUnderline = this._register(new Emitter()); + public readonly onHideLinkUnderline = this._onHideLinkUnderline.event; + + constructor( + private readonly _element: HTMLElement, + @IMouseService private readonly _mouseService: IMouseService, + @IRenderService private readonly _renderService: IRenderService, + @IBufferService private readonly _bufferService: IBufferService, + @ILinkProviderService private readonly _linkProviderService: ILinkProviderService + ) { + super(); + this._register(toDisposable(() => { + dispose(this._linkCacheDisposables); + this._linkCacheDisposables.length = 0; + this._lastMouseEvent = undefined; + // Clear out link providers as they could easily cause an embedder memory leak + this._activeProviderReplies?.clear(); + })); + // Listen to resize to catch the case where it's resized and the cursor is out of the viewport. + this._register(this._bufferService.onResize(() => { + this._clearCurrentLink(); + this._wasResized = true; + })); + this._register(addDisposableListener(this._element, 'mouseleave', () => { + this._isMouseOut = true; + this._clearCurrentLink(); + })); + this._register(addDisposableListener(this._element, 'mousemove', this._handleMouseMove.bind(this))); + this._register(addDisposableListener(this._element, 'mousedown', this._handleMouseDown.bind(this))); + this._register(addDisposableListener(this._element, 'mouseup', this._handleMouseUp.bind(this))); + } + + private _handleMouseMove(event: MouseEvent): void { + this._lastMouseEvent = event; + + const position = this._positionFromMouseEvent(event, this._element, this._mouseService); + if (!position) { + return; + } + this._isMouseOut = false; + + // Ignore the event if it's an embedder created hover widget + const composedPath = event.composedPath() as HTMLElement[]; + for (let i = 0; i < composedPath.length; i++) { + const target = composedPath[i]; + // Hit Terminal.element, break and continue + if (target.classList.contains('xterm')) { + break; + } + // It's a hover, don't respect hover event + if (target.classList.contains('xterm-hover')) { + return; + } + } + + if (!this._lastBufferCell || (position.x !== this._lastBufferCell.x || position.y !== this._lastBufferCell.y)) { + this._handleHover(position); + this._lastBufferCell = position; + } + } + + private _handleHover(position: IBufferCellPosition): void { + // TODO: This currently does not cache link provider results across wrapped lines, activeLine + // should be something like `activeRange: {startY, endY}` + // Check if we need to clear the link + if (this._activeLine !== position.y || this._wasResized) { + this._clearCurrentLink(); + this._askForLink(position, false); + this._wasResized = false; + return; + } + + // Check the if the link is in the mouse position + const isCurrentLinkInPosition = this._currentLink && this._linkAtPosition(this._currentLink.link, position); + if (!isCurrentLinkInPosition) { + this._clearCurrentLink(); + this._askForLink(position, true); + } + } + + private _askForLink(position: IBufferCellPosition, useLineCache: boolean): void { + if (!this._activeProviderReplies || !useLineCache) { + this._activeProviderReplies?.forEach(reply => { + reply?.forEach(linkWithState => { + if (linkWithState.link.dispose) { + linkWithState.link.dispose(); + } + }); + }); + this._activeProviderReplies = new Map(); + this._activeLine = position.y; + } + let linkProvided = false; + + // There is no link cached, so ask for one + for (const [i, linkProvider] of this._linkProviderService.linkProviders.entries()) { + if (useLineCache) { + const existingReply = this._activeProviderReplies?.get(i); + // If there isn't a reply, the provider hasn't responded yet. + + // TODO: If there isn't a reply yet it means that the provider is still resolving. Ensuring + // provideLinks isn't triggered again saves ILink.hover firing twice though. This probably + // needs promises to get fixed + if (existingReply) { + linkProvided = this._checkLinkProviderResult(i, position, linkProvided); + } + } else { + linkProvider.provideLinks(position.y, (links: ILink[] | undefined) => { + if (this._isMouseOut) { + return; + } + const linksWithState: ILinkWithState[] | undefined = links?.map(link => ({ link })); + this._activeProviderReplies?.set(i, linksWithState); + linkProvided = this._checkLinkProviderResult(i, position, linkProvided); + + // If all providers have responded, remove lower priority links that intersect ranges of + // higher priority links + if (this._activeProviderReplies?.size === this._linkProviderService.linkProviders.length) { + this._removeIntersectingLinks(position.y, this._activeProviderReplies); + } + }); + } + } + } + + private _removeIntersectingLinks(y: number, replies: Map): void { + const occupiedCells = new Set(); + for (let i = 0; i < replies.size; i++) { + const providerReply = replies.get(i); + if (!providerReply) { + continue; + } + for (let i = 0; i < providerReply.length; i++) { + const linkWithState = providerReply[i]; + const startX = linkWithState.link.range.start.y < y ? 0 : linkWithState.link.range.start.x; + const endX = linkWithState.link.range.end.y > y ? this._bufferService.cols : linkWithState.link.range.end.x; + for (let x = startX; x <= endX; x++) { + if (occupiedCells.has(x)) { + providerReply.splice(i--, 1); + break; + } + occupiedCells.add(x); + } + } + } + } + + private _checkLinkProviderResult(index: number, position: IBufferCellPosition, linkProvided: boolean): boolean { + if (!this._activeProviderReplies) { + return linkProvided; + } + + const links = this._activeProviderReplies.get(index); + + // Check if every provider before this one has come back undefined + let hasLinkBefore = false; + for (let j = 0; j < index; j++) { + if (!this._activeProviderReplies.has(j) || this._activeProviderReplies.get(j)) { + hasLinkBefore = true; + } + } + + // If all providers with higher priority came back undefined, then this provider's link for + // the position should be used + if (!hasLinkBefore && links) { + const linkAtPosition = links.find(link => this._linkAtPosition(link.link, position)); + if (linkAtPosition) { + linkProvided = true; + this._handleNewLink(linkAtPosition); + } + } + + // Check if all the providers have responded + if (this._activeProviderReplies.size === this._linkProviderService.linkProviders.length && !linkProvided) { + // Respect the order of the link providers + for (let j = 0; j < this._activeProviderReplies.size; j++) { + const currentLink = this._activeProviderReplies.get(j)?.find(link => this._linkAtPosition(link.link, position)); + if (currentLink) { + linkProvided = true; + this._handleNewLink(currentLink); + break; + } + } + } + + return linkProvided; + } + + private _handleMouseDown(): void { + this._mouseDownLink = this._currentLink; + } + + private _handleMouseUp(event: MouseEvent): void { + if (!this._currentLink) { + return; + } + + const position = this._positionFromMouseEvent(event, this._element, this._mouseService); + if (!position) { + return; + } + + if (this._mouseDownLink && linkEquals(this._mouseDownLink.link, this._currentLink.link) && this._linkAtPosition(this._currentLink.link, position)) { + this._currentLink.link.activate(event, this._currentLink.link.text); + } + } + + private _clearCurrentLink(startRow?: number, endRow?: number): void { + if (!this._currentLink || !this._lastMouseEvent) { + return; + } + + // If we have a start and end row, check that the link is within it + if (!startRow || !endRow || (this._currentLink.link.range.start.y >= startRow && this._currentLink.link.range.end.y <= endRow)) { + this._linkLeave(this._element, this._currentLink.link, this._lastMouseEvent); + this._currentLink = undefined; + dispose(this._linkCacheDisposables); + this._linkCacheDisposables.length = 0; + } + } + + private _handleNewLink(linkWithState: ILinkWithState): void { + if (!this._lastMouseEvent) { + return; + } + + const position = this._positionFromMouseEvent(this._lastMouseEvent, this._element, this._mouseService); + + if (!position) { + return; + } + + // Trigger hover if the we have a link at the position + if (this._linkAtPosition(linkWithState.link, position)) { + this._currentLink = linkWithState; + this._currentLink.state = { + decorations: { + underline: linkWithState.link.decorations === undefined ? true : linkWithState.link.decorations.underline, + pointerCursor: linkWithState.link.decorations === undefined ? true : linkWithState.link.decorations.pointerCursor + }, + isHovered: true + }; + this._linkHover(this._element, linkWithState.link, this._lastMouseEvent); + + // Add listener for tracking decorations changes + linkWithState.link.decorations = {} as ILinkDecorations; + Object.defineProperties(linkWithState.link.decorations, { + pointerCursor: { + get: () => this._currentLink?.state?.decorations.pointerCursor, + set: v => { + if (this._currentLink?.state && this._currentLink.state.decorations.pointerCursor !== v) { + this._currentLink.state.decorations.pointerCursor = v; + if (this._currentLink.state.isHovered) { + this._element.classList.toggle('xterm-cursor-pointer', v); + } + } + } + }, + underline: { + get: () => this._currentLink?.state?.decorations.underline, + set: v => { + if (this._currentLink?.state && this._currentLink?.state?.decorations.underline !== v) { + this._currentLink.state.decorations.underline = v; + if (this._currentLink.state.isHovered) { + this._fireUnderlineEvent(linkWithState.link, v); + } + } + } + } + }); + + // Listen to viewport changes to re-render the link under the cursor (only when the line the + // link is on changes) + this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(e => { + // Sanity check, this shouldn't happen in practice as this listener would be disposed + if (!this._currentLink) { + return; + } + // When start is 0 a scroll most likely occurred, make sure links above the fold also get + // cleared. + const start = e.start === 0 ? 0 : e.start + 1 + this._bufferService.buffer.ydisp; + const end = this._bufferService.buffer.ydisp + 1 + e.end; + // Only clear the link if the viewport change happened on this line + if (this._currentLink.link.range.start.y >= start && this._currentLink.link.range.end.y <= end) { + this._clearCurrentLink(start, end); + if (this._lastMouseEvent) { + // re-eval previously active link after changes + const position = this._positionFromMouseEvent(this._lastMouseEvent, this._element, this._mouseService!); + if (position) { + this._askForLink(position, false); + } + } + } + })); + } + } + + protected _linkHover(element: HTMLElement, link: ILink, event: MouseEvent): void { + if (this._currentLink?.state) { + this._currentLink.state.isHovered = true; + if (this._currentLink.state.decorations.underline) { + this._fireUnderlineEvent(link, true); + } + if (this._currentLink.state.decorations.pointerCursor) { + element.classList.add('xterm-cursor-pointer'); + } + } + + if (link.hover) { + link.hover(event, link.text); + } + } + + private _fireUnderlineEvent(link: ILink, showEvent: boolean): void { + const range = link.range; + const scrollOffset = this._bufferService.buffer.ydisp; + const event = this._createLinkUnderlineEvent(range.start.x - 1, range.start.y - scrollOffset - 1, range.end.x, range.end.y - scrollOffset - 1, undefined); + const emitter = showEvent ? this._onShowLinkUnderline : this._onHideLinkUnderline; + emitter.fire(event); + } + + protected _linkLeave(element: HTMLElement, link: ILink, event: MouseEvent): void { + if (this._currentLink?.state) { + this._currentLink.state.isHovered = false; + if (this._currentLink.state.decorations.underline) { + this._fireUnderlineEvent(link, false); + } + if (this._currentLink.state.decorations.pointerCursor) { + element.classList.remove('xterm-cursor-pointer'); + } + } + + if (link.leave) { + link.leave(event, link.text); + } + } + + /** + * Check if the buffer position is within the link + * @param link + * @param position + */ + private _linkAtPosition(link: ILink, position: IBufferCellPosition): boolean { + const lower = link.range.start.y * this._bufferService.cols + link.range.start.x; + const upper = link.range.end.y * this._bufferService.cols + link.range.end.x; + const current = position.y * this._bufferService.cols + position.x; + return (lower <= current && current <= upper); + } + + /** + * Get the buffer position from a mouse event + * @param event + */ + private _positionFromMouseEvent(event: MouseEvent, element: HTMLElement, mouseService: IMouseService): IBufferCellPosition | undefined { + const coords = mouseService.getCoords(event, element, this._bufferService.cols, this._bufferService.rows); + if (!coords) { + return; + } + + return { x: coords[0], y: coords[1] + this._bufferService.buffer.ydisp }; + } + + private _createLinkUnderlineEvent(x1: number, y1: number, x2: number, y2: number, fg: number | undefined): ILinkifierEvent { + return { x1, y1, x2, y2, cols: this._bufferService.cols, fg }; + } +} + +function linkEquals(a: ILink, b: ILink): boolean { + return ( + a.text === b.text && + a.range.start.x === b.range.start.x && + a.range.start.y === b.range.start.y && + a.range.end.x === b.range.end.x && + a.range.end.y === b.range.end.y + ); +} diff --git a/node_modules/@xterm/xterm/src/browser/LocalizableStrings.ts b/node_modules/@xterm/xterm/src/browser/LocalizableStrings.ts new file mode 100644 index 0000000..32055ce --- /dev/null +++ b/node_modules/@xterm/xterm/src/browser/LocalizableStrings.ts @@ -0,0 +1,23 @@ +/** + * Copyright (c) 2018 The xterm.js authors. All rights reserved. + * @license MIT + */ + +// This file contains strings that get exported in the API so they can be localized + +let promptLabelInternal = 'Terminal input'; +const promptLabel = { + get: () => promptLabelInternal, + set: (value: string) => promptLabelInternal = value +}; + +let tooMuchOutputInternal = 'Too much output to announce, navigate to rows manually to read'; +const tooMuchOutput = { + get: () => tooMuchOutputInternal, + set: (value: string) => tooMuchOutputInternal = value +}; + +export { + promptLabel, + tooMuchOutput +}; diff --git a/node_modules/@xterm/xterm/src/browser/OscLinkProvider.ts b/node_modules/@xterm/xterm/src/browser/OscLinkProvider.ts new file mode 100644 index 0000000..a079fe6 --- /dev/null +++ b/node_modules/@xterm/xterm/src/browser/OscLinkProvider.ts @@ -0,0 +1,129 @@ +/** + * Copyright (c) 2022 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { IBufferRange, ILink } from 'browser/Types'; +import { ILinkProvider } from 'browser/services/Services'; +import { CellData } from 'common/buffer/CellData'; +import { IBufferService, IOptionsService, IOscLinkService } from 'common/services/Services'; + +export class OscLinkProvider implements ILinkProvider { + constructor( + @IBufferService private readonly _bufferService: IBufferService, + @IOptionsService private readonly _optionsService: IOptionsService, + @IOscLinkService private readonly _oscLinkService: IOscLinkService + ) { + } + + public provideLinks(y: number, callback: (links: ILink[] | undefined) => void): void { + const line = this._bufferService.buffer.lines.get(y - 1); + if (!line) { + callback(undefined); + return; + } + + const result: ILink[] = []; + const linkHandler = this._optionsService.rawOptions.linkHandler; + const cell = new CellData(); + const lineLength = line.getTrimmedLength(); + let currentLinkId = -1; + let currentStart = -1; + let finishLink = false; + for (let x = 0; x < lineLength; x++) { + // Minor optimization, only check for content if there isn't a link in case the link ends with + // a null cell + if (currentStart === -1 && !line.hasContent(x)) { + continue; + } + + line.loadCell(x, cell); + if (cell.hasExtendedAttrs() && cell.extended.urlId) { + if (currentStart === -1) { + currentStart = x; + currentLinkId = cell.extended.urlId; + continue; + } else { + finishLink = cell.extended.urlId !== currentLinkId; + } + } else { + if (currentStart !== -1) { + finishLink = true; + } + } + + if (finishLink || (currentStart !== -1 && x === lineLength - 1)) { + const text = this._oscLinkService.getLinkData(currentLinkId)?.uri; + if (text) { + // These ranges are 1-based + const range: IBufferRange = { + start: { + x: currentStart + 1, + y + }, + end: { + // Offset end x if it's a link that ends on the last cell in the line + x: x + (!finishLink && x === lineLength - 1 ? 1 : 0), + y + } + }; + + let ignoreLink = false; + if (!linkHandler?.allowNonHttpProtocols) { + try { + const parsed = new URL(text); + if (!['http:', 'https:'].includes(parsed.protocol)) { + ignoreLink = true; + } + } catch (e) { + // Ignore invalid URLs to prevent unexpected behaviors + ignoreLink = true; + } + } + + if (!ignoreLink) { + // OSC links always use underline and pointer decorations + result.push({ + text, + range, + activate: (e, text) => (linkHandler ? linkHandler.activate(e, text, range) : defaultActivate(e, text)), + hover: (e, text) => linkHandler?.hover?.(e, text, range), + leave: (e, text) => linkHandler?.leave?.(e, text, range) + }); + } + } + finishLink = false; + + // Clear link or start a new link if one starts immediately + if (cell.hasExtendedAttrs() && cell.extended.urlId) { + currentStart = x; + currentLinkId = cell.extended.urlId; + } else { + currentStart = -1; + currentLinkId = -1; + } + } + } + + // TODO: Handle fetching and returning other link ranges to underline other links with the same + // id + callback(result); + } +} + +function defaultActivate(e: MouseEvent, uri: string): void { + const answer = confirm(`Do you want to navigate to ${uri}?\n\nWARNING: This link could potentially be dangerous`); + if (answer) { + const newWindow = window.open(); + if (newWindow) { + try { + newWindow.opener = null; + } catch { + // no-op, Electron can throw + } + newWindow.location.href = uri; + } else { + console.warn('Opening link blocked as opener could not be cleared'); + } + } +} diff --git a/node_modules/@xterm/xterm/src/browser/RenderDebouncer.ts b/node_modules/@xterm/xterm/src/browser/RenderDebouncer.ts new file mode 100644 index 0000000..dd3b97a --- /dev/null +++ b/node_modules/@xterm/xterm/src/browser/RenderDebouncer.ts @@ -0,0 +1,84 @@ +/** + * Copyright (c) 2018 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { IRenderDebouncerWithCallback } from 'browser/Types'; +import { ICoreBrowserService } from 'browser/services/Services'; + +/** + * Debounces calls to render terminal rows using animation frames. + */ +export class RenderDebouncer implements IRenderDebouncerWithCallback { + private _rowStart: number | undefined; + private _rowEnd: number | undefined; + private _rowCount: number | undefined; + private _animationFrame: number | undefined; + private _refreshCallbacks: FrameRequestCallback[] = []; + + constructor( + private _renderCallback: (start: number, end: number) => void, + private readonly _coreBrowserService: ICoreBrowserService + ) { + } + + public dispose(): void { + if (this._animationFrame) { + this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame); + this._animationFrame = undefined; + } + } + + public addRefreshCallback(callback: FrameRequestCallback): number { + this._refreshCallbacks.push(callback); + if (!this._animationFrame) { + this._animationFrame = this._coreBrowserService.window.requestAnimationFrame(() => this._innerRefresh()); + } + return this._animationFrame; + } + + public refresh(rowStart: number | undefined, rowEnd: number | undefined, rowCount: number): void { + this._rowCount = rowCount; + // Get the min/max row start/end for the arg values + rowStart = rowStart !== undefined ? rowStart : 0; + rowEnd = rowEnd !== undefined ? rowEnd : this._rowCount - 1; + // Set the properties to the updated values + this._rowStart = this._rowStart !== undefined ? Math.min(this._rowStart, rowStart) : rowStart; + this._rowEnd = this._rowEnd !== undefined ? Math.max(this._rowEnd, rowEnd) : rowEnd; + + if (this._animationFrame) { + return; + } + + this._animationFrame = this._coreBrowserService.window.requestAnimationFrame(() => this._innerRefresh()); + } + + private _innerRefresh(): void { + this._animationFrame = undefined; + + // Make sure values are set + if (this._rowStart === undefined || this._rowEnd === undefined || this._rowCount === undefined) { + this._runRefreshCallbacks(); + return; + } + + // Clamp values + const start = Math.max(this._rowStart, 0); + const end = Math.min(this._rowEnd, this._rowCount - 1); + + // Reset debouncer (this happens before render callback as the render could trigger it again) + this._rowStart = undefined; + this._rowEnd = undefined; + + // Run render callback + this._renderCallback(start, end); + this._runRefreshCallbacks(); + } + + private _runRefreshCallbacks(): void { + for (const callback of this._refreshCallbacks) { + callback(0); + } + this._refreshCallbacks = []; + } +} diff --git a/node_modules/@xterm/xterm/src/browser/TimeBasedDebouncer.ts b/node_modules/@xterm/xterm/src/browser/TimeBasedDebouncer.ts new file mode 100644 index 0000000..4d7a65a --- /dev/null +++ b/node_modules/@xterm/xterm/src/browser/TimeBasedDebouncer.ts @@ -0,0 +1,86 @@ +/** + * Copyright (c) 2018 The xterm.js authors. All rights reserved. + * @license MIT + */ + +const RENDER_DEBOUNCE_THRESHOLD_MS = 1000; // 1 Second + +import { IRenderDebouncer } from 'browser/Types'; + +/** + * Debounces calls to update screen readers to update at most once configurable interval of time. + */ +export class TimeBasedDebouncer implements IRenderDebouncer { + private _rowStart: number | undefined; + private _rowEnd: number | undefined; + private _rowCount: number | undefined; + + // The last moment that the Terminal was refreshed at + private _lastRefreshMs = 0; + // Whether a trailing refresh should be triggered due to a refresh request that was throttled + private _additionalRefreshRequested = false; + + private _refreshTimeoutID: number | undefined; + + constructor( + private _renderCallback: (start: number, end: number) => void, + private readonly _debounceThresholdMS = RENDER_DEBOUNCE_THRESHOLD_MS + ) { + } + + public dispose(): void { + if (this._refreshTimeoutID) { + clearTimeout(this._refreshTimeoutID); + } + } + + public refresh(rowStart: number | undefined, rowEnd: number | undefined, rowCount: number): void { + this._rowCount = rowCount; + // Get the min/max row start/end for the arg values + rowStart = rowStart !== undefined ? rowStart : 0; + rowEnd = rowEnd !== undefined ? rowEnd : this._rowCount - 1; + // Set the properties to the updated values + this._rowStart = this._rowStart !== undefined ? Math.min(this._rowStart, rowStart) : rowStart; + this._rowEnd = this._rowEnd !== undefined ? Math.max(this._rowEnd, rowEnd) : rowEnd; + + // Only refresh if the time since last refresh is above a threshold, otherwise wait for + // enough time to pass before refreshing again. + const refreshRequestTime: number = performance.now(); + if (refreshRequestTime - this._lastRefreshMs >= this._debounceThresholdMS) { + // Enough time has lapsed since the last refresh; refresh immediately + this._lastRefreshMs = refreshRequestTime; + this._innerRefresh(); + } else if (!this._additionalRefreshRequested) { + // This is the first additional request throttled; set up trailing refresh + const elapsed = refreshRequestTime - this._lastRefreshMs; + const waitPeriodBeforeTrailingRefresh = this._debounceThresholdMS - elapsed; + this._additionalRefreshRequested = true; + + this._refreshTimeoutID = window.setTimeout(() => { + this._lastRefreshMs = performance.now(); + this._innerRefresh(); + this._additionalRefreshRequested = false; + this._refreshTimeoutID = undefined; // No longer need to clear the timeout + }, waitPeriodBeforeTrailingRefresh); + } + } + + private _innerRefresh(): void { + // Make sure values are set + if (this._rowStart === undefined || this._rowEnd === undefined || this._rowCount === undefined) { + return; + } + + // Clamp values + const start = Math.max(this._rowStart, 0); + const end = Math.min(this._rowEnd, this._rowCount - 1); + + // Reset debouncer (this happens before render callback as the render could trigger it again) + this._rowStart = undefined; + this._rowEnd = undefined; + + // Run render callback + this._renderCallback(start, end); + } +} + diff --git a/node_modules/@xterm/xterm/src/browser/Types.ts b/node_modules/@xterm/xterm/src/browser/Types.ts new file mode 100644 index 0000000..10e6041 --- /dev/null +++ b/node_modules/@xterm/xterm/src/browser/Types.ts @@ -0,0 +1,226 @@ +/** + * Copyright (c) 2017 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { CharData, IColor, ICoreTerminal, ITerminalOptions } from 'common/Types'; +import { IBuffer } from 'common/buffer/Types'; +import { IDisposable, Terminal as ITerminalApi } from '@xterm/xterm'; +import { channels, css } from 'common/Color'; +import type { Event } from 'vs/base/common/event'; + +/** + * A portion of the public API that are implemented identially internally and simply passed through. + */ +type InternalPassthroughApis = Omit; + +export interface ITerminal extends InternalPassthroughApis, ICoreTerminal { + screenElement: HTMLElement | undefined; + browser: IBrowser; + buffer: IBuffer; + linkifier: ILinkifier2 | undefined; + options: Required; + + onBlur: Event; + onFocus: Event; + onA11yChar: Event; + onA11yTab: Event; + onWillOpen: Event; + + cancel(ev: MouseEvent | WheelEvent | KeyboardEvent | InputEvent, force?: boolean): boolean | void; +} + +export type CustomKeyEventHandler = (event: KeyboardEvent) => boolean; +export type CustomWheelEventHandler = (event: WheelEvent) => boolean; + +export type LineData = CharData[]; + +export interface ICompositionHelper { + readonly isComposing: boolean; + compositionstart(): void; + compositionupdate(ev: CompositionEvent): void; + compositionend(): void; + updateCompositionElements(dontRecurse?: boolean): void; + keydown(ev: KeyboardEvent): boolean; +} + +export interface IBrowser { + isNode: boolean; + userAgent: string; + platform: string; + isFirefox: boolean; + isMac: boolean; + isIpad: boolean; + isIphone: boolean; + isWindows: boolean; +} + +export interface IColorSet { + foreground: IColor; + background: IColor; + cursor: IColor; + cursorAccent: IColor; + selectionForeground: IColor | undefined; + selectionBackgroundTransparent: IColor; + /** The selection blended on top of background. */ + selectionBackgroundOpaque: IColor; + selectionInactiveBackgroundTransparent: IColor; + selectionInactiveBackgroundOpaque: IColor; + scrollbarSliderBackground: IColor; + scrollbarSliderHoverBackground: IColor; + scrollbarSliderActiveBackground: IColor; + overviewRulerBorder: IColor; + ansi: IColor[]; + /** Maps original colors to colors that respect minimum contrast ratio. */ + contrastCache: IColorContrastCache; + /** Maps original colors to colors that respect _half_ of the minimum contrast ratio. */ + halfContrastCache: IColorContrastCache; +} + +export type ReadonlyColorSet = Readonly> & { ansi: Readonly['ansi']> }; + +export interface IColorContrastCache { + clear(): void; + setCss(bg: number, fg: number, value: string | null): void; + getCss(bg: number, fg: number): string | null | undefined; + setColor(bg: number, fg: number, value: IColor | null): void; + getColor(bg: number, fg: number): IColor | null | undefined; +} + +export interface IPartialColorSet { + foreground: IColor; + background: IColor; + cursor?: IColor; + cursorAccent?: IColor; + selectionBackground?: IColor; + ansi: IColor[]; +} + +export interface IViewport extends IDisposable { + scrollBarWidth: number; + readonly onRequestScrollLines: Event<{ amount: number, suppressScrollEvent: boolean }>; + syncScrollArea(immediate?: boolean, force?: boolean): void; + getLinesScrolled(ev: WheelEvent): number; + getBufferElements(startLine: number, endLine?: number): { bufferElements: HTMLElement[], cursorElement?: HTMLElement }; + handleWheel(ev: WheelEvent): boolean; + handleTouchStart(ev: TouchEvent): void; + handleTouchMove(ev: TouchEvent): boolean; + scrollLines(disp: number): void; // todo api name? + reset(): void; +} + +export interface ILinkifierEvent { + x1: number; + y1: number; + x2: number; + y2: number; + cols: number; + fg: number | undefined; +} + +interface ILinkState { + decorations: ILinkDecorations; + isHovered: boolean; +} +export interface ILinkWithState { + link: ILink; + state?: ILinkState; +} + +export interface ILinkifier2 extends IDisposable { + onShowLinkUnderline: Event; + onHideLinkUnderline: Event; + readonly currentLink: ILinkWithState | undefined; +} + +export interface ILink { + range: IBufferRange; + text: string; + decorations?: ILinkDecorations; + activate(event: MouseEvent, text: string): void; + hover?(event: MouseEvent, text: string): void; + leave?(event: MouseEvent, text: string): void; + dispose?(): void; +} + +export interface ILinkDecorations { + pointerCursor: boolean; + underline: boolean; +} + +export interface IBufferRange { + start: IBufferCellPosition; + end: IBufferCellPosition; +} + +export interface IBufferCellPosition { + x: number; + y: number; +} + +export type CharacterJoinerHandler = (text: string) => [number, number][]; + +export interface ICharacterJoiner { + id: number; + handler: CharacterJoinerHandler; +} + +export interface IRenderDebouncer extends IDisposable { + refresh(rowStart: number | undefined, rowEnd: number | undefined, rowCount: number): void; +} + +export interface IRenderDebouncerWithCallback extends IRenderDebouncer { + addRefreshCallback(callback: FrameRequestCallback): number; +} + +export interface IBufferElementProvider { + provideBufferElements(): DocumentFragment | HTMLElement; +} + +// An IIFE to generate DEFAULT_ANSI_COLORS. +export const DEFAULT_ANSI_COLORS = Object.freeze((() => { + const colors = [ + // dark: + css.toColor('#2e3436'), + css.toColor('#cc0000'), + css.toColor('#4e9a06'), + css.toColor('#c4a000'), + css.toColor('#3465a4'), + css.toColor('#75507b'), + css.toColor('#06989a'), + css.toColor('#d3d7cf'), + // bright: + css.toColor('#555753'), + css.toColor('#ef2929'), + css.toColor('#8ae234'), + css.toColor('#fce94f'), + css.toColor('#729fcf'), + css.toColor('#ad7fa8'), + css.toColor('#34e2e2'), + css.toColor('#eeeeec') + ]; + + // Fill in the remaining 240 ANSI colors. + // Generate colors (16-231) + const v = [0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff]; + for (let i = 0; i < 216; i++) { + const r = v[(i / 36) % 6 | 0]; + const g = v[(i / 6) % 6 | 0]; + const b = v[i % 6]; + colors.push({ + css: channels.toCss(r, g, b), + rgba: channels.toRgba(r, g, b) + }); + } + + // Generate greys (232-255) + for (let i = 0; i < 24; i++) { + const c = 8 + i * 10; + colors.push({ + css: channels.toCss(c, c, c), + rgba: channels.toRgba(c, c, c) + }); + } + + return colors; +})()); diff --git a/node_modules/@xterm/xterm/src/browser/Viewport.ts b/node_modules/@xterm/xterm/src/browser/Viewport.ts new file mode 100644 index 0000000..1a9f222 --- /dev/null +++ b/node_modules/@xterm/xterm/src/browser/Viewport.ts @@ -0,0 +1,192 @@ +/** + * Copyright (c) 2024 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { ICoreBrowserService, IRenderService, IThemeService } from 'browser/services/Services'; +import { ViewportConstants } from 'browser/shared/Constants'; +import { Disposable, toDisposable } from 'vs/base/common/lifecycle'; +import { IBufferService, ICoreMouseService, IOptionsService } from 'common/services/Services'; +import { CoreMouseEventType } from 'common/Types'; +import { scheduleAtNextAnimationFrame } from 'vs/base/browser/dom'; +import { SmoothScrollableElement } from 'vs/base/browser/ui/scrollbar/scrollableElement'; +import type { ScrollableElementChangeOptions } from 'vs/base/browser/ui/scrollbar/scrollableElementOptions'; +import { Emitter, Event } from 'vs/base/common/event'; +import { Scrollable, ScrollbarVisibility, type ScrollEvent } from 'vs/base/common/scrollable'; + +export class Viewport extends Disposable { + + protected _onRequestScrollLines = this._register(new Emitter()); + public readonly onRequestScrollLines = this._onRequestScrollLines.event; + + private _scrollableElement: SmoothScrollableElement; + private _styleElement: HTMLStyleElement; + + private _queuedAnimationFrame?: number; + private _latestYDisp?: number; + private _isSyncing: boolean = false; + private _isHandlingScroll: boolean = false; + private _suppressOnScrollHandler: boolean = false; + + constructor( + element: HTMLElement, + screenElement: HTMLElement, + @IBufferService private readonly _bufferService: IBufferService, + @ICoreBrowserService coreBrowserService: ICoreBrowserService, + @ICoreMouseService coreMouseService: ICoreMouseService, + @IThemeService themeService: IThemeService, + @IOptionsService private readonly _optionsService: IOptionsService, + @IRenderService private readonly _renderService: IRenderService + ) { + super(); + + const scrollable = this._register(new Scrollable({ + forceIntegerValues: false, + smoothScrollDuration: this._optionsService.rawOptions.smoothScrollDuration, + // This is used over `IRenderService.addRefreshCallback` since it can be canceled + scheduleAtNextAnimationFrame: cb => scheduleAtNextAnimationFrame(coreBrowserService.window, cb) + })); + this._register(this._optionsService.onSpecificOptionChange('smoothScrollDuration', () => { + scrollable.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration); + })); + + this._scrollableElement = this._register(new SmoothScrollableElement(screenElement, { + vertical: ScrollbarVisibility.Auto, + horizontal: ScrollbarVisibility.Hidden, + useShadows: false, + mouseWheelSmoothScroll: true, + ...this._getChangeOptions() + }, scrollable)); + this._register(this._optionsService.onMultipleOptionChange([ + 'scrollSensitivity', + 'fastScrollSensitivity', + 'overviewRuler' + ], () => this._scrollableElement.updateOptions(this._getChangeOptions()))); + // Don't handle mouse wheel if wheel events are supported by the current mouse prototcol + this._register(coreMouseService.onProtocolChange(type => { + this._scrollableElement.updateOptions({ + handleMouseWheel: !(type & CoreMouseEventType.WHEEL) + }); + })); + + this._scrollableElement.setScrollDimensions({ height: 0, scrollHeight: 0 }); + this._register(Event.runAndSubscribe(themeService.onChangeColors, () => { + this._scrollableElement.getDomNode().style.backgroundColor = themeService.colors.background.css; + })); + element.appendChild(this._scrollableElement.getDomNode()); + this._register(toDisposable(() => this._scrollableElement.getDomNode().remove())); + + this._styleElement = coreBrowserService.mainDocument.createElement('style'); + screenElement.appendChild(this._styleElement); + this._register(toDisposable(() => this._styleElement.remove())); + this._register(Event.runAndSubscribe(themeService.onChangeColors, () => { + this._styleElement.textContent = [ + `.xterm .xterm-scrollable-element > .scrollbar > .slider {`, + ` background: ${themeService.colors.scrollbarSliderBackground.css};`, + `}`, + `.xterm .xterm-scrollable-element > .scrollbar > .slider:hover {`, + ` background: ${themeService.colors.scrollbarSliderHoverBackground.css};`, + `}`, + `.xterm .xterm-scrollable-element > .scrollbar > .slider.active {`, + ` background: ${themeService.colors.scrollbarSliderActiveBackground.css};`, + `}` + ].join('\n'); + })); + + this._register(this._bufferService.onResize(() => this.queueSync())); + this._register(this._bufferService.buffers.onBufferActivate(() => { + // Reset _latestYDisp when switching buffers to prevent stale scroll position + // from alt buffer contaminating normal buffer scroll position + this._latestYDisp = undefined; + this.queueSync(); + })); + this._register(this._bufferService.onScroll(() => this._sync())); + + this._register(this._scrollableElement.onScroll(e => this._handleScroll(e))); + } + + public scrollLines(disp: number): void { + const pos = this._scrollableElement.getScrollPosition(); + this._scrollableElement.setScrollPosition({ + reuseAnimation: true, + scrollTop: pos.scrollTop + disp * this._renderService.dimensions.css.cell.height + }); + } + + public scrollToLine(line: number, disableSmoothScroll?: boolean): void { + if (disableSmoothScroll) { + this._latestYDisp = line; + } + this._scrollableElement.setScrollPosition({ + reuseAnimation: !disableSmoothScroll, + scrollTop: line * this._renderService.dimensions.css.cell.height + }); + } + + private _getChangeOptions(): ScrollableElementChangeOptions { + return { + mouseWheelScrollSensitivity: this._optionsService.rawOptions.scrollSensitivity, + fastScrollSensitivity: this._optionsService.rawOptions.fastScrollSensitivity, + verticalScrollbarSize: this._optionsService.rawOptions.overviewRuler?.width || ViewportConstants.DEFAULT_SCROLL_BAR_WIDTH + }; + } + + public queueSync(ydisp?: number): void { + // Update state + if (ydisp !== undefined) { + this._latestYDisp = ydisp; + } + + // Don't queue more than one callback + if (this._queuedAnimationFrame !== undefined) { + return; + } + this._queuedAnimationFrame = this._renderService.addRefreshCallback(() => { + this._queuedAnimationFrame = undefined; + this._sync(this._latestYDisp); + }); + } + + private _sync(ydisp: number = this._bufferService.buffer.ydisp): void { + if (!this._renderService || this._isSyncing) { + return; + } + this._isSyncing = true; + + // Ignore any onScroll event that happens as a result of dimensions changing as this should + // never cause a scrollLines call, only setScrollPosition can do that. + this._suppressOnScrollHandler = true; + this._scrollableElement.setScrollDimensions({ + height: this._renderService.dimensions.css.canvas.height, + scrollHeight: this._renderService.dimensions.css.cell.height * this._bufferService.buffer.lines.length + }); + this._suppressOnScrollHandler = false; + + // If ydisp has been changed by some other component (input/buffer), then stop animating smooth + // scroll and scroll there immediately. + if (ydisp !== this._latestYDisp) { + this._scrollableElement.setScrollPosition({ + scrollTop: ydisp * this._renderService.dimensions.css.cell.height + }); + } + + this._isSyncing = false; + } + + private _handleScroll(e: ScrollEvent): void { + if (!this._renderService) { + return; + } + if (this._isHandlingScroll || this._suppressOnScrollHandler) { + return; + } + this._isHandlingScroll = true; + const newRow = Math.round(e.scrollTop / this._renderService.dimensions.css.cell.height); + const diff = newRow - this._bufferService.buffer.ydisp; + if (diff !== 0) { + this._latestYDisp = newRow; + this._onRequestScrollLines.fire(diff); + } + this._isHandlingScroll = false; + } +} diff --git a/node_modules/@xterm/xterm/src/browser/decorations/BufferDecorationRenderer.ts b/node_modules/@xterm/xterm/src/browser/decorations/BufferDecorationRenderer.ts new file mode 100644 index 0000000..7b9a3fd --- /dev/null +++ b/node_modules/@xterm/xterm/src/browser/decorations/BufferDecorationRenderer.ts @@ -0,0 +1,139 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { ICoreBrowserService, IRenderService } from 'browser/services/Services'; +import { Disposable, toDisposable } from 'vs/base/common/lifecycle'; +import { IBufferService, IDecorationService, IInternalDecoration } from 'common/services/Services'; + +export class BufferDecorationRenderer extends Disposable { + private readonly _container: HTMLElement; + private readonly _decorationElements: Map = new Map(); + + private _animationFrame: number | undefined; + private _altBufferIsActive: boolean = false; + private _dimensionsChanged: boolean = false; + + constructor( + private readonly _screenElement: HTMLElement, + @IBufferService private readonly _bufferService: IBufferService, + @ICoreBrowserService private readonly _coreBrowserService: ICoreBrowserService, + @IDecorationService private readonly _decorationService: IDecorationService, + @IRenderService private readonly _renderService: IRenderService + ) { + super(); + + this._container = document.createElement('div'); + this._container.classList.add('xterm-decoration-container'); + this._screenElement.appendChild(this._container); + + this._register(this._renderService.onRenderedViewportChange(() => this._doRefreshDecorations())); + this._register(this._renderService.onDimensionsChange(() => { + this._dimensionsChanged = true; + this._queueRefresh(); + })); + this._register(this._coreBrowserService.onDprChange(() => this._queueRefresh())); + this._register(this._bufferService.buffers.onBufferActivate(() => { + this._altBufferIsActive = this._bufferService.buffer === this._bufferService.buffers.alt; + })); + this._register(this._decorationService.onDecorationRegistered(() => this._queueRefresh())); + this._register(this._decorationService.onDecorationRemoved(decoration => this._removeDecoration(decoration))); + this._register(toDisposable(() => { + this._container.remove(); + this._decorationElements.clear(); + })); + } + + private _queueRefresh(): void { + if (this._animationFrame !== undefined) { + return; + } + this._animationFrame = this._renderService.addRefreshCallback(() => { + this._doRefreshDecorations(); + this._animationFrame = undefined; + }); + } + + private _doRefreshDecorations(): void { + for (const decoration of this._decorationService.decorations) { + this._renderDecoration(decoration); + } + this._dimensionsChanged = false; + } + + private _renderDecoration(decoration: IInternalDecoration): void { + this._refreshStyle(decoration); + if (this._dimensionsChanged) { + this._refreshXPosition(decoration); + } + } + + private _createElement(decoration: IInternalDecoration): HTMLElement { + const element = this._coreBrowserService.mainDocument.createElement('div'); + element.classList.add('xterm-decoration'); + element.classList.toggle('xterm-decoration-top-layer', decoration?.options?.layer === 'top'); + element.style.width = `${Math.round((decoration.options.width || 1) * this._renderService.dimensions.css.cell.width)}px`; + element.style.height = `${(decoration.options.height || 1) * this._renderService.dimensions.css.cell.height}px`; + element.style.top = `${(decoration.marker.line - this._bufferService.buffers.active.ydisp) * this._renderService.dimensions.css.cell.height}px`; + element.style.lineHeight = `${this._renderService.dimensions.css.cell.height}px`; + + const x = decoration.options.x ?? 0; + if (x && x > this._bufferService.cols) { + // exceeded the container width, so hide + element.style.display = 'none'; + } + this._refreshXPosition(decoration, element); + + return element; + } + + private _refreshStyle(decoration: IInternalDecoration): void { + const line = decoration.marker.line - this._bufferService.buffers.active.ydisp; + if (line < 0 || line >= this._bufferService.rows) { + // outside of viewport + if (decoration.element) { + decoration.element.style.display = 'none'; + decoration.onRenderEmitter.fire(decoration.element); + } + } else { + let element = this._decorationElements.get(decoration); + if (!element) { + element = this._createElement(decoration); + decoration.element = element; + this._decorationElements.set(decoration, element); + this._container.appendChild(element); + decoration.onDispose(() => { + this._decorationElements.delete(decoration); + element!.remove(); + }); + } + element.style.display = this._altBufferIsActive ? 'none' : 'block'; + if (!this._altBufferIsActive) { + element.style.width = `${Math.round((decoration.options.width || 1) * this._renderService.dimensions.css.cell.width)}px`; + element.style.height = `${(decoration.options.height || 1) * this._renderService.dimensions.css.cell.height}px`; + element.style.top = `${line * this._renderService.dimensions.css.cell.height}px`; + element.style.lineHeight = `${this._renderService.dimensions.css.cell.height}px`; + } + decoration.onRenderEmitter.fire(element); + } + } + + private _refreshXPosition(decoration: IInternalDecoration, element: HTMLElement | undefined = decoration.element): void { + if (!element) { + return; + } + const x = decoration.options.x ?? 0; + if ((decoration.options.anchor || 'left') === 'right') { + element.style.right = x ? `${x * this._renderService.dimensions.css.cell.width}px` : ''; + } else { + element.style.left = x ? `${x * this._renderService.dimensions.css.cell.width}px` : ''; + } + } + + private _removeDecoration(decoration: IInternalDecoration): void { + this._decorationElements.get(decoration)?.remove(); + this._decorationElements.delete(decoration); + decoration.dispose(); + } +} diff --git a/node_modules/@xterm/xterm/src/browser/decorations/ColorZoneStore.ts b/node_modules/@xterm/xterm/src/browser/decorations/ColorZoneStore.ts new file mode 100644 index 0000000..d066bed --- /dev/null +++ b/node_modules/@xterm/xterm/src/browser/decorations/ColorZoneStore.ts @@ -0,0 +1,117 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { IInternalDecoration } from 'common/services/Services'; + +export interface IColorZoneStore { + readonly zones: IColorZone[]; + clear(): void; + addDecoration(decoration: IInternalDecoration): void; + /** + * Sets the amount of padding in lines that will be added between zones, if new lines intersect + * the padding they will be merged into the same zone. + */ + setPadding(padding: { [position: string]: number }): void; +} + +export interface IColorZone { + /** Color in a format supported by canvas' fillStyle. */ + color: string; + position: 'full' | 'left' | 'center' | 'right' | undefined; + startBufferLine: number; + endBufferLine: number; +} + +interface IMinimalDecorationForColorZone { + marker: Pick; + options: Pick; +} + +export class ColorZoneStore implements IColorZoneStore { + private _zones: IColorZone[] = []; + + // The zone pool is used to keep zone objects from being freed between clearing the color zone + // store and fetching the zones. This helps reduce GC pressure since the color zones are + // accumulated on potentially every scroll event. + private _zonePool: IColorZone[] = []; + private _zonePoolIndex = 0; + + private _linePadding: { [position: string]: number } = { + full: 0, + left: 0, + center: 0, + right: 0 + }; + + public get zones(): IColorZone[] { + // Trim the zone pool to free unused memory + this._zonePool.length = Math.min(this._zonePool.length, this._zones.length); + return this._zones; + } + + public clear(): void { + this._zones.length = 0; + this._zonePoolIndex = 0; + } + + public addDecoration(decoration: IMinimalDecorationForColorZone): void { + if (!decoration.options.overviewRulerOptions) { + return; + } + for (const z of this._zones) { + if (z.color === decoration.options.overviewRulerOptions.color && + z.position === decoration.options.overviewRulerOptions.position) { + if (this._lineIntersectsZone(z, decoration.marker.line)) { + return; + } + if (this._lineAdjacentToZone(z, decoration.marker.line, decoration.options.overviewRulerOptions.position)) { + this._addLineToZone(z, decoration.marker.line); + return; + } + } + } + // Create using zone pool if possible + if (this._zonePoolIndex < this._zonePool.length) { + this._zonePool[this._zonePoolIndex].color = decoration.options.overviewRulerOptions.color; + this._zonePool[this._zonePoolIndex].position = decoration.options.overviewRulerOptions.position; + this._zonePool[this._zonePoolIndex].startBufferLine = decoration.marker.line; + this._zonePool[this._zonePoolIndex].endBufferLine = decoration.marker.line; + this._zones.push(this._zonePool[this._zonePoolIndex++]); + return; + } + // Create + this._zones.push({ + color: decoration.options.overviewRulerOptions.color, + position: decoration.options.overviewRulerOptions.position, + startBufferLine: decoration.marker.line, + endBufferLine: decoration.marker.line + }); + this._zonePool.push(this._zones[this._zones.length - 1]); + this._zonePoolIndex++; + } + + public setPadding(padding: { [position: string]: number }): void { + this._linePadding = padding; + } + + private _lineIntersectsZone(zone: IColorZone, line: number): boolean { + return ( + line >= zone.startBufferLine && + line <= zone.endBufferLine + ); + } + + private _lineAdjacentToZone(zone: IColorZone, line: number, position: IColorZone['position']): boolean { + return ( + (line >= zone.startBufferLine - this._linePadding[position || 'full']) && + (line <= zone.endBufferLine + this._linePadding[position || 'full']) + ); + } + + private _addLineToZone(zone: IColorZone, line: number): void { + zone.startBufferLine = Math.min(zone.startBufferLine, line); + zone.endBufferLine = Math.max(zone.endBufferLine, line); + } +} diff --git a/node_modules/@xterm/xterm/src/browser/decorations/OverviewRulerRenderer.ts b/node_modules/@xterm/xterm/src/browser/decorations/OverviewRulerRenderer.ts new file mode 100644 index 0000000..c8efb2a --- /dev/null +++ b/node_modules/@xterm/xterm/src/browser/decorations/OverviewRulerRenderer.ts @@ -0,0 +1,214 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { ColorZoneStore, IColorZone, IColorZoneStore } from 'browser/decorations/ColorZoneStore'; +import { ICoreBrowserService, IRenderService, IThemeService } from 'browser/services/Services'; +import { Disposable, toDisposable } from 'vs/base/common/lifecycle'; +import { IBufferService, IDecorationService, IOptionsService } from 'common/services/Services'; + +const enum Constants { + OVERVIEW_RULER_BORDER_WIDTH = 1 +} + +// Helper objects to avoid excessive calculation and garbage collection during rendering. These are +// static values for each render and can be accessed using the decoration position as the key. +const drawHeight = { + full: 0, + left: 0, + center: 0, + right: 0 +}; +const drawWidth = { + full: 0, + left: 0, + center: 0, + right: 0 +}; +const drawX = { + full: 0, + left: 0, + center: 0, + right: 0 +}; + +export class OverviewRulerRenderer extends Disposable { + private readonly _canvas: HTMLCanvasElement; + private readonly _ctx: CanvasRenderingContext2D; + private readonly _colorZoneStore: IColorZoneStore = new ColorZoneStore(); + private get _width(): number { + return this._optionsService.options.overviewRuler?.width || 0; + } + private _animationFrame: number | undefined; + + private _shouldUpdateDimensions: boolean | undefined = true; + private _shouldUpdateAnchor: boolean | undefined = true; + private _lastKnownBufferLength: number = 0; + + private _containerHeight: number | undefined; + + constructor( + private readonly _viewportElement: HTMLElement, + private readonly _screenElement: HTMLElement, + @IBufferService private readonly _bufferService: IBufferService, + @IDecorationService private readonly _decorationService: IDecorationService, + @IRenderService private readonly _renderService: IRenderService, + @IOptionsService private readonly _optionsService: IOptionsService, + @IThemeService private readonly _themeService: IThemeService, + @ICoreBrowserService private readonly _coreBrowserService: ICoreBrowserService + ) { + super(); + this._canvas = this._coreBrowserService.mainDocument.createElement('canvas'); + this._canvas.classList.add('xterm-decoration-overview-ruler'); + this._refreshCanvasDimensions(); + this._viewportElement.parentElement?.insertBefore(this._canvas, this._viewportElement); + this._register(toDisposable(() => this._canvas?.remove())); + + const ctx = this._canvas.getContext('2d'); + if (!ctx) { + throw new Error('Ctx cannot be null'); + } else { + this._ctx = ctx; + } + + this._register(this._decorationService.onDecorationRegistered(() => this._queueRefresh(undefined, true))); + this._register(this._decorationService.onDecorationRemoved(() => this._queueRefresh(undefined, true))); + + this._register(this._renderService.onRenderedViewportChange(() => this._queueRefresh())); + this._register(this._bufferService.buffers.onBufferActivate(() => { + this._canvas!.style.display = this._bufferService.buffer === this._bufferService.buffers.alt ? 'none' : 'block'; + })); + this._register(this._bufferService.onScroll(() => { + if (this._lastKnownBufferLength !== this._bufferService.buffers.normal.lines.length) { + this._refreshDrawHeightConstants(); + this._refreshColorZonePadding(); + } + })); + + // Container height changed + this._register(this._renderService.onRender((): void => { + if (!this._containerHeight || this._containerHeight !== this._screenElement.clientHeight) { + this._queueRefresh(true); + this._containerHeight = this._screenElement.clientHeight; + } + })); + + this._register(this._coreBrowserService.onDprChange(() => this._queueRefresh(true))); + this._register(this._optionsService.onSpecificOptionChange('overviewRuler', () => this._queueRefresh(true))); + this._register(this._themeService.onChangeColors(() => this._queueRefresh())); + this._queueRefresh(true); + } + + private _refreshDrawConstants(): void { + // width + const outerWidth = Math.floor((this._canvas.width - Constants.OVERVIEW_RULER_BORDER_WIDTH) / 3); + const innerWidth = Math.ceil((this._canvas.width - Constants.OVERVIEW_RULER_BORDER_WIDTH) / 3); + drawWidth.full = this._canvas.width; + drawWidth.left = outerWidth; + drawWidth.center = innerWidth; + drawWidth.right = outerWidth; + // height + this._refreshDrawHeightConstants(); + // x + drawX.full = Constants.OVERVIEW_RULER_BORDER_WIDTH; + drawX.left = Constants.OVERVIEW_RULER_BORDER_WIDTH; + drawX.center = Constants.OVERVIEW_RULER_BORDER_WIDTH + drawWidth.left; + drawX.right = Constants.OVERVIEW_RULER_BORDER_WIDTH + drawWidth.left + drawWidth.center; + } + + private _refreshDrawHeightConstants(): void { + drawHeight.full = Math.round(2 * this._coreBrowserService.dpr); + // Calculate actual pixels per line + const pixelsPerLine = this._canvas.height / this._bufferService.buffer.lines.length; + // Clamp actual pixels within a range + const nonFullHeight = Math.round(Math.max(Math.min(pixelsPerLine, 12), 6) * this._coreBrowserService.dpr); + drawHeight.left = nonFullHeight; + drawHeight.center = nonFullHeight; + drawHeight.right = nonFullHeight; + } + + private _refreshColorZonePadding(): void { + this._colorZoneStore.setPadding({ + full: Math.floor(this._bufferService.buffers.active.lines.length / (this._canvas.height - 1) * drawHeight.full), + left: Math.floor(this._bufferService.buffers.active.lines.length / (this._canvas.height - 1) * drawHeight.left), + center: Math.floor(this._bufferService.buffers.active.lines.length / (this._canvas.height - 1) * drawHeight.center), + right: Math.floor(this._bufferService.buffers.active.lines.length / (this._canvas.height - 1) * drawHeight.right) + }); + this._lastKnownBufferLength = this._bufferService.buffers.normal.lines.length; + } + + private _refreshCanvasDimensions(): void { + this._canvas.style.width = `${this._width}px`; + this._canvas.width = Math.round(this._width * this._coreBrowserService.dpr); + this._canvas.style.height = `${this._screenElement.clientHeight}px`; + this._canvas.height = Math.round(this._screenElement.clientHeight * this._coreBrowserService.dpr); + this._refreshDrawConstants(); + this._refreshColorZonePadding(); + } + + private _refreshDecorations(): void { + if (this._shouldUpdateDimensions) { + this._refreshCanvasDimensions(); + } + this._ctx.clearRect(0, 0, this._canvas.width, this._canvas.height); + this._colorZoneStore.clear(); + for (const decoration of this._decorationService.decorations) { + this._colorZoneStore.addDecoration(decoration); + } + this._ctx.lineWidth = 1; + this._renderRulerOutline(); + const zones = this._colorZoneStore.zones; + for (const zone of zones) { + if (zone.position !== 'full') { + this._renderColorZone(zone); + } + } + for (const zone of zones) { + if (zone.position === 'full') { + this._renderColorZone(zone); + } + } + this._shouldUpdateDimensions = false; + this._shouldUpdateAnchor = false; + } + + private _renderRulerOutline(): void { + this._ctx.fillStyle = this._themeService.colors.overviewRulerBorder.css; + this._ctx.fillRect(0, 0, Constants.OVERVIEW_RULER_BORDER_WIDTH, this._canvas.height); + if (this._optionsService.rawOptions.overviewRuler.showTopBorder) { + this._ctx.fillRect(Constants.OVERVIEW_RULER_BORDER_WIDTH, 0, this._canvas.width - Constants.OVERVIEW_RULER_BORDER_WIDTH, Constants.OVERVIEW_RULER_BORDER_WIDTH); + } + if (this._optionsService.rawOptions.overviewRuler.showBottomBorder) { + this._ctx.fillRect(Constants.OVERVIEW_RULER_BORDER_WIDTH, this._canvas.height - Constants.OVERVIEW_RULER_BORDER_WIDTH, this._canvas.width - Constants.OVERVIEW_RULER_BORDER_WIDTH, this._canvas.height); + } + } + + private _renderColorZone(zone: IColorZone): void { + this._ctx.fillStyle = zone.color; + this._ctx.fillRect( + /* x */ drawX[zone.position || 'full'], + /* y */ Math.round( + (this._canvas.height - 1) * // -1 to ensure at least 2px are allowed for decoration on last line + (zone.startBufferLine / this._bufferService.buffers.active.lines.length) - drawHeight[zone.position || 'full'] / 2 + ), + /* w */ drawWidth[zone.position || 'full'], + /* h */ Math.round( + (this._canvas.height - 1) * // -1 to ensure at least 2px are allowed for decoration on last line + ((zone.endBufferLine - zone.startBufferLine) / this._bufferService.buffers.active.lines.length) + drawHeight[zone.position || 'full'] + ) + ); + } + + private _queueRefresh(updateCanvasDimensions?: boolean, updateAnchor?: boolean): void { + this._shouldUpdateDimensions = updateCanvasDimensions || this._shouldUpdateDimensions; + this._shouldUpdateAnchor = updateAnchor || this._shouldUpdateAnchor; + if (this._animationFrame !== undefined) { + return; + } + this._animationFrame = this._coreBrowserService.window.requestAnimationFrame(() => { + this._refreshDecorations(); + this._animationFrame = undefined; + }); + } +} diff --git a/node_modules/@xterm/xterm/src/browser/input/CompositionHelper.ts b/node_modules/@xterm/xterm/src/browser/input/CompositionHelper.ts new file mode 100644 index 0000000..b87ebbe --- /dev/null +++ b/node_modules/@xterm/xterm/src/browser/input/CompositionHelper.ts @@ -0,0 +1,248 @@ +/** + * Copyright (c) 2016 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { IRenderService } from 'browser/services/Services'; +import { IBufferService, ICoreService, IOptionsService } from 'common/services/Services'; +import { C0 } from 'common/data/EscapeSequences'; + +interface IPosition { + start: number; + end: number; +} + +/** + * Encapsulates the logic for handling compositionstart, compositionupdate and compositionend + * events, displaying the in-progress composition to the UI and forwarding the final composition + * to the handler. + */ +export class CompositionHelper { + /** + * Whether input composition is currently happening, eg. via a mobile keyboard, speech input or + * IME. This variable determines whether the compositionText should be displayed on the UI. + */ + private _isComposing: boolean; + public get isComposing(): boolean { return this._isComposing; } + + /** + * The position within the input textarea's value of the current composition. + */ + private _compositionPosition: IPosition; + + /** + * Whether a composition is in the process of being sent, setting this to false will cancel any + * in-progress composition. + */ + private _isSendingComposition: boolean; + + /** + * Data already sent due to keydown event. + */ + private _dataAlreadySent: string; + + constructor( + private readonly _textarea: HTMLTextAreaElement, + private readonly _compositionView: HTMLElement, + @IBufferService private readonly _bufferService: IBufferService, + @IOptionsService private readonly _optionsService: IOptionsService, + @ICoreService private readonly _coreService: ICoreService, + @IRenderService private readonly _renderService: IRenderService + ) { + this._isComposing = false; + this._isSendingComposition = false; + this._compositionPosition = { start: 0, end: 0 }; + this._dataAlreadySent = ''; + } + + /** + * Handles the compositionstart event, activating the composition view. + */ + public compositionstart(): void { + this._isComposing = true; + this._compositionPosition.start = this._textarea.value.length; + this._compositionView.textContent = ''; + this._dataAlreadySent = ''; + this._compositionView.classList.add('active'); + } + + /** + * Handles the compositionupdate event, updating the composition view. + * @param ev The event. + */ + public compositionupdate(ev: Pick): void { + this._compositionView.textContent = ev.data; + this.updateCompositionElements(); + setTimeout(() => { + this._compositionPosition.end = this._textarea.value.length; + }, 0); + } + + /** + * Handles the compositionend event, hiding the composition view and sending the composition to + * the handler. + */ + public compositionend(): void { + this._finalizeComposition(true); + } + + /** + * Handles the keydown event, routing any necessary events to the CompositionHelper functions. + * @param ev The keydown event. + * @returns Whether the Terminal should continue processing the keydown event. + */ + public keydown(ev: KeyboardEvent): boolean { + if (this._isComposing || this._isSendingComposition) { + if (ev.keyCode === 20 || ev.keyCode === 229) { + // 20 is CapsLock, 229 is Enter + // Continue composing if the keyCode is the "composition character" + return false; + } + if (ev.keyCode === 16 || ev.keyCode === 17 || ev.keyCode === 18) { + // Continue composing if the keyCode is a modifier key + return false; + } + // Finish composition immediately. This is mainly here for the case where enter is + // pressed and the handler needs to be triggered before the command is executed. + this._finalizeComposition(false); + } + + if (ev.keyCode === 229) { + // If the "composition character" is used but gets to this point it means a non-composition + // character (eg. numbers and punctuation) was pressed when the IME was active. + this._handleAnyTextareaChanges(); + return false; + } + + return true; + } + + /** + * Finalizes the composition, resuming regular input actions. This is called when a composition + * is ending. + * @param waitForPropagation Whether to wait for events to propagate before sending + * the input. This should be false if a non-composition keystroke is entered before the + * compositionend event is triggered, such as enter, so that the composition is sent before + * the command is executed. + */ + private _finalizeComposition(waitForPropagation: boolean): void { + this._compositionView.classList.remove('active'); + this._isComposing = false; + + if (!waitForPropagation) { + // Cancel any delayed composition send requests and send the input immediately. + this._isSendingComposition = false; + const input = this._textarea.value.substring(this._compositionPosition.start, this._compositionPosition.end); + this._coreService.triggerDataEvent(input, true); + } else { + // Make a deep copy of the composition position here as a new compositionstart event may + // fire before the setTimeout executes. + const currentCompositionPosition = { + start: this._compositionPosition.start, + end: this._compositionPosition.end + }; + + // Since composition* events happen before the changes take place in the textarea on most + // browsers, use a setTimeout with 0ms time to allow the native compositionend event to + // complete. This ensures the correct character is retrieved. + // This solution was used because: + // - The compositionend event's data property is unreliable, at least on Chromium + // - The last compositionupdate event's data property does not always accurately describe + // the character, a counter example being Korean where an ending consonsant can move to + // the following character if the following input is a vowel. + this._isSendingComposition = true; + setTimeout(() => { + // Ensure that the input has not already been sent + if (this._isSendingComposition) { + this._isSendingComposition = false; + let input; + // Add length of data already sent due to keydown event, + // otherwise input characters can be duplicated. (Issue #3191) + currentCompositionPosition.start += this._dataAlreadySent.length; + if (this._isComposing) { + // Use the start position of the new composition to get the string + // if a new composition has started. + input = this._textarea.value.substring(currentCompositionPosition.start, this._compositionPosition.start); + } else { + // Don't use the end position here in order to pick up any characters after the + // composition has finished, for example when typing a non-composition character + // (eg. 2) after a composition character. + input = this._textarea.value.substring(currentCompositionPosition.start); + } + if (input.length > 0) { + this._coreService.triggerDataEvent(input, true); + } + } + }, 0); + } + } + + /** + * Apply any changes made to the textarea after the current event chain is allowed to complete. + * This should be called when not currently composing but a keydown event with the "composition + * character" (229) is triggered, in order to allow non-composition text to be entered when an + * IME is active. + */ + private _handleAnyTextareaChanges(): void { + const oldValue = this._textarea.value; + setTimeout(() => { + // Ignore if a composition has started since the timeout + if (!this._isComposing) { + const newValue = this._textarea.value; + + const diff = newValue.replace(oldValue, ''); + + this._dataAlreadySent = diff; + + if (newValue.length > oldValue.length) { + this._coreService.triggerDataEvent(diff, true); + } else if (newValue.length < oldValue.length) { + this._coreService.triggerDataEvent(`${C0.DEL}`, true); + } else if ((newValue.length === oldValue.length) && (newValue !== oldValue)) { + this._coreService.triggerDataEvent(newValue, true); + } + + } + }, 0); + } + + /** + * Positions the composition view on top of the cursor and the textarea just below it (so the + * IME helper dialog is positioned correctly). + * @param dontRecurse Whether to use setTimeout to recursively trigger another update, this is + * necessary as the IME events across browsers are not consistently triggered. + */ + public updateCompositionElements(dontRecurse?: boolean): void { + if (!this._isComposing) { + return; + } + + if (this._bufferService.buffer.isCursorInViewport) { + const cursorX = Math.min(this._bufferService.buffer.x, this._bufferService.cols - 1); + + const cellHeight = this._renderService.dimensions.css.cell.height; + const cursorTop = this._bufferService.buffer.y * this._renderService.dimensions.css.cell.height; + const cursorLeft = cursorX * this._renderService.dimensions.css.cell.width; + + this._compositionView.style.left = cursorLeft + 'px'; + this._compositionView.style.top = cursorTop + 'px'; + this._compositionView.style.height = cellHeight + 'px'; + this._compositionView.style.lineHeight = cellHeight + 'px'; + this._compositionView.style.fontFamily = this._optionsService.rawOptions.fontFamily; + this._compositionView.style.fontSize = this._optionsService.rawOptions.fontSize + 'px'; + // Sync the textarea to the exact position of the composition view so the IME knows where the + // text is. + const compositionViewBounds = this._compositionView.getBoundingClientRect(); + this._textarea.style.left = cursorLeft + 'px'; + this._textarea.style.top = cursorTop + 'px'; + // Ensure the text area is at least 1x1, otherwise certain IMEs may break + this._textarea.style.width = Math.max(compositionViewBounds.width, 1) + 'px'; + this._textarea.style.height = Math.max(compositionViewBounds.height, 1) + 'px'; + this._textarea.style.lineHeight = compositionViewBounds.height + 'px'; + } + + if (!dontRecurse) { + setTimeout(() => this.updateCompositionElements(true), 0); + } + } +} diff --git a/node_modules/@xterm/xterm/src/browser/input/Mouse.ts b/node_modules/@xterm/xterm/src/browser/input/Mouse.ts new file mode 100644 index 0000000..c40a7cc --- /dev/null +++ b/node_modules/@xterm/xterm/src/browser/input/Mouse.ts @@ -0,0 +1,54 @@ +/** + * Copyright (c) 2017 The xterm.js authors. All rights reserved. + * @license MIT + */ + +export function getCoordsRelativeToElement(window: Pick, event: {clientX: number, clientY: number}, element: HTMLElement): [number, number] { + const rect = element.getBoundingClientRect(); + const elementStyle = window.getComputedStyle(element); + const leftPadding = parseInt(elementStyle.getPropertyValue('padding-left')); + const topPadding = parseInt(elementStyle.getPropertyValue('padding-top')); + return [ + event.clientX - rect.left - leftPadding, + event.clientY - rect.top - topPadding + ]; +} + +/** + * Gets coordinates within the terminal for a particular mouse event. The result + * is returned as an array in the form [x, y] instead of an object as it's a + * little faster and this function is used in some low level code. + * @param window The window object the element belongs to. + * @param event The mouse event. + * @param element The terminal's container element. + * @param colCount The number of columns in the terminal. + * @param rowCount The number of rows n the terminal. + * @param hasValidCharSize Whether there is a valid character size available. + * @param cssCellWidth The cell width device pixel render dimensions. + * @param cssCellHeight The cell height device pixel render dimensions. + * @param isSelection Whether the request is for the selection or not. This will + * apply an offset to the x value such that the left half of the cell will + * select that cell and the right half will select the next cell. + */ +export function getCoords(window: Pick, event: Pick, element: HTMLElement, colCount: number, rowCount: number, hasValidCharSize: boolean, cssCellWidth: number, cssCellHeight: number, isSelection?: boolean): [number, number] | undefined { + // Coordinates cannot be measured if there are no valid + if (!hasValidCharSize) { + return undefined; + } + + const coords = getCoordsRelativeToElement(window, event, element); + if (!coords) { + return undefined; + } + + coords[0] = Math.ceil((coords[0] + (isSelection ? cssCellWidth / 2 : 0)) / cssCellWidth); + coords[1] = Math.ceil(coords[1] / cssCellHeight); + + // Ensure coordinates are within the terminal viewport. Note that selections + // need an addition point of precision to cover the end point (as characters + // cover half of one char and half of the next). + coords[0] = Math.min(Math.max(coords[0], 1), colCount + (isSelection ? 1 : 0)); + coords[1] = Math.min(Math.max(coords[1], 1), rowCount); + + return coords; +} diff --git a/node_modules/@xterm/xterm/src/browser/input/MoveToCell.ts b/node_modules/@xterm/xterm/src/browser/input/MoveToCell.ts new file mode 100644 index 0000000..ce4c592 --- /dev/null +++ b/node_modules/@xterm/xterm/src/browser/input/MoveToCell.ts @@ -0,0 +1,251 @@ +/** + * Copyright (c) 2018 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { C0 } from 'common/data/EscapeSequences'; +import { IBufferService } from 'common/services/Services'; + +const enum Direction { + UP = 'A', + DOWN = 'B', + RIGHT = 'C', + LEFT = 'D' +} + +/** + * Concatenates all the arrow sequences together. + * Resets the starting row to an unwrapped row, moves to the requested row, + * then moves to requested col. + */ +export function moveToCellSequence(targetX: number, targetY: number, bufferService: IBufferService, applicationCursor: boolean): string { + const startX = bufferService.buffer.x; + const startY = bufferService.buffer.y; + + // The alt buffer should try to navigate between rows + if (!bufferService.buffer.hasScrollback) { + return resetStartingRow(startX, startY, targetX, targetY, bufferService, applicationCursor) + + moveToRequestedRow(startY, targetY, bufferService, applicationCursor) + + moveToRequestedCol(startX, startY, targetX, targetY, bufferService, applicationCursor); + } + + // Only move horizontally for the normal buffer + let direction; + if (startY === targetY) { + direction = startX > targetX ? Direction.LEFT : Direction.RIGHT; + return repeat(Math.abs(startX - targetX), sequence(direction, applicationCursor)); + } + direction = startY > targetY ? Direction.LEFT : Direction.RIGHT; + const rowDifference = Math.abs(startY - targetY); + const cellsToMove = colsFromRowEnd(startY > targetY ? targetX : startX, bufferService) + + (rowDifference - 1) * bufferService.cols + 1 /* wrap around 1 row */ + + colsFromRowBeginning(startY > targetY ? startX : targetX, bufferService); + return repeat(cellsToMove, sequence(direction, applicationCursor)); +} + +/** + * Find the number of cols from a row beginning to a col. + */ +function colsFromRowBeginning(currX: number, bufferService: IBufferService): number { + return currX - 1; +} + +/** + * Find the number of cols from a col to row end. + */ +function colsFromRowEnd(currX: number, bufferService: IBufferService): number { + return bufferService.cols - currX; +} + +/** + * If the initial position of the cursor is on a row that is wrapped, move the + * cursor up to the first row that is not wrapped to have accurate vertical + * positioning. + */ +function resetStartingRow(startX: number, startY: number, targetX: number, targetY: number, bufferService: IBufferService, applicationCursor: boolean): string { + if (moveToRequestedRow(startY, targetY, bufferService, applicationCursor).length === 0) { + return ''; + } + return repeat(bufferLine( + startX, startY, startX, + startY - wrappedRowsForRow(startY, bufferService), false, bufferService + ).length, sequence(Direction.LEFT, applicationCursor)); +} + +/** + * Using the reset starting and ending row, move to the requested row, + * ignoring wrapped rows + */ +function moveToRequestedRow(startY: number, targetY: number, bufferService: IBufferService, applicationCursor: boolean): string { + const startRow = startY - wrappedRowsForRow(startY, bufferService); + const endRow = targetY - wrappedRowsForRow(targetY, bufferService); + + const rowsToMove = Math.abs(startRow - endRow) - wrappedRowsCount(startY, targetY, bufferService); + + return repeat(rowsToMove, sequence(verticalDirection(startY, targetY), applicationCursor)); +} + +/** + * Move to the requested col on the ending row + */ +function moveToRequestedCol(startX: number, startY: number, targetX: number, targetY: number, bufferService: IBufferService, applicationCursor: boolean): string { + let startRow; + if (moveToRequestedRow(startY, targetY, bufferService, applicationCursor).length > 0) { + startRow = targetY - wrappedRowsForRow(targetY, bufferService); + } else { + startRow = startY; + } + + const endRow = targetY; + const direction = horizontalDirection(startX, startY, targetX, targetY, bufferService, applicationCursor); + + return repeat(bufferLine( + startX, startRow, targetX, endRow, + direction === Direction.RIGHT, bufferService + ).length, sequence(direction, applicationCursor)); +} + +/** + * Utility functions + */ + +/** + * Calculates the number of wrapped rows between the unwrapped starting and + * ending rows. These rows need to ignored since the cursor skips over them. + */ +function wrappedRowsCount(startY: number, targetY: number, bufferService: IBufferService): number { + let wrappedRows = 0; + const startRow = startY - wrappedRowsForRow(startY, bufferService); + const endRow = targetY - wrappedRowsForRow(targetY, bufferService); + + for (let i = 0; i < Math.abs(startRow - endRow); i++) { + const direction = verticalDirection(startY, targetY) === Direction.UP ? -1 : 1; + const line = bufferService.buffer.lines.get(startRow + (direction * i)); + if (line?.isWrapped) { + wrappedRows++; + } + } + + return wrappedRows; +} + +/** + * Calculates the number of wrapped rows that make up a given row. + * @param currentRow The row to determine how many wrapped rows make it up + */ +function wrappedRowsForRow(currentRow: number, bufferService: IBufferService): number { + let rowCount = 0; + let line = bufferService.buffer.lines.get(currentRow); + let lineWraps = line?.isWrapped; + + while (lineWraps && currentRow >= 0 && currentRow < bufferService.rows) { + rowCount++; + line = bufferService.buffer.lines.get(--currentRow); + lineWraps = line?.isWrapped; + } + + return rowCount; +} + +/** + * Direction determiners + */ + +/** + * Determines if the right or left arrow is needed + */ +function horizontalDirection(startX: number, startY: number, targetX: number, targetY: number, bufferService: IBufferService, applicationCursor: boolean): Direction { + let startRow; + if (moveToRequestedRow(targetX, targetY, bufferService, applicationCursor).length > 0) { + startRow = targetY - wrappedRowsForRow(targetY, bufferService); + } else { + startRow = startY; + } + + if ((startX < targetX && + startRow <= targetY) || // down/right or same y/right + (startX >= targetX && + startRow < targetY)) { // down/left or same y/left + return Direction.RIGHT; + } + return Direction.LEFT; +} + +/** + * Determines if the up or down arrow is needed + */ +function verticalDirection(startY: number, targetY: number): Direction { + return startY > targetY ? Direction.UP : Direction.DOWN; +} + +/** + * Constructs the string of chars in the buffer from a starting row and col + * to an ending row and col + * @param startCol The starting column position + * @param startRow The starting row position + * @param endCol The ending column position + * @param endRow The ending row position + * @param forward Direction to move + */ +function bufferLine( + startCol: number, + startRow: number, + endCol: number, + endRow: number, + forward: boolean, + bufferService: IBufferService +): string { + let currentCol = startCol; + let currentRow = startRow; + let bufferStr = ''; + + while ((currentCol !== endCol || currentRow !== endRow) && + currentRow >= 0 && + currentRow < bufferService.buffer.lines.length) { + currentCol += forward ? 1 : -1; + + if (forward && currentCol > bufferService.cols - 1) { + bufferStr += bufferService.buffer.translateBufferLineToString( + currentRow, false, startCol, currentCol + ); + currentCol = 0; + startCol = 0; + currentRow++; + } else if (!forward && currentCol < 0) { + bufferStr += bufferService.buffer.translateBufferLineToString( + currentRow, false, 0, startCol + 1 + ); + currentCol = bufferService.cols - 1; + startCol = currentCol; + currentRow--; + } + } + + return bufferStr + bufferService.buffer.translateBufferLineToString( + currentRow, false, startCol, currentCol + ); +} + +/** + * Constructs the escape sequence for clicking an arrow + * @param direction The direction to move + */ +function sequence(direction: Direction, applicationCursor: boolean): string { + const mod = applicationCursor ? 'O' : '['; + return C0.ESC + mod + direction; +} + +/** + * Returns a string repeated a given number of times + * Polyfill from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat + * @param count The number of times to repeat the string + * @param str The string that is to be repeated + */ +function repeat(count: number, str: string): string { + count = Math.floor(count); + let rpt = ''; + for (let i = 0; i < count; i++) { + rpt += str; + } + return rpt; +} diff --git a/node_modules/@xterm/xterm/src/browser/public/Terminal.ts b/node_modules/@xterm/xterm/src/browser/public/Terminal.ts new file mode 100644 index 0000000..f6ec55d --- /dev/null +++ b/node_modules/@xterm/xterm/src/browser/public/Terminal.ts @@ -0,0 +1,275 @@ +/** + * Copyright (c) 2018 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import * as Strings from 'browser/LocalizableStrings'; +import { CoreBrowserTerminal as TerminalCore } from 'browser/CoreBrowserTerminal'; +import { IBufferRange, ITerminal } from 'browser/Types'; +import { Disposable } from 'vs/base/common/lifecycle'; +import { ITerminalOptions } from 'common/Types'; +import { AddonManager } from 'common/public/AddonManager'; +import { BufferNamespaceApi } from 'common/public/BufferNamespaceApi'; +import { ParserApi } from 'common/public/ParserApi'; +import { UnicodeApi } from 'common/public/UnicodeApi'; +import { IBufferNamespace as IBufferNamespaceApi, IDecoration, IDecorationOptions, IDisposable, ILinkProvider, ILocalizableStrings, IMarker, IModes, IParser, ITerminalAddon, Terminal as ITerminalApi, ITerminalInitOnlyOptions, IUnicodeHandling } from '@xterm/xterm'; +import type { Event } from 'vs/base/common/event'; + +/** + * The set of options that only have an effect when set in the Terminal constructor. + */ +const CONSTRUCTOR_ONLY_OPTIONS = ['cols', 'rows']; + +let $value = 0; + +export class Terminal extends Disposable implements ITerminalApi { + private _core: ITerminal; + private _addonManager: AddonManager; + private _parser: IParser | undefined; + private _buffer: BufferNamespaceApi | undefined; + private _publicOptions: Required; + + constructor(options?: ITerminalOptions & ITerminalInitOnlyOptions) { + super(); + + this._core = this._register(new TerminalCore(options)); + this._addonManager = this._register(new AddonManager()); + + this._publicOptions = { ... this._core.options }; + const getter = (propName: string): any => { + return this._core.options[propName]; + }; + const setter = (propName: string, value: any): void => { + this._checkReadonlyOptions(propName); + this._core.options[propName] = value; + }; + + for (const propName in this._core.options) { + const desc = { + get: getter.bind(this, propName), + set: setter.bind(this, propName) + }; + Object.defineProperty(this._publicOptions, propName, desc); + } + } + + private _checkReadonlyOptions(propName: string): void { + // Throw an error if any constructor only option is modified + // from terminal.options + // Modifications from anywhere else are allowed + if (CONSTRUCTOR_ONLY_OPTIONS.includes(propName)) { + throw new Error(`Option "${propName}" can only be set in the constructor`); + } + } + + private _checkProposedApi(): void { + if (!this._core.optionsService.rawOptions.allowProposedApi) { + throw new Error('You must set the allowProposedApi option to true to use proposed API'); + } + } + + public get onBell(): Event { return this._core.onBell; } + public get onBinary(): Event { return this._core.onBinary; } + public get onCursorMove(): Event { return this._core.onCursorMove; } + public get onData(): Event { return this._core.onData; } + public get onKey(): Event<{ key: string, domEvent: KeyboardEvent }> { return this._core.onKey; } + public get onLineFeed(): Event { return this._core.onLineFeed; } + public get onRender(): Event<{ start: number, end: number }> { return this._core.onRender; } + public get onResize(): Event<{ cols: number, rows: number }> { return this._core.onResize; } + public get onScroll(): Event { return this._core.onScroll; } + public get onSelectionChange(): Event { return this._core.onSelectionChange; } + public get onTitleChange(): Event { return this._core.onTitleChange; } + public get onWriteParsed(): Event { return this._core.onWriteParsed; } + + public get element(): HTMLElement | undefined { return this._core.element; } + public get parser(): IParser { + if (!this._parser) { + this._parser = new ParserApi(this._core); + } + return this._parser; + } + public get unicode(): IUnicodeHandling { + this._checkProposedApi(); + return new UnicodeApi(this._core); + } + public get textarea(): HTMLTextAreaElement | undefined { return this._core.textarea; } + public get rows(): number { return this._core.rows; } + public get cols(): number { return this._core.cols; } + public get buffer(): IBufferNamespaceApi { + if (!this._buffer) { + this._buffer = this._register(new BufferNamespaceApi(this._core)); + } + return this._buffer; + } + public get markers(): ReadonlyArray { + this._checkProposedApi(); + return this._core.markers; + } + public get modes(): IModes { + const m = this._core.coreService.decPrivateModes; + let mouseTrackingMode: 'none' | 'x10' | 'vt200' | 'drag' | 'any' = 'none'; + switch (this._core.coreMouseService.activeProtocol) { + case 'X10': mouseTrackingMode = 'x10'; break; + case 'VT200': mouseTrackingMode = 'vt200'; break; + case 'DRAG': mouseTrackingMode = 'drag'; break; + case 'ANY': mouseTrackingMode = 'any'; break; + } + return { + applicationCursorKeysMode: m.applicationCursorKeys, + applicationKeypadMode: m.applicationKeypad, + bracketedPasteMode: m.bracketedPasteMode, + insertMode: this._core.coreService.modes.insertMode, + mouseTrackingMode: mouseTrackingMode, + originMode: m.origin, + reverseWraparoundMode: m.reverseWraparound, + sendFocusMode: m.sendFocus, + synchronizedOutputMode: m.synchronizedOutput, + wraparoundMode: m.wraparound + }; + } + public get options(): Required { + return this._publicOptions; + } + public set options(options: ITerminalOptions) { + for (const propName in options) { + this._publicOptions[propName] = options[propName]; + } + } + public blur(): void { + this._core.blur(); + } + public focus(): void { + this._core.focus(); + } + public input(data: string, wasUserInput: boolean = true): void { + this._core.input(data, wasUserInput); + } + public resize(columns: number, rows: number): void { + this._verifyIntegers(columns, rows); + this._core.resize(columns, rows); + } + public open(parent: HTMLElement): void { + this._core.open(parent); + } + public attachCustomKeyEventHandler(customKeyEventHandler: (event: KeyboardEvent) => boolean): void { + this._core.attachCustomKeyEventHandler(customKeyEventHandler); + } + public attachCustomWheelEventHandler(customWheelEventHandler: (event: WheelEvent) => boolean): void { + this._core.attachCustomWheelEventHandler(customWheelEventHandler); + } + public registerLinkProvider(linkProvider: ILinkProvider): IDisposable { + return this._core.registerLinkProvider(linkProvider); + } + public registerCharacterJoiner(handler: (text: string) => [number, number][]): number { + this._checkProposedApi(); + return this._core.registerCharacterJoiner(handler); + } + public deregisterCharacterJoiner(joinerId: number): void { + this._checkProposedApi(); + this._core.deregisterCharacterJoiner(joinerId); + } + public registerMarker(cursorYOffset: number = 0): IMarker { + this._verifyIntegers(cursorYOffset); + return this._core.registerMarker(cursorYOffset); + } + public registerDecoration(decorationOptions: IDecorationOptions): IDecoration | undefined { + this._checkProposedApi(); + this._verifyPositiveIntegers(decorationOptions.x ?? 0, decorationOptions.width ?? 0, decorationOptions.height ?? 0); + return this._core.registerDecoration(decorationOptions); + } + public hasSelection(): boolean { + return this._core.hasSelection(); + } + public select(column: number, row: number, length: number): void { + this._verifyIntegers(column, row, length); + this._core.select(column, row, length); + } + public getSelection(): string { + return this._core.getSelection(); + } + public getSelectionPosition(): IBufferRange | undefined { + return this._core.getSelectionPosition(); + } + public clearSelection(): void { + this._core.clearSelection(); + } + public selectAll(): void { + this._core.selectAll(); + } + public selectLines(start: number, end: number): void { + this._verifyIntegers(start, end); + this._core.selectLines(start, end); + } + public dispose(): void { + super.dispose(); + } + public scrollLines(amount: number): void { + this._verifyIntegers(amount); + this._core.scrollLines(amount); + } + public scrollPages(pageCount: number): void { + this._verifyIntegers(pageCount); + this._core.scrollPages(pageCount); + } + public scrollToTop(): void { + this._core.scrollToTop(); + } + public scrollToBottom(): void { + this._core.scrollToBottom(); + } + public scrollToLine(line: number): void { + this._verifyIntegers(line); + this._core.scrollToLine(line); + } + public clear(): void { + this._core.clear(); + } + public write(data: string | Uint8Array, callback?: () => void): void { + this._core.write(data, callback); + } + public writeln(data: string | Uint8Array, callback?: () => void): void { + this._core.write(data); + this._core.write('\r\n', callback); + } + public paste(data: string): void { + this._core.paste(data); + } + public refresh(start: number, end: number): void { + this._verifyIntegers(start, end); + this._core.refresh(start, end); + } + public reset(): void { + this._core.reset(); + } + public clearTextureAtlas(): void { + this._core.clearTextureAtlas(); + } + public loadAddon(addon: ITerminalAddon): void { + this._addonManager.loadAddon(this, addon); + } + public static get strings(): ILocalizableStrings { + // A wrapper is required here because esbuild prevents setting an `export let` + return { + get promptLabel(): string { return Strings.promptLabel.get(); }, + set promptLabel(value: string) { Strings.promptLabel.set(value); }, + get tooMuchOutput(): string { return Strings.tooMuchOutput.get(); }, + set tooMuchOutput(value: string) { Strings.tooMuchOutput.set(value); } + }; + } + + private _verifyIntegers(...values: number[]): void { + for ($value of values) { + if ($value === Infinity || isNaN($value) || $value % 1 !== 0) { + throw new Error('This API only accepts integers'); + } + } + } + + private _verifyPositiveIntegers(...values: number[]): void { + for ($value of values) { + if ($value && ($value === Infinity || isNaN($value) || $value % 1 !== 0 || $value < 0)) { + throw new Error('This API only accepts positive integers'); + } + } + } +} diff --git a/node_modules/@xterm/xterm/src/browser/renderer/dom/DomRenderer.ts b/node_modules/@xterm/xterm/src/browser/renderer/dom/DomRenderer.ts new file mode 100644 index 0000000..1c27179 --- /dev/null +++ b/node_modules/@xterm/xterm/src/browser/renderer/dom/DomRenderer.ts @@ -0,0 +1,542 @@ +/** + * Copyright (c) 2018 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { DomRendererRowFactory, RowCss } from 'browser/renderer/dom/DomRendererRowFactory'; +import { WidthCache } from 'browser/renderer/dom/WidthCache'; +import { INVERTED_DEFAULT_COLOR } from 'browser/renderer/shared/Constants'; +import { createRenderDimensions } from 'browser/renderer/shared/RendererUtils'; +import { createSelectionRenderModel } from 'browser/renderer/shared/SelectionRenderModel'; +import { IRenderDimensions, IRenderer, IRequestRedrawEvent, ISelectionRenderModel } from 'browser/renderer/shared/Types'; +import { ICharSizeService, ICoreBrowserService, IThemeService } from 'browser/services/Services'; +import { ILinkifier2, ILinkifierEvent, ITerminal, ReadonlyColorSet } from 'browser/Types'; +import { color } from 'common/Color'; +import { Disposable, toDisposable } from 'vs/base/common/lifecycle'; +import { IBufferService, ICoreService, IInstantiationService, IOptionsService } from 'common/services/Services'; +import { Emitter } from 'vs/base/common/event'; + + +const TERMINAL_CLASS_PREFIX = 'xterm-dom-renderer-owner-'; +const ROW_CONTAINER_CLASS = 'xterm-rows'; +const FG_CLASS_PREFIX = 'xterm-fg-'; +const BG_CLASS_PREFIX = 'xterm-bg-'; +const FOCUS_CLASS = 'xterm-focus'; +const SELECTION_CLASS = 'xterm-selection'; + +let nextTerminalId = 1; + +/** + * The standard renderer and fallback for when the webgl addon is slow. This is not meant to be + * particularly fast and will even lack some features such as custom glyphs, hoever this is more + * reliable as webgl may not work on some machines. + */ +export class DomRenderer extends Disposable implements IRenderer { + private _rowFactory: DomRendererRowFactory; + private _terminalClass: number = nextTerminalId++; + + private _themeStyleElement!: HTMLStyleElement; + private _dimensionsStyleElement!: HTMLStyleElement; + private _rowContainer: HTMLElement; + private _rowElements: HTMLElement[] = []; + private _selectionContainer: HTMLElement; + private _widthCache: WidthCache; + private _selectionRenderModel: ISelectionRenderModel = createSelectionRenderModel(); + + public dimensions: IRenderDimensions; + + public readonly onRequestRedraw = this._register(new Emitter()).event; + + constructor( + private readonly _terminal: ITerminal, + private readonly _document: Document, + private readonly _element: HTMLElement, + private readonly _screenElement: HTMLElement, + private readonly _viewportElement: HTMLElement, + private readonly _helperContainer: HTMLElement, + private readonly _linkifier2: ILinkifier2, + @IInstantiationService instantiationService: IInstantiationService, + @ICharSizeService private readonly _charSizeService: ICharSizeService, + @IOptionsService private readonly _optionsService: IOptionsService, + @IBufferService private readonly _bufferService: IBufferService, + @ICoreService private readonly _coreService: ICoreService, + @ICoreBrowserService private readonly _coreBrowserService: ICoreBrowserService, + @IThemeService private readonly _themeService: IThemeService + ) { + super(); + this._rowContainer = this._document.createElement('div'); + this._rowContainer.classList.add(ROW_CONTAINER_CLASS); + this._rowContainer.style.lineHeight = 'normal'; + this._rowContainer.setAttribute('aria-hidden', 'true'); + this._refreshRowElements(this._bufferService.cols, this._bufferService.rows); + this._selectionContainer = this._document.createElement('div'); + this._selectionContainer.classList.add(SELECTION_CLASS); + this._selectionContainer.setAttribute('aria-hidden', 'true'); + + this.dimensions = createRenderDimensions(); + this._updateDimensions(); + this._register(this._optionsService.onOptionChange(() => this._handleOptionsChanged())); + + this._register(this._themeService.onChangeColors(e => this._injectCss(e))); + this._injectCss(this._themeService.colors); + + this._rowFactory = instantiationService.createInstance(DomRendererRowFactory, document); + + this._element.classList.add(TERMINAL_CLASS_PREFIX + this._terminalClass); + this._screenElement.appendChild(this._rowContainer); + this._screenElement.appendChild(this._selectionContainer); + + this._register(this._linkifier2.onShowLinkUnderline(e => this._handleLinkHover(e))); + this._register(this._linkifier2.onHideLinkUnderline(e => this._handleLinkLeave(e))); + + this._register(toDisposable(() => { + this._element.classList.remove(TERMINAL_CLASS_PREFIX + this._terminalClass); + + // Outside influences such as React unmounts may manipulate the DOM before our disposal. + // https://github.com/xtermjs/xterm.js/issues/2960 + this._rowContainer.remove(); + this._selectionContainer.remove(); + this._widthCache.dispose(); + this._themeStyleElement.remove(); + this._dimensionsStyleElement.remove(); + })); + + this._widthCache = new WidthCache(this._document, this._helperContainer); + this._widthCache.setFont( + this._optionsService.rawOptions.fontFamily, + this._optionsService.rawOptions.fontSize, + this._optionsService.rawOptions.fontWeight, + this._optionsService.rawOptions.fontWeightBold + ); + this._setDefaultSpacing(); + } + + private _updateDimensions(): void { + const dpr = this._coreBrowserService.dpr; + this.dimensions.device.char.width = this._charSizeService.width * dpr; + this.dimensions.device.char.height = Math.ceil(this._charSizeService.height * dpr); + this.dimensions.device.cell.width = this.dimensions.device.char.width + Math.round(this._optionsService.rawOptions.letterSpacing); + this.dimensions.device.cell.height = Math.floor(this.dimensions.device.char.height * this._optionsService.rawOptions.lineHeight); + this.dimensions.device.char.left = 0; + this.dimensions.device.char.top = 0; + this.dimensions.device.canvas.width = this.dimensions.device.cell.width * this._bufferService.cols; + this.dimensions.device.canvas.height = this.dimensions.device.cell.height * this._bufferService.rows; + this.dimensions.css.canvas.width = Math.round(this.dimensions.device.canvas.width / dpr); + this.dimensions.css.canvas.height = Math.round(this.dimensions.device.canvas.height / dpr); + this.dimensions.css.cell.width = this.dimensions.css.canvas.width / this._bufferService.cols; + this.dimensions.css.cell.height = this.dimensions.css.canvas.height / this._bufferService.rows; + + for (const element of this._rowElements) { + element.style.width = `${this.dimensions.css.canvas.width}px`; + element.style.height = `${this.dimensions.css.cell.height}px`; + element.style.lineHeight = `${this.dimensions.css.cell.height}px`; + // Make sure rows don't overflow onto following row + element.style.overflow = 'hidden'; + } + + if (!this._dimensionsStyleElement) { + this._dimensionsStyleElement = this._document.createElement('style'); + this._screenElement.appendChild(this._dimensionsStyleElement); + } + + const styles = + `${this._terminalSelector} .${ROW_CONTAINER_CLASS} span {` + + ` display: inline-block;` + // TODO: find workaround for inline-block (creates ~20% render penalty) + ` height: 100%;` + + ` vertical-align: top;` + + `}`; + + this._dimensionsStyleElement.textContent = styles; + + this._selectionContainer.style.height = this._viewportElement.style.height; + this._screenElement.style.width = `${this.dimensions.css.canvas.width}px`; + this._screenElement.style.height = `${this.dimensions.css.canvas.height}px`; + } + + private _injectCss(colors: ReadonlyColorSet): void { + if (!this._themeStyleElement) { + this._themeStyleElement = this._document.createElement('style'); + this._screenElement.appendChild(this._themeStyleElement); + } + + // Base CSS + let styles = + `${this._terminalSelector} .${ROW_CONTAINER_CLASS} {` + + // Disabling pointer events circumvents a browser behavior that prevents `click` events from + // being delivered if the target element is replaced during the click. This happened due to + // refresh() being called during the mousedown handler to start a selection. + ` pointer-events: none;` + + ` color: ${colors.foreground.css};` + + ` font-family: ${this._optionsService.rawOptions.fontFamily};` + + ` font-size: ${this._optionsService.rawOptions.fontSize}px;` + + ` font-kerning: none;` + + ` white-space: pre` + + `}`; + styles += + `${this._terminalSelector} .${ROW_CONTAINER_CLASS} .xterm-dim {` + + ` color: ${color.multiplyOpacity(colors.foreground, 0.5).css};` + + `}`; + // Text styles + styles += + `${this._terminalSelector} span:not(.${RowCss.BOLD_CLASS}) {` + + ` font-weight: ${this._optionsService.rawOptions.fontWeight};` + + `}` + + `${this._terminalSelector} span.${RowCss.BOLD_CLASS} {` + + ` font-weight: ${this._optionsService.rawOptions.fontWeightBold};` + + `}` + + `${this._terminalSelector} span.${RowCss.ITALIC_CLASS} {` + + ` font-style: italic;` + + `}`; + // Blink animation + const blinkAnimationUnderlineId = `blink_underline_${this._terminalClass}`; + const blinkAnimationBarId = `blink_bar_${this._terminalClass}`; + const blinkAnimationBlockId = `blink_block_${this._terminalClass}`; + styles += + `@keyframes ${blinkAnimationUnderlineId} {` + + ` 50% {` + + ` border-bottom-style: hidden;` + + ` }` + + `}`; + styles += + `@keyframes ${blinkAnimationBarId} {` + + ` 50% {` + + ` box-shadow: none;` + + ` }` + + `}`; + styles += + `@keyframes ${blinkAnimationBlockId} {` + + ` 0% {` + + ` background-color: ${colors.cursor.css};` + + ` color: ${colors.cursorAccent.css};` + + ` }` + + ` 50% {` + + ` background-color: inherit;` + + ` color: ${colors.cursor.css};` + + ` }` + + `}`; + // Cursor + styles += + `${this._terminalSelector} .${ROW_CONTAINER_CLASS}.${FOCUS_CLASS} .${RowCss.CURSOR_CLASS}.${RowCss.CURSOR_BLINK_CLASS}.${RowCss.CURSOR_STYLE_UNDERLINE_CLASS} {` + + ` animation: ${blinkAnimationUnderlineId} 1s step-end infinite;` + + `}` + + `${this._terminalSelector} .${ROW_CONTAINER_CLASS}.${FOCUS_CLASS} .${RowCss.CURSOR_CLASS}.${RowCss.CURSOR_BLINK_CLASS}.${RowCss.CURSOR_STYLE_BAR_CLASS} {` + + ` animation: ${blinkAnimationBarId} 1s step-end infinite;` + + `}` + + `${this._terminalSelector} .${ROW_CONTAINER_CLASS}.${FOCUS_CLASS} .${RowCss.CURSOR_CLASS}.${RowCss.CURSOR_BLINK_CLASS}.${RowCss.CURSOR_STYLE_BLOCK_CLASS} {` + + ` animation: ${blinkAnimationBlockId} 1s step-end infinite;` + + `}` + + // !important helps fix an issue where the cursor will not render on top of the selection, + // however it's very hard to fix this issue and retain the blink animation without the use of + // !important. So this edge case fails when cursor blink is on. + `${this._terminalSelector} .${ROW_CONTAINER_CLASS} .${RowCss.CURSOR_CLASS}.${RowCss.CURSOR_STYLE_BLOCK_CLASS} {` + + ` background-color: ${colors.cursor.css};` + + ` color: ${colors.cursorAccent.css};` + + `}` + + `${this._terminalSelector} .${ROW_CONTAINER_CLASS} .${RowCss.CURSOR_CLASS}.${RowCss.CURSOR_STYLE_BLOCK_CLASS}:not(.${RowCss.CURSOR_BLINK_CLASS}) {` + + ` background-color: ${colors.cursor.css} !important;` + + ` color: ${colors.cursorAccent.css} !important;` + + `}` + + `${this._terminalSelector} .${ROW_CONTAINER_CLASS} .${RowCss.CURSOR_CLASS}.${RowCss.CURSOR_STYLE_OUTLINE_CLASS} {` + + ` outline: 1px solid ${colors.cursor.css};` + + ` outline-offset: -1px;` + + `}` + + `${this._terminalSelector} .${ROW_CONTAINER_CLASS} .${RowCss.CURSOR_CLASS}.${RowCss.CURSOR_STYLE_BAR_CLASS} {` + + ` box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${colors.cursor.css} inset;` + + `}` + + `${this._terminalSelector} .${ROW_CONTAINER_CLASS} .${RowCss.CURSOR_CLASS}.${RowCss.CURSOR_STYLE_UNDERLINE_CLASS} {` + + ` border-bottom: 1px ${colors.cursor.css};` + + ` border-bottom-style: solid;` + + ` height: calc(100% - 1px);` + + `}`; + // Selection + styles += + `${this._terminalSelector} .${SELECTION_CLASS} {` + + ` position: absolute;` + + ` top: 0;` + + ` left: 0;` + + ` z-index: 1;` + + ` pointer-events: none;` + + `}` + + `${this._terminalSelector}.focus .${SELECTION_CLASS} div {` + + ` position: absolute;` + + ` background-color: ${colors.selectionBackgroundOpaque.css};` + + `}` + + `${this._terminalSelector} .${SELECTION_CLASS} div {` + + ` position: absolute;` + + ` background-color: ${colors.selectionInactiveBackgroundOpaque.css};` + + `}`; + // Colors + for (const [i, c] of colors.ansi.entries()) { + styles += + `${this._terminalSelector} .${FG_CLASS_PREFIX}${i} { color: ${c.css}; }` + + `${this._terminalSelector} .${FG_CLASS_PREFIX}${i}.${RowCss.DIM_CLASS} { color: ${color.multiplyOpacity(c, 0.5).css}; }` + + `${this._terminalSelector} .${BG_CLASS_PREFIX}${i} { background-color: ${c.css}; }`; + } + styles += + `${this._terminalSelector} .${FG_CLASS_PREFIX}${INVERTED_DEFAULT_COLOR} { color: ${color.opaque(colors.background).css}; }` + + `${this._terminalSelector} .${FG_CLASS_PREFIX}${INVERTED_DEFAULT_COLOR}.${RowCss.DIM_CLASS} { color: ${color.multiplyOpacity(color.opaque(colors.background), 0.5).css}; }` + + `${this._terminalSelector} .${BG_CLASS_PREFIX}${INVERTED_DEFAULT_COLOR} { background-color: ${colors.foreground.css}; }`; + + this._themeStyleElement.textContent = styles; + } + + /** + * default letter spacing + * Due to rounding issues in dimensions dpr calc glyph might render + * slightly too wide or too narrow. The method corrects the stacking offsets + * by applying a default letter-spacing for all chars. + * The value gets passed to the row factory to avoid setting this value again + * (render speedup is roughly 10%). + */ + private _setDefaultSpacing(): void { + // measure same char as in CharSizeService to get the base deviation + const spacing = this.dimensions.css.cell.width - this._widthCache.get('W', false, false); + this._rowContainer.style.letterSpacing = `${spacing}px`; + this._rowFactory.defaultSpacing = spacing; + } + + public handleDevicePixelRatioChange(): void { + this._updateDimensions(); + this._widthCache.clear(); + this._setDefaultSpacing(); + } + + private _refreshRowElements(cols: number, rows: number): void { + // Add missing elements + for (let i = this._rowElements.length; i <= rows; i++) { + const row = this._document.createElement('div'); + this._rowContainer.appendChild(row); + this._rowElements.push(row); + } + // Remove excess elements + while (this._rowElements.length > rows) { + this._rowContainer.removeChild(this._rowElements.pop()!); + } + } + + public handleResize(cols: number, rows: number): void { + this._refreshRowElements(cols, rows); + this._updateDimensions(); + this.handleSelectionChanged(this._selectionRenderModel.selectionStart, this._selectionRenderModel.selectionEnd, this._selectionRenderModel.columnSelectMode); + } + + public handleCharSizeChanged(): void { + this._updateDimensions(); + this._widthCache.clear(); + this._setDefaultSpacing(); + } + + public handleBlur(): void { + this._rowContainer.classList.remove(FOCUS_CLASS); + this.renderRows(0, this._bufferService.rows - 1); + } + + public handleFocus(): void { + this._rowContainer.classList.add(FOCUS_CLASS); + this.renderRows(this._bufferService.buffer.y, this._bufferService.buffer.y); + } + + public handleSelectionChanged(start: [number, number] | undefined, end: [number, number] | undefined, columnSelectMode: boolean): void { + // Remove all selections + this._selectionContainer.replaceChildren(); + this._rowFactory.handleSelectionChanged(start, end, columnSelectMode); + this.renderRows(0, this._bufferService.rows - 1); + + // Selection does not exist + if (!start || !end) { + return; + } + + this._selectionRenderModel.update(this._terminal, start, end, columnSelectMode); + if (!this._selectionRenderModel.hasSelection) { + return; + } + + // Translate from buffer position to viewport position + const viewportStartRow = this._selectionRenderModel.viewportStartRow; + const viewportEndRow = this._selectionRenderModel.viewportEndRow; + const viewportCappedStartRow = this._selectionRenderModel.viewportCappedStartRow; + const viewportCappedEndRow = this._selectionRenderModel.viewportCappedEndRow; + + // Create the selections + const documentFragment = this._document.createDocumentFragment(); + + if (columnSelectMode) { + const isXFlipped = start[0] > end[0]; + documentFragment.appendChild( + this._createSelectionElement(viewportCappedStartRow, isXFlipped ? end[0] : start[0], isXFlipped ? start[0] : end[0], viewportCappedEndRow - viewportCappedStartRow + 1) + ); + } else { + // Draw first row + const startCol = viewportStartRow === viewportCappedStartRow ? start[0] : 0; + const endCol = viewportCappedStartRow === viewportEndRow ? end[0] : this._bufferService.cols; + documentFragment.appendChild(this._createSelectionElement(viewportCappedStartRow, startCol, endCol)); + // Draw middle rows + const middleRowsCount = viewportCappedEndRow - viewportCappedStartRow - 1; + documentFragment.appendChild(this._createSelectionElement(viewportCappedStartRow + 1, 0, this._bufferService.cols, middleRowsCount)); + // Draw final row + if (viewportCappedStartRow !== viewportCappedEndRow) { + // Only draw viewportEndRow if it's not the same as viewporttartRow + const endCol = viewportEndRow === viewportCappedEndRow ? end[0] : this._bufferService.cols; + documentFragment.appendChild(this._createSelectionElement(viewportCappedEndRow, 0, endCol)); + } + } + this._selectionContainer.appendChild(documentFragment); + } + + /** + * Creates a selection element at the specified position. + * @param row The row of the selection. + * @param colStart The start column. + * @param colEnd The end columns. + */ + private _createSelectionElement(row: number, colStart: number, colEnd: number, rowCount: number = 1): HTMLElement { + const element = this._document.createElement('div'); + const left = colStart * this.dimensions.css.cell.width; + let width = this.dimensions.css.cell.width * (colEnd - colStart); + if (left + width > this.dimensions.css.canvas.width) { + width = this.dimensions.css.canvas.width - left; + } + + element.style.height = `${rowCount * this.dimensions.css.cell.height}px`; + element.style.top = `${row * this.dimensions.css.cell.height}px`; + element.style.left = `${left}px`; + element.style.width = `${width}px`; + return element; + } + + public handleCursorMove(): void { + // No-op, the cursor is drawn when rows are drawn + } + + private _handleOptionsChanged(): void { + // Force a refresh + this._updateDimensions(); + // Refresh CSS + this._injectCss(this._themeService.colors); + // update spacing cache + this._widthCache.setFont( + this._optionsService.rawOptions.fontFamily, + this._optionsService.rawOptions.fontSize, + this._optionsService.rawOptions.fontWeight, + this._optionsService.rawOptions.fontWeightBold + ); + this._setDefaultSpacing(); + } + + public clear(): void { + for (const e of this._rowElements) { + /** + * NOTE: This used to be `e.innerText = '';` but that doesn't work when using `jsdom` and + * `@testing-library/react` + * + * references: + * - https://github.com/testing-library/react-testing-library/issues/1146 + * - https://github.com/jsdom/jsdom/issues/1245 + */ + e.replaceChildren(); + } + } + + public renderRows(start: number, end: number): void { + const buffer = this._bufferService.buffer; + const cursorAbsoluteY = buffer.ybase + buffer.y; + const cursorX = Math.min(buffer.x, this._bufferService.cols - 1); + const cursorBlink = this._coreService.decPrivateModes.cursorBlink ?? this._optionsService.rawOptions.cursorBlink; + const cursorStyle = this._coreService.decPrivateModes.cursorStyle ?? this._optionsService.rawOptions.cursorStyle; + const cursorInactiveStyle = this._optionsService.rawOptions.cursorInactiveStyle; + + for (let y = start; y <= end; y++) { + const row = y + buffer.ydisp; + const rowElement = this._rowElements[y]; + const lineData = buffer.lines.get(row); + if (!rowElement || !lineData) { + break; + } + rowElement.replaceChildren( + ...this._rowFactory.createRow( + lineData, + row, + row === cursorAbsoluteY, + cursorStyle, + cursorInactiveStyle, + cursorX, + cursorBlink, + this.dimensions.css.cell.width, + this._widthCache, + -1, + -1 + ) + ); + } + } + + private get _terminalSelector(): string { + return `.${TERMINAL_CLASS_PREFIX}${this._terminalClass}`; + } + + private _handleLinkHover(e: ILinkifierEvent): void { + this._setCellUnderline(e.x1, e.x2, e.y1, e.y2, e.cols, true); + } + + private _handleLinkLeave(e: ILinkifierEvent): void { + this._setCellUnderline(e.x1, e.x2, e.y1, e.y2, e.cols, false); + } + + private _setCellUnderline(x: number, x2: number, y: number, y2: number, cols: number, enabled: boolean): void { + /** + * NOTE: The linkifier may send out of viewport y-values if: + * - negative y-value: the link started at a higher line + * - y-value >= maxY: the link ends at a line below viewport + * + * For negative y-values we can simply adjust x = 0, + * as higher up link start means, that everything from + * (0,0) is a link under top-down-left-right char progression + * + * Additionally there might be a small chance of out-of-sync x|y-values + * from a race condition of render updates vs. link event handler execution: + * - (sync) resize: chances terminal buffer in sync, schedules render update async + * - (async) link handler race condition: new buffer metrics, but still on old render state + * - (async) render update: brings term metrics and render state back in sync + */ + // clip coords into viewport + if (y < 0) x = 0; + if (y2 < 0) x2 = 0; + const maxY = this._bufferService.rows - 1; + y = Math.max(Math.min(y, maxY), 0); + y2 = Math.max(Math.min(y2, maxY), 0); + + cols = Math.min(cols, this._bufferService.cols); + const buffer = this._bufferService.buffer; + const cursorAbsoluteY = buffer.ybase + buffer.y; + const cursorX = Math.min(buffer.x, cols - 1); + const cursorBlink = this._optionsService.rawOptions.cursorBlink; + const cursorStyle = this._optionsService.rawOptions.cursorStyle; + const cursorInactiveStyle = this._optionsService.rawOptions.cursorInactiveStyle; + + // refresh rows within link range + for (let i = y; i <= y2; ++i) { + const row = i + buffer.ydisp; + const rowElement = this._rowElements[i]; + const bufferline = buffer.lines.get(row); + if (!rowElement || !bufferline) { + break; + } + rowElement.replaceChildren( + ...this._rowFactory.createRow( + bufferline, + row, + row === cursorAbsoluteY, + cursorStyle, + cursorInactiveStyle, + cursorX, + cursorBlink, + this.dimensions.css.cell.width, + this._widthCache, + enabled ? (i === y ? x : 0) : -1, + enabled ? ((i === y2 ? x2 : cols) - 1) : -1 + ) + ); + } + } +} diff --git a/node_modules/@xterm/xterm/src/browser/renderer/dom/DomRendererRowFactory.ts b/node_modules/@xterm/xterm/src/browser/renderer/dom/DomRendererRowFactory.ts new file mode 100644 index 0000000..96d3f17 --- /dev/null +++ b/node_modules/@xterm/xterm/src/browser/renderer/dom/DomRendererRowFactory.ts @@ -0,0 +1,546 @@ +/** + * Copyright (c) 2018, 2023 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { IBufferLine, ICellData, IColor } from 'common/Types'; +import { INVERTED_DEFAULT_COLOR } from 'browser/renderer/shared/Constants'; +import { WHITESPACE_CELL_CHAR, Attributes } from 'common/buffer/Constants'; +import { CellData } from 'common/buffer/CellData'; +import { ICoreService, IDecorationService, IOptionsService } from 'common/services/Services'; +import { channels, color } from 'common/Color'; +import { ICharacterJoinerService, ICoreBrowserService, IThemeService } from 'browser/services/Services'; +import { JoinedCellData } from 'browser/services/CharacterJoinerService'; +import { treatGlyphAsBackgroundColor } from 'browser/renderer/shared/RendererUtils'; +import { AttributeData } from 'common/buffer/AttributeData'; +import { WidthCache } from 'browser/renderer/dom/WidthCache'; +import { IColorContrastCache } from 'browser/Types'; + + +export const enum RowCss { + BOLD_CLASS = 'xterm-bold', + DIM_CLASS = 'xterm-dim', + ITALIC_CLASS = 'xterm-italic', + UNDERLINE_CLASS = 'xterm-underline', + OVERLINE_CLASS = 'xterm-overline', + STRIKETHROUGH_CLASS = 'xterm-strikethrough', + CURSOR_CLASS = 'xterm-cursor', + CURSOR_BLINK_CLASS = 'xterm-cursor-blink', + CURSOR_STYLE_BLOCK_CLASS = 'xterm-cursor-block', + CURSOR_STYLE_OUTLINE_CLASS = 'xterm-cursor-outline', + CURSOR_STYLE_BAR_CLASS = 'xterm-cursor-bar', + CURSOR_STYLE_UNDERLINE_CLASS = 'xterm-cursor-underline' +} + + +export class DomRendererRowFactory { + private _workCell: CellData = new CellData(); + + private _selectionStart: [number, number] | undefined; + private _selectionEnd: [number, number] | undefined; + private _columnSelectMode: boolean = false; + + public defaultSpacing = 0; + + constructor( + private readonly _document: Document, + @ICharacterJoinerService private readonly _characterJoinerService: ICharacterJoinerService, + @IOptionsService private readonly _optionsService: IOptionsService, + @ICoreBrowserService private readonly _coreBrowserService: ICoreBrowserService, + @ICoreService private readonly _coreService: ICoreService, + @IDecorationService private readonly _decorationService: IDecorationService, + @IThemeService private readonly _themeService: IThemeService + ) {} + + public handleSelectionChanged(start: [number, number] | undefined, end: [number, number] | undefined, columnSelectMode: boolean): void { + this._selectionStart = start; + this._selectionEnd = end; + this._columnSelectMode = columnSelectMode; + } + + public createRow( + lineData: IBufferLine, + row: number, + isCursorRow: boolean, + cursorStyle: string | undefined, + cursorInactiveStyle: string | undefined, + cursorX: number, + cursorBlink: boolean, + cellWidth: number, + widthCache: WidthCache, + linkStart: number, + linkEnd: number + ): HTMLSpanElement[] { + + const elements: HTMLSpanElement[] = []; + const joinedRanges = this._characterJoinerService.getJoinedCharacters(row); + const colors = this._themeService.colors; + + let lineLength = lineData.getNoBgTrimmedLength(); + if (isCursorRow && lineLength < cursorX + 1) { + lineLength = cursorX + 1; + } + + let charElement: HTMLSpanElement | undefined; + let cellAmount = 0; + let text = ''; + let i = 0; + let oldBg = 0; + let oldFg = 0; + let oldExt = 0; + let oldLinkHover: number | boolean = false; + let oldSpacing = 0; + let oldIsInSelection: boolean = false; + let spacing = 0; + let skipJoinedCheckUntilX = 0; + const classes: string[] = []; + + const hasHover = linkStart !== -1 && linkEnd !== -1; + + for (let x = 0; x < lineLength; x++) { + lineData.loadCell(x, this._workCell); + let width = this._workCell.getWidth(); + + // The character to the left is a wide character, drawing is owned by the char at x-1 + if (width === 0) { + continue; + } + + // If true, indicates that the current character(s) to draw were joined. + let isJoined = false; + + // Indicates whether this cell is part of a joined range that should be ignored as it cannot + // be rendered entirely, like the selection state differs across the range. + let isValidJoinRange = (x >= skipJoinedCheckUntilX); + + let lastCharX = x; + + // Process any joined character ranges as needed. Because of how the + // ranges are produced, we know that they are valid for the characters + // and attributes of our input. + let cell = this._workCell; + if (joinedRanges.length > 0 && x === joinedRanges[0][0] && isValidJoinRange) { + const range = joinedRanges.shift()!; + // If the ligature's selection state is not consistent, don't join it. This helps the + // selection render correctly regardless whether they should be joined. + const firstSelectionState = this._isCellInSelection(range[0], row); + for (i = range[0] + 1; i < range[1]; i++) { + isValidJoinRange &&= (firstSelectionState === this._isCellInSelection(i, row)); + } + // Similarly, if the cursor is in the ligature, don't join it. + isValidJoinRange &&= !isCursorRow || cursorX < range[0] || cursorX >= range[1]; + if (!isValidJoinRange) { + skipJoinedCheckUntilX = range[1]; + } else { + isJoined = true; + + // We already know the exact start and end column of the joined range, + // so we get the string and width representing it directly + cell = new JoinedCellData( + this._workCell, + lineData.translateToString(true, range[0], range[1]), + range[1] - range[0] + ); + + // Skip over the cells occupied by this range in the loop + lastCharX = range[1] - 1; + + // Recalculate width + width = cell.getWidth(); + } + } + + const isInSelection = this._isCellInSelection(x, row); + const isCursorCell = isCursorRow && x === cursorX; + const isLinkHover = hasHover && x >= linkStart && x <= linkEnd; + + let isDecorated = false; + this._decorationService.forEachDecorationAtCell(x, row, undefined, d => { + isDecorated = true; + }); + + // get chars to render for this cell + let chars = cell.getChars() || WHITESPACE_CELL_CHAR; + if (chars === ' ' && (cell.isUnderline() || cell.isOverline())) { + chars = '\xa0'; + } + + // lookup char render width and calc spacing + spacing = width * cellWidth - widthCache.get(chars, cell.isBold(), cell.isItalic()); + + if (!charElement) { + charElement = this._document.createElement('span'); + } else { + /** + * chars can only be merged on existing span if: + * - existing span only contains mergeable chars (cellAmount != 0) + * - bg did not change (or both are in selection) + * - fg did not change (or both are in selection and selection fg is set) + * - ext did not change + * - underline from hover state did not change + * - cell content renders to same letter-spacing + * - cell is not cursor + */ + if ( + cellAmount + && ( + (isInSelection && oldIsInSelection) + || (!isInSelection && !oldIsInSelection && cell.bg === oldBg) + ) + && ( + (isInSelection && oldIsInSelection && colors.selectionForeground) + || cell.fg === oldFg + ) + && cell.extended.ext === oldExt + && isLinkHover === oldLinkHover + && spacing === oldSpacing + && !isCursorCell + && !isJoined + && !isDecorated + && isValidJoinRange + ) { + // no span alterations, thus only account chars skipping all code below + if (cell.isInvisible()) { + text += WHITESPACE_CELL_CHAR; + } else { + text += chars; + } + cellAmount++; + continue; + } else { + /** + * cannot merge: + * - apply left-over text to old span + * - create new span, reset state holders cellAmount & text + */ + if (cellAmount) { + charElement.textContent = text; + } + charElement = this._document.createElement('span'); + cellAmount = 0; + text = ''; + } + } + // preserve conditions for next merger eval round + oldBg = cell.bg; + oldFg = cell.fg; + oldExt = cell.extended.ext; + oldLinkHover = isLinkHover; + oldSpacing = spacing; + oldIsInSelection = isInSelection; + + if (isJoined) { + // The DOM renderer colors the background of the cursor but for ligatures all cells are + // joined. The workaround here is to show a cursor around the whole ligature so it shows up, + // the cursor looks the same when on any character of the ligature though + if (cursorX >= x && cursorX <= lastCharX) { + cursorX = x; + } + } + + if (!this._coreService.isCursorHidden && isCursorCell && this._coreService.isCursorInitialized) { + classes.push(RowCss.CURSOR_CLASS); + if (this._coreBrowserService.isFocused) { + if (cursorBlink) { + classes.push(RowCss.CURSOR_BLINK_CLASS); + } + classes.push( + cursorStyle === 'bar' + ? RowCss.CURSOR_STYLE_BAR_CLASS + : cursorStyle === 'underline' + ? RowCss.CURSOR_STYLE_UNDERLINE_CLASS + : RowCss.CURSOR_STYLE_BLOCK_CLASS + ); + } else { + if (cursorInactiveStyle) { + switch (cursorInactiveStyle) { + case 'outline': + classes.push(RowCss.CURSOR_STYLE_OUTLINE_CLASS); + break; + case 'block': + classes.push(RowCss.CURSOR_STYLE_BLOCK_CLASS); + break; + case 'bar': + classes.push(RowCss.CURSOR_STYLE_BAR_CLASS); + break; + case 'underline': + classes.push(RowCss.CURSOR_STYLE_UNDERLINE_CLASS); + break; + default: + break; + } + } + } + } + + if (cell.isBold()) { + classes.push(RowCss.BOLD_CLASS); + } + + if (cell.isItalic()) { + classes.push(RowCss.ITALIC_CLASS); + } + + if (cell.isDim()) { + classes.push(RowCss.DIM_CLASS); + } + + if (cell.isInvisible()) { + text = WHITESPACE_CELL_CHAR; + } else { + text = cell.getChars() || WHITESPACE_CELL_CHAR; + } + + if (cell.isUnderline()) { + classes.push(`${RowCss.UNDERLINE_CLASS}-${cell.extended.underlineStyle}`); + if (text === ' ') { + text = '\xa0'; // =   + } + if (!cell.isUnderlineColorDefault()) { + if (cell.isUnderlineColorRGB()) { + charElement.style.textDecorationColor = `rgb(${AttributeData.toColorRGB(cell.getUnderlineColor()).join(',')})`; + } else { + let fg = cell.getUnderlineColor(); + if (this._optionsService.rawOptions.drawBoldTextInBrightColors && cell.isBold() && fg < 8) { + fg += 8; + } + charElement.style.textDecorationColor = colors.ansi[fg].css; + } + } + } + + if (cell.isOverline()) { + classes.push(RowCss.OVERLINE_CLASS); + if (text === ' ') { + text = '\xa0'; // =   + } + } + + if (cell.isStrikethrough()) { + classes.push(RowCss.STRIKETHROUGH_CLASS); + } + + // apply link hover underline late, effectively overrides any previous text-decoration + // settings + if (isLinkHover) { + charElement.style.textDecoration = 'underline'; + } + + let fg = cell.getFgColor(); + let fgColorMode = cell.getFgColorMode(); + let bg = cell.getBgColor(); + let bgColorMode = cell.getBgColorMode(); + const isInverse = !!cell.isInverse(); + if (isInverse) { + const temp = fg; + fg = bg; + bg = temp; + const temp2 = fgColorMode; + fgColorMode = bgColorMode; + bgColorMode = temp2; + } + + // Apply any decoration foreground/background overrides, this must happen after inverse has + // been applied + let bgOverride: IColor | undefined; + let fgOverride: IColor | undefined; + let isTop = false; + this._decorationService.forEachDecorationAtCell(x, row, undefined, d => { + if (d.options.layer !== 'top' && isTop) { + return; + } + if (d.backgroundColorRGB) { + bgColorMode = Attributes.CM_RGB; + bg = d.backgroundColorRGB.rgba >> 8 & 0xFFFFFF; + bgOverride = d.backgroundColorRGB; + } + if (d.foregroundColorRGB) { + fgColorMode = Attributes.CM_RGB; + fg = d.foregroundColorRGB.rgba >> 8 & 0xFFFFFF; + fgOverride = d.foregroundColorRGB; + } + isTop = d.options.layer === 'top'; + }); + + // Apply selection + if (!isTop && isInSelection) { + // If in the selection, force the element to be above the selection to improve contrast and + // support opaque selections. The applies background is not actually needed here as + // selection is drawn in a seperate container, the main purpose of this to ensuring minimum + // contrast ratio + bgOverride = this._coreBrowserService.isFocused ? colors.selectionBackgroundOpaque : colors.selectionInactiveBackgroundOpaque; + bg = bgOverride.rgba >> 8 & 0xFFFFFF; + bgColorMode = Attributes.CM_RGB; + // Since an opaque selection is being rendered, the selection pretends to be a decoration to + // ensure text is drawn above the selection. + isTop = true; + // Apply selection foreground if applicable + if (colors.selectionForeground) { + fgColorMode = Attributes.CM_RGB; + fg = colors.selectionForeground.rgba >> 8 & 0xFFFFFF; + fgOverride = colors.selectionForeground; + } + } + + // If it's a top decoration, render above the selection + if (isTop) { + classes.push('xterm-decoration-top'); + } + + // Background + let resolvedBg: IColor; + switch (bgColorMode) { + case Attributes.CM_P16: + case Attributes.CM_P256: + resolvedBg = colors.ansi[bg]; + classes.push(`xterm-bg-${bg}`); + break; + case Attributes.CM_RGB: + resolvedBg = channels.toColor(bg >> 16, bg >> 8 & 0xFF, bg & 0xFF); + this._addStyle(charElement, `background-color:#${padStart((bg >>> 0).toString(16), '0', 6)}`); + break; + case Attributes.CM_DEFAULT: + default: + if (isInverse) { + resolvedBg = colors.foreground; + classes.push(`xterm-bg-${INVERTED_DEFAULT_COLOR}`); + } else { + resolvedBg = colors.background; + } + } + + // If there is no background override by now it's the original color, so apply dim if needed + if (!bgOverride) { + if (cell.isDim()) { + bgOverride = color.multiplyOpacity(resolvedBg, 0.5); + } + } + + // Foreground + switch (fgColorMode) { + case Attributes.CM_P16: + case Attributes.CM_P256: + if (cell.isBold() && fg < 8 && this._optionsService.rawOptions.drawBoldTextInBrightColors) { + fg += 8; + } + if (!this._applyMinimumContrast(charElement, resolvedBg, colors.ansi[fg], cell, bgOverride, undefined)) { + classes.push(`xterm-fg-${fg}`); + } + break; + case Attributes.CM_RGB: + const color = channels.toColor( + (fg >> 16) & 0xFF, + (fg >> 8) & 0xFF, + (fg ) & 0xFF + ); + if (!this._applyMinimumContrast(charElement, resolvedBg, color, cell, bgOverride, fgOverride)) { + this._addStyle(charElement, `color:#${padStart(fg.toString(16), '0', 6)}`); + } + break; + case Attributes.CM_DEFAULT: + default: + if (!this._applyMinimumContrast(charElement, resolvedBg, colors.foreground, cell, bgOverride, fgOverride)) { + if (isInverse) { + classes.push(`xterm-fg-${INVERTED_DEFAULT_COLOR}`); + } + } + } + + // apply CSS classes + // slightly faster than using classList by omitting + // checks for doubled entries (code above should not have doublets) + if (classes.length) { + charElement.className = classes.join(' '); + classes.length = 0; + } + + // exclude conditions for cell merging - never merge these + if (!isCursorCell && !isJoined && !isDecorated && isValidJoinRange) { + cellAmount++; + } else { + charElement.textContent = text; + } + // apply letter-spacing rule + if (spacing !== this.defaultSpacing) { + charElement.style.letterSpacing = `${spacing}px`; + } + + elements.push(charElement); + x = lastCharX; + } + + // postfix text of last merged span + if (charElement && cellAmount) { + charElement.textContent = text; + } + + return elements; + } + + private _applyMinimumContrast(element: HTMLElement, bg: IColor, fg: IColor, cell: ICellData, bgOverride: IColor | undefined, fgOverride: IColor | undefined): boolean { + if (this._optionsService.rawOptions.minimumContrastRatio === 1 || treatGlyphAsBackgroundColor(cell.getCode())) { + return false; + } + + // Try get from cache first, only use the cache when there are no decoration overrides + const cache = this._getContrastCache(cell); + let adjustedColor: IColor | undefined | null = undefined; + if (!bgOverride && !fgOverride) { + adjustedColor = cache.getColor(bg.rgba, fg.rgba); + } + + // Calculate and store in cache + if (adjustedColor === undefined) { + // Dim cells only require half the contrast, otherwise they wouldn't be distinguishable from + // non-dim cells + const ratio = this._optionsService.rawOptions.minimumContrastRatio / (cell.isDim() ? 2 : 1); + adjustedColor = color.ensureContrastRatio(bgOverride || bg, fgOverride || fg, ratio); + cache.setColor((bgOverride || bg).rgba, (fgOverride || fg).rgba, adjustedColor ?? null); + } + + if (adjustedColor) { + this._addStyle(element, `color:${adjustedColor.css}`); + return true; + } + + return false; + } + + private _getContrastCache(cell: ICellData): IColorContrastCache { + if (cell.isDim()) { + return this._themeService.colors.halfContrastCache; + } + return this._themeService.colors.contrastCache; + } + + private _addStyle(element: HTMLElement, style: string): void { + element.setAttribute('style', `${element.getAttribute('style') || ''}${style};`); + } + + private _isCellInSelection(x: number, y: number): boolean { + const start = this._selectionStart; + const end = this._selectionEnd; + if (!start || !end) { + return false; + } + if (this._columnSelectMode) { + if (start[0] <= end[0]) { + return x >= start[0] && y >= start[1] && + x < end[0] && y <= end[1]; + } + return x < start[0] && y >= start[1] && + x >= end[0] && y <= end[1]; + } + return (y > start[1] && y < end[1]) || + (start[1] === end[1] && y === start[1] && x >= start[0] && x < end[0]) || + (start[1] < end[1] && y === end[1] && x < end[0]) || + (start[1] < end[1] && y === start[1] && x >= start[0]); + } +} + +function padStart(text: string, padChar: string, length: number): string { + while (text.length < length) { + text = padChar + text; + } + return text; +} diff --git a/node_modules/@xterm/xterm/src/browser/renderer/dom/WidthCache.ts b/node_modules/@xterm/xterm/src/browser/renderer/dom/WidthCache.ts new file mode 100644 index 0000000..03d6cb7 --- /dev/null +++ b/node_modules/@xterm/xterm/src/browser/renderer/dom/WidthCache.ts @@ -0,0 +1,167 @@ +/** + * Copyright (c) 2023 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { IDisposable } from 'common/Types'; +import { FontWeight } from 'common/services/Services'; + + +export const enum WidthCacheSettings { + /** sentinel for unset values in flat cache */ + FLAT_UNSET = -9999, + /** size of flat cache, size-1 equals highest codepoint handled by flat */ + FLAT_SIZE = 256, + /** char repeat for measuring */ + REPEAT = 32 +} + + +const enum FontVariant { + REGULAR = 0, + BOLD = 1, + ITALIC = 2, + BOLD_ITALIC = 3 +} + + +export class WidthCache implements IDisposable { + // flat cache for regular variant up to CacheSettings.FLAT_SIZE + // NOTE: ~4x faster access than holey (serving >>80% of terminal content) + // It has a small memory footprint (only 1MB for full BMP caching), + // still the sweet spot is not reached before touching 32k different codepoints, + // thus we store the remaining <<20% of terminal data in a holey structure. + protected _flat = new Float32Array(WidthCacheSettings.FLAT_SIZE); + + // holey cache for bold, italic and bold&italic for any string + // FIXME: can grow really big over time (~8.5 MB for full BMP caching), + // so a shared API across terminals is needed + protected _holey: Map | undefined; + + private _font = ''; + private _fontSize = 0; + private _weight: FontWeight = 'normal'; + private _weightBold: FontWeight = 'bold'; + private _container: HTMLDivElement; + private _measureElements: HTMLSpanElement[] = []; + + constructor(_document: Document, _helperContainer: HTMLElement) { + this._container = _document.createElement('div'); + this._container.classList.add('xterm-width-cache-measure-container'); + this._container.setAttribute('aria-hidden', 'true'); + // SP should stack in spans + this._container.style.whiteSpace = 'pre'; + // avoid undercuts in non-monospace fonts from kerning + this._container.style.fontKerning = 'none'; + + const regular = _document.createElement('span'); + regular.classList.add('xterm-char-measure-element'); + + const bold = _document.createElement('span'); + bold.classList.add('xterm-char-measure-element'); + bold.style.fontWeight = 'bold'; + + const italic = _document.createElement('span'); + italic.classList.add('xterm-char-measure-element'); + italic.style.fontStyle = 'italic'; + + const boldItalic = _document.createElement('span'); + boldItalic.classList.add('xterm-char-measure-element'); + boldItalic.style.fontWeight = 'bold'; + boldItalic.style.fontStyle = 'italic'; + + // NOTE: must be in order of FontVariant + this._measureElements = [regular, bold, italic, boldItalic]; + this._container.appendChild(regular); + this._container.appendChild(bold); + this._container.appendChild(italic); + this._container.appendChild(boldItalic); + + _helperContainer.appendChild(this._container); + + this.clear(); + } + + public dispose(): void { + this._container.remove(); // remove elements from DOM + this._measureElements.length = 0; // release element refs + this._holey = undefined; // free cache memory via GC + } + + /** + * Clear the width cache. + */ + public clear(): void { + this._flat.fill(WidthCacheSettings.FLAT_UNSET); + // .clear() has some overhead, re-assign instead (>3 times faster) + this._holey = new Map(); + } + + /** + * Set the font for measuring. + * Must be called for any changes on font settings. + * Also clears the cache. + */ + public setFont(font: string, fontSize: number, weight: FontWeight, weightBold: FontWeight): void { + // skip if nothing changed + if (font === this._font + && fontSize === this._fontSize + && weight === this._weight + && weightBold === this._weightBold + ) { + return; + } + + this._font = font; + this._fontSize = fontSize; + this._weight = weight; + this._weightBold = weightBold; + + this._container.style.fontFamily = this._font; + this._container.style.fontSize = `${this._fontSize}px`; + this._measureElements[FontVariant.REGULAR].style.fontWeight = `${weight}`; + this._measureElements[FontVariant.BOLD].style.fontWeight = `${weightBold}`; + this._measureElements[FontVariant.ITALIC].style.fontWeight = `${weight}`; + this._measureElements[FontVariant.BOLD_ITALIC].style.fontWeight = `${weightBold}`; + + this.clear(); + } + + /** + * Get the render width for cell content `c` with current font settings. + * `variant` denotes the font variant to be used. + */ + public get(c: string, bold: boolean | number, italic: boolean | number): number { + let cp = 0; + if (!bold && !italic && c.length === 1 && (cp = c.charCodeAt(0)) < WidthCacheSettings.FLAT_SIZE) { + if (this._flat[cp] !== WidthCacheSettings.FLAT_UNSET) { + return this._flat[cp]; + } + const width = this._measure(c, 0); + if (width > 0) { + this._flat[cp] = width; + } + return width; + } + let key = c; + if (bold) key += 'B'; + if (italic) key += 'I'; + let width = this._holey!.get(key); + if (width === undefined) { + let variant = 0; + if (bold) variant |= FontVariant.BOLD; + if (italic) variant |= FontVariant.ITALIC; + width = this._measure(c, variant); + if (width > 0) { + this._holey!.set(key, width); + } + } + return width; + } + + protected _measure(c: string, variant: FontVariant): number { + const el = this._measureElements[variant]; + el.textContent = c.repeat(WidthCacheSettings.REPEAT); + return el.offsetWidth / WidthCacheSettings.REPEAT; + } +} diff --git a/node_modules/@xterm/xterm/src/browser/renderer/shared/Constants.ts b/node_modules/@xterm/xterm/src/browser/renderer/shared/Constants.ts new file mode 100644 index 0000000..4bc4f98 --- /dev/null +++ b/node_modules/@xterm/xterm/src/browser/renderer/shared/Constants.ts @@ -0,0 +1,6 @@ +/** + * Copyright (c) 2017 The xterm.js authors. All rights reserved. + * @license MIT + */ + +export const INVERTED_DEFAULT_COLOR = 257; diff --git a/node_modules/@xterm/xterm/src/browser/renderer/shared/RendererUtils.ts b/node_modules/@xterm/xterm/src/browser/renderer/shared/RendererUtils.ts new file mode 100644 index 0000000..0106436 --- /dev/null +++ b/node_modules/@xterm/xterm/src/browser/renderer/shared/RendererUtils.ts @@ -0,0 +1,95 @@ +/** + * Copyright (c) 2019 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { IDimensions, IRenderDimensions } from 'browser/renderer/shared/Types'; + +export function throwIfFalsy(value: T | undefined | null): T { + if (!value) { + throw new Error('value must not be falsy'); + } + return value; +} + +export function isPowerlineGlyph(codepoint: number): boolean { + // Only return true for Powerline symbols which require + // different padding and should be excluded from minimum contrast + // ratio standards + return 0xE0A4 <= codepoint && codepoint <= 0xE0D6; +} + +export function isRestrictedPowerlineGlyph(codepoint: number): boolean { + return 0xE0B0 <= codepoint && codepoint <= 0xE0B7; +} + +function isNerdFontGlyph(codepoint: number): boolean { + return 0xE000 <= codepoint && codepoint <= 0xF8FF; +} + +function isBoxOrBlockGlyph(codepoint: number): boolean { + return 0x2500 <= codepoint && codepoint <= 0x259F; +} + +export function isEmoji(codepoint: number): boolean { + return ( + codepoint >= 0x1F600 && codepoint <= 0x1F64F || // Emoticons + codepoint >= 0x1F300 && codepoint <= 0x1F5FF || // Misc Symbols and Pictographs + codepoint >= 0x1F680 && codepoint <= 0x1F6FF || // Transport and Map + codepoint >= 0x2600 && codepoint <= 0x26FF || // Misc symbols + codepoint >= 0x2700 && codepoint <= 0x27BF || // Dingbats + codepoint >= 0xFE00 && codepoint <= 0xFE0F || // Variation Selectors + codepoint >= 0x1F900 && codepoint <= 0x1F9FF || // Supplemental Symbols and Pictographs + codepoint >= 0x1F1E6 && codepoint <= 0x1F1FF + ); +} + +export function allowRescaling(codepoint: number | undefined, width: number, glyphSizeX: number, deviceCellWidth: number): boolean { + return ( + // Is single cell width + width === 1 && + // Glyph exceeds cell bounds, add 50% to avoid hurting readability by rescaling glyphs that + // barely overlap + glyphSizeX > Math.ceil(deviceCellWidth * 1.5) && + // Never rescale ascii + codepoint !== undefined && codepoint > 0xFF && + // Never rescale emoji + !isEmoji(codepoint) && + // Never rescale powerline or nerd fonts + !isPowerlineGlyph(codepoint) && !isNerdFontGlyph(codepoint) + ); +} + +export function treatGlyphAsBackgroundColor(codepoint: number): boolean { + return isPowerlineGlyph(codepoint) || isBoxOrBlockGlyph(codepoint); +} + +export function createRenderDimensions(): IRenderDimensions { + return { + css: { + canvas: createDimension(), + cell: createDimension() + }, + device: { + canvas: createDimension(), + cell: createDimension(), + char: { + width: 0, + height: 0, + left: 0, + top: 0 + } + } + }; +} + +function createDimension(): IDimensions { + return { + width: 0, + height: 0 + }; +} + +export function computeNextVariantOffset(cellWidth: number, lineWidth: number, currentOffset: number = 0): number { + return (cellWidth - (Math.round(lineWidth) * 2 - currentOffset)) % (Math.round(lineWidth) * 2); +} diff --git a/node_modules/@xterm/xterm/src/browser/renderer/shared/SelectionRenderModel.ts b/node_modules/@xterm/xterm/src/browser/renderer/shared/SelectionRenderModel.ts new file mode 100644 index 0000000..d3b7a99 --- /dev/null +++ b/node_modules/@xterm/xterm/src/browser/renderer/shared/SelectionRenderModel.ts @@ -0,0 +1,93 @@ +/** + * Copyright (c) 2022 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { ITerminal } from 'browser/Types'; +import { ISelectionRenderModel } from 'browser/renderer/shared/Types'; +import { Terminal } from '@xterm/xterm'; + +class SelectionRenderModel implements ISelectionRenderModel { + public hasSelection!: boolean; + public columnSelectMode!: boolean; + public viewportStartRow!: number; + public viewportEndRow!: number; + public viewportCappedStartRow!: number; + public viewportCappedEndRow!: number; + public startCol!: number; + public endCol!: number; + public selectionStart: [number, number] | undefined; + public selectionEnd: [number, number] | undefined; + + constructor() { + this.clear(); + } + + public clear(): void { + this.hasSelection = false; + this.columnSelectMode = false; + this.viewportStartRow = 0; + this.viewportEndRow = 0; + this.viewportCappedStartRow = 0; + this.viewportCappedEndRow = 0; + this.startCol = 0; + this.endCol = 0; + this.selectionStart = undefined; + this.selectionEnd = undefined; + } + + public update(terminal: ITerminal, start: [number, number] | undefined, end: [number, number] | undefined, columnSelectMode: boolean = false): void { + this.selectionStart = start; + this.selectionEnd = end; + // Selection does not exist + if (!start || !end || (start[0] === end[0] && start[1] === end[1])) { + this.clear(); + return; + } + + // Translate from buffer position to viewport position + const viewportY = terminal.buffers.active.ydisp; + const viewportStartRow = start[1] - viewportY; + const viewportEndRow = end[1] - viewportY; + const viewportCappedStartRow = Math.max(viewportStartRow, 0); + const viewportCappedEndRow = Math.min(viewportEndRow, terminal.rows - 1); + + // No need to draw the selection + if (viewportCappedStartRow >= terminal.rows || viewportCappedEndRow < 0) { + this.clear(); + return; + } + + this.hasSelection = true; + this.columnSelectMode = columnSelectMode; + this.viewportStartRow = viewportStartRow; + this.viewportEndRow = viewportEndRow; + this.viewportCappedStartRow = viewportCappedStartRow; + this.viewportCappedEndRow = viewportCappedEndRow; + this.startCol = start[0]; + this.endCol = end[0]; + } + + public isCellSelected(terminal: Terminal, x: number, y: number): boolean { + if (!this.hasSelection) { + return false; + } + y -= terminal.buffer.active.viewportY; + if (this.columnSelectMode) { + if (this.startCol <= this.endCol) { + return x >= this.startCol && y >= this.viewportCappedStartRow && + x < this.endCol && y <= this.viewportCappedEndRow; + } + return x < this.startCol && y >= this.viewportCappedStartRow && + x >= this.endCol && y <= this.viewportCappedEndRow; + } + return (y > this.viewportStartRow && y < this.viewportEndRow) || + (this.viewportStartRow === this.viewportEndRow && y === this.viewportStartRow && x >= this.startCol && x < this.endCol) || + (this.viewportStartRow < this.viewportEndRow && y === this.viewportEndRow && x < this.endCol) || + (this.viewportStartRow < this.viewportEndRow && y === this.viewportStartRow && x >= this.startCol); + } +} + +export function createSelectionRenderModel(): ISelectionRenderModel { + return new SelectionRenderModel(); +} diff --git a/node_modules/@xterm/xterm/src/browser/renderer/shared/Types.ts b/node_modules/@xterm/xterm/src/browser/renderer/shared/Types.ts new file mode 100644 index 0000000..f783ffe --- /dev/null +++ b/node_modules/@xterm/xterm/src/browser/renderer/shared/Types.ts @@ -0,0 +1,84 @@ +/** + * Copyright (c) 2017 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { Terminal } from '@xterm/xterm'; +import { ITerminal } from 'browser/Types'; +import { IDisposable } from 'common/Types'; +import type { Event } from 'vs/base/common/event'; + +export interface IDimensions { + width: number; + height: number; +} + +export interface IOffset { + top: number; + left: number; +} + +export interface IRenderDimensions { + /** + * Dimensions measured in CSS pixels (ie. device pixels / device pixel ratio). + */ + css: { + canvas: IDimensions; + cell: IDimensions; + }; + /** + * Dimensions measured in actual pixels as rendered to the device. + */ + device: { + canvas: IDimensions; + cell: IDimensions; + char: IDimensions & IOffset; + }; +} + +export interface IRequestRedrawEvent { + start: number; + end: number; +} + +/** + * Note that IRenderer implementations should emit the refresh event after + * rendering rows to the screen. + */ +export interface IRenderer extends IDisposable { + readonly dimensions: IRenderDimensions; + + /** + * Fires when the renderer is requesting to be redrawn on the next animation + * frame but is _not_ a result of content changing (eg. selection changes). + */ + readonly onRequestRedraw: Event; + + dispose(): void; + handleDevicePixelRatioChange(): void; + handleResize(cols: number, rows: number): void; + handleCharSizeChanged(): void; + handleBlur(): void; + handleFocus(): void; + handleSelectionChanged(start: [number, number] | undefined, end: [number, number] | undefined, columnSelectMode: boolean): void; + handleCursorMove(): void; + clear(): void; + renderRows(start: number, end: number): void; + clearTextureAtlas?(): void; +} + +export interface ISelectionRenderModel { + readonly hasSelection: boolean; + readonly columnSelectMode: boolean; + readonly viewportStartRow: number; + readonly viewportEndRow: number; + readonly viewportCappedStartRow: number; + readonly viewportCappedEndRow: number; + readonly startCol: number; + readonly endCol: number; + readonly selectionStart: [number, number] | undefined; + readonly selectionEnd: [number, number] | undefined; + clear(): void; + update(terminal: ITerminal, start: [number, number] | undefined, end: [number, number] | undefined, columnSelectMode?: boolean): void; + isCellSelected(terminal: Terminal, x: number, y: number): boolean; +} diff --git a/node_modules/@xterm/xterm/src/browser/selection/SelectionModel.ts b/node_modules/@xterm/xterm/src/browser/selection/SelectionModel.ts new file mode 100644 index 0000000..b26cf94 --- /dev/null +++ b/node_modules/@xterm/xterm/src/browser/selection/SelectionModel.ts @@ -0,0 +1,144 @@ +/** + * Copyright (c) 2017 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { IBufferService } from 'common/services/Services'; + +/** + * Represents a selection within the buffer. This model only cares about column + * and row coordinates, not wide characters. + */ +export class SelectionModel { + /** + * Whether select all is currently active. + */ + public isSelectAllActive: boolean = false; + + /** + * The minimal length of the selection from the start position. When double + * clicking on a word, the word will be selected which makes the selection + * start at the start of the word and makes this variable the length. + */ + public selectionStartLength: number = 0; + + /** + * The [x, y] position the selection starts at. + */ + public selectionStart: [number, number] | undefined; + + /** + * The [x, y] position the selection ends at. + */ + public selectionEnd: [number, number] | undefined; + + constructor( + private _bufferService: IBufferService + ) { + } + + /** + * Clears the current selection. + */ + public clearSelection(): void { + this.selectionStart = undefined; + this.selectionEnd = undefined; + this.isSelectAllActive = false; + this.selectionStartLength = 0; + } + + /** + * The final selection start, taking into consideration select all. + */ + public get finalSelectionStart(): [number, number] | undefined { + if (this.isSelectAllActive) { + return [0, 0]; + } + + if (!this.selectionEnd || !this.selectionStart) { + return this.selectionStart; + } + + return this.areSelectionValuesReversed() ? this.selectionEnd : this.selectionStart; + } + + /** + * The final selection end, taking into consideration select all, double click + * word selection and triple click line selection. + */ + public get finalSelectionEnd(): [number, number] | undefined { + if (this.isSelectAllActive) { + return [this._bufferService.cols, this._bufferService.buffer.ybase + this._bufferService.rows - 1]; + } + + if (!this.selectionStart) { + return undefined; + } + + // Use the selection start + length if the end doesn't exist or they're reversed + if (!this.selectionEnd || this.areSelectionValuesReversed()) { + const startPlusLength = this.selectionStart[0] + this.selectionStartLength; + if (startPlusLength > this._bufferService.cols) { + // Ensure the trailing EOL isn't included when the selection ends on the right edge + if (startPlusLength % this._bufferService.cols === 0) { + return [this._bufferService.cols, this.selectionStart[1] + Math.floor(startPlusLength / this._bufferService.cols) - 1]; + } + return [startPlusLength % this._bufferService.cols, this.selectionStart[1] + Math.floor(startPlusLength / this._bufferService.cols)]; + } + return [startPlusLength, this.selectionStart[1]]; + } + + // Ensure the the word/line is selected after a double/triple click + if (this.selectionStartLength) { + // Select the larger of the two when start and end are on the same line + if (this.selectionEnd[1] === this.selectionStart[1]) { + // Keep the whole wrapped word/line selected if the content wraps multiple lines + const startPlusLength = this.selectionStart[0] + this.selectionStartLength; + if (startPlusLength > this._bufferService.cols) { + return [startPlusLength % this._bufferService.cols, this.selectionStart[1] + Math.floor(startPlusLength / this._bufferService.cols)]; + } + return [Math.max(startPlusLength, this.selectionEnd[0]), this.selectionEnd[1]]; + } + } + return this.selectionEnd; + } + + /** + * Returns whether the selection start and end are reversed. + */ + public areSelectionValuesReversed(): boolean { + const start = this.selectionStart; + const end = this.selectionEnd; + if (!start || !end) { + return false; + } + return start[1] > end[1] || (start[1] === end[1] && start[0] > end[0]); + } + + /** + * Handle the buffer being trimmed, adjust the selection position. + * @param amount The amount the buffer is being trimmed. + * @returns Whether a refresh is necessary. + */ + public handleTrim(amount: number): boolean { + // Adjust the selection position based on the trimmed amount. + if (this.selectionStart) { + this.selectionStart[1] -= amount; + } + if (this.selectionEnd) { + this.selectionEnd[1] -= amount; + } + + // The selection has moved off the buffer, clear it. + if (this.selectionEnd && this.selectionEnd[1] < 0) { + this.clearSelection(); + return true; + } + + // If the selection start is trimmed, ensure the start column is 0. + if (this.selectionStart && this.selectionStart[1] < 0) { + this.selectionStart[1] = 0; + } + return false; + } +} diff --git a/node_modules/@xterm/xterm/src/browser/selection/Types.ts b/node_modules/@xterm/xterm/src/browser/selection/Types.ts new file mode 100644 index 0000000..8adfc17 --- /dev/null +++ b/node_modules/@xterm/xterm/src/browser/selection/Types.ts @@ -0,0 +1,15 @@ +/** + * Copyright (c) 2017 The xterm.js authors. All rights reserved. + * @license MIT + */ + +export interface ISelectionRedrawRequestEvent { + start: [number, number] | undefined; + end: [number, number] | undefined; + columnSelectMode: boolean; +} + +export interface ISelectionRequestScrollLinesEvent { + amount: number; + suppressScrollEvent: boolean; +} diff --git a/node_modules/@xterm/xterm/src/browser/services/CharSizeService.ts b/node_modules/@xterm/xterm/src/browser/services/CharSizeService.ts new file mode 100644 index 0000000..5d23105 --- /dev/null +++ b/node_modules/@xterm/xterm/src/browser/services/CharSizeService.ts @@ -0,0 +1,127 @@ +/** + * Copyright (c) 2016 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { IOptionsService } from 'common/services/Services'; +import { ICharSizeService } from 'browser/services/Services'; +import { Disposable } from 'vs/base/common/lifecycle'; +import { Emitter } from 'vs/base/common/event'; + +export class CharSizeService extends Disposable implements ICharSizeService { + public serviceBrand: undefined; + + public width: number = 0; + public height: number = 0; + private _measureStrategy: IMeasureStrategy; + + public get hasValidSize(): boolean { return this.width > 0 && this.height > 0; } + + private readonly _onCharSizeChange = this._register(new Emitter()); + public readonly onCharSizeChange = this._onCharSizeChange.event; + + constructor( + document: Document, + parentElement: HTMLElement, + @IOptionsService private readonly _optionsService: IOptionsService + ) { + super(); + try { + this._measureStrategy = this._register(new TextMetricsMeasureStrategy(this._optionsService)); + } catch { + this._measureStrategy = this._register(new DomMeasureStrategy(document, parentElement, this._optionsService)); + } + this._register(this._optionsService.onMultipleOptionChange(['fontFamily', 'fontSize'], () => this.measure())); + } + + public measure(): void { + const result = this._measureStrategy.measure(); + if (result.width !== this.width || result.height !== this.height) { + this.width = result.width; + this.height = result.height; + this._onCharSizeChange.fire(); + } + } +} + +interface IMeasureStrategy { + measure(): Readonly; +} + +interface IMeasureResult { + width: number; + height: number; +} + +const enum DomMeasureStrategyConstants { + REPEAT = 32 +} + +abstract class BaseMeasureStategy extends Disposable implements IMeasureStrategy { + protected _result: IMeasureResult = { width: 0, height: 0 }; + + protected _validateAndSet(width: number | undefined, height: number | undefined): void { + // If values are 0 then the element is likely currently display:none, in which case we should + // retain the previous value. + if (width !== undefined && width > 0 && height !== undefined && height > 0) { + this._result.width = width; + this._result.height = height; + } + } + + public abstract measure(): Readonly; +} + +class DomMeasureStrategy extends BaseMeasureStategy { + private _measureElement: HTMLElement; + + constructor( + private _document: Document, + private _parentElement: HTMLElement, + private _optionsService: IOptionsService + ) { + super(); + this._measureElement = this._document.createElement('span'); + this._measureElement.classList.add('xterm-char-measure-element'); + this._measureElement.textContent = 'W'.repeat(DomMeasureStrategyConstants.REPEAT); + this._measureElement.setAttribute('aria-hidden', 'true'); + this._measureElement.style.whiteSpace = 'pre'; + this._measureElement.style.fontKerning = 'none'; + this._parentElement.appendChild(this._measureElement); + } + + public measure(): Readonly { + this._measureElement.style.fontFamily = this._optionsService.rawOptions.fontFamily; + this._measureElement.style.fontSize = `${this._optionsService.rawOptions.fontSize}px`; + + // Note that this triggers a synchronous layout + this._validateAndSet(Number(this._measureElement.offsetWidth) / DomMeasureStrategyConstants.REPEAT, Number(this._measureElement.offsetHeight)); + + return this._result; + } +} + +class TextMetricsMeasureStrategy extends BaseMeasureStategy { + private _canvas: OffscreenCanvas; + private _ctx: OffscreenCanvasRenderingContext2D; + + constructor( + private _optionsService: IOptionsService + ) { + super(); + // This will throw if any required API is not supported + this._canvas = new OffscreenCanvas(100, 100); + this._ctx = this._canvas.getContext('2d')!; + const a = this._ctx.measureText('W'); + if (!('width' in a && 'fontBoundingBoxAscent' in a && 'fontBoundingBoxDescent' in a)) { + throw new Error('Required font metrics not supported'); + } + } + + public measure(): Readonly { + this._ctx.font = `${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`; + const metrics = this._ctx.measureText('W'); + this._validateAndSet(metrics.width, metrics.fontBoundingBoxAscent + metrics.fontBoundingBoxDescent); + return this._result; + } +} diff --git a/node_modules/@xterm/xterm/src/browser/services/CharacterJoinerService.ts b/node_modules/@xterm/xterm/src/browser/services/CharacterJoinerService.ts new file mode 100644 index 0000000..ca4f198 --- /dev/null +++ b/node_modules/@xterm/xterm/src/browser/services/CharacterJoinerService.ts @@ -0,0 +1,339 @@ +/** + * Copyright (c) 2018 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { IBufferLine, ICellData, CharData } from 'common/Types'; +import { ICharacterJoiner } from 'browser/Types'; +import { AttributeData } from 'common/buffer/AttributeData'; +import { WHITESPACE_CELL_CHAR, Content } from 'common/buffer/Constants'; +import { CellData } from 'common/buffer/CellData'; +import { IBufferService } from 'common/services/Services'; +import { ICharacterJoinerService } from 'browser/services/Services'; + +export class JoinedCellData extends AttributeData implements ICellData { + private _width: number; + // .content carries no meaning for joined CellData, simply nullify it + // thus we have to overload all other .content accessors + public content: number = 0; + public fg: number; + public bg: number; + public combinedData: string = ''; + + constructor(firstCell: ICellData, chars: string, width: number) { + super(); + this.fg = firstCell.fg; + this.bg = firstCell.bg; + this.combinedData = chars; + this._width = width; + } + + public isCombined(): number { + // always mark joined cell data as combined + return Content.IS_COMBINED_MASK; + } + + public getWidth(): number { + return this._width; + } + + public getChars(): string { + return this.combinedData; + } + + public getCode(): number { + // code always gets the highest possible fake codepoint (read as -1) + // this is needed as code is used by caches as identifier + return 0x1FFFFF; + } + + public setFromCharData(value: CharData): void { + throw new Error('not implemented'); + } + + public getAsCharData(): CharData { + return [this.fg, this.getChars(), this.getWidth(), this.getCode()]; + } +} + +export class CharacterJoinerService implements ICharacterJoinerService { + public serviceBrand: undefined; + + private _characterJoiners: ICharacterJoiner[] = []; + private _nextCharacterJoinerId: number = 0; + private _workCell: CellData = new CellData(); + + constructor( + @IBufferService private _bufferService: IBufferService + ) { } + + public register(handler: (text: string) => [number, number][]): number { + const joiner: ICharacterJoiner = { + id: this._nextCharacterJoinerId++, + handler + }; + + this._characterJoiners.push(joiner); + return joiner.id; + } + + public deregister(joinerId: number): boolean { + for (let i = 0; i < this._characterJoiners.length; i++) { + if (this._characterJoiners[i].id === joinerId) { + this._characterJoiners.splice(i, 1); + return true; + } + } + + return false; + } + + public getJoinedCharacters(row: number): [number, number][] { + if (this._characterJoiners.length === 0) { + return []; + } + + const line = this._bufferService.buffer.lines.get(row); + if (!line || line.length === 0) { + return []; + } + + const ranges: [number, number][] = []; + const lineStr = line.translateToString(true); + + // Because some cells can be represented by multiple javascript characters, + // we track the cell and the string indexes separately. This allows us to + // translate the string ranges we get from the joiners back into cell ranges + // for use when rendering + let rangeStartColumn = 0; + let currentStringIndex = 0; + let rangeStartStringIndex = 0; + let rangeAttrFG = line.getFg(0); + let rangeAttrBG = line.getBg(0); + + for (let x = 0; x < line.getTrimmedLength(); x++) { + line.loadCell(x, this._workCell); + + if (this._workCell.getWidth() === 0) { + // If this character is of width 0, skip it. + continue; + } + + // End of range + if (this._workCell.fg !== rangeAttrFG || this._workCell.bg !== rangeAttrBG) { + // If we ended up with a sequence of more than one character, + // look for ranges to join. + if (x - rangeStartColumn > 1) { + const joinedRanges = this._getJoinedRanges( + lineStr, + rangeStartStringIndex, + currentStringIndex, + line, + rangeStartColumn + ); + for (let i = 0; i < joinedRanges.length; i++) { + ranges.push(joinedRanges[i]); + } + } + + // Reset our markers for a new range. + rangeStartColumn = x; + rangeStartStringIndex = currentStringIndex; + rangeAttrFG = this._workCell.fg; + rangeAttrBG = this._workCell.bg; + } + + currentStringIndex += this._workCell.getChars().length || WHITESPACE_CELL_CHAR.length; + } + + // Process any trailing ranges. + if (this._bufferService.cols - rangeStartColumn > 1) { + const joinedRanges = this._getJoinedRanges( + lineStr, + rangeStartStringIndex, + currentStringIndex, + line, + rangeStartColumn + ); + for (let i = 0; i < joinedRanges.length; i++) { + ranges.push(joinedRanges[i]); + } + } + + return ranges; + } + + /** + * Given a segment of a line of text, find all ranges of text that should be + * joined in a single rendering unit. Ranges are internally converted to + * column ranges, rather than string ranges. + * @param line String representation of the full line of text + * @param startIndex Start position of the range to search in the string (inclusive) + * @param endIndex End position of the range to search in the string (exclusive) + */ + private _getJoinedRanges(line: string, startIndex: number, endIndex: number, lineData: IBufferLine, startCol: number): [number, number][] { + const text = line.substring(startIndex, endIndex); + // At this point we already know that there is at least one joiner so + // we can just pull its value and assign it directly rather than + // merging it into an empty array, which incurs unnecessary writes. + let allJoinedRanges: [number, number][] = []; + try { + allJoinedRanges = this._characterJoiners[0].handler(text); + } catch (error) { + console.error(error); + } + for (let i = 1; i < this._characterJoiners.length; i++) { + // We merge any overlapping ranges across the different joiners + try { + const joinerRanges = this._characterJoiners[i].handler(text); + for (let j = 0; j < joinerRanges.length; j++) { + CharacterJoinerService._mergeRanges(allJoinedRanges, joinerRanges[j]); + } + } catch (error) { + console.error(error); + } + } + this._stringRangesToCellRanges(allJoinedRanges, lineData, startCol); + return allJoinedRanges; + } + + /** + * Modifies the provided ranges in-place to adjust for variations between + * string length and cell width so that the range represents a cell range, + * rather than the string range the joiner provides. + * @param ranges String ranges containing start (inclusive) and end (exclusive) index + * @param line Cell data for the relevant line in the terminal + * @param startCol Offset within the line to start from + */ + private _stringRangesToCellRanges(ranges: [number, number][], line: IBufferLine, startCol: number): void { + let currentRangeIndex = 0; + let currentRangeStarted = false; + let currentStringIndex = 0; + let currentRange = ranges[currentRangeIndex]; + + // If we got through all of the ranges, stop searching + if (!currentRange) { + return; + } + + for (let x = startCol; x < this._bufferService.cols; x++) { + const width = line.getWidth(x); + const length = line.getString(x).length || WHITESPACE_CELL_CHAR.length; + + // We skip zero-width characters when creating the string to join the text + // so we do the same here + if (width === 0) { + continue; + } + + // Adjust the start of the range + if (!currentRangeStarted && currentRange[0] <= currentStringIndex) { + currentRange[0] = x; + currentRangeStarted = true; + } + + // Adjust the end of the range + if (currentRange[1] <= currentStringIndex) { + currentRange[1] = x; + + // We're finished with this range, so we move to the next one + currentRange = ranges[++currentRangeIndex]; + + // If there are no more ranges left, stop searching + if (!currentRange) { + break; + } + + // Ranges can be on adjacent characters. Because the end index of the + // ranges are exclusive, this means that the index for the start of a + // range can be the same as the end index of the previous range. To + // account for the start of the next range, we check here just in case. + if (currentRange[0] <= currentStringIndex) { + currentRange[0] = x; + currentRangeStarted = true; + } else { + currentRangeStarted = false; + } + } + + // Adjust the string index based on the character length to line up with + // the column adjustment + currentStringIndex += length; + } + + // If there is still a range left at the end, it must extend all the way to + // the end of the line. + if (currentRange) { + currentRange[1] = this._bufferService.cols; + } + } + + /** + * Merges the range defined by the provided start and end into the list of + * existing ranges. The merge is done in place on the existing range for + * performance and is also returned. + * @param ranges Existing range list + * @param newRange Tuple of two numbers representing the new range to merge in. + * @returns The ranges input with the new range merged in place + */ + private static _mergeRanges(ranges: [number, number][], newRange: [number, number]): [number, number][] { + let inRange = false; + for (let i = 0; i < ranges.length; i++) { + const range = ranges[i]; + if (!inRange) { + if (newRange[1] <= range[0]) { + // Case 1: New range is before the search range + ranges.splice(i, 0, newRange); + return ranges; + } + + if (newRange[1] <= range[1]) { + // Case 2: New range is either wholly contained within the + // search range or overlaps with the front of it + range[0] = Math.min(newRange[0], range[0]); + return ranges; + } + + if (newRange[0] < range[1]) { + // Case 3: New range either wholly contains the search range + // or overlaps with the end of it + range[0] = Math.min(newRange[0], range[0]); + inRange = true; + } + + // Case 4: New range starts after the search range + continue; + } else { + if (newRange[1] <= range[0]) { + // Case 5: New range extends from previous range but doesn't + // reach the current one + ranges[i - 1][1] = newRange[1]; + return ranges; + } + + if (newRange[1] <= range[1]) { + // Case 6: New range extends from prvious range into the + // current range + ranges[i - 1][1] = Math.max(newRange[1], range[1]); + ranges.splice(i, 1); + return ranges; + } + + // Case 7: New range extends from previous range past the + // end of the current range + ranges.splice(i, 1); + i--; + } + } + + if (inRange) { + // Case 8: New range extends past the last existing range + ranges[ranges.length - 1][1] = newRange[1]; + } else { + // Case 9: New range starts after the last existing range + ranges.push(newRange); + } + + return ranges; + } +} diff --git a/node_modules/@xterm/xterm/src/browser/services/CoreBrowserService.ts b/node_modules/@xterm/xterm/src/browser/services/CoreBrowserService.ts new file mode 100644 index 0000000..d8ea0a6 --- /dev/null +++ b/node_modules/@xterm/xterm/src/browser/services/CoreBrowserService.ts @@ -0,0 +1,137 @@ +/** + * Copyright (c) 2019 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { ICoreBrowserService } from './Services'; +import { Emitter, Event } from 'vs/base/common/event'; +import { addDisposableListener } from 'vs/base/browser/dom'; +import { Disposable, MutableDisposable, toDisposable } from 'vs/base/common/lifecycle'; + +export class CoreBrowserService extends Disposable implements ICoreBrowserService { + public serviceBrand: undefined; + + private _isFocused = false; + private _cachedIsFocused: boolean | undefined = undefined; + private _screenDprMonitor = this._register(new ScreenDprMonitor(this._window)); + + private readonly _onDprChange = this._register(new Emitter()); + public readonly onDprChange = this._onDprChange.event; + private readonly _onWindowChange = this._register(new Emitter()); + public readonly onWindowChange = this._onWindowChange.event; + + constructor( + private _textarea: HTMLTextAreaElement, + private _window: Window & typeof globalThis, + public readonly mainDocument: Document + ) { + super(); + + // Monitor device pixel ratio + this._register(this.onWindowChange(w => this._screenDprMonitor.setWindow(w))); + this._register(Event.forward(this._screenDprMonitor.onDprChange, this._onDprChange)); + + this._register(addDisposableListener(this._textarea, 'focus', () => this._isFocused = true)); + this._register(addDisposableListener(this._textarea, 'blur', () => this._isFocused = false)); + } + + public get window(): Window & typeof globalThis { + return this._window; + } + + public set window(value: Window & typeof globalThis) { + if (this._window !== value) { + this._window = value; + this._onWindowChange.fire(this._window); + } + } + + public get dpr(): number { + return this.window.devicePixelRatio; + } + + public get isFocused(): boolean { + if (this._cachedIsFocused === undefined) { + this._cachedIsFocused = this._isFocused && this._textarea.ownerDocument.hasFocus(); + queueMicrotask(() => this._cachedIsFocused = undefined); + } + return this._cachedIsFocused; + } +} + + +/** + * The screen device pixel ratio monitor allows listening for when the + * window.devicePixelRatio value changes. This is done not with polling but with + * the use of window.matchMedia to watch media queries. When the event fires, + * the listener will be reattached using a different media query to ensure that + * any further changes will _register. + * + * The listener should fire on both window zoom changes and switching to a + * monitor with a different DPI. + */ +class ScreenDprMonitor extends Disposable { + private _currentDevicePixelRatio: number; + private _outerListener: ((this: MediaQueryList, ev: MediaQueryListEvent) => any) | undefined; + private _resolutionMediaMatchList: MediaQueryList | undefined; + private _windowResizeListener = this._register(new MutableDisposable()); + + private readonly _onDprChange = this._register(new Emitter()); + public readonly onDprChange = this._onDprChange.event; + + constructor(private _parentWindow: Window) { + super(); + + // Initialize listener and dpr value + this._outerListener = () => this._setDprAndFireIfDiffers(); + this._currentDevicePixelRatio = this._parentWindow.devicePixelRatio; + this._updateDpr(); + + // Monitor active window resize + this._setWindowResizeListener(); + + // Setup additional disposables + this._register(toDisposable(() => this.clearListener())); + } + + + public setWindow(parentWindow: Window): void { + this._parentWindow = parentWindow; + this._setWindowResizeListener(); + this._setDprAndFireIfDiffers(); + } + + private _setWindowResizeListener(): void { + this._windowResizeListener.value = addDisposableListener(this._parentWindow, 'resize', () => this._setDprAndFireIfDiffers()); + } + + private _setDprAndFireIfDiffers(): void { + if (this._parentWindow.devicePixelRatio !== this._currentDevicePixelRatio) { + this._onDprChange.fire(this._parentWindow.devicePixelRatio); + } + this._updateDpr(); + } + + private _updateDpr(): void { + if (!this._outerListener) { + return; + } + + // Clear listeners for old DPR + this._resolutionMediaMatchList?.removeListener(this._outerListener); + + // Add listeners for new DPR + this._currentDevicePixelRatio = this._parentWindow.devicePixelRatio; + this._resolutionMediaMatchList = this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`); + this._resolutionMediaMatchList.addListener(this._outerListener); + } + + public clearListener(): void { + if (!this._resolutionMediaMatchList || !this._outerListener) { + return; + } + this._resolutionMediaMatchList.removeListener(this._outerListener); + this._resolutionMediaMatchList = undefined; + this._outerListener = undefined; + } +} diff --git a/node_modules/@xterm/xterm/src/browser/services/LinkProviderService.ts b/node_modules/@xterm/xterm/src/browser/services/LinkProviderService.ts new file mode 100644 index 0000000..a8687e5 --- /dev/null +++ b/node_modules/@xterm/xterm/src/browser/services/LinkProviderService.ts @@ -0,0 +1,28 @@ +import { ILinkProvider, ILinkProviderService } from 'browser/services/Services'; +import { Disposable, toDisposable } from 'vs/base/common/lifecycle'; +import { IDisposable } from 'common/Types'; + +export class LinkProviderService extends Disposable implements ILinkProviderService { + declare public serviceBrand: undefined; + + public readonly linkProviders: ILinkProvider[] = []; + + constructor() { + super(); + this._register(toDisposable(() => this.linkProviders.length = 0)); + } + + public registerLinkProvider(linkProvider: ILinkProvider): IDisposable { + this.linkProviders.push(linkProvider); + return { + dispose: () => { + // Remove the link provider from the list + const providerIndex = this.linkProviders.indexOf(linkProvider); + + if (providerIndex !== -1) { + this.linkProviders.splice(providerIndex, 1); + } + } + }; + } +} diff --git a/node_modules/@xterm/xterm/src/browser/services/MouseService.ts b/node_modules/@xterm/xterm/src/browser/services/MouseService.ts new file mode 100644 index 0000000..664d845 --- /dev/null +++ b/node_modules/@xterm/xterm/src/browser/services/MouseService.ts @@ -0,0 +1,46 @@ +/** + * Copyright (c) 2017 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { ICharSizeService, IRenderService, IMouseService } from './Services'; +import { getCoords, getCoordsRelativeToElement } from 'browser/input/Mouse'; + +export class MouseService implements IMouseService { + public serviceBrand: undefined; + + constructor( + @IRenderService private readonly _renderService: IRenderService, + @ICharSizeService private readonly _charSizeService: ICharSizeService + ) { + } + + public getCoords(event: {clientX: number, clientY: number}, element: HTMLElement, colCount: number, rowCount: number, isSelection?: boolean): [number, number] | undefined { + return getCoords( + window, + event, + element, + colCount, + rowCount, + this._charSizeService.hasValidSize, + this._renderService.dimensions.css.cell.width, + this._renderService.dimensions.css.cell.height, + isSelection + ); + } + + public getMouseReportCoords(event: MouseEvent, element: HTMLElement): { col: number, row: number, x: number, y: number } | undefined { + const coords = getCoordsRelativeToElement(window, event, element); + if (!this._charSizeService.hasValidSize) { + return undefined; + } + coords[0] = Math.min(Math.max(coords[0], 0), this._renderService.dimensions.css.canvas.width - 1); + coords[1] = Math.min(Math.max(coords[1], 0), this._renderService.dimensions.css.canvas.height - 1); + return { + col: Math.floor(coords[0] / this._renderService.dimensions.css.cell.width), + row: Math.floor(coords[1] / this._renderService.dimensions.css.cell.height), + x: Math.floor(coords[0]), + y: Math.floor(coords[1]) + }; + } +} diff --git a/node_modules/@xterm/xterm/src/browser/services/RenderService.ts b/node_modules/@xterm/xterm/src/browser/services/RenderService.ts new file mode 100644 index 0000000..e9acbeb --- /dev/null +++ b/node_modules/@xterm/xterm/src/browser/services/RenderService.ts @@ -0,0 +1,376 @@ +/** + * Copyright (c) 2019 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { RenderDebouncer } from 'browser/RenderDebouncer'; +import { IRenderDebouncerWithCallback } from 'browser/Types'; +import { IRenderDimensions, IRenderer } from 'browser/renderer/shared/Types'; +import { ICharSizeService, ICoreBrowserService, IRenderService, IThemeService } from 'browser/services/Services'; +import { Disposable, MutableDisposable, toDisposable } from 'vs/base/common/lifecycle'; +import { DebouncedIdleTask } from 'common/TaskQueue'; +import { IBufferService, ICoreService, IDecorationService, IOptionsService } from 'common/services/Services'; +import { Emitter } from 'vs/base/common/event'; + +interface ISelectionState { + start: [number, number] | undefined; + end: [number, number] | undefined; + columnSelectMode: boolean; +} + +const enum Constants { + SYNCHRONIZED_OUTPUT_TIMEOUT_MS = 1000 +} + +export class RenderService extends Disposable implements IRenderService { + public serviceBrand: undefined; + + private _renderer: MutableDisposable = this._register(new MutableDisposable()); + private _renderDebouncer: IRenderDebouncerWithCallback; + private _pausedResizeTask = new DebouncedIdleTask(); + private _observerDisposable = this._register(new MutableDisposable()); + + private _isPaused: boolean = false; + private _needsFullRefresh: boolean = false; + private _isNextRenderRedrawOnly: boolean = true; + private _needsSelectionRefresh: boolean = false; + private _canvasWidth: number = 0; + private _canvasHeight: number = 0; + private _syncOutputHandler: SynchronizedOutputHandler; + private _selectionState: ISelectionState = { + start: undefined, + end: undefined, + columnSelectMode: false + }; + + private readonly _onDimensionsChange = this._register(new Emitter()); + public readonly onDimensionsChange = this._onDimensionsChange.event; + private readonly _onRenderedViewportChange = this._register(new Emitter<{ start: number, end: number }>()); + public readonly onRenderedViewportChange = this._onRenderedViewportChange.event; + private readonly _onRender = this._register(new Emitter<{ start: number, end: number }>()); + public readonly onRender = this._onRender.event; + private readonly _onRefreshRequest = this._register(new Emitter<{ start: number, end: number }>()); + public readonly onRefreshRequest = this._onRefreshRequest.event; + + public get dimensions(): IRenderDimensions { return this._renderer.value!.dimensions; } + + constructor( + private _rowCount: number, + screenElement: HTMLElement, + @IOptionsService private readonly _optionsService: IOptionsService, + @ICharSizeService private readonly _charSizeService: ICharSizeService, + @ICoreService private readonly _coreService: ICoreService, + @IDecorationService decorationService: IDecorationService, + @IBufferService bufferService: IBufferService, + @ICoreBrowserService private readonly _coreBrowserService: ICoreBrowserService, + @IThemeService themeService: IThemeService + ) { + super(); + + this._renderDebouncer = new RenderDebouncer((start, end) => this._renderRows(start, end), this._coreBrowserService); + this._register(this._renderDebouncer); + + this._syncOutputHandler = new SynchronizedOutputHandler( + this._coreBrowserService, + this._coreService, + () => this._fullRefresh() + ); + this._register(toDisposable(() => this._syncOutputHandler.dispose())); + + this._register(this._coreBrowserService.onDprChange(() => this.handleDevicePixelRatioChange())); + + this._register(bufferService.onResize(() => this._fullRefresh())); + this._register(bufferService.buffers.onBufferActivate(() => this._renderer.value?.clear())); + this._register(this._optionsService.onOptionChange(() => this._handleOptionsChanged())); + this._register(this._charSizeService.onCharSizeChange(() => this.handleCharSizeChanged())); + + // Do a full refresh whenever any decoration is added or removed. This may not actually result + // in changes but since decorations should be used sparingly or added/removed all in the same + // frame this should have minimal performance impact. + this._register(decorationService.onDecorationRegistered(() => this._fullRefresh())); + this._register(decorationService.onDecorationRemoved(() => this._fullRefresh())); + + // Clear the renderer when the a change that could affect glyphs occurs + this._register(this._optionsService.onMultipleOptionChange([ + 'customGlyphs', + 'drawBoldTextInBrightColors', + 'letterSpacing', + 'lineHeight', + 'fontFamily', + 'fontSize', + 'fontWeight', + 'fontWeightBold', + 'minimumContrastRatio', + 'rescaleOverlappingGlyphs' + ], () => { + this.clear(); + this.handleResize(bufferService.cols, bufferService.rows); + this._fullRefresh(); + })); + + // Refresh the cursor line when the cursor changes + this._register(this._optionsService.onMultipleOptionChange([ + 'cursorBlink', + 'cursorStyle' + ], () => this.refreshRows(bufferService.buffer.y, bufferService.buffer.y, true))); + + this._register(themeService.onChangeColors(() => this._fullRefresh())); + + this._registerIntersectionObserver(this._coreBrowserService.window, screenElement); + this._register(this._coreBrowserService.onWindowChange((w) => this._registerIntersectionObserver(w, screenElement))); + } + + private _registerIntersectionObserver(w: Window & typeof globalThis, screenElement: HTMLElement): void { + // Detect whether IntersectionObserver is detected and enable renderer pause + // and resume based on terminal visibility if so + if ('IntersectionObserver' in w) { + const observer = new w.IntersectionObserver(e => this._handleIntersectionChange(e[e.length - 1]), { threshold: 0 }); + observer.observe(screenElement); + this._observerDisposable.value = toDisposable(() => observer.disconnect()); + } + } + + private _handleIntersectionChange(entry: IntersectionObserverEntry): void { + this._isPaused = entry.isIntersecting === undefined ? (entry.intersectionRatio === 0) : !entry.isIntersecting; + + // Terminal was hidden on open + if (!this._isPaused && !this._charSizeService.hasValidSize) { + this._charSizeService.measure(); + } + + if (!this._isPaused && this._needsFullRefresh) { + this._pausedResizeTask.flush(); + this.refreshRows(0, this._rowCount - 1); + this._needsFullRefresh = false; + } + } + + public refreshRows(start: number, end: number, isRedrawOnly: boolean = false): void { + if (this._isPaused) { + this._needsFullRefresh = true; + return; + } + + if (this._coreService.decPrivateModes.synchronizedOutput) { + this._syncOutputHandler.bufferRows(start, end); + return; + } + + const buffered = this._syncOutputHandler.flush(); + if (buffered) { + start = Math.min(start, buffered.start); + end = Math.max(end, buffered.end); + } + + if (!isRedrawOnly) { + this._isNextRenderRedrawOnly = false; + } + this._renderDebouncer.refresh(start, end, this._rowCount); + } + + private _renderRows(start: number, end: number): void { + if (!this._renderer.value) { + return; + } + + // Skip rendering if synchronized output mode is enabled. This check must happen here + // (in addition to refreshRows) to handle renders that were queued before the mode was enabled. + if (this._coreService.decPrivateModes.synchronizedOutput) { + this._syncOutputHandler.bufferRows(start, end); + return; + } + + // Since this is debounced, a resize event could have happened between the time a refresh was + // requested and when this triggers. Clamp the values of start and end to ensure they're valid + // given the current viewport state. + start = Math.min(start, this._rowCount - 1); + end = Math.min(end, this._rowCount - 1); + + // Render + this._renderer.value.renderRows(start, end); + + // Update selection if needed + if (this._needsSelectionRefresh) { + this._renderer.value.handleSelectionChanged(this._selectionState.start, this._selectionState.end, this._selectionState.columnSelectMode); + this._needsSelectionRefresh = false; + } + + // Fire render event only if it was not a redraw + if (!this._isNextRenderRedrawOnly) { + this._onRenderedViewportChange.fire({ start, end }); + } + this._onRender.fire({ start, end }); + this._isNextRenderRedrawOnly = true; + } + + public resize(cols: number, rows: number): void { + this._rowCount = rows; + this._fireOnCanvasResize(); + } + + private _handleOptionsChanged(): void { + if (!this._renderer.value) { + return; + } + this.refreshRows(0, this._rowCount - 1); + this._fireOnCanvasResize(); + } + + private _fireOnCanvasResize(): void { + if (!this._renderer.value) { + return; + } + // Don't fire the event if the dimensions haven't changed + if (this._renderer.value.dimensions.css.canvas.width === this._canvasWidth && this._renderer.value.dimensions.css.canvas.height === this._canvasHeight) { + return; + } + this._onDimensionsChange.fire(this._renderer.value.dimensions); + } + + public hasRenderer(): boolean { + return !!this._renderer.value; + } + + public setRenderer(renderer: IRenderer): void { + this._renderer.value = renderer; + // If the value was not set, the terminal is being disposed so ignore it + if (this._renderer.value) { + this._renderer.value.onRequestRedraw(e => this.refreshRows(e.start, e.end, true)); + + // Force a refresh + this._needsSelectionRefresh = true; + this._fullRefresh(); + } + } + + public addRefreshCallback(callback: FrameRequestCallback): number { + return this._renderDebouncer.addRefreshCallback(callback); + } + + private _fullRefresh(): void { + if (this._isPaused) { + this._needsFullRefresh = true; + } else { + this.refreshRows(0, this._rowCount - 1); + } + } + + public clearTextureAtlas(): void { + if (!this._renderer.value) { + return; + } + this._renderer.value.clearTextureAtlas?.(); + this._fullRefresh(); + } + + public handleDevicePixelRatioChange(): void { + // Force char size measurement as DomMeasureStrategy(getBoundingClientRect) is not stable + // when devicePixelRatio changes + this._charSizeService.measure(); + + if (!this._renderer.value) { + return; + } + this._renderer.value.handleDevicePixelRatioChange(); + this.refreshRows(0, this._rowCount - 1); + } + + public handleResize(cols: number, rows: number): void { + if (!this._renderer.value) { + return; + } + if (this._isPaused) { + this._pausedResizeTask.set(() => this._renderer.value?.handleResize(cols, rows)); + } else { + this._renderer.value.handleResize(cols, rows); + } + this._fullRefresh(); + } + + // TODO: Is this useful when we have onResize? + public handleCharSizeChanged(): void { + this._renderer.value?.handleCharSizeChanged(); + } + + public handleBlur(): void { + this._renderer.value?.handleBlur(); + } + + public handleFocus(): void { + this._renderer.value?.handleFocus(); + } + + public handleSelectionChanged(start: [number, number] | undefined, end: [number, number] | undefined, columnSelectMode: boolean): void { + this._selectionState.start = start; + this._selectionState.end = end; + this._selectionState.columnSelectMode = columnSelectMode; + this._renderer.value?.handleSelectionChanged(start, end, columnSelectMode); + } + + public handleCursorMove(): void { + this._renderer.value?.handleCursorMove(); + } + + public clear(): void { + this._renderer.value?.clear(); + } +} + +/** + * Buffers row refresh requests during synchronized output mode (DEC mode 2026). + * When the mode is disabled, the accumulated row range is flushed for rendering. + * A safety timeout ensures rendering occurs even if the end sequence is not received. + */ +class SynchronizedOutputHandler { + private _start: number = 0; + private _end: number = 0; + private _timeout: number | undefined; + private _isBuffering: boolean = false; + + constructor( + private readonly _coreBrowserService: ICoreBrowserService, + private readonly _coreService: ICoreService, + private readonly _onTimeout: () => void + ) {} + + public bufferRows(start: number, end: number): void { + if (!this._isBuffering) { + this._start = start; + this._end = end; + this._isBuffering = true; + } else { + this._start = Math.min(this._start, start); + this._end = Math.max(this._end, end); + } + + if (this._timeout === undefined) { + this._timeout = this._coreBrowserService.window.setTimeout(() => { + this._timeout = undefined; + this._coreService.decPrivateModes.synchronizedOutput = false; + this._onTimeout(); + }, Constants.SYNCHRONIZED_OUTPUT_TIMEOUT_MS); + } + } + + public flush(): { start: number, end: number } | undefined { + if (this._timeout !== undefined) { + this._coreBrowserService.window.clearTimeout(this._timeout); + this._timeout = undefined; + } + + if (!this._isBuffering) { + return undefined; + } + + const result = { start: this._start, end: this._end }; + this._isBuffering = false; + return result; + } + + public dispose(): void { + if (this._timeout !== undefined) { + this._coreBrowserService.window.clearTimeout(this._timeout); + this._timeout = undefined; + } + } +} diff --git a/node_modules/@xterm/xterm/src/browser/services/SelectionService.ts b/node_modules/@xterm/xterm/src/browser/services/SelectionService.ts new file mode 100644 index 0000000..39d666d --- /dev/null +++ b/node_modules/@xterm/xterm/src/browser/services/SelectionService.ts @@ -0,0 +1,1039 @@ +/** + * Copyright (c) 2017 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { IBufferRange, ILinkifier2 } from 'browser/Types'; +import { getCoordsRelativeToElement } from 'browser/input/Mouse'; +import { moveToCellSequence } from 'browser/input/MoveToCell'; +import { SelectionModel } from 'browser/selection/SelectionModel'; +import { ISelectionRedrawRequestEvent, ISelectionRequestScrollLinesEvent } from 'browser/selection/Types'; +import { ICoreBrowserService, IMouseService, IRenderService, ISelectionService } from 'browser/services/Services'; +import { Disposable, toDisposable } from 'vs/base/common/lifecycle'; +import * as Browser from 'common/Platform'; +import { IBufferLine, IDisposable } from 'common/Types'; +import { getRangeLength } from 'common/buffer/BufferRange'; +import { CellData } from 'common/buffer/CellData'; +import { IBuffer } from 'common/buffer/Types'; +import { IBufferService, ICoreService, IOptionsService } from 'common/services/Services'; +import { Emitter } from 'vs/base/common/event'; + +/** + * The number of pixels the mouse needs to be above or below the viewport in + * order to scroll at the maximum speed. + */ +const DRAG_SCROLL_MAX_THRESHOLD = 50; + +/** + * The maximum scrolling speed + */ +const DRAG_SCROLL_MAX_SPEED = 15; + +/** + * The number of milliseconds between drag scroll updates. + */ +const DRAG_SCROLL_INTERVAL = 50; + +/** + * The maximum amount of time that can have elapsed for an alt click to move the + * cursor. + */ +const ALT_CLICK_MOVE_CURSOR_TIME = 500; + +const NON_BREAKING_SPACE_CHAR = String.fromCharCode(160); +const ALL_NON_BREAKING_SPACE_REGEX = new RegExp(NON_BREAKING_SPACE_CHAR, 'g'); + +/** + * Represents a position of a word on a line. + */ +interface IWordPosition { + start: number; + length: number; +} + +/** + * A selection mode, this drives how the selection behaves on mouse move. + */ +export const enum SelectionMode { + NORMAL, + WORD, + LINE, + COLUMN +} + +/** + * A class that manages the selection of the terminal. With help from + * SelectionModel, SelectionService handles with all logic associated with + * dealing with the selection, including handling mouse interaction, wide + * characters and fetching the actual text within the selection. Rendering is + * not handled by the SelectionService but the onRedrawRequest event is fired + * when the selection is ready to be redrawn (on an animation frame). + */ +export class SelectionService extends Disposable implements ISelectionService { + public serviceBrand: undefined; + + protected _model: SelectionModel; + + /** + * The amount to scroll every drag scroll update (depends on how far the mouse + * drag is above or below the terminal). + */ + private _dragScrollAmount: number = 0; + + /** + * The current selection mode. + */ + protected _activeSelectionMode: SelectionMode; + + /** + * A setInterval timer that is active while the mouse is down whose callback + * scrolls the viewport when necessary. + */ + private _dragScrollIntervalTimer: number | undefined; + + /** + * The animation frame ID used for refreshing the selection. + */ + private _refreshAnimationFrame: number | undefined; + + /** + * Whether selection is enabled. + */ + private _enabled = true; + + private _mouseMoveListener: EventListener; + private _mouseUpListener: EventListener; + private _trimListener: IDisposable; + private _workCell: CellData = new CellData(); + + private _mouseDownTimeStamp: number = 0; + private _oldHasSelection: boolean = false; + private _oldSelectionStart: [number, number] | undefined = undefined; + private _oldSelectionEnd: [number, number] | undefined = undefined; + + private readonly _onLinuxMouseSelection = this._register(new Emitter()); + public readonly onLinuxMouseSelection = this._onLinuxMouseSelection.event; + private readonly _onRedrawRequest = this._register(new Emitter()); + public readonly onRequestRedraw = this._onRedrawRequest.event; + private readonly _onSelectionChange = this._register(new Emitter()); + public readonly onSelectionChange = this._onSelectionChange.event; + private readonly _onRequestScrollLines = this._register(new Emitter()); + public readonly onRequestScrollLines = this._onRequestScrollLines.event; + + constructor( + private readonly _element: HTMLElement, + private readonly _screenElement: HTMLElement, + private readonly _linkifier: ILinkifier2, + @IBufferService private readonly _bufferService: IBufferService, + @ICoreService private readonly _coreService: ICoreService, + @IMouseService private readonly _mouseService: IMouseService, + @IOptionsService private readonly _optionsService: IOptionsService, + @IRenderService private readonly _renderService: IRenderService, + @ICoreBrowserService private readonly _coreBrowserService: ICoreBrowserService + ) { + super(); + + // Init listeners + this._mouseMoveListener = event => this._handleMouseMove(event as MouseEvent); + this._mouseUpListener = event => this._handleMouseUp(event as MouseEvent); + this._coreService.onUserInput(() => { + if (this.hasSelection) { + this.clearSelection(); + } + }); + this._trimListener = this._bufferService.buffer.lines.onTrim(amount => this._handleTrim(amount)); + this._register(this._bufferService.buffers.onBufferActivate(e => this._handleBufferActivate(e))); + + this.enable(); + + this._model = new SelectionModel(this._bufferService); + this._activeSelectionMode = SelectionMode.NORMAL; + + this._register(toDisposable(() => { + this._removeMouseDownListeners(); + })); + + // Clear selection when resizing vertically. This experience could be improved, this is the + // simple option to fix the buggy behavior. https://github.com/xtermjs/xterm.js/issues/5300 + this._register(this._bufferService.onResize(e => { + if (e.rowsChanged) { + this.clearSelection(); + } + })); + } + + public reset(): void { + this.clearSelection(); + } + + /** + * Disables the selection manager. This is useful for when terminal mouse + * are enabled. + */ + public disable(): void { + this.clearSelection(); + this._enabled = false; + } + + /** + * Enable the selection manager. + */ + public enable(): void { + this._enabled = true; + } + + public get selectionStart(): [number, number] | undefined { return this._model.finalSelectionStart; } + public get selectionEnd(): [number, number] | undefined { return this._model.finalSelectionEnd; } + + /** + * Gets whether there is an active text selection. + */ + public get hasSelection(): boolean { + const start = this._model.finalSelectionStart; + const end = this._model.finalSelectionEnd; + if (!start || !end) { + return false; + } + return start[0] !== end[0] || start[1] !== end[1]; + } + + /** + * Gets the text currently selected. + */ + public get selectionText(): string { + const start = this._model.finalSelectionStart; + const end = this._model.finalSelectionEnd; + if (!start || !end) { + return ''; + } + + const buffer = this._bufferService.buffer; + const result: string[] = []; + + if (this._activeSelectionMode === SelectionMode.COLUMN) { + // Ignore zero width selections + if (start[0] === end[0]) { + return ''; + } + + // For column selection it's not enough to rely on final selection's swapping of reversed + // values, it also needs the x coordinates to swap independently of the y coordinate is needed + const startCol = start[0] < end[0] ? start[0] : end[0]; + const endCol = start[0] < end[0] ? end[0] : start[0]; + for (let i = start[1]; i <= end[1]; i++) { + const lineText = buffer.translateBufferLineToString(i, true, startCol, endCol); + result.push(lineText); + } + } else { + // Get first row + const startRowEndCol = start[1] === end[1] ? end[0] : undefined; + result.push(buffer.translateBufferLineToString(start[1], true, start[0], startRowEndCol)); + + // Get middle rows + for (let i = start[1] + 1; i <= end[1] - 1; i++) { + const bufferLine = buffer.lines.get(i); + const lineText = buffer.translateBufferLineToString(i, true); + if (bufferLine?.isWrapped) { + result[result.length - 1] += lineText; + } else { + result.push(lineText); + } + } + + // Get final row + if (start[1] !== end[1]) { + const bufferLine = buffer.lines.get(end[1]); + const lineText = buffer.translateBufferLineToString(end[1], true, 0, end[0]); + if (bufferLine && bufferLine!.isWrapped) { + result[result.length - 1] += lineText; + } else { + result.push(lineText); + } + } + } + + // Format string by replacing non-breaking space chars with regular spaces + // and joining the array into a multi-line string. + const formattedResult = result.map(line => { + return line.replace(ALL_NON_BREAKING_SPACE_REGEX, ' '); + }).join(Browser.isWindows ? '\r\n' : '\n'); + + return formattedResult; + } + + /** + * Clears the current terminal selection. + */ + public clearSelection(): void { + this._model.clearSelection(); + this._removeMouseDownListeners(); + this.refresh(); + this._onSelectionChange.fire(); + } + + /** + * Queues a refresh, redrawing the selection on the next opportunity. + * @param isLinuxMouseSelection Whether the selection should be registered as a new + * selection on Linux. + */ + public refresh(isLinuxMouseSelection?: boolean): void { + // Queue the refresh for the renderer + if (!this._refreshAnimationFrame) { + this._refreshAnimationFrame = this._coreBrowserService.window.requestAnimationFrame(() => this._refresh()); + } + + // If the platform is Linux and the refresh call comes from a mouse event, + // we need to update the selection for middle click to paste selection. + if (Browser.isLinux && isLinuxMouseSelection) { + const selectionText = this.selectionText; + if (selectionText.length) { + this._onLinuxMouseSelection.fire(this.selectionText); + } + } + } + + /** + * Fires the refresh event, causing consumers to pick it up and redraw the + * selection state. + */ + private _refresh(): void { + this._refreshAnimationFrame = undefined; + this._onRedrawRequest.fire({ + start: this._model.finalSelectionStart, + end: this._model.finalSelectionEnd, + columnSelectMode: this._activeSelectionMode === SelectionMode.COLUMN + }); + } + + /** + * Checks if the current click was inside the current selection + * @param event The mouse event + */ + private _isClickInSelection(event: MouseEvent): boolean { + const coords = this._getMouseBufferCoords(event); + const start = this._model.finalSelectionStart; + const end = this._model.finalSelectionEnd; + + if (!start || !end || !coords) { + return false; + } + + return this._areCoordsInSelection(coords, start, end); + } + + public isCellInSelection(x: number, y: number): boolean { + const start = this._model.finalSelectionStart; + const end = this._model.finalSelectionEnd; + if (!start || !end) { + return false; + } + return this._areCoordsInSelection([x, y], start, end); + } + + protected _areCoordsInSelection(coords: [number, number], start: [number, number], end: [number, number]): boolean { + return (coords[1] > start[1] && coords[1] < end[1]) || + (start[1] === end[1] && coords[1] === start[1] && coords[0] >= start[0] && coords[0] < end[0]) || + (start[1] < end[1] && coords[1] === end[1] && coords[0] < end[0]) || + (start[1] < end[1] && coords[1] === start[1] && coords[0] >= start[0]); + } + + /** + * Selects word at the current mouse event coordinates. + * @param event The mouse event. + */ + private _selectWordAtCursor(event: MouseEvent, allowWhitespaceOnlySelection: boolean): boolean { + // Check if there is a link under the cursor first and select that if so + const range = this._linkifier.currentLink?.link?.range; + if (range) { + this._model.selectionStart = [range.start.x - 1, range.start.y - 1]; + this._model.selectionStartLength = getRangeLength(range, this._bufferService.cols); + this._model.selectionEnd = undefined; + return true; + } + + const coords = this._getMouseBufferCoords(event); + if (coords) { + this._selectWordAt(coords, allowWhitespaceOnlySelection); + this._model.selectionEnd = undefined; + return true; + } + return false; + } + + /** + * Selects all text within the terminal. + */ + public selectAll(): void { + this._model.isSelectAllActive = true; + this.refresh(); + this._onSelectionChange.fire(); + } + + public selectLines(start: number, end: number): void { + this._model.clearSelection(); + start = Math.max(start, 0); + end = Math.min(end, this._bufferService.buffer.lines.length - 1); + this._model.selectionStart = [0, start]; + this._model.selectionEnd = [this._bufferService.cols, end]; + this.refresh(); + this._onSelectionChange.fire(); + } + + /** + * Handle the buffer being trimmed, adjust the selection position. + * @param amount The amount the buffer is being trimmed. + */ + private _handleTrim(amount: number): void { + const needsRefresh = this._model.handleTrim(amount); + if (needsRefresh) { + this.refresh(); + } + } + + /** + * Gets the 0-based [x, y] buffer coordinates of the current mouse event. + * @param event The mouse event. + */ + private _getMouseBufferCoords(event: MouseEvent): [number, number] | undefined { + const coords = this._mouseService.getCoords(event, this._screenElement, this._bufferService.cols, this._bufferService.rows, true); + if (!coords) { + return undefined; + } + + // Convert to 0-based + coords[0]--; + coords[1]--; + + // Convert viewport coords to buffer coords + coords[1] += this._bufferService.buffer.ydisp; + return coords; + } + + /** + * Gets the amount the viewport should be scrolled based on how far out of the + * terminal the mouse is. + * @param event The mouse event. + */ + private _getMouseEventScrollAmount(event: MouseEvent): number { + let offset = getCoordsRelativeToElement(this._coreBrowserService.window, event, this._screenElement)[1]; + const terminalHeight = this._renderService.dimensions.css.canvas.height; + if (offset >= 0 && offset <= terminalHeight) { + return 0; + } + if (offset > terminalHeight) { + offset -= terminalHeight; + } + + offset = Math.min(Math.max(offset, -DRAG_SCROLL_MAX_THRESHOLD), DRAG_SCROLL_MAX_THRESHOLD); + offset /= DRAG_SCROLL_MAX_THRESHOLD; + return (offset / Math.abs(offset)) + Math.round(offset * (DRAG_SCROLL_MAX_SPEED - 1)); + } + + /** + * Returns whether the selection manager should force selection, regardless of + * whether the terminal is in mouse events mode. + * @param event The mouse event. + */ + public shouldForceSelection(event: MouseEvent): boolean { + if (Browser.isMac) { + return event.altKey && this._optionsService.rawOptions.macOptionClickForcesSelection; + } + + return event.shiftKey; + } + + /** + * Handles te mousedown event, setting up for a new selection. + * @param event The mousedown event. + */ + public handleMouseDown(event: MouseEvent): void { + this._mouseDownTimeStamp = event.timeStamp; + // If we have selection, we want the context menu on right click even if the + // terminal is in mouse mode. + if (event.button === 2 && this.hasSelection) { + return; + } + + // Only action the primary button + if (event.button !== 0) { + return; + } + + // Allow selection when using a specific modifier key, even when disabled + if (!this._enabled) { + if (!this.shouldForceSelection(event)) { + return; + } + + // Don't send the mouse down event to the current process, we want to select + event.stopPropagation(); + } + + // Tell the browser not to start a regular selection + event.preventDefault(); + + // Reset drag scroll state + this._dragScrollAmount = 0; + + if (this._enabled && event.shiftKey) { + this._handleIncrementalClick(event); + } else { + if (event.detail === 1) { + this._handleSingleClick(event); + } else if (event.detail === 2) { + this._handleDoubleClick(event); + } else if (event.detail === 3) { + this._handleTripleClick(event); + } + } + + this._addMouseDownListeners(); + this.refresh(true); + } + + /** + * Adds listeners when mousedown is triggered. + */ + private _addMouseDownListeners(): void { + // Listen on the document so that dragging outside of viewport works + if (this._screenElement.ownerDocument) { + this._screenElement.ownerDocument.addEventListener('mousemove', this._mouseMoveListener); + this._screenElement.ownerDocument.addEventListener('mouseup', this._mouseUpListener); + } + this._dragScrollIntervalTimer = this._coreBrowserService.window.setInterval(() => this._dragScroll(), DRAG_SCROLL_INTERVAL); + } + + /** + * Removes the listeners that are registered when mousedown is triggered. + */ + private _removeMouseDownListeners(): void { + if (this._screenElement.ownerDocument) { + this._screenElement.ownerDocument.removeEventListener('mousemove', this._mouseMoveListener); + this._screenElement.ownerDocument.removeEventListener('mouseup', this._mouseUpListener); + } + this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer); + this._dragScrollIntervalTimer = undefined; + } + + /** + * Performs an incremental click, setting the selection end position to the mouse + * position. + * @param event The mouse event. + */ + private _handleIncrementalClick(event: MouseEvent): void { + if (this._model.selectionStart) { + this._model.selectionEnd = this._getMouseBufferCoords(event); + } + } + + /** + * Performs a single click, resetting relevant state and setting the selection + * start position. + * @param event The mouse event. + */ + private _handleSingleClick(event: MouseEvent): void { + this._model.selectionStartLength = 0; + this._model.isSelectAllActive = false; + this._activeSelectionMode = this.shouldColumnSelect(event) ? SelectionMode.COLUMN : SelectionMode.NORMAL; + + // Initialize the new selection + this._model.selectionStart = this._getMouseBufferCoords(event); + if (!this._model.selectionStart) { + return; + } + this._model.selectionEnd = undefined; + + // Ensure the line exists + const line = this._bufferService.buffer.lines.get(this._model.selectionStart[1]); + if (!line) { + return; + } + + // Return early if the click event is not in the buffer (eg. in scroll bar) + if (line.length === this._model.selectionStart[0]) { + return; + } + + // If the mouse is over the second half of a wide character, adjust the + // selection to cover the whole character + if (line.hasWidth(this._model.selectionStart[0]) === 0) { + this._model.selectionStart[0]++; + } + } + + /** + * Performs a double click, selecting the current word. + * @param event The mouse event. + */ + private _handleDoubleClick(event: MouseEvent): void { + if (this._selectWordAtCursor(event, true)) { + this._activeSelectionMode = SelectionMode.WORD; + } + } + + /** + * Performs a triple click, selecting the current line and activating line + * select mode. + * @param event The mouse event. + */ + private _handleTripleClick(event: MouseEvent): void { + const coords = this._getMouseBufferCoords(event); + if (coords) { + this._activeSelectionMode = SelectionMode.LINE; + this._selectLineAt(coords[1]); + } + } + + /** + * Returns whether the selection manager should operate in column select mode + * @param event the mouse or keyboard event + */ + public shouldColumnSelect(event: KeyboardEvent | MouseEvent): boolean { + return event.altKey && !(Browser.isMac && this._optionsService.rawOptions.macOptionClickForcesSelection); + } + + /** + * Handles the mousemove event when the mouse button is down, recording the + * end of the selection and refreshing the selection. + * @param event The mousemove event. + */ + private _handleMouseMove(event: MouseEvent): void { + // If the mousemove listener is active it means that a selection is + // currently being made, we should stop propagation to prevent mouse events + // to be sent to the pty. + event.stopImmediatePropagation(); + + // Do nothing if there is no selection start, this can happen if the first + // click in the terminal is an incremental click + if (!this._model.selectionStart) { + return; + } + + // Record the previous position so we know whether to redraw the selection + // at the end. + const previousSelectionEnd = this._model.selectionEnd ? [this._model.selectionEnd[0], this._model.selectionEnd[1]] : null; + + // Set the initial selection end based on the mouse coordinates + this._model.selectionEnd = this._getMouseBufferCoords(event); + if (!this._model.selectionEnd) { + this.refresh(true); + return; + } + + // Select the entire line if line select mode is active. + if (this._activeSelectionMode === SelectionMode.LINE) { + if (this._model.selectionEnd[1] < this._model.selectionStart[1]) { + this._model.selectionEnd[0] = 0; + } else { + this._model.selectionEnd[0] = this._bufferService.cols; + } + } else if (this._activeSelectionMode === SelectionMode.WORD) { + this._selectToWordAt(this._model.selectionEnd); + } + + // Determine the amount of scrolling that will happen. + this._dragScrollAmount = this._getMouseEventScrollAmount(event); + + // If the cursor was above or below the viewport, make sure it's at the + // start or end of the viewport respectively. This should only happen when + // NOT in column select mode. + if (this._activeSelectionMode !== SelectionMode.COLUMN) { + if (this._dragScrollAmount > 0) { + this._model.selectionEnd[0] = this._bufferService.cols; + } else if (this._dragScrollAmount < 0) { + this._model.selectionEnd[0] = 0; + } + } + + // If the character is a wide character include the cell to the right in the + // selection. Note that selections at the very end of the line will never + // have a character. + const buffer = this._bufferService.buffer; + if (this._model.selectionEnd[1] < buffer.lines.length) { + const line = buffer.lines.get(this._model.selectionEnd[1]); + if (line && line.hasWidth(this._model.selectionEnd[0]) === 0) { + if (this._model.selectionEnd[0] < this._bufferService.cols) { + this._model.selectionEnd[0]++; + } + } + } + + // Only draw here if the selection changes. + if (!previousSelectionEnd || + previousSelectionEnd[0] !== this._model.selectionEnd[0] || + previousSelectionEnd[1] !== this._model.selectionEnd[1]) { + this.refresh(true); + } + } + + /** + * The callback that occurs every DRAG_SCROLL_INTERVAL ms that does the + * scrolling of the viewport. + */ + private _dragScroll(): void { + if (!this._model.selectionEnd || !this._model.selectionStart) { + return; + } + if (this._dragScrollAmount) { + this._onRequestScrollLines.fire({ amount: this._dragScrollAmount, suppressScrollEvent: false }); + // Re-evaluate selection + // If the cursor was above or below the viewport, make sure it's at the + // start or end of the viewport respectively. This should only happen when + // NOT in column select mode. + const buffer = this._bufferService.buffer; + if (this._dragScrollAmount > 0) { + if (this._activeSelectionMode !== SelectionMode.COLUMN) { + this._model.selectionEnd[0] = this._bufferService.cols; + } + this._model.selectionEnd[1] = Math.min(buffer.ydisp + this._bufferService.rows, buffer.lines.length - 1); + } else { + if (this._activeSelectionMode !== SelectionMode.COLUMN) { + this._model.selectionEnd[0] = 0; + } + this._model.selectionEnd[1] = buffer.ydisp; + } + this.refresh(); + } + } + + /** + * Handles the mouseup event, removing the mousedown listeners. + * @param event The mouseup event. + */ + private _handleMouseUp(event: MouseEvent): void { + const timeElapsed = event.timeStamp - this._mouseDownTimeStamp; + + this._removeMouseDownListeners(); + + if (this.selectionText.length <= 1 && timeElapsed < ALT_CLICK_MOVE_CURSOR_TIME && event.altKey && this._optionsService.rawOptions.altClickMovesCursor) { + if (this._bufferService.buffer.ybase === this._bufferService.buffer.ydisp) { + const coordinates = this._mouseService.getCoords( + event, + this._element, + this._bufferService.cols, + this._bufferService.rows, + false + ); + if (coordinates && coordinates[0] !== undefined && coordinates[1] !== undefined) { + const sequence = moveToCellSequence(coordinates[0] - 1, coordinates[1] - 1, this._bufferService, this._coreService.decPrivateModes.applicationCursorKeys); + this._coreService.triggerDataEvent(sequence, true); + } + } + } else { + this._fireEventIfSelectionChanged(); + } + } + + private _fireEventIfSelectionChanged(): void { + const start = this._model.finalSelectionStart; + const end = this._model.finalSelectionEnd; + const hasSelection = !!start && !!end && (start[0] !== end[0] || start[1] !== end[1]); + + if (!hasSelection) { + if (this._oldHasSelection) { + this._fireOnSelectionChange(start, end, hasSelection); + } + return; + } + + // Sanity check, these should not be undefined as there is a selection + if (!start || !end) { + return; + } + + if (!this._oldSelectionStart || !this._oldSelectionEnd || ( + start[0] !== this._oldSelectionStart[0] || start[1] !== this._oldSelectionStart[1] || + end[0] !== this._oldSelectionEnd[0] || end[1] !== this._oldSelectionEnd[1])) { + + this._fireOnSelectionChange(start, end, hasSelection); + } + } + + private _fireOnSelectionChange(start: [number, number] | undefined, end: [number, number] | undefined, hasSelection: boolean): void { + this._oldSelectionStart = start; + this._oldSelectionEnd = end; + this._oldHasSelection = hasSelection; + this._onSelectionChange.fire(); + } + + private _handleBufferActivate(e: {activeBuffer: IBuffer, inactiveBuffer: IBuffer}): void { + this.clearSelection(); + // Only adjust the selection on trim, shiftElements is rarely used (only in + // reverseIndex) and delete in a splice is only ever used when the same + // number of elements was just added. Given this is could actually be + // beneficial to leave the selection as is for these cases. + this._trimListener.dispose(); + this._trimListener = e.activeBuffer.lines.onTrim(amount => this._handleTrim(amount)); + } + + /** + * Converts a viewport column (0 to cols - 1) to the character index on the + * buffer line, the latter takes into account wide and null characters. + * @param bufferLine The buffer line to use. + * @param x The x index in the buffer line to convert. + */ + private _convertViewportColToCharacterIndex(bufferLine: IBufferLine, x: number): number { + let charIndex = x; + for (let i = 0; x >= i; i++) { + const length = bufferLine.loadCell(i, this._workCell).getChars().length; + if (this._workCell.getWidth() === 0) { + // Wide characters aren't included in the line string so decrement the + // index so the index is back on the wide character. + charIndex--; + } else if (length > 1 && x !== i) { + // Emojis take up multiple characters, so adjust accordingly. For these + // we don't want ot include the character at the column as we're + // returning the start index in the string, not the end index. + charIndex += length - 1; + } + } + return charIndex; + } + + public setSelection(col: number, row: number, length: number): void { + this._model.clearSelection(); + this._removeMouseDownListeners(); + this._model.selectionStart = [col, row]; + this._model.selectionStartLength = length; + this.refresh(); + this._fireEventIfSelectionChanged(); + } + + public rightClickSelect(ev: MouseEvent): void { + if (!this._isClickInSelection(ev)) { + if (this._selectWordAtCursor(ev, false)) { + this.refresh(true); + } + this._fireEventIfSelectionChanged(); + } + } + + /** + * Gets positional information for the word at the coordinated specified. + * @param coords The coordinates to get the word at. + */ + private _getWordAt(coords: [number, number], allowWhitespaceOnlySelection: boolean, followWrappedLinesAbove: boolean = true, followWrappedLinesBelow: boolean = true): IWordPosition | undefined { + // Ensure coords are within viewport (eg. not within scroll bar) + if (coords[0] >= this._bufferService.cols) { + return undefined; + } + + const buffer = this._bufferService.buffer; + const bufferLine = buffer.lines.get(coords[1]); + if (!bufferLine) { + return undefined; + } + + const line = buffer.translateBufferLineToString(coords[1], false); + + // Get actual index, taking into consideration wide characters + let startIndex = this._convertViewportColToCharacterIndex(bufferLine, coords[0]); + let endIndex = startIndex; + + // Record offset to be used later + const charOffset = coords[0] - startIndex; + let leftWideCharCount = 0; + let rightWideCharCount = 0; + let leftLongCharOffset = 0; + let rightLongCharOffset = 0; + + if (line.charAt(startIndex) === ' ') { + // Expand until non-whitespace is hit + while (startIndex > 0 && line.charAt(startIndex - 1) === ' ') { + startIndex--; + } + while (endIndex < line.length && line.charAt(endIndex + 1) === ' ') { + endIndex++; + } + } else { + // Expand until whitespace is hit. This algorithm works by scanning left + // and right from the starting position, keeping both the index format + // (line) and the column format (bufferLine) in sync. When a wide + // character is hit, it is recorded and the column index is adjusted. + let startCol = coords[0]; + let endCol = coords[0]; + + // Consider the initial position, skip it and increment the wide char + // variable + if (bufferLine.getWidth(startCol) === 0) { + leftWideCharCount++; + startCol--; + } + if (bufferLine.getWidth(endCol) === 2) { + rightWideCharCount++; + endCol++; + } + + // Adjust the end index for characters whose length are > 1 (emojis) + const length = bufferLine.getString(endCol).length; + if (length > 1) { + rightLongCharOffset += length - 1; + endIndex += length - 1; + } + + // Expand the string in both directions until a space is hit + while (startCol > 0 && startIndex > 0 && !this._isCharWordSeparator(bufferLine.loadCell(startCol - 1, this._workCell))) { + bufferLine.loadCell(startCol - 1, this._workCell); + const length = this._workCell.getChars().length; + if (this._workCell.getWidth() === 0) { + // If the next character is a wide char, record it and skip the column + leftWideCharCount++; + startCol--; + } else if (length > 1) { + // If the next character's string is longer than 1 char (eg. emoji), + // adjust the index + leftLongCharOffset += length - 1; + startIndex -= length - 1; + } + startIndex--; + startCol--; + } + while (endCol < bufferLine.length && endIndex + 1 < line.length && !this._isCharWordSeparator(bufferLine.loadCell(endCol + 1, this._workCell))) { + bufferLine.loadCell(endCol + 1, this._workCell); + const length = this._workCell.getChars().length; + if (this._workCell.getWidth() === 2) { + // If the next character is a wide char, record it and skip the column + rightWideCharCount++; + endCol++; + } else if (length > 1) { + // If the next character's string is longer than 1 char (eg. emoji), + // adjust the index + rightLongCharOffset += length - 1; + endIndex += length - 1; + } + endIndex++; + endCol++; + } + } + + // Incremenet the end index so it is at the start of the next character + endIndex++; + + // Calculate the start _column_, converting the the string indexes back to + // column coordinates. + let start = + startIndex // The index of the selection's start char in the line string + + charOffset // The difference between the initial char's column and index + - leftWideCharCount // The number of wide chars left of the initial char + + leftLongCharOffset; // The number of additional chars left of the initial char added by columns with strings longer than 1 (emojis) + + // Calculate the length in _columns_, converting the the string indexes back + // to column coordinates. + let length = Math.min(this._bufferService.cols, // Disallow lengths larger than the terminal cols + endIndex // The index of the selection's end char in the line string + - startIndex // The index of the selection's start char in the line string + + leftWideCharCount // The number of wide chars left of the initial char + + rightWideCharCount // The number of wide chars right of the initial char (inclusive) + - leftLongCharOffset // The number of additional chars left of the initial char added by columns with strings longer than 1 (emojis) + - rightLongCharOffset); // The number of additional chars right of the initial char (inclusive) added by columns with strings longer than 1 (emojis) + + if (!allowWhitespaceOnlySelection && line.slice(startIndex, endIndex).trim() === '') { + return undefined; + } + + // Recurse upwards if the line is wrapped and the word wraps to the above line + if (followWrappedLinesAbove) { + if (start === 0 && bufferLine.getCodePoint(0) !== 32 /* ' ' */) { + const previousBufferLine = buffer.lines.get(coords[1] - 1); + if (previousBufferLine && bufferLine.isWrapped && previousBufferLine.getCodePoint(this._bufferService.cols - 1) !== 32 /* ' ' */) { + const previousLineWordPosition = this._getWordAt([this._bufferService.cols - 1, coords[1] - 1], false, true, false); + if (previousLineWordPosition) { + const offset = this._bufferService.cols - previousLineWordPosition.start; + start -= offset; + length += offset; + } + } + } + } + + // Recurse downwards if the line is wrapped and the word wraps to the next line + if (followWrappedLinesBelow) { + if (start + length === this._bufferService.cols && bufferLine.getCodePoint(this._bufferService.cols - 1) !== 32 /* ' ' */) { + const nextBufferLine = buffer.lines.get(coords[1] + 1); + if (nextBufferLine?.isWrapped && nextBufferLine.getCodePoint(0) !== 32 /* ' ' */) { + const nextLineWordPosition = this._getWordAt([0, coords[1] + 1], false, false, true); + if (nextLineWordPosition) { + length += nextLineWordPosition.length; + } + } + } + } + + return { start, length }; + } + + /** + * Selects the word at the coordinates specified. + * @param coords The coordinates to get the word at. + * @param allowWhitespaceOnlySelection If whitespace should be selected + */ + protected _selectWordAt(coords: [number, number], allowWhitespaceOnlySelection: boolean): void { + const wordPosition = this._getWordAt(coords, allowWhitespaceOnlySelection); + if (wordPosition) { + // Adjust negative start value + while (wordPosition.start < 0) { + wordPosition.start += this._bufferService.cols; + coords[1]--; + } + this._model.selectionStart = [wordPosition.start, coords[1]]; + this._model.selectionStartLength = wordPosition.length; + } + } + + /** + * Sets the selection end to the word at the coordinated specified. + * @param coords The coordinates to get the word at. + */ + private _selectToWordAt(coords: [number, number]): void { + const wordPosition = this._getWordAt(coords, true); + if (wordPosition) { + let endRow = coords[1]; + + // Adjust negative start value + while (wordPosition.start < 0) { + wordPosition.start += this._bufferService.cols; + endRow--; + } + + // Adjust wrapped length value, this only needs to happen when values are reversed as in that + // case we're interested in the start of the word, not the end + if (!this._model.areSelectionValuesReversed()) { + while (wordPosition.start + wordPosition.length > this._bufferService.cols) { + wordPosition.length -= this._bufferService.cols; + endRow++; + } + } + + this._model.selectionEnd = [this._model.areSelectionValuesReversed() ? wordPosition.start : wordPosition.start + wordPosition.length, endRow]; + } + } + + /** + * Gets whether the character is considered a word separator by the select + * word logic. + * @param cell The cell to check. + */ + private _isCharWordSeparator(cell: CellData): boolean { + // Zero width characters are never separators as they are always to the + // right of wide characters + if (cell.getWidth() === 0) { + return false; + } + return this._optionsService.rawOptions.wordSeparator.indexOf(cell.getChars()) >= 0; + } + + /** + * Selects the line specified. + * @param line The line index. + */ + protected _selectLineAt(line: number): void { + const wrappedRange = this._bufferService.buffer.getWrappedRangeForLine(line); + const range: IBufferRange = { + start: { x: 0, y: wrappedRange.first }, + end: { x: this._bufferService.cols - 1, y: wrappedRange.last } + }; + this._model.selectionStart = [0, wrappedRange.first]; + this._model.selectionEnd = undefined; + this._model.selectionStartLength = getRangeLength(range, this._bufferService.cols); + } +} diff --git a/node_modules/@xterm/xterm/src/browser/services/Services.ts b/node_modules/@xterm/xterm/src/browser/services/Services.ts new file mode 100644 index 0000000..19a8fcb --- /dev/null +++ b/node_modules/@xterm/xterm/src/browser/services/Services.ts @@ -0,0 +1,158 @@ +/** + * Copyright (c) 2019 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { IRenderDimensions, IRenderer } from 'browser/renderer/shared/Types'; +import { IColorSet, ILink, ReadonlyColorSet } from 'browser/Types'; +import { ISelectionRedrawRequestEvent as ISelectionRequestRedrawEvent, ISelectionRequestScrollLinesEvent } from 'browser/selection/Types'; +import { createDecorator } from 'common/services/ServiceRegistry'; +import { AllColorIndex, IDisposable } from 'common/Types'; +import type { Event } from 'vs/base/common/event'; + +export const ICharSizeService = createDecorator('CharSizeService'); +export interface ICharSizeService { + serviceBrand: undefined; + + readonly width: number; + readonly height: number; + readonly hasValidSize: boolean; + + readonly onCharSizeChange: Event; + + measure(): void; +} + +export const ICoreBrowserService = createDecorator('CoreBrowserService'); +export interface ICoreBrowserService { + serviceBrand: undefined; + + readonly isFocused: boolean; + + readonly onDprChange: Event; + readonly onWindowChange: Event; + + /** + * Gets or sets the parent window that the terminal is rendered into. DOM and rendering APIs (e.g. + * requestAnimationFrame) should be invoked in the context of this window. This should be set when + * the window hosting the xterm.js instance changes. + */ + window: Window & typeof globalThis; + /** + * The document of the primary window to be used to create elements when working with multiple + * windows. This is defined by the documentOverride setting. + */ + readonly mainDocument: Document; + /** + * Helper for getting the devicePixelRatio of the parent window. + */ + readonly dpr: number; +} + +export const IMouseService = createDecorator('MouseService'); +export interface IMouseService { + serviceBrand: undefined; + + getCoords(event: {clientX: number, clientY: number}, element: HTMLElement, colCount: number, rowCount: number, isSelection?: boolean): [number, number] | undefined; + getMouseReportCoords(event: MouseEvent, element: HTMLElement): { col: number, row: number, x: number, y: number } | undefined; +} + +export const IRenderService = createDecorator('RenderService'); +export interface IRenderService extends IDisposable { + serviceBrand: undefined; + + onDimensionsChange: Event; + /** + * Fires when buffer changes are rendered. This does not fire when only cursor + * or selections are rendered. + */ + onRenderedViewportChange: Event<{ start: number, end: number }>; + /** + * Fires on render + */ + onRender: Event<{ start: number, end: number }>; + onRefreshRequest: Event<{ start: number, end: number }>; + + dimensions: IRenderDimensions; + + addRefreshCallback(callback: FrameRequestCallback): number; + + refreshRows(start: number, end: number): void; + clearTextureAtlas(): void; + resize(cols: number, rows: number): void; + hasRenderer(): boolean; + setRenderer(renderer: IRenderer): void; + handleDevicePixelRatioChange(): void; + handleResize(cols: number, rows: number): void; + handleCharSizeChanged(): void; + handleBlur(): void; + handleFocus(): void; + handleSelectionChanged(start: [number, number] | undefined, end: [number, number] | undefined, columnSelectMode: boolean): void; + handleCursorMove(): void; + clear(): void; +} + +export const ISelectionService = createDecorator('SelectionService'); +export interface ISelectionService { + serviceBrand: undefined; + + readonly selectionText: string; + readonly hasSelection: boolean; + readonly selectionStart: [number, number] | undefined; + readonly selectionEnd: [number, number] | undefined; + + readonly onLinuxMouseSelection: Event; + readonly onRequestRedraw: Event; + readonly onRequestScrollLines: Event; + readonly onSelectionChange: Event; + + disable(): void; + enable(): void; + reset(): void; + setSelection(row: number, col: number, length: number): void; + selectAll(): void; + selectLines(start: number, end: number): void; + clearSelection(): void; + rightClickSelect(event: MouseEvent): void; + shouldColumnSelect(event: KeyboardEvent | MouseEvent): boolean; + shouldForceSelection(event: MouseEvent): boolean; + refresh(isLinuxMouseSelection?: boolean): void; + handleMouseDown(event: MouseEvent): void; + isCellInSelection(x: number, y: number): boolean; +} + +export const ICharacterJoinerService = createDecorator('CharacterJoinerService'); +export interface ICharacterJoinerService { + serviceBrand: undefined; + + register(handler: (text: string) => [number, number][]): number; + deregister(joinerId: number): boolean; + getJoinedCharacters(row: number): [number, number][]; +} + +export const IThemeService = createDecorator('ThemeService'); +export interface IThemeService { + serviceBrand: undefined; + + readonly colors: ReadonlyColorSet; + + readonly onChangeColors: Event; + + restoreColor(slot?: AllColorIndex): void; + /** + * Allows external modifying of colors in the theme, this is used instead of {@link colors} to + * prevent accidental writes. + */ + modifyColors(callback: (colors: IColorSet) => void): void; +} + + +export const ILinkProviderService = createDecorator('LinkProviderService'); +export interface ILinkProviderService extends IDisposable { + serviceBrand: undefined; + readonly linkProviders: ReadonlyArray; + registerLinkProvider(linkProvider: ILinkProvider): IDisposable; +} +export interface ILinkProvider { + provideLinks(y: number, callback: (links: ILink[] | undefined) => void): void; +} diff --git a/node_modules/@xterm/xterm/src/browser/services/ThemeService.ts b/node_modules/@xterm/xterm/src/browser/services/ThemeService.ts new file mode 100644 index 0000000..cd85e0f --- /dev/null +++ b/node_modules/@xterm/xterm/src/browser/services/ThemeService.ts @@ -0,0 +1,198 @@ +/** + * Copyright (c) 2022 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { ColorContrastCache } from 'browser/ColorContrastCache'; +import { IThemeService } from 'browser/services/Services'; +import { DEFAULT_ANSI_COLORS, IColorContrastCache, IColorSet, ReadonlyColorSet } from 'browser/Types'; +import { color, css, NULL_COLOR } from 'common/Color'; +import { Disposable } from 'vs/base/common/lifecycle'; +import { IOptionsService, ITheme } from 'common/services/Services'; +import { AllColorIndex, IColor, SpecialColorIndex } from 'common/Types'; +import { Emitter } from 'vs/base/common/event'; + +interface IRestoreColorSet { + foreground: IColor; + background: IColor; + cursor: IColor; + ansi: IColor[]; +} + + +const DEFAULT_FOREGROUND = css.toColor('#ffffff'); +const DEFAULT_BACKGROUND = css.toColor('#000000'); +const DEFAULT_CURSOR = css.toColor('#ffffff'); +const DEFAULT_CURSOR_ACCENT = DEFAULT_BACKGROUND; +const DEFAULT_SELECTION = { + css: 'rgba(255, 255, 255, 0.3)', + rgba: 0xFFFFFF4D +}; +const DEFAULT_OVERVIEW_RULER_BORDER = DEFAULT_FOREGROUND; + +export class ThemeService extends Disposable implements IThemeService { + public serviceBrand: undefined; + + private _colors: IColorSet; + private _contrastCache: IColorContrastCache = new ColorContrastCache(); + private _halfContrastCache: IColorContrastCache = new ColorContrastCache(); + private _restoreColors!: IRestoreColorSet; + + public get colors(): ReadonlyColorSet { return this._colors; } + + private readonly _onChangeColors = this._register(new Emitter()); + public readonly onChangeColors = this._onChangeColors.event; + + constructor( + @IOptionsService private readonly _optionsService: IOptionsService + ) { + super(); + + this._colors = { + foreground: DEFAULT_FOREGROUND, + background: DEFAULT_BACKGROUND, + cursor: DEFAULT_CURSOR, + cursorAccent: DEFAULT_CURSOR_ACCENT, + selectionForeground: undefined, + selectionBackgroundTransparent: DEFAULT_SELECTION, + selectionBackgroundOpaque: color.blend(DEFAULT_BACKGROUND, DEFAULT_SELECTION), + selectionInactiveBackgroundTransparent: DEFAULT_SELECTION, + selectionInactiveBackgroundOpaque: color.blend(DEFAULT_BACKGROUND, DEFAULT_SELECTION), + scrollbarSliderBackground: color.opacity(DEFAULT_FOREGROUND, 0.2), + scrollbarSliderHoverBackground: color.opacity(DEFAULT_FOREGROUND, 0.4), + scrollbarSliderActiveBackground: color.opacity(DEFAULT_FOREGROUND, 0.5), + overviewRulerBorder: DEFAULT_FOREGROUND, + ansi: DEFAULT_ANSI_COLORS.slice(), + contrastCache: this._contrastCache, + halfContrastCache: this._halfContrastCache + }; + this._updateRestoreColors(); + this._setTheme(this._optionsService.rawOptions.theme); + + this._register(this._optionsService.onSpecificOptionChange('minimumContrastRatio', () => this._contrastCache.clear())); + this._register(this._optionsService.onSpecificOptionChange('theme', () => this._setTheme(this._optionsService.rawOptions.theme))); + } + + /** + * Sets the terminal's theme. + * @param theme The theme to use. If a partial theme is provided then default + * colors will be used where colors are not defined. + */ + private _setTheme(theme: ITheme = {}): void { + const colors = this._colors; + colors.foreground = parseColor(theme.foreground, DEFAULT_FOREGROUND); + colors.background = parseColor(theme.background, DEFAULT_BACKGROUND); + colors.cursor = color.blend(colors.background, parseColor(theme.cursor, DEFAULT_CURSOR)); + colors.cursorAccent = color.blend(colors.background, parseColor(theme.cursorAccent, DEFAULT_CURSOR_ACCENT)); + colors.selectionBackgroundTransparent = parseColor(theme.selectionBackground, DEFAULT_SELECTION); + colors.selectionBackgroundOpaque = color.blend(colors.background, colors.selectionBackgroundTransparent); + colors.selectionInactiveBackgroundTransparent = parseColor(theme.selectionInactiveBackground, colors.selectionBackgroundTransparent); + colors.selectionInactiveBackgroundOpaque = color.blend(colors.background, colors.selectionInactiveBackgroundTransparent); + colors.selectionForeground = theme.selectionForeground ? parseColor(theme.selectionForeground, NULL_COLOR) : undefined; + if (colors.selectionForeground === NULL_COLOR) { + colors.selectionForeground = undefined; + } + + /** + * If selection color is opaque, blend it with background with 0.3 opacity + * Issue #2737 + */ + if (color.isOpaque(colors.selectionBackgroundTransparent)) { + const opacity = 0.3; + colors.selectionBackgroundTransparent = color.opacity(colors.selectionBackgroundTransparent, opacity); + } + if (color.isOpaque(colors.selectionInactiveBackgroundTransparent)) { + const opacity = 0.3; + colors.selectionInactiveBackgroundTransparent = color.opacity(colors.selectionInactiveBackgroundTransparent, opacity); + } + colors.scrollbarSliderBackground = parseColor(theme.scrollbarSliderBackground, color.opacity(colors.foreground, 0.2)); + colors.scrollbarSliderHoverBackground = parseColor(theme.scrollbarSliderHoverBackground, color.opacity(colors.foreground, 0.4)); + colors.scrollbarSliderActiveBackground = parseColor(theme.scrollbarSliderActiveBackground, color.opacity(colors.foreground, 0.5)); + colors.overviewRulerBorder = parseColor(theme.overviewRulerBorder, DEFAULT_OVERVIEW_RULER_BORDER); + colors.ansi = DEFAULT_ANSI_COLORS.slice(); + colors.ansi[0] = parseColor(theme.black, DEFAULT_ANSI_COLORS[0]); + colors.ansi[1] = parseColor(theme.red, DEFAULT_ANSI_COLORS[1]); + colors.ansi[2] = parseColor(theme.green, DEFAULT_ANSI_COLORS[2]); + colors.ansi[3] = parseColor(theme.yellow, DEFAULT_ANSI_COLORS[3]); + colors.ansi[4] = parseColor(theme.blue, DEFAULT_ANSI_COLORS[4]); + colors.ansi[5] = parseColor(theme.magenta, DEFAULT_ANSI_COLORS[5]); + colors.ansi[6] = parseColor(theme.cyan, DEFAULT_ANSI_COLORS[6]); + colors.ansi[7] = parseColor(theme.white, DEFAULT_ANSI_COLORS[7]); + colors.ansi[8] = parseColor(theme.brightBlack, DEFAULT_ANSI_COLORS[8]); + colors.ansi[9] = parseColor(theme.brightRed, DEFAULT_ANSI_COLORS[9]); + colors.ansi[10] = parseColor(theme.brightGreen, DEFAULT_ANSI_COLORS[10]); + colors.ansi[11] = parseColor(theme.brightYellow, DEFAULT_ANSI_COLORS[11]); + colors.ansi[12] = parseColor(theme.brightBlue, DEFAULT_ANSI_COLORS[12]); + colors.ansi[13] = parseColor(theme.brightMagenta, DEFAULT_ANSI_COLORS[13]); + colors.ansi[14] = parseColor(theme.brightCyan, DEFAULT_ANSI_COLORS[14]); + colors.ansi[15] = parseColor(theme.brightWhite, DEFAULT_ANSI_COLORS[15]); + if (theme.extendedAnsi) { + const colorCount = Math.min(colors.ansi.length - 16, theme.extendedAnsi.length); + for (let i = 0; i < colorCount; i++) { + colors.ansi[i + 16] = parseColor(theme.extendedAnsi[i], DEFAULT_ANSI_COLORS[i + 16]); + } + } + // Clear our the cache + this._contrastCache.clear(); + this._halfContrastCache.clear(); + this._updateRestoreColors(); + this._onChangeColors.fire(this.colors); + } + + public restoreColor(slot?: AllColorIndex): void { + this._restoreColor(slot); + this._onChangeColors.fire(this.colors); + } + + private _restoreColor(slot: AllColorIndex | undefined): void { + // unset slot restores all ansi colors + if (slot === undefined) { + for (let i = 0; i < this._restoreColors.ansi.length; ++i) { + this._colors.ansi[i] = this._restoreColors.ansi[i]; + } + return; + } + switch (slot) { + case SpecialColorIndex.FOREGROUND: + this._colors.foreground = this._restoreColors.foreground; + break; + case SpecialColorIndex.BACKGROUND: + this._colors.background = this._restoreColors.background; + break; + case SpecialColorIndex.CURSOR: + this._colors.cursor = this._restoreColors.cursor; + break; + default: + this._colors.ansi[slot] = this._restoreColors.ansi[slot]; + } + } + + public modifyColors(callback: (colors: IColorSet) => void): void { + callback(this._colors); + // Assume the change happened + this._onChangeColors.fire(this.colors); + } + + private _updateRestoreColors(): void { + this._restoreColors = { + foreground: this._colors.foreground, + background: this._colors.background, + cursor: this._colors.cursor, + ansi: this._colors.ansi.slice() + }; + } +} + +function parseColor( + cssString: string | undefined, + fallback: IColor +): IColor { + if (cssString !== undefined) { + try { + return css.toColor(cssString); + } catch { + // no-op + } + } + return fallback; +} diff --git a/node_modules/@xterm/xterm/src/browser/shared/Constants.ts b/node_modules/@xterm/xterm/src/browser/shared/Constants.ts new file mode 100644 index 0000000..58b7d2f --- /dev/null +++ b/node_modules/@xterm/xterm/src/browser/shared/Constants.ts @@ -0,0 +1,8 @@ +/** + * Copyright (c) 2024 The xterm.js authors. All rights reserved. + * @license MIT + */ + +export const enum ViewportConstants { + DEFAULT_SCROLL_BAR_WIDTH = 14 +} diff --git a/node_modules/@xterm/xterm/src/common/CircularList.ts b/node_modules/@xterm/xterm/src/common/CircularList.ts new file mode 100644 index 0000000..a46faca --- /dev/null +++ b/node_modules/@xterm/xterm/src/common/CircularList.ts @@ -0,0 +1,241 @@ +/** + * Copyright (c) 2016 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { ICircularList } from 'common/Types'; +import { Disposable } from 'vs/base/common/lifecycle'; +import { Emitter } from 'vs/base/common/event'; + +export interface IInsertEvent { + index: number; + amount: number; +} + +export interface IDeleteEvent { + index: number; + amount: number; +} + +/** + * Represents a circular list; a list with a maximum size that wraps around when push is called, + * overriding values at the start of the list. + */ +export class CircularList extends Disposable implements ICircularList { + protected _array: (T | undefined)[]; + private _startIndex: number; + private _length: number; + + public readonly onDeleteEmitter = this._register(new Emitter()); + public readonly onDelete = this.onDeleteEmitter.event; + public readonly onInsertEmitter = this._register(new Emitter()); + public readonly onInsert = this.onInsertEmitter.event; + public readonly onTrimEmitter = this._register(new Emitter()); + public readonly onTrim = this.onTrimEmitter.event; + + constructor( + private _maxLength: number + ) { + super(); + this._array = new Array(this._maxLength); + this._startIndex = 0; + this._length = 0; + } + + public get maxLength(): number { + return this._maxLength; + } + + public set maxLength(newMaxLength: number) { + // There was no change in maxLength, return early. + if (this._maxLength === newMaxLength) { + return; + } + + // Reconstruct array, starting at index 0. Only transfer values from the + // indexes 0 to length. + const newArray = new Array(newMaxLength); + for (let i = 0; i < Math.min(newMaxLength, this.length); i++) { + newArray[i] = this._array[this._getCyclicIndex(i)]; + } + this._array = newArray; + this._maxLength = newMaxLength; + this._startIndex = 0; + } + + public get length(): number { + return this._length; + } + + public set length(newLength: number) { + if (newLength > this._length) { + for (let i = this._length; i < newLength; i++) { + this._array[i] = undefined; + } + } + this._length = newLength; + } + + /** + * Gets the value at an index. + * + * Note that for performance reasons there is no bounds checking here, the index reference is + * circular so this should always return a value and never throw. + * @param index The index of the value to get. + * @returns The value corresponding to the index. + */ + public get(index: number): T | undefined { + return this._array[this._getCyclicIndex(index)]; + } + + /** + * Sets the value at an index. + * + * Note that for performance reasons there is no bounds checking here, the index reference is + * circular so this should always return a value and never throw. + * @param index The index to set. + * @param value The value to set. + */ + public set(index: number, value: T | undefined): void { + this._array[this._getCyclicIndex(index)] = value; + } + + /** + * Pushes a new value onto the list, wrapping around to the start of the array, overriding index 0 + * if the maximum length is reached. + * @param value The value to push onto the list. + */ + public push(value: T): void { + this._array[this._getCyclicIndex(this._length)] = value; + if (this._length === this._maxLength) { + this._startIndex = ++this._startIndex % this._maxLength; + this.onTrimEmitter.fire(1); + } else { + this._length++; + } + } + + /** + * Advance ringbuffer index and return current element for recycling. + * Note: The buffer must be full for this method to work. + * @throws When the buffer is not full. + */ + public recycle(): T { + if (this._length !== this._maxLength) { + throw new Error('Can only recycle when the buffer is full'); + } + this._startIndex = ++this._startIndex % this._maxLength; + this.onTrimEmitter.fire(1); + return this._array[this._getCyclicIndex(this._length - 1)]!; + } + + /** + * Ringbuffer is at max length. + */ + public get isFull(): boolean { + return this._length === this._maxLength; + } + + /** + * Removes and returns the last value on the list. + * @returns The popped value. + */ + public pop(): T | undefined { + return this._array[this._getCyclicIndex(this._length-- - 1)]; + } + + /** + * Deletes and/or inserts items at a particular index (in that order). Unlike + * Array.prototype.splice, this operation does not return the deleted items as a new array in + * order to save creating a new array. Note that this operation may shift all values in the list + * in the worst case. + * @param start The index to delete and/or insert. + * @param deleteCount The number of elements to delete. + * @param items The items to insert. + */ + public splice(start: number, deleteCount: number, ...items: T[]): void { + // Delete items + if (deleteCount) { + for (let i = start; i < this._length - deleteCount; i++) { + this._array[this._getCyclicIndex(i)] = this._array[this._getCyclicIndex(i + deleteCount)]; + } + this._length -= deleteCount; + this.onDeleteEmitter.fire({ index: start, amount: deleteCount }); + } + + // Add items + for (let i = this._length - 1; i >= start; i--) { + this._array[this._getCyclicIndex(i + items.length)] = this._array[this._getCyclicIndex(i)]; + } + for (let i = 0; i < items.length; i++) { + this._array[this._getCyclicIndex(start + i)] = items[i]; + } + if (items.length) { + this.onInsertEmitter.fire({ index: start, amount: items.length }); + } + + // Adjust length as needed + if (this._length + items.length > this._maxLength) { + const countToTrim = (this._length + items.length) - this._maxLength; + this._startIndex += countToTrim; + this._length = this._maxLength; + this.onTrimEmitter.fire(countToTrim); + } else { + this._length += items.length; + } + } + + /** + * Trims a number of items from the start of the list. + * @param count The number of items to remove. + */ + public trimStart(count: number): void { + if (count > this._length) { + count = this._length; + } + this._startIndex += count; + this._length -= count; + this.onTrimEmitter.fire(count); + } + + public shiftElements(start: number, count: number, offset: number): void { + if (count <= 0) { + return; + } + if (start < 0 || start >= this._length) { + throw new Error('start argument out of range'); + } + if (start + offset < 0) { + throw new Error('Cannot shift elements in list beyond index 0'); + } + + if (offset > 0) { + for (let i = count - 1; i >= 0; i--) { + this.set(start + i + offset, this.get(start + i)); + } + const expandListBy = (start + count + offset) - this._length; + if (expandListBy > 0) { + this._length += expandListBy; + while (this._length > this._maxLength) { + this._length--; + this._startIndex++; + this.onTrimEmitter.fire(1); + } + } + } else { + for (let i = 0; i < count; i++) { + this.set(start + i + offset, this.get(start + i)); + } + } + } + + /** + * Gets the cyclic index for the specified regular index. The cyclic index can then be used on the + * backing array to get the element associated with the regular index. + * @param index The regular index. + * @returns The cyclic index. + */ + private _getCyclicIndex(index: number): number { + return (this._startIndex + index) % this._maxLength; + } +} diff --git a/node_modules/@xterm/xterm/src/common/Clone.ts b/node_modules/@xterm/xterm/src/common/Clone.ts new file mode 100644 index 0000000..37821fe --- /dev/null +++ b/node_modules/@xterm/xterm/src/common/Clone.ts @@ -0,0 +1,23 @@ +/** + * Copyright (c) 2016 The xterm.js authors. All rights reserved. + * @license MIT + */ + +/* + * A simple utility for cloning values + */ +export function clone(val: T, depth: number = 5): T { + if (typeof val !== 'object') { + return val; + } + + // If we're cloning an array, use an array as the base, otherwise use an object + const clonedObject: any = Array.isArray(val) ? [] : {}; + + for (const key in val) { + // Recursively clone eack item unless we're at the maximum depth + clonedObject[key] = depth <= 1 ? val[key] : (val[key] && clone(val[key], depth - 1)); + } + + return clonedObject as T; +} diff --git a/node_modules/@xterm/xterm/src/common/Color.ts b/node_modules/@xterm/xterm/src/common/Color.ts new file mode 100644 index 0000000..b7b3ff4 --- /dev/null +++ b/node_modules/@xterm/xterm/src/common/Color.ts @@ -0,0 +1,376 @@ +/** + * Copyright (c) 2019 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { IColor, IColorRGB } from 'common/Types'; + +let $r = 0; +let $g = 0; +let $b = 0; +let $a = 0; + +export const NULL_COLOR: IColor = { + css: '#00000000', + rgba: 0 +}; + +/** + * Helper functions where the source type is "channels" (individual color channels as numbers). + */ +export namespace channels { + export function toCss(r: number, g: number, b: number, a?: number): string { + if (a !== undefined) { + return `#${toPaddedHex(r)}${toPaddedHex(g)}${toPaddedHex(b)}${toPaddedHex(a)}`; + } + return `#${toPaddedHex(r)}${toPaddedHex(g)}${toPaddedHex(b)}`; + } + + export function toRgba(r: number, g: number, b: number, a: number = 0xFF): number { + // Note: The aggregated number is RGBA32 (BE), thus needs to be converted to ABGR32 + // on LE systems, before it can be used for direct 32-bit buffer writes. + // >>> 0 forces an unsigned int + return (r << 24 | g << 16 | b << 8 | a) >>> 0; + } + + export function toColor(r: number, g: number, b: number, a?: number): IColor { + return { + css: channels.toCss(r, g, b, a), + rgba: channels.toRgba(r, g, b, a) + }; + } +} + +/** + * Helper functions where the source type is `IColor`. + */ +export namespace color { + export function blend(bg: IColor, fg: IColor): IColor { + $a = (fg.rgba & 0xFF) / 255; + if ($a === 1) { + return { + css: fg.css, + rgba: fg.rgba + }; + } + const fgR = (fg.rgba >> 24) & 0xFF; + const fgG = (fg.rgba >> 16) & 0xFF; + const fgB = (fg.rgba >> 8) & 0xFF; + const bgR = (bg.rgba >> 24) & 0xFF; + const bgG = (bg.rgba >> 16) & 0xFF; + const bgB = (bg.rgba >> 8) & 0xFF; + $r = bgR + Math.round((fgR - bgR) * $a); + $g = bgG + Math.round((fgG - bgG) * $a); + $b = bgB + Math.round((fgB - bgB) * $a); + const css = channels.toCss($r, $g, $b); + const rgba = channels.toRgba($r, $g, $b); + return { css, rgba }; + } + + export function isOpaque(color: IColor): boolean { + return (color.rgba & 0xFF) === 0xFF; + } + + export function ensureContrastRatio(bg: IColor, fg: IColor, ratio: number): IColor | undefined { + const result = rgba.ensureContrastRatio(bg.rgba, fg.rgba, ratio); + if (!result) { + return undefined; + } + return channels.toColor( + (result >> 24 & 0xFF), + (result >> 16 & 0xFF), + (result >> 8 & 0xFF) + ); + } + + export function opaque(color: IColor): IColor { + const rgbaColor = (color.rgba | 0xFF) >>> 0; + [$r, $g, $b] = rgba.toChannels(rgbaColor); + return { + css: channels.toCss($r, $g, $b), + rgba: rgbaColor + }; + } + + export function opacity(color: IColor, opacity: number): IColor { + $a = Math.round(opacity * 0xFF); + [$r, $g, $b] = rgba.toChannels(color.rgba); + return { + css: channels.toCss($r, $g, $b, $a), + rgba: channels.toRgba($r, $g, $b, $a) + }; + } + + export function multiplyOpacity(color: IColor, factor: number): IColor { + $a = color.rgba & 0xFF; + return opacity(color, ($a * factor) / 0xFF); + } + + export function toColorRGB(color: IColor): IColorRGB { + return [(color.rgba >> 24) & 0xFF, (color.rgba >> 16) & 0xFF, (color.rgba >> 8) & 0xFF]; + } +} + +/** + * Helper functions where the source type is "css" (string: '#rgb', '#rgba', '#rrggbb', + * '#rrggbbaa'). + */ +export namespace css { + // Attempt to set get the shared canvas context + let $ctx: CanvasRenderingContext2D | undefined; + let $litmusColor: CanvasGradient | undefined; + try { + // This is guaranteed to run in the first window, so document should be correct + const canvas = document.createElement('canvas'); + canvas.width = 1; + canvas.height = 1; + const ctx = canvas.getContext('2d', { + willReadFrequently: true + }); + if (ctx) { + $ctx = ctx; + $ctx.globalCompositeOperation = 'copy'; + $litmusColor = $ctx.createLinearGradient(0, 0, 1, 1); + } + } + catch { + // noop + } + + /** + * Converts a css string to an IColor, this should handle all valid CSS color strings and will + * throw if it's invalid. The ideal format to use is `#rrggbb[aa]` as it's the fastest to parse. + * + * Only `#rgb[a]`, `#rrggbb[aa]`, `rgb()` and `rgba()` formats are supported when run in a Node + * environment. + */ + export function toColor(css: string): IColor { + // Formats: #rgb[a] and #rrggbb[aa] + if (css.match(/#[\da-f]{3,8}/i)) { + switch (css.length) { + case 4: { // #rgb + $r = parseInt(css.slice(1, 2).repeat(2), 16); + $g = parseInt(css.slice(2, 3).repeat(2), 16); + $b = parseInt(css.slice(3, 4).repeat(2), 16); + return channels.toColor($r, $g, $b); + } + case 5: { // #rgba + $r = parseInt(css.slice(1, 2).repeat(2), 16); + $g = parseInt(css.slice(2, 3).repeat(2), 16); + $b = parseInt(css.slice(3, 4).repeat(2), 16); + $a = parseInt(css.slice(4, 5).repeat(2), 16); + return channels.toColor($r, $g, $b, $a); + } + case 7: // #rrggbb + return { + css, + rgba: (parseInt(css.slice(1), 16) << 8 | 0xFF) >>> 0 + }; + case 9: // #rrggbbaa + return { + css, + rgba: parseInt(css.slice(1), 16) >>> 0 + }; + } + } + + // Formats: rgb() or rgba() + const rgbaMatch = css.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/); + if (rgbaMatch) { + $r = parseInt(rgbaMatch[1]); + $g = parseInt(rgbaMatch[2]); + $b = parseInt(rgbaMatch[3]); + $a = Math.round((rgbaMatch[5] === undefined ? 1 : parseFloat(rgbaMatch[5])) * 0xFF); + return channels.toColor($r, $g, $b, $a); + } + + // Validate the context is available for canvas-based color parsing + if (!$ctx || !$litmusColor) { + throw new Error('css.toColor: Unsupported css format'); + } + + // Validate the color using canvas fillStyle + // See https://html.spec.whatwg.org/multipage/canvas.html#fill-and-stroke-styles + $ctx.fillStyle = $litmusColor; + $ctx.fillStyle = css; + if (typeof $ctx.fillStyle !== 'string') { + throw new Error('css.toColor: Unsupported css format'); + } + + $ctx.fillRect(0, 0, 1, 1); + [$r, $g, $b, $a] = $ctx.getImageData(0, 0, 1, 1).data; + + // Validate the color is non-transparent as color hue gets lost when drawn to the canvas + if ($a !== 0xFF) { + throw new Error('css.toColor: Unsupported css format'); + } + + // Extract the color from the canvas' fillStyle property which exposes the color value in rgba() + // format + // See https://html.spec.whatwg.org/multipage/canvas.html#serialisation-of-a-color + return { + rgba: channels.toRgba($r, $g, $b, $a), + css + }; + } +} + +/** + * Helper functions where the source type is "rgb" (number: 0xrrggbb). + */ +export namespace rgb { + /** + * Gets the relative luminance of an RGB color, this is useful in determining the contrast ratio + * between two colors. + * @param rgb The color to use. + * @see https://www.w3.org/TR/WCAG20/#relativeluminancedef + */ + export function relativeLuminance(rgb: number): number { + return relativeLuminance2( + (rgb >> 16) & 0xFF, + (rgb >> 8 ) & 0xFF, + (rgb ) & 0xFF); + } + + /** + * Gets the relative luminance of an RGB color, this is useful in determining the contrast ratio + * between two colors. + * @param r The red channel (0x00 to 0xFF). + * @param g The green channel (0x00 to 0xFF). + * @param b The blue channel (0x00 to 0xFF). + * @see https://www.w3.org/TR/WCAG20/#relativeluminancedef + */ + export function relativeLuminance2(r: number, g: number, b: number): number { + const rs = r / 255; + const gs = g / 255; + const bs = b / 255; + const rr = rs <= 0.03928 ? rs / 12.92 : Math.pow((rs + 0.055) / 1.055, 2.4); + const rg = gs <= 0.03928 ? gs / 12.92 : Math.pow((gs + 0.055) / 1.055, 2.4); + const rb = bs <= 0.03928 ? bs / 12.92 : Math.pow((bs + 0.055) / 1.055, 2.4); + return rr * 0.2126 + rg * 0.7152 + rb * 0.0722; + } +} + +/** + * Helper functions where the source type is "rgba" (number: 0xrrggbbaa). + */ +export namespace rgba { + export function blend(bg: number, fg: number): number { + $a = (fg & 0xFF) / 0xFF; + if ($a === 1) { + return fg; + } + const fgR = (fg >> 24) & 0xFF; + const fgG = (fg >> 16) & 0xFF; + const fgB = (fg >> 8) & 0xFF; + const bgR = (bg >> 24) & 0xFF; + const bgG = (bg >> 16) & 0xFF; + const bgB = (bg >> 8) & 0xFF; + $r = bgR + Math.round((fgR - bgR) * $a); + $g = bgG + Math.round((fgG - bgG) * $a); + $b = bgB + Math.round((fgB - bgB) * $a); + return channels.toRgba($r, $g, $b); + } + + /** + * Given a foreground color and a background color, either increase or reduce the luminance of the + * foreground color until the specified contrast ratio is met. If pure white or black is hit + * without the contrast ratio being met, go the other direction using the background color as the + * foreground color and take either the first or second result depending on which has the higher + * contrast ratio. + * + * `undefined` will be returned if the contrast ratio is already met. + * + * @param bgRgba The background color in rgba format. + * @param fgRgba The foreground color in rgba format. + * @param ratio The contrast ratio to achieve. + */ + export function ensureContrastRatio(bgRgba: number, fgRgba: number, ratio: number): number | undefined { + const bgL = rgb.relativeLuminance(bgRgba >> 8); + const fgL = rgb.relativeLuminance(fgRgba >> 8); + const cr = contrastRatio(bgL, fgL); + if (cr < ratio) { + if (fgL < bgL) { + const resultA = reduceLuminance(bgRgba, fgRgba, ratio); + const resultARatio = contrastRatio(bgL, rgb.relativeLuminance(resultA >> 8)); + if (resultARatio < ratio) { + const resultB = increaseLuminance(bgRgba, fgRgba, ratio); + const resultBRatio = contrastRatio(bgL, rgb.relativeLuminance(resultB >> 8)); + return resultARatio > resultBRatio ? resultA : resultB; + } + return resultA; + } + const resultA = increaseLuminance(bgRgba, fgRgba, ratio); + const resultARatio = contrastRatio(bgL, rgb.relativeLuminance(resultA >> 8)); + if (resultARatio < ratio) { + const resultB = reduceLuminance(bgRgba, fgRgba, ratio); + const resultBRatio = contrastRatio(bgL, rgb.relativeLuminance(resultB >> 8)); + return resultARatio > resultBRatio ? resultA : resultB; + } + return resultA; + } + return undefined; + } + + export function reduceLuminance(bgRgba: number, fgRgba: number, ratio: number): number { + // This is a naive but fast approach to reducing luminance as converting to + // HSL and back is expensive + const bgR = (bgRgba >> 24) & 0xFF; + const bgG = (bgRgba >> 16) & 0xFF; + const bgB = (bgRgba >> 8) & 0xFF; + let fgR = (fgRgba >> 24) & 0xFF; + let fgG = (fgRgba >> 16) & 0xFF; + let fgB = (fgRgba >> 8) & 0xFF; + let cr = contrastRatio(rgb.relativeLuminance2(fgR, fgG, fgB), rgb.relativeLuminance2(bgR, bgG, bgB)); + while (cr < ratio && (fgR > 0 || fgG > 0 || fgB > 0)) { + // Reduce by 10% until the ratio is hit + fgR -= Math.max(0, Math.ceil(fgR * 0.1)); + fgG -= Math.max(0, Math.ceil(fgG * 0.1)); + fgB -= Math.max(0, Math.ceil(fgB * 0.1)); + cr = contrastRatio(rgb.relativeLuminance2(fgR, fgG, fgB), rgb.relativeLuminance2(bgR, bgG, bgB)); + } + return (fgR << 24 | fgG << 16 | fgB << 8 | 0xFF) >>> 0; + } + + export function increaseLuminance(bgRgba: number, fgRgba: number, ratio: number): number { + // This is a naive but fast approach to increasing luminance as converting to + // HSL and back is expensive + const bgR = (bgRgba >> 24) & 0xFF; + const bgG = (bgRgba >> 16) & 0xFF; + const bgB = (bgRgba >> 8) & 0xFF; + let fgR = (fgRgba >> 24) & 0xFF; + let fgG = (fgRgba >> 16) & 0xFF; + let fgB = (fgRgba >> 8) & 0xFF; + let cr = contrastRatio(rgb.relativeLuminance2(fgR, fgG, fgB), rgb.relativeLuminance2(bgR, bgG, bgB)); + while (cr < ratio && (fgR < 0xFF || fgG < 0xFF || fgB < 0xFF)) { + // Increase by 10% until the ratio is hit + fgR = Math.min(0xFF, fgR + Math.ceil((255 - fgR) * 0.1)); + fgG = Math.min(0xFF, fgG + Math.ceil((255 - fgG) * 0.1)); + fgB = Math.min(0xFF, fgB + Math.ceil((255 - fgB) * 0.1)); + cr = contrastRatio(rgb.relativeLuminance2(fgR, fgG, fgB), rgb.relativeLuminance2(bgR, bgG, bgB)); + } + return (fgR << 24 | fgG << 16 | fgB << 8 | 0xFF) >>> 0; + } + + export function toChannels(value: number): [number, number, number, number] { + return [(value >> 24) & 0xFF, (value >> 16) & 0xFF, (value >> 8) & 0xFF, value & 0xFF]; + } +} + +export function toPaddedHex(c: number): string { + const s = c.toString(16); + return s.length < 2 ? '0' + s : s; +} + +/** + * Gets the contrast ratio between two relative luminance values. + * @param l1 The first relative luminance. + * @param l2 The first relative luminance. + * @see https://www.w3.org/TR/WCAG20/#contrast-ratiodef + */ +export function contrastRatio(l1: number, l2: number): number { + if (l1 < l2) { + return (l2 + 0.05) / (l1 + 0.05); + } + return (l1 + 0.05) / (l2 + 0.05); +} diff --git a/node_modules/@xterm/xterm/src/common/CoreTerminal.ts b/node_modules/@xterm/xterm/src/common/CoreTerminal.ts new file mode 100644 index 0000000..90e27a5 --- /dev/null +++ b/node_modules/@xterm/xterm/src/common/CoreTerminal.ts @@ -0,0 +1,283 @@ +/** + * Copyright (c) 2014-2020 The xterm.js authors. All rights reserved. + * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License) + * @license MIT + * + * Originally forked from (with the author's permission): + * Fabrice Bellard's javascript vt100 for jslinux: + * http://bellard.org/jslinux/ + * Copyright (c) 2011 Fabrice Bellard + * The original design remains. The terminal itself + * has been extended to include xterm CSI codes, among + * other features. + * + * Terminal Emulation References: + * http://vt100.net/ + * http://invisible-island.net/xterm/ctlseqs/ctlseqs.txt + * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html + * http://invisible-island.net/vttest/ + * http://www.inwap.com/pdp10/ansicode.txt + * http://linux.die.net/man/4/console_codes + * http://linux.die.net/man/7/urxvt + */ + +import { IInstantiationService, IOptionsService, IBufferService, ILogService, ICharsetService, ICoreService, ICoreMouseService, IUnicodeService, LogLevelEnum, ITerminalOptions, IOscLinkService } from 'common/services/Services'; +import { InstantiationService } from 'common/services/InstantiationService'; +import { LogService } from 'common/services/LogService'; +import { BufferService, MINIMUM_COLS, MINIMUM_ROWS } from 'common/services/BufferService'; +import { OptionsService } from 'common/services/OptionsService'; +import { IDisposable, IAttributeData, ICoreTerminal, IScrollEvent } from 'common/Types'; +import { CoreService } from 'common/services/CoreService'; +import { CoreMouseService } from 'common/services/CoreMouseService'; +import { UnicodeService } from 'common/services/UnicodeService'; +import { CharsetService } from 'common/services/CharsetService'; +import { updateWindowsModeWrappedState } from 'common/WindowsMode'; +import { IFunctionIdentifier, IParams } from 'common/parser/Types'; +import { IBufferSet } from 'common/buffer/Types'; +import { InputHandler } from 'common/InputHandler'; +import { WriteBuffer } from 'common/input/WriteBuffer'; +import { OscLinkService } from 'common/services/OscLinkService'; +import { Emitter, Event } from 'vs/base/common/event'; +import { Disposable, MutableDisposable, toDisposable } from 'vs/base/common/lifecycle'; + +// Only trigger this warning a single time per session +let hasWriteSyncWarnHappened = false; + +export abstract class CoreTerminal extends Disposable implements ICoreTerminal { + protected readonly _instantiationService: IInstantiationService; + protected readonly _bufferService: IBufferService; + protected readonly _logService: ILogService; + protected readonly _charsetService: ICharsetService; + protected readonly _oscLinkService: IOscLinkService; + + public readonly coreMouseService: ICoreMouseService; + public readonly coreService: ICoreService; + public readonly unicodeService: IUnicodeService; + public readonly optionsService: IOptionsService; + + protected _inputHandler: InputHandler; + private _writeBuffer: WriteBuffer; + private _windowsWrappingHeuristics = this._register(new MutableDisposable()); + + private readonly _onBinary = this._register(new Emitter()); + public readonly onBinary = this._onBinary.event; + private readonly _onData = this._register(new Emitter()); + public readonly onData = this._onData.event; + protected _onLineFeed = this._register(new Emitter()); + public readonly onLineFeed = this._onLineFeed.event; + private readonly _onResize = this._register(new Emitter<{ cols: number, rows: number }>()); + public readonly onResize = this._onResize.event; + protected readonly _onWriteParsed = this._register(new Emitter()); + public readonly onWriteParsed = this._onWriteParsed.event; + + /** + * Internally we track the source of the scroll but this is meaningless outside the library so + * it's filtered out. + */ + protected _onScrollApi?: Emitter; + protected _onScroll = this._register(new Emitter()); + public get onScroll(): Event { + if (!this._onScrollApi) { + this._onScrollApi = this._register(new Emitter()); + this._onScroll.event(ev => { + this._onScrollApi?.fire(ev.position); + }); + } + return this._onScrollApi.event; + } + + public get cols(): number { return this._bufferService.cols; } + public get rows(): number { return this._bufferService.rows; } + public get buffers(): IBufferSet { return this._bufferService.buffers; } + public get options(): Required { return this.optionsService.options; } + public set options(options: ITerminalOptions) { + for (const key in options) { + this.optionsService.options[key] = options[key]; + } + } + + constructor( + options: Partial + ) { + super(); + + // Setup and initialize services + this._instantiationService = new InstantiationService(); + this.optionsService = this._register(new OptionsService(options)); + this._instantiationService.setService(IOptionsService, this.optionsService); + this._bufferService = this._register(this._instantiationService.createInstance(BufferService)); + this._instantiationService.setService(IBufferService, this._bufferService); + this._logService = this._register(this._instantiationService.createInstance(LogService)); + this._instantiationService.setService(ILogService, this._logService); + this.coreService = this._register(this._instantiationService.createInstance(CoreService)); + this._instantiationService.setService(ICoreService, this.coreService); + this.coreMouseService = this._register(this._instantiationService.createInstance(CoreMouseService)); + this._instantiationService.setService(ICoreMouseService, this.coreMouseService); + this.unicodeService = this._register(this._instantiationService.createInstance(UnicodeService)); + this._instantiationService.setService(IUnicodeService, this.unicodeService); + this._charsetService = this._instantiationService.createInstance(CharsetService); + this._instantiationService.setService(ICharsetService, this._charsetService); + this._oscLinkService = this._instantiationService.createInstance(OscLinkService); + this._instantiationService.setService(IOscLinkService, this._oscLinkService); + + + // Register input handler and handle/forward events + this._inputHandler = this._register(new InputHandler(this._bufferService, this._charsetService, this.coreService, this._logService, this.optionsService, this._oscLinkService, this.coreMouseService, this.unicodeService)); + this._register(Event.forward(this._inputHandler.onLineFeed, this._onLineFeed)); + this._register(this._inputHandler); + + // Setup listeners + this._register(Event.forward(this._bufferService.onResize, this._onResize)); + this._register(Event.forward(this.coreService.onData, this._onData)); + this._register(Event.forward(this.coreService.onBinary, this._onBinary)); + this._register(this.coreService.onRequestScrollToBottom(() => this.scrollToBottom(true))); + this._register(this.coreService.onUserInput(() => this._writeBuffer.handleUserInput())); + this._register(this.optionsService.onMultipleOptionChange(['windowsMode', 'windowsPty'], () => this._handleWindowsPtyOptionChange())); + this._register(this._bufferService.onScroll(() => { + this._onScroll.fire({ position: this._bufferService.buffer.ydisp }); + this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop, this._bufferService.buffer.scrollBottom); + })); + // Setup WriteBuffer + this._writeBuffer = this._register(new WriteBuffer((data, promiseResult) => this._inputHandler.parse(data, promiseResult))); + this._register(Event.forward(this._writeBuffer.onWriteParsed, this._onWriteParsed)); + } + + public write(data: string | Uint8Array, callback?: () => void): void { + this._writeBuffer.write(data, callback); + } + + /** + * Write data to terminal synchonously. + * + * This method is unreliable with async parser handlers, thus should not + * be used anymore. If you need blocking semantics on data input consider + * `write` with a callback instead. + * + * @deprecated Unreliable, will be removed soon. + */ + public writeSync(data: string | Uint8Array, maxSubsequentCalls?: number): void { + if (this._logService.logLevel <= LogLevelEnum.WARN && !hasWriteSyncWarnHappened) { + this._logService.warn('writeSync is unreliable and will be removed soon.'); + hasWriteSyncWarnHappened = true; + } + this._writeBuffer.writeSync(data, maxSubsequentCalls); + } + + public input(data: string, wasUserInput: boolean = true): void { + this.coreService.triggerDataEvent(data, wasUserInput); + } + + public resize(x: number, y: number): void { + if (isNaN(x) || isNaN(y)) { + return; + } + + x = Math.max(x, MINIMUM_COLS); + y = Math.max(y, MINIMUM_ROWS); + + this._bufferService.resize(x, y); + } + + /** + * Scroll the terminal down 1 row, creating a blank line. + * @param eraseAttr The attribute data to use the for blank line. + * @param isWrapped Whether the new line is wrapped from the previous line. + */ + public scroll(eraseAttr: IAttributeData, isWrapped: boolean = false): void { + this._bufferService.scroll(eraseAttr, isWrapped); + } + + /** + * Scroll the display of the terminal + * @param disp The number of lines to scroll down (negative scroll up). + * @param suppressScrollEvent Don't emit the scroll event as scrollLines. This is used to avoid + * unwanted events being handled by the viewport when the event was triggered from the viewport + * originally. + */ + public scrollLines(disp: number, suppressScrollEvent?: boolean): void { + this._bufferService.scrollLines(disp, suppressScrollEvent); + } + + public scrollPages(pageCount: number): void { + this.scrollLines(pageCount * (this.rows - 1)); + } + + public scrollToTop(): void { + this.scrollLines(-this._bufferService.buffer.ydisp); + } + + public scrollToBottom(disableSmoothScroll?: boolean): void { + this.scrollLines(this._bufferService.buffer.ybase - this._bufferService.buffer.ydisp); + } + + public scrollToLine(line: number): void { + const scrollAmount = line - this._bufferService.buffer.ydisp; + if (scrollAmount !== 0) { + this.scrollLines(scrollAmount); + } + } + + /** Add handler for ESC escape sequence. See xterm.d.ts for details. */ + public registerEscHandler(id: IFunctionIdentifier, callback: () => boolean | Promise): IDisposable { + return this._inputHandler.registerEscHandler(id, callback); + } + + /** Add handler for DCS escape sequence. See xterm.d.ts for details. */ + public registerDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: IParams) => boolean | Promise): IDisposable { + return this._inputHandler.registerDcsHandler(id, callback); + } + + /** Add handler for CSI escape sequence. See xterm.d.ts for details. */ + public registerCsiHandler(id: IFunctionIdentifier, callback: (params: IParams) => boolean | Promise): IDisposable { + return this._inputHandler.registerCsiHandler(id, callback); + } + + /** Add handler for OSC escape sequence. See xterm.d.ts for details. */ + public registerOscHandler(ident: number, callback: (data: string) => boolean | Promise): IDisposable { + return this._inputHandler.registerOscHandler(ident, callback); + } + + protected _setup(): void { + this._handleWindowsPtyOptionChange(); + } + + public reset(): void { + this._inputHandler.reset(); + this._bufferService.reset(); + this._charsetService.reset(); + this.coreService.reset(); + this.coreMouseService.reset(); + } + + + private _handleWindowsPtyOptionChange(): void { + let value = false; + const windowsPty = this.optionsService.rawOptions.windowsPty; + if (windowsPty && windowsPty.buildNumber !== undefined && windowsPty.buildNumber !== undefined) { + value = !!(windowsPty.backend === 'conpty' && windowsPty.buildNumber < 21376); + } else if (this.optionsService.rawOptions.windowsMode) { + value = true; + } + if (value) { + this._enableWindowsWrappingHeuristics(); + } else { + this._windowsWrappingHeuristics.clear(); + } + } + + protected _enableWindowsWrappingHeuristics(): void { + if (!this._windowsWrappingHeuristics.value) { + const disposables: IDisposable[] = []; + disposables.push(this.onLineFeed(updateWindowsModeWrappedState.bind(null, this._bufferService))); + disposables.push(this.registerCsiHandler({ final: 'H' }, () => { + updateWindowsModeWrappedState(this._bufferService); + return false; + })); + this._windowsWrappingHeuristics.value = toDisposable(() => { + for (const d of disposables) { + d.dispose(); + } + }); + } + } +} diff --git a/node_modules/@xterm/xterm/src/common/InputHandler.ts b/node_modules/@xterm/xterm/src/common/InputHandler.ts new file mode 100644 index 0000000..ba53941 --- /dev/null +++ b/node_modules/@xterm/xterm/src/common/InputHandler.ts @@ -0,0 +1,3495 @@ +/** + * Copyright (c) 2014 The xterm.js authors. All rights reserved. + * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License) + * @license MIT + */ + +import { IInputHandler, IAttributeData, IDisposable, IWindowOptions, IColorEvent, IParseStack, ColorIndex, ColorRequestType, SpecialColorIndex } from 'common/Types'; +import { C0, C1 } from 'common/data/EscapeSequences'; +import { CHARSETS, DEFAULT_CHARSET } from 'common/data/Charsets'; +import { EscapeSequenceParser } from 'common/parser/EscapeSequenceParser'; +import { Disposable } from 'vs/base/common/lifecycle'; +import { StringToUtf32, stringFromCodePoint, Utf8ToUtf32 } from 'common/input/TextDecoder'; +import { BufferLine, DEFAULT_ATTR_DATA } from 'common/buffer/BufferLine'; +import { IParsingState, IEscapeSequenceParser, IParams, IFunctionIdentifier } from 'common/parser/Types'; +import { NULL_CELL_CODE, NULL_CELL_WIDTH, Attributes, FgFlags, BgFlags, Content, UnderlineStyle } from 'common/buffer/Constants'; +import { CellData } from 'common/buffer/CellData'; +import { AttributeData } from 'common/buffer/AttributeData'; +import { ICoreService, IBufferService, IOptionsService, ILogService, ICoreMouseService, ICharsetService, IUnicodeService, LogLevelEnum, IOscLinkService } from 'common/services/Services'; +import { UnicodeService } from 'common/services/UnicodeService'; +import { OscHandler } from 'common/parser/OscParser'; +import { DcsHandler } from 'common/parser/DcsParser'; +import { IBuffer } from 'common/buffer/Types'; +import { parseColor } from 'common/input/XParseColor'; +import { Emitter } from 'vs/base/common/event'; + +/** + * Map collect to glevel. Used in `selectCharset`. + */ +const GLEVEL: { [key: string]: number } = { '(': 0, ')': 1, '*': 2, '+': 3, '-': 1, '.': 2 }; + +/** + * VT commands done by the parser - FIXME: move this to the parser? + */ +// @vt: #Y ESC CSI "Control Sequence Introducer" "ESC [" "Start of a CSI sequence." +// @vt: #Y ESC OSC "Operating System Command" "ESC ]" "Start of an OSC sequence." +// @vt: #Y ESC DCS "Device Control String" "ESC P" "Start of a DCS sequence." +// @vt: #Y ESC ST "String Terminator" "ESC \" "Terminator used for string type sequences." +// @vt: #Y ESC PM "Privacy Message" "ESC ^" "Start of a privacy message." +// @vt: #Y ESC APC "Application Program Command" "ESC _" "Start of an APC sequence." +// @vt: #Y C1 CSI "Control Sequence Introducer" "\x9B" "Start of a CSI sequence." +// @vt: #Y C1 OSC "Operating System Command" "\x9D" "Start of an OSC sequence." +// @vt: #Y C1 DCS "Device Control String" "\x90" "Start of a DCS sequence." +// @vt: #Y C1 ST "String Terminator" "\x9C" "Terminator used for string type sequences." +// @vt: #Y C1 PM "Privacy Message" "\x9E" "Start of a privacy message." +// @vt: #Y C1 APC "Application Program Command" "\x9F" "Start of an APC sequence." +// @vt: #Y C0 NUL "Null" "\0, \x00" "NUL is ignored." +// @vt: #Y C0 ESC "Escape" "\e, \x1B" "Start of a sequence. Cancels any other sequence." + +/** + * Document xterm VT features here that are currently unsupported + */ +// @vt: #E[Supported via @xterm/addon-image.] DCS SIXEL "SIXEL Graphics" "DCS Ps ; Ps ; Ps ; q Pt ST" "Draw SIXEL image." +// @vt: #N DCS DECUDK "User Defined Keys" "DCS Ps ; Ps \| Pt ST" "Definitions for user-defined keys." +// @vt: #N DCS XTGETTCAP "Request Terminfo String" "DCS + q Pt ST" "Request Terminfo String." +// @vt: #N DCS XTSETTCAP "Set Terminfo Data" "DCS + p Pt ST" "Set Terminfo Data." +// @vt: #N OSC 1 "Set Icon Name" "OSC 1 ; Pt BEL" "Set icon name." + +/** + * Max length of the UTF32 input buffer. Real memory consumption is 4 times higher. + */ +const MAX_PARSEBUFFER_LENGTH = 131072; + +/** + * Limit length of title and icon name stacks. + */ +const STACK_LIMIT = 10; + +// map params to window option +function paramToWindowOption(n: number, opts: IWindowOptions): boolean { + if (n > 24) { + return opts.setWinLines || false; + } + switch (n) { + case 1: return !!opts.restoreWin; + case 2: return !!opts.minimizeWin; + case 3: return !!opts.setWinPosition; + case 4: return !!opts.setWinSizePixels; + case 5: return !!opts.raiseWin; + case 6: return !!opts.lowerWin; + case 7: return !!opts.refreshWin; + case 8: return !!opts.setWinSizeChars; + case 9: return !!opts.maximizeWin; + case 10: return !!opts.fullscreenWin; + case 11: return !!opts.getWinState; + case 13: return !!opts.getWinPosition; + case 14: return !!opts.getWinSizePixels; + case 15: return !!opts.getScreenSizePixels; + case 16: return !!opts.getCellSizePixels; + case 18: return !!opts.getWinSizeChars; + case 19: return !!opts.getScreenSizeChars; + case 20: return !!opts.getIconTitle; + case 21: return !!opts.getWinTitle; + case 22: return !!opts.pushTitle; + case 23: return !!opts.popTitle; + case 24: return !!opts.setWinLines; + } + return false; +} + +export enum WindowsOptionsReportType { + GET_WIN_SIZE_PIXELS = 0, + GET_CELL_SIZE_PIXELS = 1 +} + +// create a warning log if an async handler takes longer than the limit (in ms) +const SLOW_ASYNC_LIMIT = 5000; + +// Work variables to avoid garbage collection +let $temp = 0; + +/** + * The terminal's standard implementation of IInputHandler, this handles all + * input from the Parser. + * + * Refer to http://invisible-island.net/xterm/ctlseqs/ctlseqs.html to understand + * each function's header comment. + */ +export class InputHandler extends Disposable implements IInputHandler { + private _parseBuffer: Uint32Array = new Uint32Array(4096); + private _stringDecoder: StringToUtf32 = new StringToUtf32(); + private _utf8Decoder: Utf8ToUtf32 = new Utf8ToUtf32(); + private _windowTitle = ''; + private _iconName = ''; + private _dirtyRowTracker: IDirtyRowTracker; + protected _windowTitleStack: string[] = []; + protected _iconNameStack: string[] = []; + + private _curAttrData: IAttributeData = DEFAULT_ATTR_DATA.clone(); + public getAttrData(): IAttributeData { return this._curAttrData; } + private _eraseAttrDataInternal: IAttributeData = DEFAULT_ATTR_DATA.clone(); + + private _activeBuffer: IBuffer; + + private readonly _onRequestBell = this._register(new Emitter()); + public readonly onRequestBell = this._onRequestBell.event; + private readonly _onRequestRefreshRows = this._register(new Emitter<{ start: number, end: number } | undefined>()); + public readonly onRequestRefreshRows = this._onRequestRefreshRows.event; + private readonly _onRequestReset = this._register(new Emitter()); + public readonly onRequestReset = this._onRequestReset.event; + private readonly _onRequestSendFocus = this._register(new Emitter()); + public readonly onRequestSendFocus = this._onRequestSendFocus.event; + private readonly _onRequestSyncScrollBar = this._register(new Emitter()); + public readonly onRequestSyncScrollBar = this._onRequestSyncScrollBar.event; + private readonly _onRequestWindowsOptionsReport = this._register(new Emitter()); + public readonly onRequestWindowsOptionsReport = this._onRequestWindowsOptionsReport.event; + + private readonly _onA11yChar = this._register(new Emitter()); + public readonly onA11yChar = this._onA11yChar.event; + private readonly _onA11yTab = this._register(new Emitter()); + public readonly onA11yTab = this._onA11yTab.event; + private readonly _onCursorMove = this._register(new Emitter()); + public readonly onCursorMove = this._onCursorMove.event; + private readonly _onLineFeed = this._register(new Emitter()); + public readonly onLineFeed = this._onLineFeed.event; + private readonly _onScroll = this._register(new Emitter()); + public readonly onScroll = this._onScroll.event; + private readonly _onTitleChange = this._register(new Emitter()); + public readonly onTitleChange = this._onTitleChange.event; + private readonly _onColor = this._register(new Emitter()); + public readonly onColor = this._onColor.event; + + private _parseStack: IParseStack = { + paused: false, + cursorStartX: 0, + cursorStartY: 0, + decodedLength: 0, + position: 0 + }; + + constructor( + private readonly _bufferService: IBufferService, + private readonly _charsetService: ICharsetService, + private readonly _coreService: ICoreService, + private readonly _logService: ILogService, + private readonly _optionsService: IOptionsService, + private readonly _oscLinkService: IOscLinkService, + private readonly _coreMouseService: ICoreMouseService, + private readonly _unicodeService: IUnicodeService, + private readonly _parser: IEscapeSequenceParser = new EscapeSequenceParser() + ) { + super(); + this._register(this._parser); + this._dirtyRowTracker = new DirtyRowTracker(this._bufferService); + + // Track properties used in performance critical code manually to avoid using slow getters + this._activeBuffer = this._bufferService.buffer; + this._register(this._bufferService.buffers.onBufferActivate(e => this._activeBuffer = e.activeBuffer)); + + /** + * custom fallback handlers + */ + this._parser.setCsiHandlerFallback((ident, params) => { + this._logService.debug('Unknown CSI code: ', { identifier: this._parser.identToString(ident), params: params.toArray() }); + }); + this._parser.setEscHandlerFallback(ident => { + this._logService.debug('Unknown ESC code: ', { identifier: this._parser.identToString(ident) }); + }); + this._parser.setExecuteHandlerFallback(code => { + this._logService.debug('Unknown EXECUTE code: ', { code }); + }); + this._parser.setOscHandlerFallback((identifier, action, data) => { + this._logService.debug('Unknown OSC code: ', { identifier, action, data }); + }); + this._parser.setDcsHandlerFallback((ident, action, payload) => { + if (action === 'HOOK') { + payload = payload.toArray(); + } + this._logService.debug('Unknown DCS code: ', { identifier: this._parser.identToString(ident), action, payload }); + }); + + /** + * print handler + */ + this._parser.setPrintHandler((data, start, end) => this.print(data, start, end)); + + /** + * CSI handler + */ + this._parser.registerCsiHandler({ final: '@' }, params => this.insertChars(params)); + this._parser.registerCsiHandler({ intermediates: ' ', final: '@' }, params => this.scrollLeft(params)); + this._parser.registerCsiHandler({ final: 'A' }, params => this.cursorUp(params)); + this._parser.registerCsiHandler({ intermediates: ' ', final: 'A' }, params => this.scrollRight(params)); + this._parser.registerCsiHandler({ final: 'B' }, params => this.cursorDown(params)); + this._parser.registerCsiHandler({ final: 'C' }, params => this.cursorForward(params)); + this._parser.registerCsiHandler({ final: 'D' }, params => this.cursorBackward(params)); + this._parser.registerCsiHandler({ final: 'E' }, params => this.cursorNextLine(params)); + this._parser.registerCsiHandler({ final: 'F' }, params => this.cursorPrecedingLine(params)); + this._parser.registerCsiHandler({ final: 'G' }, params => this.cursorCharAbsolute(params)); + this._parser.registerCsiHandler({ final: 'H' }, params => this.cursorPosition(params)); + this._parser.registerCsiHandler({ final: 'I' }, params => this.cursorForwardTab(params)); + this._parser.registerCsiHandler({ final: 'J' }, params => this.eraseInDisplay(params, false)); + this._parser.registerCsiHandler({ prefix: '?', final: 'J' }, params => this.eraseInDisplay(params, true)); + this._parser.registerCsiHandler({ final: 'K' }, params => this.eraseInLine(params, false)); + this._parser.registerCsiHandler({ prefix: '?', final: 'K' }, params => this.eraseInLine(params, true)); + this._parser.registerCsiHandler({ final: 'L' }, params => this.insertLines(params)); + this._parser.registerCsiHandler({ final: 'M' }, params => this.deleteLines(params)); + this._parser.registerCsiHandler({ final: 'P' }, params => this.deleteChars(params)); + this._parser.registerCsiHandler({ final: 'S' }, params => this.scrollUp(params)); + this._parser.registerCsiHandler({ final: 'T' }, params => this.scrollDown(params)); + this._parser.registerCsiHandler({ final: 'X' }, params => this.eraseChars(params)); + this._parser.registerCsiHandler({ final: 'Z' }, params => this.cursorBackwardTab(params)); + this._parser.registerCsiHandler({ final: '`' }, params => this.charPosAbsolute(params)); + this._parser.registerCsiHandler({ final: 'a' }, params => this.hPositionRelative(params)); + this._parser.registerCsiHandler({ final: 'b' }, params => this.repeatPrecedingCharacter(params)); + this._parser.registerCsiHandler({ final: 'c' }, params => this.sendDeviceAttributesPrimary(params)); + this._parser.registerCsiHandler({ prefix: '>', final: 'c' }, params => this.sendDeviceAttributesSecondary(params)); + this._parser.registerCsiHandler({ final: 'd' }, params => this.linePosAbsolute(params)); + this._parser.registerCsiHandler({ final: 'e' }, params => this.vPositionRelative(params)); + this._parser.registerCsiHandler({ final: 'f' }, params => this.hVPosition(params)); + this._parser.registerCsiHandler({ final: 'g' }, params => this.tabClear(params)); + this._parser.registerCsiHandler({ final: 'h' }, params => this.setMode(params)); + this._parser.registerCsiHandler({ prefix: '?', final: 'h' }, params => this.setModePrivate(params)); + this._parser.registerCsiHandler({ final: 'l' }, params => this.resetMode(params)); + this._parser.registerCsiHandler({ prefix: '?', final: 'l' }, params => this.resetModePrivate(params)); + this._parser.registerCsiHandler({ final: 'm' }, params => this.charAttributes(params)); + this._parser.registerCsiHandler({ final: 'n' }, params => this.deviceStatus(params)); + this._parser.registerCsiHandler({ prefix: '?', final: 'n' }, params => this.deviceStatusPrivate(params)); + this._parser.registerCsiHandler({ intermediates: '!', final: 'p' }, params => this.softReset(params)); + this._parser.registerCsiHandler({ intermediates: ' ', final: 'q' }, params => this.setCursorStyle(params)); + this._parser.registerCsiHandler({ final: 'r' }, params => this.setScrollRegion(params)); + this._parser.registerCsiHandler({ final: 's' }, params => this.saveCursor(params)); + this._parser.registerCsiHandler({ final: 't' }, params => this.windowOptions(params)); + this._parser.registerCsiHandler({ final: 'u' }, params => this.restoreCursor(params)); + this._parser.registerCsiHandler({ intermediates: '\'', final: '}' }, params => this.insertColumns(params)); + this._parser.registerCsiHandler({ intermediates: '\'', final: '~' }, params => this.deleteColumns(params)); + this._parser.registerCsiHandler({ intermediates: '"', final: 'q' }, params => this.selectProtected(params)); + this._parser.registerCsiHandler({ intermediates: '$', final: 'p' }, params => this.requestMode(params, true)); + this._parser.registerCsiHandler({ prefix: '?', intermediates: '$', final: 'p' }, params => this.requestMode(params, false)); + + /** + * execute handler + */ + this._parser.setExecuteHandler(C0.BEL, () => this.bell()); + this._parser.setExecuteHandler(C0.LF, () => this.lineFeed()); + this._parser.setExecuteHandler(C0.VT, () => this.lineFeed()); + this._parser.setExecuteHandler(C0.FF, () => this.lineFeed()); + this._parser.setExecuteHandler(C0.CR, () => this.carriageReturn()); + this._parser.setExecuteHandler(C0.BS, () => this.backspace()); + this._parser.setExecuteHandler(C0.HT, () => this.tab()); + this._parser.setExecuteHandler(C0.SO, () => this.shiftOut()); + this._parser.setExecuteHandler(C0.SI, () => this.shiftIn()); + // FIXME: What do to with missing? Old code just added those to print. + + this._parser.setExecuteHandler(C1.IND, () => this.index()); + this._parser.setExecuteHandler(C1.NEL, () => this.nextLine()); + this._parser.setExecuteHandler(C1.HTS, () => this.tabSet()); + + /** + * OSC handler + */ + // 0 - icon name + title + this._parser.registerOscHandler(0, new OscHandler(data => { this.setTitle(data); this.setIconName(data); return true; })); + // 1 - icon name + this._parser.registerOscHandler(1, new OscHandler(data => this.setIconName(data))); + // 2 - title + this._parser.registerOscHandler(2, new OscHandler(data => this.setTitle(data))); + // 3 - set property X in the form "prop=value" + // 4 - Change Color Number + this._parser.registerOscHandler(4, new OscHandler(data => this.setOrReportIndexedColor(data))); + // 5 - Change Special Color Number + // 6 - Enable/disable Special Color Number c + // 7 - current directory? (not in xterm spec, see https://gitlab.com/gnachman/iterm2/issues/3939) + // 8 - create hyperlink (not in xterm spec, see https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda) + this._parser.registerOscHandler(8, new OscHandler(data => this.setHyperlink(data))); + // 10 - Change VT100 text foreground color to Pt. + this._parser.registerOscHandler(10, new OscHandler(data => this.setOrReportFgColor(data))); + // 11 - Change VT100 text background color to Pt. + this._parser.registerOscHandler(11, new OscHandler(data => this.setOrReportBgColor(data))); + // 12 - Change text cursor color to Pt. + this._parser.registerOscHandler(12, new OscHandler(data => this.setOrReportCursorColor(data))); + // 13 - Change mouse foreground color to Pt. + // 14 - Change mouse background color to Pt. + // 15 - Change Tektronix foreground color to Pt. + // 16 - Change Tektronix background color to Pt. + // 17 - Change highlight background color to Pt. + // 18 - Change Tektronix cursor color to Pt. + // 19 - Change highlight foreground color to Pt. + // 46 - Change Log File to Pt. + // 50 - Set Font to Pt. + // 51 - reserved for Emacs shell. + // 52 - Manipulate Selection Data. + // 104 ; c - Reset Color Number c. + this._parser.registerOscHandler(104, new OscHandler(data => this.restoreIndexedColor(data))); + // 105 ; c - Reset Special Color Number c. + // 106 ; c; f - Enable/disable Special Color Number c. + // 110 - Reset VT100 text foreground color. + this._parser.registerOscHandler(110, new OscHandler(data => this.restoreFgColor(data))); + // 111 - Reset VT100 text background color. + this._parser.registerOscHandler(111, new OscHandler(data => this.restoreBgColor(data))); + // 112 - Reset text cursor color. + this._parser.registerOscHandler(112, new OscHandler(data => this.restoreCursorColor(data))); + // 113 - Reset mouse foreground color. + // 114 - Reset mouse background color. + // 115 - Reset Tektronix foreground color. + // 116 - Reset Tektronix background color. + // 117 - Reset highlight color. + // 118 - Reset Tektronix cursor color. + // 119 - Reset highlight foreground color. + + /** + * ESC handlers + */ + this._parser.registerEscHandler({ final: '7' }, () => this.saveCursor()); + this._parser.registerEscHandler({ final: '8' }, () => this.restoreCursor()); + this._parser.registerEscHandler({ final: 'D' }, () => this.index()); + this._parser.registerEscHandler({ final: 'E' }, () => this.nextLine()); + this._parser.registerEscHandler({ final: 'H' }, () => this.tabSet()); + this._parser.registerEscHandler({ final: 'M' }, () => this.reverseIndex()); + this._parser.registerEscHandler({ final: '=' }, () => this.keypadApplicationMode()); + this._parser.registerEscHandler({ final: '>' }, () => this.keypadNumericMode()); + this._parser.registerEscHandler({ final: 'c' }, () => this.fullReset()); + this._parser.registerEscHandler({ final: 'n' }, () => this.setgLevel(2)); + this._parser.registerEscHandler({ final: 'o' }, () => this.setgLevel(3)); + this._parser.registerEscHandler({ final: '|' }, () => this.setgLevel(3)); + this._parser.registerEscHandler({ final: '}' }, () => this.setgLevel(2)); + this._parser.registerEscHandler({ final: '~' }, () => this.setgLevel(1)); + this._parser.registerEscHandler({ intermediates: '%', final: '@' }, () => this.selectDefaultCharset()); + this._parser.registerEscHandler({ intermediates: '%', final: 'G' }, () => this.selectDefaultCharset()); + for (const flag in CHARSETS) { + this._parser.registerEscHandler({ intermediates: '(', final: flag }, () => this.selectCharset('(' + flag)); + this._parser.registerEscHandler({ intermediates: ')', final: flag }, () => this.selectCharset(')' + flag)); + this._parser.registerEscHandler({ intermediates: '*', final: flag }, () => this.selectCharset('*' + flag)); + this._parser.registerEscHandler({ intermediates: '+', final: flag }, () => this.selectCharset('+' + flag)); + this._parser.registerEscHandler({ intermediates: '-', final: flag }, () => this.selectCharset('-' + flag)); + this._parser.registerEscHandler({ intermediates: '.', final: flag }, () => this.selectCharset('.' + flag)); + this._parser.registerEscHandler({ intermediates: '/', final: flag }, () => this.selectCharset('/' + flag)); // TODO: supported? + } + this._parser.registerEscHandler({ intermediates: '#', final: '8' }, () => this.screenAlignmentPattern()); + + /** + * error handler + */ + this._parser.setErrorHandler((state: IParsingState) => { + this._logService.error('Parsing error: ', state); + return state; + }); + + /** + * DCS handler + */ + this._parser.registerDcsHandler({ intermediates: '$', final: 'q' }, new DcsHandler((data, params) => this.requestStatusString(data, params))); + } + + /** + * Async parse support. + */ + private _preserveStack(cursorStartX: number, cursorStartY: number, decodedLength: number, position: number): void { + this._parseStack.paused = true; + this._parseStack.cursorStartX = cursorStartX; + this._parseStack.cursorStartY = cursorStartY; + this._parseStack.decodedLength = decodedLength; + this._parseStack.position = position; + } + + private _logSlowResolvingAsync(p: Promise): void { + // log a limited warning about an async handler taking too long + if (this._logService.logLevel <= LogLevelEnum.WARN) { + Promise.race([p, new Promise((res, rej) => setTimeout(() => rej('#SLOW_TIMEOUT'), SLOW_ASYNC_LIMIT))]) + .catch(err => { + if (err !== '#SLOW_TIMEOUT') { + throw err; + } + console.warn(`async parser handler taking longer than ${SLOW_ASYNC_LIMIT} ms`); + }); + } + } + + private _getCurrentLinkId(): number { + return this._curAttrData.extended.urlId; + } + + /** + * Parse call with async handler support. + * + * Whether the stack state got preserved for the next call, is indicated by the return value: + * - undefined (void): + * all handlers were sync, no stack save, continue normally with next chunk + * - Promise\: + * execution stopped at async handler, stack saved, continue with same chunk and the promise + * resolve value as `promiseResult` until the method returns `undefined` + * + * Note: This method should only be called by `Terminal.write` to ensure correct execution order + * and proper continuation of async parser handlers. + */ + public parse(data: string | Uint8Array, promiseResult?: boolean): void | Promise { + let result: void | Promise; + let cursorStartX = this._activeBuffer.x; + let cursorStartY = this._activeBuffer.y; + let start = 0; + const wasPaused = this._parseStack.paused; + + if (wasPaused) { + // assumption: _parseBuffer never mutates between async calls + if (result = this._parser.parse(this._parseBuffer, this._parseStack.decodedLength, promiseResult)) { + this._logSlowResolvingAsync(result); + return result; + } + cursorStartX = this._parseStack.cursorStartX; + cursorStartY = this._parseStack.cursorStartY; + this._parseStack.paused = false; + if (data.length > MAX_PARSEBUFFER_LENGTH) { + start = this._parseStack.position + MAX_PARSEBUFFER_LENGTH; + } + } + + // Log debug data, the log level gate is to prevent extra work in this hot path + if (this._logService.logLevel <= LogLevelEnum.DEBUG) { + this._logService.debug(`parsing data ${typeof data === 'string' ? ` "${data}"` : ` "${Array.prototype.map.call(data, e => String.fromCharCode(e)).join('')}"`}`); + } + if (this._logService.logLevel === LogLevelEnum.TRACE) { + this._logService.trace(`parsing data (codes)`, typeof data === 'string' + ? data.split('').map(e => e.charCodeAt(0)) + : data + ); + } + + // resize input buffer if needed + if (this._parseBuffer.length < data.length) { + if (this._parseBuffer.length < MAX_PARSEBUFFER_LENGTH) { + this._parseBuffer = new Uint32Array(Math.min(data.length, MAX_PARSEBUFFER_LENGTH)); + } + } + + // Clear the dirty row service so we know which lines changed as a result of parsing + // Important: do not clear between async calls, otherwise we lost pending update information. + if (!wasPaused) { + this._dirtyRowTracker.clearRange(); + } + + // process big data in smaller chunks + if (data.length > MAX_PARSEBUFFER_LENGTH) { + for (let i = start; i < data.length; i += MAX_PARSEBUFFER_LENGTH) { + const end = i + MAX_PARSEBUFFER_LENGTH < data.length ? i + MAX_PARSEBUFFER_LENGTH : data.length; + const len = (typeof data === 'string') + ? this._stringDecoder.decode(data.substring(i, end), this._parseBuffer) + : this._utf8Decoder.decode(data.subarray(i, end), this._parseBuffer); + if (result = this._parser.parse(this._parseBuffer, len)) { + this._preserveStack(cursorStartX, cursorStartY, len, i); + this._logSlowResolvingAsync(result); + return result; + } + } + } else { + if (!wasPaused) { + const len = (typeof data === 'string') + ? this._stringDecoder.decode(data, this._parseBuffer) + : this._utf8Decoder.decode(data, this._parseBuffer); + if (result = this._parser.parse(this._parseBuffer, len)) { + this._preserveStack(cursorStartX, cursorStartY, len, 0); + this._logSlowResolvingAsync(result); + return result; + } + } + } + + if (this._activeBuffer.x !== cursorStartX || this._activeBuffer.y !== cursorStartY) { + this._onCursorMove.fire(); + } + + // Refresh any dirty rows accumulated as part of parsing, fire only for rows within the + // _viewport_ which is relative to ydisp, not relative to ybase. + const viewportEnd = this._dirtyRowTracker.end + (this._bufferService.buffer.ybase - this._bufferService.buffer.ydisp); + const viewportStart = this._dirtyRowTracker.start + (this._bufferService.buffer.ybase - this._bufferService.buffer.ydisp); + if (viewportStart < this._bufferService.rows) { + this._onRequestRefreshRows.fire({ + start: Math.min(viewportStart, this._bufferService.rows - 1), + end: Math.min(viewportEnd, this._bufferService.rows - 1) + }); + } + } + + public print(data: Uint32Array, start: number, end: number): void { + let code: number; + let chWidth: number; + const charset = this._charsetService.charset; + const screenReaderMode = this._optionsService.rawOptions.screenReaderMode; + const cols = this._bufferService.cols; + const wraparoundMode = this._coreService.decPrivateModes.wraparound; + const insertMode = this._coreService.modes.insertMode; + const curAttr = this._curAttrData; + let bufferRow = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y)!; + + this._dirtyRowTracker.markDirty(this._activeBuffer.y); + + // handle wide chars: reset start_cell-1 if we would overwrite the second cell of a wide char + if (this._activeBuffer.x && end - start > 0 && bufferRow.getWidth(this._activeBuffer.x - 1) === 2) { + bufferRow.setCellFromCodepoint(this._activeBuffer.x - 1, 0, 1, curAttr); + } + + let precedingJoinState = this._parser.precedingJoinState; + for (let pos = start; pos < end; ++pos) { + code = data[pos]; + + // get charset replacement character + // charset is only defined for ASCII, therefore we only + // search for an replacement char if code < 127 + if (code < 127 && charset) { + const ch = charset[String.fromCharCode(code)]; + if (ch) { + code = ch.charCodeAt(0); + } + } + + const currentInfo = this._unicodeService.charProperties(code, precedingJoinState); + chWidth = UnicodeService.extractWidth(currentInfo); + const shouldJoin = UnicodeService.extractShouldJoin(currentInfo); + const oldWidth = shouldJoin ? UnicodeService.extractWidth(precedingJoinState) : 0; + precedingJoinState = currentInfo; + + if (screenReaderMode) { + this._onA11yChar.fire(stringFromCodePoint(code)); + } + if (this._getCurrentLinkId()) { + this._oscLinkService.addLineToLink(this._getCurrentLinkId(), this._activeBuffer.ybase + this._activeBuffer.y); + } + + // goto next line if ch would overflow + // NOTE: To avoid costly width checks here, + // the terminal does not allow a cols < 2. + if (this._activeBuffer.x + chWidth - oldWidth > cols) { + // autowrap - DECAWM + // automatically wraps to the beginning of the next line + if (wraparoundMode) { + const oldRow = bufferRow; + let oldCol = this._activeBuffer.x - oldWidth; + this._activeBuffer.x = oldWidth; + this._activeBuffer.y++; + if (this._activeBuffer.y === this._activeBuffer.scrollBottom + 1) { + this._activeBuffer.y--; + this._bufferService.scroll(this._eraseAttrData(), true); + } else { + if (this._activeBuffer.y >= this._bufferService.rows) { + this._activeBuffer.y = this._bufferService.rows - 1; + } + // The line already exists (eg. the initial viewport), mark it as a + // wrapped line + this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y)!.isWrapped = true; + } + // row changed, get it again + bufferRow = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y)!; + if (oldWidth > 0 && bufferRow instanceof BufferLine) { + // Combining character widens 1 column to 2. + // Move old character to next line. + bufferRow.copyCellsFrom(oldRow as BufferLine, + oldCol, 0, oldWidth, false); + } + // clear left over cells to the right + while (oldCol < cols) { + oldRow.setCellFromCodepoint(oldCol++, 0, 1, curAttr); + } + } else { + this._activeBuffer.x = cols - 1; + if (chWidth === 2) { + // FIXME: check for xterm behavior + // What to do here? We got a wide char that does not fit into last cell + continue; + } + } + } + + // insert combining char at last cursor position + // this._activeBuffer.x should never be 0 for a combining char + // since they always follow a cell consuming char + // therefore we can test for this._activeBuffer.x to avoid overflow left + if (shouldJoin && this._activeBuffer.x) { + const offset = bufferRow.getWidth(this._activeBuffer.x - 1) ? 1 : 2; + // if empty cell after fullwidth, need to go 2 cells back + // it is save to step 2 cells back here + // since an empty cell is only set by fullwidth chars + bufferRow.addCodepointToCell(this._activeBuffer.x - offset, + code, chWidth); + for (let delta = chWidth - oldWidth; --delta >= 0;) { + bufferRow.setCellFromCodepoint(this._activeBuffer.x++, 0, 0, curAttr); + } + continue; + } + + // insert mode: move characters to right + if (insertMode) { + // right shift cells according to the width + bufferRow.insertCells(this._activeBuffer.x, chWidth - oldWidth, this._activeBuffer.getNullCell(curAttr)); + // test last cell - since the last cell has only room for + // a halfwidth char any fullwidth shifted there is lost + // and will be set to empty cell + if (bufferRow.getWidth(cols - 1) === 2) { + bufferRow.setCellFromCodepoint(cols - 1, NULL_CELL_CODE, NULL_CELL_WIDTH, curAttr); + } + } + + // write current char to buffer and advance cursor + bufferRow.setCellFromCodepoint(this._activeBuffer.x++, code, chWidth, curAttr); + + // fullwidth char - also set next cell to placeholder stub and advance cursor + // for graphemes bigger than fullwidth we can simply loop to zero + // we already made sure above, that this._activeBuffer.x + chWidth will not overflow right + if (chWidth > 0) { + while (--chWidth) { + // other than a regular empty cell a cell following a wide char has no width + bufferRow.setCellFromCodepoint(this._activeBuffer.x++, 0, 0, curAttr); + } + } + } + + this._parser.precedingJoinState = precedingJoinState; + + // handle wide chars: reset cell to the right if it is second cell of a wide char + if (this._activeBuffer.x < cols && end - start > 0 && bufferRow.getWidth(this._activeBuffer.x) === 0 && !bufferRow.hasContent(this._activeBuffer.x)) { + bufferRow.setCellFromCodepoint(this._activeBuffer.x, 0, 1, curAttr); + } + + this._dirtyRowTracker.markDirty(this._activeBuffer.y); + } + + /** + * Forward registerCsiHandler from parser. + */ + public registerCsiHandler(id: IFunctionIdentifier, callback: (params: IParams) => boolean | Promise): IDisposable { + if (id.final === 't' && !id.prefix && !id.intermediates) { + // security: always check whether window option is allowed + return this._parser.registerCsiHandler(id, params => { + if (!paramToWindowOption(params.params[0], this._optionsService.rawOptions.windowOptions)) { + return true; + } + return callback(params); + }); + } + return this._parser.registerCsiHandler(id, callback); + } + + /** + * Forward registerDcsHandler from parser. + */ + public registerDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: IParams) => boolean | Promise): IDisposable { + return this._parser.registerDcsHandler(id, new DcsHandler(callback)); + } + + /** + * Forward registerEscHandler from parser. + */ + public registerEscHandler(id: IFunctionIdentifier, callback: () => boolean | Promise): IDisposable { + return this._parser.registerEscHandler(id, callback); + } + + /** + * Forward registerOscHandler from parser. + */ + public registerOscHandler(ident: number, callback: (data: string) => boolean | Promise): IDisposable { + return this._parser.registerOscHandler(ident, new OscHandler(callback)); + } + + /** + * BEL + * Bell (Ctrl-G). + * + * @vt: #Y C0 BEL "Bell" "\a, \x07" "Ring the bell." + * The behavior of the bell is further customizable with `ITerminalOptions.bellStyle` + * and `ITerminalOptions.bellSound`. + */ + public bell(): boolean { + this._onRequestBell.fire(); + return true; + } + + /** + * LF + * Line Feed or New Line (NL). (LF is Ctrl-J). + * + * @vt: #Y C0 LF "Line Feed" "\n, \x0A" "Move the cursor one row down, scrolling if needed." + * Scrolling is restricted to scroll margins and will only happen on the bottom line. + * + * @vt: #Y C0 VT "Vertical Tabulation" "\v, \x0B" "Treated as LF." + * @vt: #Y C0 FF "Form Feed" "\f, \x0C" "Treated as LF." + */ + public lineFeed(): boolean { + this._dirtyRowTracker.markDirty(this._activeBuffer.y); + if (this._optionsService.rawOptions.convertEol) { + this._activeBuffer.x = 0; + } + this._activeBuffer.y++; + if (this._activeBuffer.y === this._activeBuffer.scrollBottom + 1) { + this._activeBuffer.y--; + this._bufferService.scroll(this._eraseAttrData()); + } else if (this._activeBuffer.y >= this._bufferService.rows) { + this._activeBuffer.y = this._bufferService.rows - 1; + } else { + // There was an explicit line feed (not just a carriage return), so clear the wrapped state of + // the line. This is particularly important on conpty/Windows where revisiting lines to + // reprint is common, especially on resize. Note that the windowsMode wrapped line heuristics + // can mess with this so windowsMode should be disabled, which is recommended on Windows build + // 21376 and above. + this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y)!.isWrapped = false; + } + // If the end of the line is hit, prevent this action from wrapping around to the next line. + if (this._activeBuffer.x >= this._bufferService.cols) { + this._activeBuffer.x--; + } + this._dirtyRowTracker.markDirty(this._activeBuffer.y); + + this._onLineFeed.fire(); + return true; + } + + /** + * CR + * Carriage Return (Ctrl-M). + * + * @vt: #Y C0 CR "Carriage Return" "\r, \x0D" "Move the cursor to the beginning of the row." + */ + public carriageReturn(): boolean { + this._activeBuffer.x = 0; + return true; + } + + /** + * BS + * Backspace (Ctrl-H). + * + * @vt: #Y C0 BS "Backspace" "\b, \x08" "Move the cursor one position to the left." + * By default it is not possible to move the cursor past the leftmost position. + * If `reverse wrap-around` (`CSI ? 45 h`) is set, a previous soft line wrap (DECAWM) + * can be undone with BS within the scroll margins. In that case the cursor will wrap back + * to the end of the previous row. Note that it is not possible to peek back into the scrollbuffer + * with the cursor, thus at the home position (top-leftmost cell) this has no effect. + */ + public backspace(): boolean { + // reverse wrap-around is disabled + if (!this._coreService.decPrivateModes.reverseWraparound) { + this._restrictCursor(); + if (this._activeBuffer.x > 0) { + this._activeBuffer.x--; + } + return true; + } + + // reverse wrap-around is enabled + // other than for normal operation mode, reverse wrap-around allows the cursor + // to be at x=cols to be able to address the last cell of a row by BS + this._restrictCursor(this._bufferService.cols); + + if (this._activeBuffer.x > 0) { + this._activeBuffer.x--; + } else { + /** + * reverse wrap-around handling: + * Our implementation deviates from xterm on purpose. Details: + * - only previous soft NLs can be reversed (isWrapped=true) + * - only works within scrollborders (top/bottom, left/right not yet supported) + * - cannot peek into scrollbuffer + * - any cursor movement sequence keeps working as expected + */ + if (this._activeBuffer.x === 0 + && this._activeBuffer.y > this._activeBuffer.scrollTop + && this._activeBuffer.y <= this._activeBuffer.scrollBottom + && this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y)?.isWrapped) { + this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y)!.isWrapped = false; + this._activeBuffer.y--; + this._activeBuffer.x = this._bufferService.cols - 1; + // find last taken cell - last cell can have 3 different states: + // - hasContent(true) + hasWidth(1): narrow char - we are done + // - hasWidth(0): second part of wide char - we are done + // - hasContent(false) + hasWidth(1): empty cell due to early wrapping wide char, go one + // cell further back + const line = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y)!; + if (line.hasWidth(this._activeBuffer.x) && !line.hasContent(this._activeBuffer.x)) { + this._activeBuffer.x--; + // We do this only once, since width=1 + hasContent=false currently happens only once + // before early wrapping of a wide char. + // This needs to be fixed once we support graphemes taking more than 2 cells. + } + } + } + this._restrictCursor(); + return true; + } + + /** + * TAB + * Horizontal Tab (HT) (Ctrl-I). + * + * @vt: #Y C0 HT "Horizontal Tabulation" "\t, \x09" "Move the cursor to the next character tab stop." + */ + public tab(): boolean { + if (this._activeBuffer.x >= this._bufferService.cols) { + return true; + } + const originalX = this._activeBuffer.x; + this._activeBuffer.x = this._activeBuffer.nextStop(); + if (this._optionsService.rawOptions.screenReaderMode) { + this._onA11yTab.fire(this._activeBuffer.x - originalX); + } + return true; + } + + /** + * SO + * Shift Out (Ctrl-N) -> Switch to Alternate Character Set. This invokes the + * G1 character set. + * + * @vt: #P[Only limited ISO-2022 charset support.] C0 SO "Shift Out" "\x0E" "Switch to an alternative character set." + */ + public shiftOut(): boolean { + this._charsetService.setgLevel(1); + return true; + } + + /** + * SI + * Shift In (Ctrl-O) -> Switch to Standard Character Set. This invokes the G0 + * character set (the default). + * + * @vt: #Y C0 SI "Shift In" "\x0F" "Return to regular character set after Shift Out." + */ + public shiftIn(): boolean { + this._charsetService.setgLevel(0); + return true; + } + + /** + * Restrict cursor to viewport size / scroll margin (origin mode). + */ + private _restrictCursor(maxCol: number = this._bufferService.cols - 1): void { + this._activeBuffer.x = Math.min(maxCol, Math.max(0, this._activeBuffer.x)); + this._activeBuffer.y = this._coreService.decPrivateModes.origin + ? Math.min(this._activeBuffer.scrollBottom, Math.max(this._activeBuffer.scrollTop, this._activeBuffer.y)) + : Math.min(this._bufferService.rows - 1, Math.max(0, this._activeBuffer.y)); + this._dirtyRowTracker.markDirty(this._activeBuffer.y); + } + + /** + * Set absolute cursor position. + */ + private _setCursor(x: number, y: number): void { + this._dirtyRowTracker.markDirty(this._activeBuffer.y); + if (this._coreService.decPrivateModes.origin) { + this._activeBuffer.x = x; + this._activeBuffer.y = this._activeBuffer.scrollTop + y; + } else { + this._activeBuffer.x = x; + this._activeBuffer.y = y; + } + this._restrictCursor(); + this._dirtyRowTracker.markDirty(this._activeBuffer.y); + } + + /** + * Set relative cursor position. + */ + private _moveCursor(x: number, y: number): void { + // for relative changes we have to make sure we are within 0 .. cols/rows - 1 + // before calculating the new position + this._restrictCursor(); + this._setCursor(this._activeBuffer.x + x, this._activeBuffer.y + y); + } + + /** + * CSI Ps A + * Cursor Up Ps Times (default = 1) (CUU). + * + * @vt: #Y CSI CUU "Cursor Up" "CSI Ps A" "Move cursor `Ps` times up (default=1)." + * If the cursor would pass the top scroll margin, it will stop there. + */ + public cursorUp(params: IParams): boolean { + // stop at scrollTop + const diffToTop = this._activeBuffer.y - this._activeBuffer.scrollTop; + if (diffToTop >= 0) { + this._moveCursor(0, -Math.min(diffToTop, params.params[0] || 1)); + } else { + this._moveCursor(0, -(params.params[0] || 1)); + } + return true; + } + + /** + * CSI Ps B + * Cursor Down Ps Times (default = 1) (CUD). + * + * @vt: #Y CSI CUD "Cursor Down" "CSI Ps B" "Move cursor `Ps` times down (default=1)." + * If the cursor would pass the bottom scroll margin, it will stop there. + */ + public cursorDown(params: IParams): boolean { + // stop at scrollBottom + const diffToBottom = this._activeBuffer.scrollBottom - this._activeBuffer.y; + if (diffToBottom >= 0) { + this._moveCursor(0, Math.min(diffToBottom, params.params[0] || 1)); + } else { + this._moveCursor(0, params.params[0] || 1); + } + return true; + } + + /** + * CSI Ps C + * Cursor Forward Ps Times (default = 1) (CUF). + * + * @vt: #Y CSI CUF "Cursor Forward" "CSI Ps C" "Move cursor `Ps` times forward (default=1)." + */ + public cursorForward(params: IParams): boolean { + this._moveCursor(params.params[0] || 1, 0); + return true; + } + + /** + * CSI Ps D + * Cursor Backward Ps Times (default = 1) (CUB). + * + * @vt: #Y CSI CUB "Cursor Backward" "CSI Ps D" "Move cursor `Ps` times backward (default=1)." + */ + public cursorBackward(params: IParams): boolean { + this._moveCursor(-(params.params[0] || 1), 0); + return true; + } + + /** + * CSI Ps E + * Cursor Next Line Ps Times (default = 1) (CNL). + * Other than cursorDown (CUD) also set the cursor to first column. + * + * @vt: #Y CSI CNL "Cursor Next Line" "CSI Ps E" "Move cursor `Ps` times down (default=1) and to the first column." + * Same as CUD, additionally places the cursor at the first column. + */ + public cursorNextLine(params: IParams): boolean { + this.cursorDown(params); + this._activeBuffer.x = 0; + return true; + } + + /** + * CSI Ps F + * Cursor Previous Line Ps Times (default = 1) (CPL). + * Other than cursorUp (CUU) also set the cursor to first column. + * + * @vt: #Y CSI CPL "Cursor Backward" "CSI Ps F" "Move cursor `Ps` times up (default=1) and to the first column." + * Same as CUU, additionally places the cursor at the first column. + */ + public cursorPrecedingLine(params: IParams): boolean { + this.cursorUp(params); + this._activeBuffer.x = 0; + return true; + } + + /** + * CSI Ps G + * Cursor Character Absolute [column] (default = [row,1]) (CHA). + * + * @vt: #Y CSI CHA "Cursor Horizontal Absolute" "CSI Ps G" "Move cursor to `Ps`-th column of the active row (default=1)." + */ + public cursorCharAbsolute(params: IParams): boolean { + this._setCursor((params.params[0] || 1) - 1, this._activeBuffer.y); + return true; + } + + /** + * CSI Ps ; Ps H + * Cursor Position [row;column] (default = [1,1]) (CUP). + * + * @vt: #Y CSI CUP "Cursor Position" "CSI Ps ; Ps H" "Set cursor to position [`Ps`, `Ps`] (default = [1, 1])." + * If ORIGIN mode is set, places the cursor to the absolute position within the scroll margins. + * If ORIGIN mode is not set, places the cursor to the absolute position within the viewport. + * Note that the coordinates are 1-based, thus the top left position starts at `1 ; 1`. + */ + public cursorPosition(params: IParams): boolean { + this._setCursor( + // col + (params.length >= 2) ? (params.params[1] || 1) - 1 : 0, + // row + (params.params[0] || 1) - 1 + ); + return true; + } + + /** + * CSI Pm ` Character Position Absolute + * [column] (default = [row,1]) (HPA). + * Currently same functionality as CHA. + * + * @vt: #Y CSI HPA "Horizontal Position Absolute" "CSI Ps ` " "Same as CHA." + */ + public charPosAbsolute(params: IParams): boolean { + this._setCursor((params.params[0] || 1) - 1, this._activeBuffer.y); + return true; + } + + /** + * CSI Pm a Character Position Relative + * [columns] (default = [row,col+1]) (HPR) + * + * @vt: #Y CSI HPR "Horizontal Position Relative" "CSI Ps a" "Same as CUF." + */ + public hPositionRelative(params: IParams): boolean { + this._moveCursor(params.params[0] || 1, 0); + return true; + } + + /** + * CSI Pm d Vertical Position Absolute (VPA) + * [row] (default = [1,column]) + * + * @vt: #Y CSI VPA "Vertical Position Absolute" "CSI Ps d" "Move cursor to `Ps`-th row (default=1)." + */ + public linePosAbsolute(params: IParams): boolean { + this._setCursor(this._activeBuffer.x, (params.params[0] || 1) - 1); + return true; + } + + /** + * CSI Pm e Vertical Position Relative (VPR) + * [rows] (default = [row+1,column]) + * reuse CSI Ps B ? + * + * @vt: #Y CSI VPR "Vertical Position Relative" "CSI Ps e" "Move cursor `Ps` times down (default=1)." + */ + public vPositionRelative(params: IParams): boolean { + this._moveCursor(0, params.params[0] || 1); + return true; + } + + /** + * CSI Ps ; Ps f + * Horizontal and Vertical Position [row;column] (default = + * [1,1]) (HVP). + * Same as CUP. + * + * @vt: #Y CSI HVP "Horizontal and Vertical Position" "CSI Ps ; Ps f" "Same as CUP." + */ + public hVPosition(params: IParams): boolean { + this.cursorPosition(params); + return true; + } + + /** + * CSI Ps g Tab Clear (TBC). + * Ps = 0 -> Clear Current Column (default). + * Ps = 3 -> Clear All. + * Potentially: + * Ps = 2 -> Clear Stops on Line. + * http://vt100.net/annarbor/aaa-ug/section6.html + * + * @vt: #Y CSI TBC "Tab Clear" "CSI Ps g" "Clear tab stops at current position (0) or all (3) (default=0)." + * Clearing tabstops off the active row (Ps = 2, VT100) is currently not supported. + */ + public tabClear(params: IParams): boolean { + const param = params.params[0]; + if (param === 0) { + delete this._activeBuffer.tabs[this._activeBuffer.x]; + } else if (param === 3) { + this._activeBuffer.tabs = {}; + } + return true; + } + + /** + * CSI Ps I + * Cursor Forward Tabulation Ps tab stops (default = 1) (CHT). + * + * @vt: #Y CSI CHT "Cursor Horizontal Tabulation" "CSI Ps I" "Move cursor `Ps` times tabs forward (default=1)." + */ + public cursorForwardTab(params: IParams): boolean { + if (this._activeBuffer.x >= this._bufferService.cols) { + return true; + } + let param = params.params[0] || 1; + while (param--) { + this._activeBuffer.x = this._activeBuffer.nextStop(); + } + return true; + } + + /** + * CSI Ps Z Cursor Backward Tabulation Ps tab stops (default = 1) (CBT). + * + * @vt: #Y CSI CBT "Cursor Backward Tabulation" "CSI Ps Z" "Move cursor `Ps` tabs backward (default=1)." + */ + public cursorBackwardTab(params: IParams): boolean { + if (this._activeBuffer.x >= this._bufferService.cols) { + return true; + } + let param = params.params[0] || 1; + + while (param--) { + this._activeBuffer.x = this._activeBuffer.prevStop(); + } + return true; + } + + /** + * CSI Ps " q Select Character Protection Attribute (DECSCA). + * + * @vt: #Y CSI DECSCA "Select Character Protection Attribute" "CSI Ps " q" "Whether DECSED and DECSEL can erase (0=default, 2) or not (1)." + */ + public selectProtected(params: IParams): boolean { + const p = params.params[0]; + if (p === 1) this._curAttrData.bg |= BgFlags.PROTECTED; + if (p === 2 || p === 0) this._curAttrData.bg &= ~BgFlags.PROTECTED; + return true; + } + + + /** + * Helper method to erase cells in a terminal row. + * The cell gets replaced with the eraseChar of the terminal. + * @param y The row index relative to the viewport. + * @param start The start x index of the range to be erased. + * @param end The end x index of the range to be erased (exclusive). + * @param clearWrap clear the isWrapped flag + * @param respectProtect Whether to respect the protection attribute (DECSCA). + */ + private _eraseInBufferLine(y: number, start: number, end: number, clearWrap: boolean = false, respectProtect: boolean = false): void { + const line = this._activeBuffer.lines.get(this._activeBuffer.ybase + y)!; + line.replaceCells( + start, + end, + this._activeBuffer.getNullCell(this._eraseAttrData()), + respectProtect + ); + if (clearWrap) { + line.isWrapped = false; + } + } + + /** + * Helper method to reset cells in a terminal row. The cell gets replaced with the eraseChar of + * the terminal and the isWrapped property is set to false. + * @param y row index + */ + private _resetBufferLine(y: number, respectProtect: boolean = false): void { + const line = this._activeBuffer.lines.get(this._activeBuffer.ybase + y); + if (line) { + line.fill(this._activeBuffer.getNullCell(this._eraseAttrData()), respectProtect); + this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase + y); + line.isWrapped = false; + } + } + + /** + * CSI Ps J Erase in Display (ED). + * Ps = 0 -> Erase Below (default). + * Ps = 1 -> Erase Above. + * Ps = 2 -> Erase All. + * Ps = 3 -> Erase Saved Lines (xterm). + * CSI ? Ps J + * Erase in Display (DECSED). + * Ps = 0 -> Selective Erase Below (default). + * Ps = 1 -> Selective Erase Above. + * Ps = 2 -> Selective Erase All. + * + * @vt: #Y CSI ED "Erase In Display" "CSI Ps J" "Erase various parts of the viewport." + * Supported param values: + * + * | Ps | Effect | + * | -- | ------------------------------------------------------------ | + * | 0 | Erase from the cursor through the end of the viewport. | + * | 1 | Erase from the beginning of the viewport through the cursor. | + * | 2 | Erase complete viewport. | + * | 3 | Erase scrollback. | + * + * @vt: #Y CSI DECSED "Selective Erase In Display" "CSI ? Ps J" "Same as ED with respecting protection flag." + */ + public eraseInDisplay(params: IParams, respectProtect: boolean = false): boolean { + this._restrictCursor(this._bufferService.cols); + let j; + switch (params.params[0]) { + case 0: + j = this._activeBuffer.y; + this._dirtyRowTracker.markDirty(j); + this._eraseInBufferLine(j++, this._activeBuffer.x, this._bufferService.cols, this._activeBuffer.x === 0, respectProtect); + for (; j < this._bufferService.rows; j++) { + this._resetBufferLine(j, respectProtect); + } + this._dirtyRowTracker.markDirty(j); + break; + case 1: + j = this._activeBuffer.y; + this._dirtyRowTracker.markDirty(j); + // Deleted front part of line and everything before. This line will no longer be wrapped. + this._eraseInBufferLine(j, 0, this._activeBuffer.x + 1, true, respectProtect); + if (this._activeBuffer.x + 1 >= this._bufferService.cols) { + // Deleted entire previous line. This next line can no longer be wrapped. + this._activeBuffer.lines.get(j + 1)!.isWrapped = false; + } + while (j--) { + this._resetBufferLine(j, respectProtect); + } + this._dirtyRowTracker.markDirty(0); + break; + case 2: + if (this._optionsService.rawOptions.scrollOnEraseInDisplay) { + j = this._bufferService.rows; + this._dirtyRowTracker.markRangeDirty(0, j - 1); + while (j--) { + const currentLine = this._activeBuffer.lines.get(this._activeBuffer.ybase + j); + if (currentLine?.getTrimmedLength()) { + break; + } + } + for (; j >= 0; j--) { + this._bufferService.scroll(this._eraseAttrData()); + } + } + else { + j = this._bufferService.rows; + this._dirtyRowTracker.markDirty(j - 1); + while (j--) { + this._resetBufferLine(j, respectProtect); + } + this._dirtyRowTracker.markDirty(0); + } + break; + case 3: + // Clear scrollback (everything not in viewport) + const scrollBackSize = this._activeBuffer.lines.length - this._bufferService.rows; + if (scrollBackSize > 0) { + this._activeBuffer.lines.trimStart(scrollBackSize); + this._activeBuffer.ybase = Math.max(this._activeBuffer.ybase - scrollBackSize, 0); + this._activeBuffer.ydisp = Math.max(this._activeBuffer.ydisp - scrollBackSize, 0); + // Force a scroll event to refresh viewport + this._onScroll.fire(0); + } + break; + } + return true; + } + + /** + * CSI Ps K Erase in Line (EL). + * Ps = 0 -> Erase to Right (default). + * Ps = 1 -> Erase to Left. + * Ps = 2 -> Erase All. + * CSI ? Ps K + * Erase in Line (DECSEL). + * Ps = 0 -> Selective Erase to Right (default). + * Ps = 1 -> Selective Erase to Left. + * Ps = 2 -> Selective Erase All. + * + * @vt: #Y CSI EL "Erase In Line" "CSI Ps K" "Erase various parts of the active row." + * Supported param values: + * + * | Ps | Effect | + * | -- | -------------------------------------------------------- | + * | 0 | Erase from the cursor through the end of the row. | + * | 1 | Erase from the beginning of the line through the cursor. | + * | 2 | Erase complete line. | + * + * @vt: #Y CSI DECSEL "Selective Erase In Line" "CSI ? Ps K" "Same as EL with respecting protecting flag." + */ + public eraseInLine(params: IParams, respectProtect: boolean = false): boolean { + this._restrictCursor(this._bufferService.cols); + switch (params.params[0]) { + case 0: + this._eraseInBufferLine(this._activeBuffer.y, this._activeBuffer.x, this._bufferService.cols, this._activeBuffer.x === 0, respectProtect); + break; + case 1: + this._eraseInBufferLine(this._activeBuffer.y, 0, this._activeBuffer.x + 1, false, respectProtect); + break; + case 2: + this._eraseInBufferLine(this._activeBuffer.y, 0, this._bufferService.cols, true, respectProtect); + break; + } + this._dirtyRowTracker.markDirty(this._activeBuffer.y); + return true; + } + + /** + * CSI Ps L + * Insert Ps Line(s) (default = 1) (IL). + * + * @vt: #Y CSI IL "Insert Line" "CSI Ps L" "Insert `Ps` blank lines at active row (default=1)." + * For every inserted line at the scroll top one line at the scroll bottom gets removed. + * The cursor is set to the first column. + * IL has no effect if the cursor is outside the scroll margins. + */ + public insertLines(params: IParams): boolean { + this._restrictCursor(); + let param = params.params[0] || 1; + + if (this._activeBuffer.y > this._activeBuffer.scrollBottom || this._activeBuffer.y < this._activeBuffer.scrollTop) { + return true; + } + + const row: number = this._activeBuffer.ybase + this._activeBuffer.y; + + const scrollBottomRowsOffset = this._bufferService.rows - 1 - this._activeBuffer.scrollBottom; + const scrollBottomAbsolute = this._bufferService.rows - 1 + this._activeBuffer.ybase - scrollBottomRowsOffset + 1; + while (param--) { + // test: echo -e '\e[44m\e[1L\e[0m' + // blankLine(true) - xterm/linux behavior + this._activeBuffer.lines.splice(scrollBottomAbsolute - 1, 1); + this._activeBuffer.lines.splice(row, 0, this._activeBuffer.getBlankLine(this._eraseAttrData())); + } + + this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y, this._activeBuffer.scrollBottom); + this._activeBuffer.x = 0; // see https://vt100.net/docs/vt220-rm/chapter4.html - vt220 only? + return true; + } + + /** + * CSI Ps M + * Delete Ps Line(s) (default = 1) (DL). + * + * @vt: #Y CSI DL "Delete Line" "CSI Ps M" "Delete `Ps` lines at active row (default=1)." + * For every deleted line at the scroll top one blank line at the scroll bottom gets appended. + * The cursor is set to the first column. + * DL has no effect if the cursor is outside the scroll margins. + */ + public deleteLines(params: IParams): boolean { + this._restrictCursor(); + let param = params.params[0] || 1; + + if (this._activeBuffer.y > this._activeBuffer.scrollBottom || this._activeBuffer.y < this._activeBuffer.scrollTop) { + return true; + } + + const row: number = this._activeBuffer.ybase + this._activeBuffer.y; + + let j: number; + j = this._bufferService.rows - 1 - this._activeBuffer.scrollBottom; + j = this._bufferService.rows - 1 + this._activeBuffer.ybase - j; + while (param--) { + // test: echo -e '\e[44m\e[1M\e[0m' + // blankLine(true) - xterm/linux behavior + this._activeBuffer.lines.splice(row, 1); + this._activeBuffer.lines.splice(j, 0, this._activeBuffer.getBlankLine(this._eraseAttrData())); + } + + this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y, this._activeBuffer.scrollBottom); + this._activeBuffer.x = 0; // see https://vt100.net/docs/vt220-rm/chapter4.html - vt220 only? + return true; + } + + /** + * CSI Ps @ + * Insert Ps (Blank) Character(s) (default = 1) (ICH). + * + * @vt: #Y CSI ICH "Insert Characters" "CSI Ps @" "Insert `Ps` (blank) characters (default = 1)." + * The ICH sequence inserts `Ps` blank characters. The cursor remains at the beginning of the + * blank characters. Text between the cursor and right margin moves to the right. Characters moved + * past the right margin are lost. + * + * + * FIXME: check against xterm - should not work outside of scroll margins (see VT520 manual) + */ + public insertChars(params: IParams): boolean { + this._restrictCursor(); + const line = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y); + if (line) { + line.insertCells( + this._activeBuffer.x, + params.params[0] || 1, + this._activeBuffer.getNullCell(this._eraseAttrData()) + ); + this._dirtyRowTracker.markDirty(this._activeBuffer.y); + } + return true; + } + + /** + * CSI Ps P + * Delete Ps Character(s) (default = 1) (DCH). + * + * @vt: #Y CSI DCH "Delete Character" "CSI Ps P" "Delete `Ps` characters (default=1)." + * As characters are deleted, the remaining characters between the cursor and right margin move to + * the left. Character attributes move with the characters. The terminal adds blank characters at + * the right margin. + * + * + * FIXME: check against xterm - should not work outside of scroll margins (see VT520 manual) + */ + public deleteChars(params: IParams): boolean { + this._restrictCursor(); + const line = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y); + if (line) { + line.deleteCells( + this._activeBuffer.x, + params.params[0] || 1, + this._activeBuffer.getNullCell(this._eraseAttrData()) + ); + this._dirtyRowTracker.markDirty(this._activeBuffer.y); + } + return true; + } + + /** + * CSI Ps S Scroll up Ps lines (default = 1) (SU). + * + * @vt: #Y CSI SU "Scroll Up" "CSI Ps S" "Scroll `Ps` lines up (default=1)." + * + * + * FIXME: scrolled out lines at top = 1 should add to scrollback (xterm) + */ + public scrollUp(params: IParams): boolean { + let param = params.params[0] || 1; + + while (param--) { + this._activeBuffer.lines.splice(this._activeBuffer.ybase + this._activeBuffer.scrollTop, 1); + this._activeBuffer.lines.splice(this._activeBuffer.ybase + this._activeBuffer.scrollBottom, 0, this._activeBuffer.getBlankLine(this._eraseAttrData())); + } + this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom); + return true; + } + + /** + * CSI Ps T Scroll down Ps lines (default = 1) (SD). + * + * @vt: #Y CSI SD "Scroll Down" "CSI Ps T" "Scroll `Ps` lines down (default=1)." + */ + public scrollDown(params: IParams): boolean { + let param = params.params[0] || 1; + + while (param--) { + this._activeBuffer.lines.splice(this._activeBuffer.ybase + this._activeBuffer.scrollBottom, 1); + this._activeBuffer.lines.splice(this._activeBuffer.ybase + this._activeBuffer.scrollTop, 0, this._activeBuffer.getBlankLine(DEFAULT_ATTR_DATA)); + } + this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom); + return true; + } + + /** + * CSI Ps SP @ Scroll left Ps columns (default = 1) (SL) ECMA-48 + * + * Notation: (Pn) + * Representation: CSI Pn 02/00 04/00 + * Parameter default value: Pn = 1 + * SL causes the data in the presentation component to be moved by n character positions + * if the line orientation is horizontal, or by n line positions if the line orientation + * is vertical, such that the data appear to move to the left; where n equals the value of Pn. + * The active presentation position is not affected by this control function. + * + * Supported: + * - always left shift (no line orientation setting respected) + * + * @vt: #Y CSI SL "Scroll Left" "CSI Ps SP @" "Scroll viewport `Ps` times to the left." + * SL moves the content of all lines within the scroll margins `Ps` times to the left. + * SL has no effect outside of the scroll margins. + */ + public scrollLeft(params: IParams): boolean { + if (this._activeBuffer.y > this._activeBuffer.scrollBottom || this._activeBuffer.y < this._activeBuffer.scrollTop) { + return true; + } + const param = params.params[0] || 1; + for (let y = this._activeBuffer.scrollTop; y <= this._activeBuffer.scrollBottom; ++y) { + const line = this._activeBuffer.lines.get(this._activeBuffer.ybase + y)!; + line.deleteCells(0, param, this._activeBuffer.getNullCell(this._eraseAttrData())); + line.isWrapped = false; + } + this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom); + return true; + } + + /** + * CSI Ps SP A Scroll right Ps columns (default = 1) (SR) ECMA-48 + * + * Notation: (Pn) + * Representation: CSI Pn 02/00 04/01 + * Parameter default value: Pn = 1 + * SR causes the data in the presentation component to be moved by n character positions + * if the line orientation is horizontal, or by n line positions if the line orientation + * is vertical, such that the data appear to move to the right; where n equals the value of Pn. + * The active presentation position is not affected by this control function. + * + * Supported: + * - always right shift (no line orientation setting respected) + * + * @vt: #Y CSI SR "Scroll Right" "CSI Ps SP A" "Scroll viewport `Ps` times to the right." + * SL moves the content of all lines within the scroll margins `Ps` times to the right. + * Content at the right margin is lost. + * SL has no effect outside of the scroll margins. + */ + public scrollRight(params: IParams): boolean { + if (this._activeBuffer.y > this._activeBuffer.scrollBottom || this._activeBuffer.y < this._activeBuffer.scrollTop) { + return true; + } + const param = params.params[0] || 1; + for (let y = this._activeBuffer.scrollTop; y <= this._activeBuffer.scrollBottom; ++y) { + const line = this._activeBuffer.lines.get(this._activeBuffer.ybase + y)!; + line.insertCells(0, param, this._activeBuffer.getNullCell(this._eraseAttrData())); + line.isWrapped = false; + } + this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom); + return true; + } + + /** + * CSI Pm ' } + * Insert Ps Column(s) (default = 1) (DECIC), VT420 and up. + * + * @vt: #Y CSI DECIC "Insert Columns" "CSI Ps ' }" "Insert `Ps` columns at cursor position." + * DECIC inserts `Ps` times blank columns at the cursor position for all lines with the scroll + * margins, moving content to the right. Content at the right margin is lost. DECIC has no effect + * outside the scrolling margins. + */ + public insertColumns(params: IParams): boolean { + if (this._activeBuffer.y > this._activeBuffer.scrollBottom || this._activeBuffer.y < this._activeBuffer.scrollTop) { + return true; + } + const param = params.params[0] || 1; + for (let y = this._activeBuffer.scrollTop; y <= this._activeBuffer.scrollBottom; ++y) { + const line = this._activeBuffer.lines.get(this._activeBuffer.ybase + y)!; + line.insertCells(this._activeBuffer.x, param, this._activeBuffer.getNullCell(this._eraseAttrData())); + line.isWrapped = false; + } + this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom); + return true; + } + + /** + * CSI Pm ' ~ + * Delete Ps Column(s) (default = 1) (DECDC), VT420 and up. + * + * @vt: #Y CSI DECDC "Delete Columns" "CSI Ps ' ~" "Delete `Ps` columns at cursor position." + * DECDC deletes `Ps` times columns at the cursor position for all lines with the scroll margins, + * moving content to the left. Blank columns are added at the right margin. + * DECDC has no effect outside the scrolling margins. + */ + public deleteColumns(params: IParams): boolean { + if (this._activeBuffer.y > this._activeBuffer.scrollBottom || this._activeBuffer.y < this._activeBuffer.scrollTop) { + return true; + } + const param = params.params[0] || 1; + for (let y = this._activeBuffer.scrollTop; y <= this._activeBuffer.scrollBottom; ++y) { + const line = this._activeBuffer.lines.get(this._activeBuffer.ybase + y)!; + line.deleteCells(this._activeBuffer.x, param, this._activeBuffer.getNullCell(this._eraseAttrData())); + line.isWrapped = false; + } + this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom); + return true; + } + + /** + * CSI Ps X + * Erase Ps Character(s) (default = 1) (ECH). + * + * @vt: #Y CSI ECH "Erase Character" "CSI Ps X" "Erase `Ps` characters from current cursor position to the right (default=1)." + * ED erases `Ps` characters from current cursor position to the right. + * ED works inside or outside the scrolling margins. + */ + public eraseChars(params: IParams): boolean { + this._restrictCursor(); + const line = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y); + if (line) { + line.replaceCells( + this._activeBuffer.x, + this._activeBuffer.x + (params.params[0] || 1), + this._activeBuffer.getNullCell(this._eraseAttrData()) + ); + this._dirtyRowTracker.markDirty(this._activeBuffer.y); + } + return true; + } + + /** + * CSI Ps b Repeat the preceding graphic character Ps times (REP). + * From ECMA 48 (@see http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-048.pdf) + * Notation: (Pn) + * Representation: CSI Pn 06/02 + * Parameter default value: Pn = 1 + * REP is used to indicate that the preceding character in the data stream, + * if it is a graphic character (represented by one or more bit combinations) including SPACE, + * is to be repeated n times, where n equals the value of Pn. + * If the character preceding REP is a control function or part of a control function, + * the effect of REP is not defined by this Standard. + * + * We extend xterm's behavior to allow repeating entire grapheme clusters. + * This isn't 100% xterm-compatible, but it seems saner and more useful. + * - text attrs are applied normally + * - wrap around is respected + * - any valid sequence resets the carried forward char + * + * Note: To get reset on a valid sequence working correctly without much runtime penalty, the + * preceding codepoint is stored on the parser in `this.print` and reset during `parser.parse`. + * + * @vt: #Y CSI REP "Repeat Preceding Character" "CSI Ps b" "Repeat preceding character `Ps` times (default=1)." + * REP repeats the previous character `Ps` times advancing the cursor, also wrapping if DECAWM is + * set. REP has no effect if the sequence does not follow a printable ASCII character + * (NOOP for any other sequence in between or NON ASCII characters). + */ + public repeatPrecedingCharacter(params: IParams): boolean { + const joinState = this._parser.precedingJoinState; + if (!joinState) { + return true; + } + // call print to insert the chars and handle correct wrapping + const length = params.params[0] || 1; + const chWidth = UnicodeService.extractWidth(joinState); + const x = this._activeBuffer.x - chWidth; + const bufferRow = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y)!; + const text = bufferRow.getString(x); + const data = new Uint32Array(text.length * length); + let idata = 0; + for (let itext = 0; itext < text.length;) { + const ch = text.codePointAt(itext) || 0; + data[idata++] = ch; + itext += ch > 0xffff ? 2 : 1; + } + let tlength = idata; + for (let i = 1; i < length; ++i) { + data.copyWithin(tlength, 0, idata); + tlength += idata; + } + this.print(data, 0, tlength); + return true; + } + + /** + * CSI Ps c Send Device Attributes (Primary DA). + * Ps = 0 or omitted -> request attributes from terminal. The + * response depends on the decTerminalID resource setting. + * -> CSI ? 1 ; 2 c (``VT100 with Advanced Video Option'') + * -> CSI ? 1 ; 0 c (``VT101 with No Options'') + * -> CSI ? 6 c (``VT102'') + * -> CSI ? 6 0 ; 1 ; 2 ; 6 ; 8 ; 9 ; 1 5 ; c (``VT220'') + * The VT100-style response parameters do not mean anything by + * themselves. VT220 parameters do, telling the host what fea- + * tures the terminal supports: + * Ps = 1 -> 132-columns. + * Ps = 2 -> Printer. + * Ps = 6 -> Selective erase. + * Ps = 8 -> User-defined keys. + * Ps = 9 -> National replacement character sets. + * Ps = 1 5 -> Technical characters. + * Ps = 2 2 -> ANSI color, e.g., VT525. + * Ps = 2 9 -> ANSI text locator (i.e., DEC Locator mode). + * + * @vt: #Y CSI DA1 "Primary Device Attributes" "CSI c" "Send primary device attributes." + * + * + * TODO: fix and cleanup response + */ + public sendDeviceAttributesPrimary(params: IParams): boolean { + if (params.params[0] > 0) { + return true; + } + if (this._is('xterm') || this._is('rxvt-unicode') || this._is('screen')) { + this._coreService.triggerDataEvent(C0.ESC + '[?1;2c'); + } else if (this._is('linux')) { + this._coreService.triggerDataEvent(C0.ESC + '[?6c'); + } + return true; + } + + /** + * CSI > Ps c + * Send Device Attributes (Secondary DA). + * Ps = 0 or omitted -> request the terminal's identification + * code. The response depends on the decTerminalID resource set- + * ting. It should apply only to VT220 and up, but xterm extends + * this to VT100. + * -> CSI > Pp ; Pv ; Pc c + * where Pp denotes the terminal type + * Pp = 0 -> ``VT100''. + * Pp = 1 -> ``VT220''. + * and Pv is the firmware version (for xterm, this was originally + * the XFree86 patch number, starting with 95). In a DEC termi- + * nal, Pc indicates the ROM cartridge registration number and is + * always zero. + * More information: + * xterm/charproc.c - line 2012, for more information. + * vim responds with ^[[?0c or ^[[?1c after the terminal's response (?) + * + * @vt: #Y CSI DA2 "Secondary Device Attributes" "CSI > c" "Send primary device attributes." + * + * + * TODO: fix and cleanup response + */ + public sendDeviceAttributesSecondary(params: IParams): boolean { + if (params.params[0] > 0) { + return true; + } + // xterm and urxvt + // seem to spit this + // out around ~370 times (?). + if (this._is('xterm')) { + this._coreService.triggerDataEvent(C0.ESC + '[>0;276;0c'); + } else if (this._is('rxvt-unicode')) { + this._coreService.triggerDataEvent(C0.ESC + '[>85;95;0c'); + } else if (this._is('linux')) { + // not supported by linux console. + // linux console echoes parameters. + this._coreService.triggerDataEvent(params.params[0] + 'c'); + } else if (this._is('screen')) { + this._coreService.triggerDataEvent(C0.ESC + '[>83;40003;0c'); + } + return true; + } + + /** + * Evaluate if the current terminal is the given argument. + * @param term The terminal name to evaluate + */ + private _is(term: string): boolean { + return (this._optionsService.rawOptions.termName + '').indexOf(term) === 0; + } + + /** + * CSI Pm h Set Mode (SM). + * Ps = 2 -> Keyboard Action Mode (AM). + * Ps = 4 -> Insert Mode (IRM). + * Ps = 1 2 -> Send/receive (SRM). + * Ps = 2 0 -> Automatic Newline (LNM). + * + * @vt: #P[Only IRM is supported.] CSI SM "Set Mode" "CSI Pm h" "Set various terminal modes." + * Supported param values by SM: + * + * | Param | Action | Support | + * | ----- | -------------------------------------- | ------- | + * | 2 | Keyboard Action Mode (KAM). Always on. | #N | + * | 4 | Insert Mode (IRM). | #Y | + * | 12 | Send/receive (SRM). Always off. | #N | + * | 20 | Automatic Newline (LNM). | #Y | + */ + public setMode(params: IParams): boolean { + for (let i = 0; i < params.length; i++) { + switch (params.params[i]) { + case 4: + this._coreService.modes.insertMode = true; + break; + case 20: + this._optionsService.options.convertEol = true; + break; + } + } + return true; + } + + /** + * CSI ? Pm h + * DEC Private Mode Set (DECSET). + * Ps = 1 -> Application Cursor Keys (DECCKM). + * Ps = 2 -> Designate USASCII for character sets G0-G3 + * (DECANM), and set VT100 mode. + * Ps = 3 -> 132 Column Mode (DECCOLM). + * Ps = 4 -> Smooth (Slow) Scroll (DECSCLM). + * Ps = 5 -> Reverse Video (DECSCNM). + * Ps = 6 -> Origin Mode (DECOM). + * Ps = 7 -> Wraparound Mode (DECAWM). + * Ps = 8 -> Auto-repeat Keys (DECARM). + * Ps = 9 -> Send Mouse X & Y on button press. See the sec- + * tion Mouse Tracking. + * Ps = 1 0 -> Show toolbar (rxvt). + * Ps = 1 2 -> Start Blinking Cursor (att610). + * Ps = 1 8 -> Print form feed (DECPFF). + * Ps = 1 9 -> Set print extent to full screen (DECPEX). + * Ps = 2 5 -> Show Cursor (DECTCEM). + * Ps = 3 0 -> Show scrollbar (rxvt). + * Ps = 3 5 -> Enable font-shifting functions (rxvt). + * Ps = 3 8 -> Enter Tektronix Mode (DECTEK). + * Ps = 4 0 -> Allow 80 -> 132 Mode. + * Ps = 4 1 -> more(1) fix (see curses resource). + * Ps = 4 2 -> Enable Nation Replacement Character sets (DECN- + * RCM). + * Ps = 4 4 -> Turn On Margin Bell. + * Ps = 4 5 -> Reverse-wraparound Mode. + * Ps = 4 6 -> Start Logging. This is normally disabled by a + * compile-time option. + * Ps = 4 7 -> Use Alternate Screen Buffer. (This may be dis- + * abled by the titeInhibit resource). + * Ps = 6 6 -> Application keypad (DECNKM). + * Ps = 6 7 -> Backarrow key sends backspace (DECBKM). + * Ps = 1 0 0 0 -> Send Mouse X & Y on button press and + * release. See the section Mouse Tracking. + * Ps = 1 0 0 1 -> Use Hilite Mouse Tracking. + * Ps = 1 0 0 2 -> Use Cell Motion Mouse Tracking. + * Ps = 1 0 0 3 -> Use All Motion Mouse Tracking. + * Ps = 1 0 0 4 -> Send FocusIn/FocusOut events. + * Ps = 1 0 0 5 -> Enable Extended Mouse Mode. + * Ps = 1 0 1 0 -> Scroll to bottom on tty output (rxvt). + * Ps = 1 0 1 1 -> Scroll to bottom on key press (rxvt). + * Ps = 1 0 3 4 -> Interpret "meta" key, sets eighth bit. + * (enables the eightBitInput resource). + * Ps = 1 0 3 5 -> Enable special modifiers for Alt and Num- + * Lock keys. (This enables the numLock resource). + * Ps = 1 0 3 6 -> Send ESC when Meta modifies a key. (This + * enables the metaSendsEscape resource). + * Ps = 1 0 3 7 -> Send DEL from the editing-keypad Delete + * key. + * Ps = 1 0 3 9 -> Send ESC when Alt modifies a key. (This + * enables the altSendsEscape resource). + * Ps = 1 0 4 0 -> Keep selection even if not highlighted. + * (This enables the keepSelection resource). + * Ps = 1 0 4 1 -> Use the CLIPBOARD selection. (This enables + * the selectToClipboard resource). + * Ps = 1 0 4 2 -> Enable Urgency window manager hint when + * Control-G is received. (This enables the bellIsUrgent + * resource). + * Ps = 1 0 4 3 -> Enable raising of the window when Control-G + * is received. (enables the popOnBell resource). + * Ps = 1 0 4 7 -> Use Alternate Screen Buffer. (This may be + * disabled by the titeInhibit resource). + * Ps = 1 0 4 8 -> Save cursor as in DECSC. (This may be dis- + * abled by the titeInhibit resource). + * Ps = 1 0 4 9 -> Save cursor as in DECSC and use Alternate + * Screen Buffer, clearing it first. (This may be disabled by + * the titeInhibit resource). This combines the effects of the 1 + * 0 4 7 and 1 0 4 8 modes. Use this with terminfo-based + * applications rather than the 4 7 mode. + * Ps = 1 0 5 0 -> Set terminfo/termcap function-key mode. + * Ps = 1 0 5 1 -> Set Sun function-key mode. + * Ps = 1 0 5 2 -> Set HP function-key mode. + * Ps = 1 0 5 3 -> Set SCO function-key mode. + * Ps = 1 0 6 0 -> Set legacy keyboard emulation (X11R6). + * Ps = 1 0 6 1 -> Set VT220 keyboard emulation. + * Ps = 2 0 0 4 -> Set bracketed paste mode. + * Modes: + * http: *vt100.net/docs/vt220-rm/chapter4.html + * + * @vt: #P[See below for supported modes.] CSI DECSET "DEC Private Set Mode" "CSI ? Pm h" "Set various terminal attributes." + * Supported param values by DECSET: + * + * | param | Action | Support | + * | ----- | ------------------------------------------------------- | --------| + * | 1 | Application Cursor Keys (DECCKM). | #Y | + * | 2 | Designate US-ASCII for character sets G0-G3 (DECANM). | #Y | + * | 3 | 132 Column Mode (DECCOLM). | #Y | + * | 6 | Origin Mode (DECOM). | #Y | + * | 7 | Auto-wrap Mode (DECAWM). | #Y | + * | 8 | Auto-repeat Keys (DECARM). Always on. | #N | + * | 9 | X10 xterm mouse protocol. | #Y | + * | 12 | Start Blinking Cursor. | #Y | + * | 25 | Show Cursor (DECTCEM). | #Y | + * | 45 | Reverse wrap-around. | #Y | + * | 47 | Use Alternate Screen Buffer. | #Y | + * | 66 | Application keypad (DECNKM). | #Y | + * | 1000 | X11 xterm mouse protocol. | #Y | + * | 1002 | Use Cell Motion Mouse Tracking. | #Y | + * | 1003 | Use All Motion Mouse Tracking. | #Y | + * | 1004 | Send FocusIn/FocusOut events | #Y | + * | 1005 | Enable UTF-8 Mouse Mode. | #N | + * | 1006 | Enable SGR Mouse Mode. | #Y | + * | 1015 | Enable urxvt Mouse Mode. | #N | + * | 1016 | Enable SGR-Pixels Mouse Mode. | #Y | + * | 1047 | Use Alternate Screen Buffer. | #Y | + * | 1048 | Save cursor as in DECSC. | #Y | + * | 1049 | Save cursor and switch to alternate buffer clearing it. | #P[Does not clear the alternate buffer.] | + * | 2004 | Set bracketed paste mode. | #Y | + * + * + * FIXME: implement DECSCNM, 1049 should clear altbuffer + */ + public setModePrivate(params: IParams): boolean { + for (let i = 0; i < params.length; i++) { + switch (params.params[i]) { + case 1: + this._coreService.decPrivateModes.applicationCursorKeys = true; + break; + case 2: + this._charsetService.setgCharset(0, DEFAULT_CHARSET); + this._charsetService.setgCharset(1, DEFAULT_CHARSET); + this._charsetService.setgCharset(2, DEFAULT_CHARSET); + this._charsetService.setgCharset(3, DEFAULT_CHARSET); + // set VT100 mode here + break; + case 3: + /** + * DECCOLM - 132 column mode. + * This is only active if 'SetWinLines' (24) is enabled + * through `options.windowsOptions`. + */ + if (this._optionsService.rawOptions.windowOptions.setWinLines) { + this._bufferService.resize(132, this._bufferService.rows); + this._onRequestReset.fire(); + } + break; + case 6: + this._coreService.decPrivateModes.origin = true; + this._setCursor(0, 0); + break; + case 7: + this._coreService.decPrivateModes.wraparound = true; + break; + case 12: + this._optionsService.options.cursorBlink = true; + break; + case 45: + this._coreService.decPrivateModes.reverseWraparound = true; + break; + case 66: + this._logService.debug('Serial port requested application keypad.'); + this._coreService.decPrivateModes.applicationKeypad = true; + this._onRequestSyncScrollBar.fire(); + break; + case 9: // X10 Mouse + // no release, no motion, no wheel, no modifiers. + this._coreMouseService.activeProtocol = 'X10'; + break; + case 1000: // vt200 mouse + // no motion. + this._coreMouseService.activeProtocol = 'VT200'; + break; + case 1002: // button event mouse + this._coreMouseService.activeProtocol = 'DRAG'; + break; + case 1003: // any event mouse + // any event - sends motion events, + // even if there is no button held down. + this._coreMouseService.activeProtocol = 'ANY'; + break; + case 1004: // send focusin/focusout events + // focusin: ^[[I + // focusout: ^[[O + this._coreService.decPrivateModes.sendFocus = true; + this._onRequestSendFocus.fire(); + break; + case 1005: // utf8 ext mode mouse - removed in #2507 + this._logService.debug('DECSET 1005 not supported (see #2507)'); + break; + case 1006: // sgr ext mode mouse + this._coreMouseService.activeEncoding = 'SGR'; + break; + case 1015: // urxvt ext mode mouse - removed in #2507 + this._logService.debug('DECSET 1015 not supported (see #2507)'); + break; + case 1016: // sgr pixels mode mouse + this._coreMouseService.activeEncoding = 'SGR_PIXELS'; + break; + case 25: // show cursor + this._coreService.isCursorHidden = false; + break; + case 1048: // alt screen cursor + this.saveCursor(); + break; + case 1049: // alt screen buffer cursor + this.saveCursor(); + // FALL-THROUGH + case 47: // alt screen buffer + case 1047: // alt screen buffer + this._bufferService.buffers.activateAltBuffer(this._eraseAttrData()); + this._coreService.isCursorInitialized = true; + this._onRequestRefreshRows.fire(undefined); + this._onRequestSyncScrollBar.fire(); + break; + case 2004: // bracketed paste mode (https://cirw.in/blog/bracketed-paste) + this._coreService.decPrivateModes.bracketedPasteMode = true; + break; + case 2026: // synchronized output (https://github.com/contour-terminal/vt-extensions/blob/master/synchronized-output.md) + this._coreService.decPrivateModes.synchronizedOutput = true; + break; + } + } + return true; + } + + + /** + * CSI Pm l Reset Mode (RM). + * Ps = 2 -> Keyboard Action Mode (AM). + * Ps = 4 -> Replace Mode (IRM). + * Ps = 1 2 -> Send/receive (SRM). + * Ps = 2 0 -> Normal Linefeed (LNM). + * + * @vt: #P[Only IRM is supported.] CSI RM "Reset Mode" "CSI Pm l" "Set various terminal attributes." + * Supported param values by RM: + * + * | Param | Action | Support | + * | ----- | -------------------------------------- | ------- | + * | 2 | Keyboard Action Mode (KAM). Always on. | #N | + * | 4 | Replace Mode (IRM). (default) | #Y | + * | 12 | Send/receive (SRM). Always off. | #N | + * | 20 | Normal Linefeed (LNM). | #Y | + * + * + * FIXME: why is LNM commented out? + */ + public resetMode(params: IParams): boolean { + for (let i = 0; i < params.length; i++) { + switch (params.params[i]) { + case 4: + this._coreService.modes.insertMode = false; + break; + case 20: + this._optionsService.options.convertEol = false; + break; + } + } + return true; + } + + /** + * CSI ? Pm l + * DEC Private Mode Reset (DECRST). + * Ps = 1 -> Normal Cursor Keys (DECCKM). + * Ps = 2 -> Designate VT52 mode (DECANM). + * Ps = 3 -> 80 Column Mode (DECCOLM). + * Ps = 4 -> Jump (Fast) Scroll (DECSCLM). + * Ps = 5 -> Normal Video (DECSCNM). + * Ps = 6 -> Normal Cursor Mode (DECOM). + * Ps = 7 -> No Wraparound Mode (DECAWM). + * Ps = 8 -> No Auto-repeat Keys (DECARM). + * Ps = 9 -> Don't send Mouse X & Y on button press. + * Ps = 1 0 -> Hide toolbar (rxvt). + * Ps = 1 2 -> Stop Blinking Cursor (att610). + * Ps = 1 8 -> Don't print form feed (DECPFF). + * Ps = 1 9 -> Limit print to scrolling region (DECPEX). + * Ps = 2 5 -> Hide Cursor (DECTCEM). + * Ps = 3 0 -> Don't show scrollbar (rxvt). + * Ps = 3 5 -> Disable font-shifting functions (rxvt). + * Ps = 4 0 -> Disallow 80 -> 132 Mode. + * Ps = 4 1 -> No more(1) fix (see curses resource). + * Ps = 4 2 -> Disable Nation Replacement Character sets (DEC- + * NRCM). + * Ps = 4 4 -> Turn Off Margin Bell. + * Ps = 4 5 -> No Reverse-wraparound Mode. + * Ps = 4 6 -> Stop Logging. (This is normally disabled by a + * compile-time option). + * Ps = 4 7 -> Use Normal Screen Buffer. + * Ps = 6 6 -> Numeric keypad (DECNKM). + * Ps = 6 7 -> Backarrow key sends delete (DECBKM). + * Ps = 1 0 0 0 -> Don't send Mouse X & Y on button press and + * release. See the section Mouse Tracking. + * Ps = 1 0 0 1 -> Don't use Hilite Mouse Tracking. + * Ps = 1 0 0 2 -> Don't use Cell Motion Mouse Tracking. + * Ps = 1 0 0 3 -> Don't use All Motion Mouse Tracking. + * Ps = 1 0 0 4 -> Don't send FocusIn/FocusOut events. + * Ps = 1 0 0 5 -> Disable Extended Mouse Mode. + * Ps = 1 0 1 0 -> Don't scroll to bottom on tty output + * (rxvt). + * Ps = 1 0 1 1 -> Don't scroll to bottom on key press (rxvt). + * Ps = 1 0 3 4 -> Don't interpret "meta" key. (This disables + * the eightBitInput resource). + * Ps = 1 0 3 5 -> Disable special modifiers for Alt and Num- + * Lock keys. (This disables the numLock resource). + * Ps = 1 0 3 6 -> Don't send ESC when Meta modifies a key. + * (This disables the metaSendsEscape resource). + * Ps = 1 0 3 7 -> Send VT220 Remove from the editing-keypad + * Delete key. + * Ps = 1 0 3 9 -> Don't send ESC when Alt modifies a key. + * (This disables the altSendsEscape resource). + * Ps = 1 0 4 0 -> Do not keep selection when not highlighted. + * (This disables the keepSelection resource). + * Ps = 1 0 4 1 -> Use the PRIMARY selection. (This disables + * the selectToClipboard resource). + * Ps = 1 0 4 2 -> Disable Urgency window manager hint when + * Control-G is received. (This disables the bellIsUrgent + * resource). + * Ps = 1 0 4 3 -> Disable raising of the window when Control- + * G is received. (This disables the popOnBell resource). + * Ps = 1 0 4 7 -> Use Normal Screen Buffer, clearing screen + * first if in the Alternate Screen. (This may be disabled by + * the titeInhibit resource). + * Ps = 1 0 4 8 -> Restore cursor as in DECRC. (This may be + * disabled by the titeInhibit resource). + * Ps = 1 0 4 9 -> Use Normal Screen Buffer and restore cursor + * as in DECRC. (This may be disabled by the titeInhibit + * resource). This combines the effects of the 1 0 4 7 and 1 0 + * 4 8 modes. Use this with terminfo-based applications rather + * than the 4 7 mode. + * Ps = 1 0 5 0 -> Reset terminfo/termcap function-key mode. + * Ps = 1 0 5 1 -> Reset Sun function-key mode. + * Ps = 1 0 5 2 -> Reset HP function-key mode. + * Ps = 1 0 5 3 -> Reset SCO function-key mode. + * Ps = 1 0 6 0 -> Reset legacy keyboard emulation (X11R6). + * Ps = 1 0 6 1 -> Reset keyboard emulation to Sun/PC style. + * Ps = 2 0 0 4 -> Reset bracketed paste mode. + * + * @vt: #P[See below for supported modes.] CSI DECRST "DEC Private Reset Mode" "CSI ? Pm l" "Reset various terminal attributes." + * Supported param values by DECRST: + * + * | param | Action | Support | + * | ----- | ------------------------------------------------------- | ------- | + * | 1 | Normal Cursor Keys (DECCKM). | #Y | + * | 2 | Designate VT52 mode (DECANM). | #N | + * | 3 | 80 Column Mode (DECCOLM). | #B[Switches to old column width instead of 80.] | + * | 6 | Normal Cursor Mode (DECOM). | #Y | + * | 7 | No Wraparound Mode (DECAWM). | #Y | + * | 8 | No Auto-repeat Keys (DECARM). | #N | + * | 9 | Don't send Mouse X & Y on button press. | #Y | + * | 12 | Stop Blinking Cursor. | #Y | + * | 25 | Hide Cursor (DECTCEM). | #Y | + * | 45 | No reverse wrap-around. | #Y | + * | 47 | Use Normal Screen Buffer. | #Y | + * | 66 | Numeric keypad (DECNKM). | #Y | + * | 1000 | Don't send Mouse reports. | #Y | + * | 1002 | Don't use Cell Motion Mouse Tracking. | #Y | + * | 1003 | Don't use All Motion Mouse Tracking. | #Y | + * | 1004 | Don't send FocusIn/FocusOut events. | #Y | + * | 1005 | Disable UTF-8 Mouse Mode. | #N | + * | 1006 | Disable SGR Mouse Mode. | #Y | + * | 1015 | Disable urxvt Mouse Mode. | #N | + * | 1016 | Disable SGR-Pixels Mouse Mode. | #Y | + * | 1047 | Use Normal Screen Buffer (clearing screen if in alt). | #Y | + * | 1048 | Restore cursor as in DECRC. | #Y | + * | 1049 | Use Normal Screen Buffer and restore cursor. | #Y | + * | 2004 | Reset bracketed paste mode. | #Y | + * + * + * FIXME: DECCOLM is currently broken (already fixed in window options PR) + */ + public resetModePrivate(params: IParams): boolean { + for (let i = 0; i < params.length; i++) { + switch (params.params[i]) { + case 1: + this._coreService.decPrivateModes.applicationCursorKeys = false; + break; + case 3: + /** + * DECCOLM - 80 column mode. + * This is only active if 'SetWinLines' (24) is enabled + * through `options.windowsOptions`. + */ + if (this._optionsService.rawOptions.windowOptions.setWinLines) { + this._bufferService.resize(80, this._bufferService.rows); + this._onRequestReset.fire(); + } + break; + case 6: + this._coreService.decPrivateModes.origin = false; + this._setCursor(0, 0); + break; + case 7: + this._coreService.decPrivateModes.wraparound = false; + break; + case 12: + this._optionsService.options.cursorBlink = false; + break; + case 45: + this._coreService.decPrivateModes.reverseWraparound = false; + break; + case 66: + this._logService.debug('Switching back to normal keypad.'); + this._coreService.decPrivateModes.applicationKeypad = false; + this._onRequestSyncScrollBar.fire(); + break; + case 9: // X10 Mouse + case 1000: // vt200 mouse + case 1002: // button event mouse + case 1003: // any event mouse + this._coreMouseService.activeProtocol = 'NONE'; + break; + case 1004: // send focusin/focusout events + this._coreService.decPrivateModes.sendFocus = false; + break; + case 1005: // utf8 ext mode mouse - removed in #2507 + this._logService.debug('DECRST 1005 not supported (see #2507)'); + break; + case 1006: // sgr ext mode mouse + this._coreMouseService.activeEncoding = 'DEFAULT'; + break; + case 1015: // urxvt ext mode mouse - removed in #2507 + this._logService.debug('DECRST 1015 not supported (see #2507)'); + break; + case 1016: // sgr pixels mode mouse + this._coreMouseService.activeEncoding = 'DEFAULT'; + break; + case 25: // hide cursor + this._coreService.isCursorHidden = true; + break; + case 1048: // alt screen cursor + this.restoreCursor(); + break; + case 1049: // alt screen buffer cursor + // FALL-THROUGH + case 47: // normal screen buffer + case 1047: // normal screen buffer - clearing it first + // Ensure the selection manager has the correct buffer + this._bufferService.buffers.activateNormalBuffer(); + if (params.params[i] === 1049) { + this.restoreCursor(); + } + this._coreService.isCursorInitialized = true; + this._onRequestRefreshRows.fire(undefined); + this._onRequestSyncScrollBar.fire(); + break; + case 2004: // bracketed paste mode (https://cirw.in/blog/bracketed-paste) + this._coreService.decPrivateModes.bracketedPasteMode = false; + break; + case 2026: // synchronized output (https://github.com/contour-terminal/vt-extensions/blob/master/synchronized-output.md) + this._coreService.decPrivateModes.synchronizedOutput = false; + this._onRequestRefreshRows.fire(undefined); + break; + } + } + return true; + } + + /** + * CSI Ps $ p Request ANSI Mode (DECRQM). + * + * Reports CSI Ps; Pm $ y (DECRPM), where Ps is the mode number as in SM/RM, + * and Pm is the mode value: + * 0 - not recognized + * 1 - set + * 2 - reset + * 3 - permanently set + * 4 - permanently reset + * + * @vt: #Y CSI DECRQM "Request Mode" "CSI Ps $p" "Request mode state." + * Returns a report as `CSI Ps; Pm $ y` (DECRPM), where `Ps` is the mode number as in SM/RM + * or DECSET/DECRST, and `Pm` is the mode value: + * - 0: not recognized + * - 1: set + * - 2: reset + * - 3: permanently set + * - 4: permanently reset + * + * For modes not understood xterm.js always returns `notRecognized`. In general this means, + * that a certain operation mode is not implemented and cannot be used. + * + * Modes changing the active terminal buffer (47, 1047, 1049) are not subqueried + * and only report, whether the alternate buffer is set. + * + * Mouse encodings and mouse protocols are handled mutual exclusive, + * thus only one of each of those can be set at a given time. + * + * There is a chance, that some mode reports are not fully in line with xterm.js' behavior, + * e.g. if the default implementation already exposes a certain behavior. If you find + * discrepancies in the mode reports, please file a bug. + */ + public requestMode(params: IParams, ansi: boolean): boolean { + // return value as in DECRPM + const enum V { + NOT_RECOGNIZED = 0, + SET = 1, + RESET = 2, + PERMANENTLY_SET = 3, + PERMANENTLY_RESET = 4 + } + + // access helpers + const dm = this._coreService.decPrivateModes; + const { activeProtocol: mouseProtocol, activeEncoding: mouseEncoding } = this._coreMouseService; + const cs = this._coreService; + const { buffers, cols } = this._bufferService; + const { active, alt } = buffers; + const opts = this._optionsService.rawOptions; + + const f = (m: number, v: V): boolean => { + cs.triggerDataEvent(`${C0.ESC}[${ansi ? '' : '?'}${m};${v}$y`); + return true; + }; + const b2v = (value: boolean): V => value ? V.SET : V.RESET; + + const p = params.params[0]; + + if (ansi) { + if (p === 2) return f(p, V.PERMANENTLY_RESET); + if (p === 4) return f(p, b2v(cs.modes.insertMode)); + if (p === 12) return f(p, V.PERMANENTLY_SET); + if (p === 20) return f(p, b2v(opts.convertEol)); + return f(p, V.NOT_RECOGNIZED); + } + + if (p === 1) return f(p, b2v(dm.applicationCursorKeys)); + if (p === 3) return f(p, opts.windowOptions.setWinLines ? (cols === 80 ? V.RESET : cols === 132 ? V.SET : V.NOT_RECOGNIZED) : V.NOT_RECOGNIZED); + if (p === 6) return f(p, b2v(dm.origin)); + if (p === 7) return f(p, b2v(dm.wraparound)); + if (p === 8) return f(p, V.PERMANENTLY_SET); + if (p === 9) return f(p, b2v(mouseProtocol === 'X10')); + if (p === 12) return f(p, b2v(opts.cursorBlink)); + if (p === 25) return f(p, b2v(!cs.isCursorHidden)); + if (p === 45) return f(p, b2v(dm.reverseWraparound)); + if (p === 66) return f(p, b2v(dm.applicationKeypad)); + if (p === 67) return f(p, V.PERMANENTLY_RESET); + if (p === 1000) return f(p, b2v(mouseProtocol === 'VT200')); + if (p === 1002) return f(p, b2v(mouseProtocol === 'DRAG')); + if (p === 1003) return f(p, b2v(mouseProtocol === 'ANY')); + if (p === 1004) return f(p, b2v(dm.sendFocus)); + if (p === 1005) return f(p, V.PERMANENTLY_RESET); + if (p === 1006) return f(p, b2v(mouseEncoding === 'SGR')); + if (p === 1015) return f(p, V.PERMANENTLY_RESET); + if (p === 1016) return f(p, b2v(mouseEncoding === 'SGR_PIXELS')); + if (p === 1048) return f(p, V.SET); // xterm always returns SET here + if (p === 47 || p === 1047 || p === 1049) return f(p, b2v(active === alt)); + if (p === 2004) return f(p, b2v(dm.bracketedPasteMode)); + if (p === 2026) return f(p, b2v(dm.synchronizedOutput)); + return f(p, V.NOT_RECOGNIZED); + } + + /** + * Helper to write color information packed with color mode. + */ + private _updateAttrColor(color: number, mode: number, c1: number, c2: number, c3: number): number { + if (mode === 2) { + color |= Attributes.CM_RGB; + color &= ~Attributes.RGB_MASK; + color |= AttributeData.fromColorRGB([c1, c2, c3]); + } else if (mode === 5) { + color &= ~(Attributes.CM_MASK | Attributes.PCOLOR_MASK); + color |= Attributes.CM_P256 | (c1 & 0xff); + } + return color; + } + + /** + * Helper to extract and apply color params/subparams. + * Returns advance for params index. + */ + private _extractColor(params: IParams, pos: number, attr: IAttributeData): number { + // normalize params + // meaning: [target, CM, ign, val, val, val] + // RGB : [ 38/48, 2, ign, r, g, b] + // P256 : [ 38/48, 5, ign, v, ign, ign] + const accu = [0, 0, -1, 0, 0, 0]; + + // alignment placeholder for non color space sequences + let cSpace = 0; + + // return advance we took in params + let advance = 0; + + do { + accu[advance + cSpace] = params.params[pos + advance]; + if (params.hasSubParams(pos + advance)) { + const subparams = params.getSubParams(pos + advance)!; + let i = 0; + do { + if (accu[1] === 5) { + cSpace = 1; + } + accu[advance + i + 1 + cSpace] = subparams[i]; + } while (++i < subparams.length && i + advance + 1 + cSpace < accu.length); + break; + } + // exit early if can decide color mode with semicolons + if ((accu[1] === 5 && advance + cSpace >= 2) + || (accu[1] === 2 && advance + cSpace >= 5)) { + break; + } + // offset colorSpace slot for semicolon mode + if (accu[1]) { + cSpace = 1; + } + } while (++advance + pos < params.length && advance + cSpace < accu.length); + + // set default values to 0 + for (let i = 2; i < accu.length; ++i) { + if (accu[i] === -1) { + accu[i] = 0; + } + } + + // apply colors + switch (accu[0]) { + case 38: + attr.fg = this._updateAttrColor(attr.fg, accu[1], accu[3], accu[4], accu[5]); + break; + case 48: + attr.bg = this._updateAttrColor(attr.bg, accu[1], accu[3], accu[4], accu[5]); + break; + case 58: + attr.extended = attr.extended.clone(); + attr.extended.underlineColor = this._updateAttrColor(attr.extended.underlineColor, accu[1], accu[3], accu[4], accu[5]); + } + + return advance; + } + + /** + * SGR 4 subparams: + * 4:0 - equal to SGR 24 (turn off all underline) + * 4:1 - equal to SGR 4 (single underline) + * 4:2 - equal to SGR 21 (double underline) + * 4:3 - curly underline + * 4:4 - dotted underline + * 4:5 - dashed underline + */ + private _processUnderline(style: number, attr: IAttributeData): void { + // treat extended attrs as immutable, thus always clone from old one + // this is needed since the buffer only holds references to it + attr.extended = attr.extended.clone(); + + // default to 1 == single underline + if (!~style || style > 5) { + style = 1; + } + attr.extended.underlineStyle = style; + attr.fg |= FgFlags.UNDERLINE; + + // 0 deactivates underline + if (style === 0) { + attr.fg &= ~FgFlags.UNDERLINE; + } + + // update HAS_EXTENDED in BG + attr.updateExtended(); + } + + private _processSGR0(attr: IAttributeData): void { + attr.fg = DEFAULT_ATTR_DATA.fg; + attr.bg = DEFAULT_ATTR_DATA.bg; + attr.extended = attr.extended.clone(); + // Reset underline style and color. Note that we don't want to reset other + // fields such as the url id. + attr.extended.underlineStyle = UnderlineStyle.NONE; + attr.extended.underlineColor &= ~(Attributes.CM_MASK | Attributes.RGB_MASK); + attr.updateExtended(); + } + + /** + * CSI Pm m Character Attributes (SGR). + * + * @vt: #P[See below for supported attributes.] CSI SGR "Select Graphic Rendition" "CSI Pm m" "Set/Reset various text attributes." + * SGR selects one or more character attributes at the same time. Multiple params (up to 32) + * are applied in order from left to right. The changed attributes are applied to all new + * characters received. If you move characters in the viewport by scrolling or any other means, + * then the attributes move with the characters. + * + * Supported param values by SGR: + * + * | Param | Meaning | Support | + * | --------- | -------------------------------------------------------- | ------- | + * | 0 | Normal (default). Resets any other preceding SGR. | #Y | + * | 1 | Bold. (also see `options.drawBoldTextInBrightColors`) | #Y | + * | 2 | Faint, decreased intensity. | #Y | + * | 3 | Italic. | #Y | + * | 4 | Underlined (see below for style support). | #Y | + * | 5 | Slowly blinking. | #N | + * | 6 | Rapidly blinking. | #N | + * | 7 | Inverse. Flips foreground and background color. | #Y | + * | 8 | Invisible (hidden). | #Y | + * | 9 | Crossed-out characters (strikethrough). | #Y | + * | 21 | Doubly underlined. | #Y | + * | 22 | Normal (neither bold nor faint). | #Y | + * | 23 | No italic. | #Y | + * | 24 | Not underlined. | #Y | + * | 25 | Steady (not blinking). | #Y | + * | 27 | Positive (not inverse). | #Y | + * | 28 | Visible (not hidden). | #Y | + * | 29 | Not Crossed-out (strikethrough). | #Y | + * | 30 | Foreground color: Black. | #Y | + * | 31 | Foreground color: Red. | #Y | + * | 32 | Foreground color: Green. | #Y | + * | 33 | Foreground color: Yellow. | #Y | + * | 34 | Foreground color: Blue. | #Y | + * | 35 | Foreground color: Magenta. | #Y | + * | 36 | Foreground color: Cyan. | #Y | + * | 37 | Foreground color: White. | #Y | + * | 38 | Foreground color: Extended color. | #P[Support for RGB and indexed colors, see below.] | + * | 39 | Foreground color: Default (original). | #Y | + * | 40 | Background color: Black. | #Y | + * | 41 | Background color: Red. | #Y | + * | 42 | Background color: Green. | #Y | + * | 43 | Background color: Yellow. | #Y | + * | 44 | Background color: Blue. | #Y | + * | 45 | Background color: Magenta. | #Y | + * | 46 | Background color: Cyan. | #Y | + * | 47 | Background color: White. | #Y | + * | 48 | Background color: Extended color. | #P[Support for RGB and indexed colors, see below.] | + * | 49 | Background color: Default (original). | #Y | + * | 53 | Overlined. | #Y | + * | 55 | Not Overlined. | #Y | + * | 58 | Underline color: Extended color. | #P[Support for RGB and indexed colors, see below.] | + * | 90 - 97 | Bright foreground color (analogous to 30 - 37). | #Y | + * | 100 - 107 | Bright background color (analogous to 40 - 47). | #Y | + * + * Underline supports subparams to denote the style in the form `4 : x`: + * + * | x | Meaning | Support | + * | ------ | ------------------------------------------------------------- | ------- | + * | 0 | No underline. Same as `SGR 24 m`. | #Y | + * | 1 | Single underline. Same as `SGR 4 m`. | #Y | + * | 2 | Double underline. | #Y | + * | 3 | Curly underline. | #Y | + * | 4 | Dotted underline. | #Y | + * | 5 | Dashed underline. | #Y | + * | other | Single underline. Same as `SGR 4 m`. | #Y | + * + * Extended colors are supported for foreground (Ps=38), background (Ps=48) and underline (Ps=58) + * as follows: + * + * | Ps + 1 | Meaning | Support | + * | ------ | ------------------------------------------------------------- | ------- | + * | 0 | Implementation defined. | #N | + * | 1 | Transparent. | #N | + * | 2 | RGB color as `Ps ; 2 ; R ; G ; B` or `Ps : 2 : : R : G : B`. | #Y | + * | 3 | CMY color. | #N | + * | 4 | CMYK color. | #N | + * | 5 | Indexed (256 colors) as `Ps ; 5 ; INDEX` or `Ps : 5 : INDEX`. | #Y | + * + * + * FIXME: blinking is implemented in attrs, but not working in renderers? + * FIXME: remove dead branch for p=100 + */ + public charAttributes(params: IParams): boolean { + // Optimize a single SGR0. + if (params.length === 1 && params.params[0] === 0) { + this._processSGR0(this._curAttrData); + return true; + } + + const l = params.length; + let p; + const attr = this._curAttrData; + + for (let i = 0; i < l; i++) { + p = params.params[i]; + if (p >= 30 && p <= 37) { + // fg color 8 + attr.fg &= ~(Attributes.CM_MASK | Attributes.PCOLOR_MASK); + attr.fg |= Attributes.CM_P16 | (p - 30); + } else if (p >= 40 && p <= 47) { + // bg color 8 + attr.bg &= ~(Attributes.CM_MASK | Attributes.PCOLOR_MASK); + attr.bg |= Attributes.CM_P16 | (p - 40); + } else if (p >= 90 && p <= 97) { + // fg color 16 + attr.fg &= ~(Attributes.CM_MASK | Attributes.PCOLOR_MASK); + attr.fg |= Attributes.CM_P16 | (p - 90) | 8; + } else if (p >= 100 && p <= 107) { + // bg color 16 + attr.bg &= ~(Attributes.CM_MASK | Attributes.PCOLOR_MASK); + attr.bg |= Attributes.CM_P16 | (p - 100) | 8; + } else if (p === 0) { + // default + this._processSGR0(attr); + } else if (p === 1) { + // bold text + attr.fg |= FgFlags.BOLD; + } else if (p === 3) { + // italic text + attr.bg |= BgFlags.ITALIC; + } else if (p === 4) { + // underlined text + attr.fg |= FgFlags.UNDERLINE; + this._processUnderline(params.hasSubParams(i) ? params.getSubParams(i)![0] : UnderlineStyle.SINGLE, attr); + } else if (p === 5) { + // blink + attr.fg |= FgFlags.BLINK; + } else if (p === 7) { + // inverse and positive + // test with: echo -e '\e[31m\e[42mhello\e[7mworld\e[27mhi\e[m' + attr.fg |= FgFlags.INVERSE; + } else if (p === 8) { + // invisible + attr.fg |= FgFlags.INVISIBLE; + } else if (p === 9) { + // strikethrough + attr.fg |= FgFlags.STRIKETHROUGH; + } else if (p === 2) { + // dimmed text + attr.bg |= BgFlags.DIM; + } else if (p === 21) { + // double underline + this._processUnderline(UnderlineStyle.DOUBLE, attr); + } else if (p === 22) { + // not bold nor faint + attr.fg &= ~FgFlags.BOLD; + attr.bg &= ~BgFlags.DIM; + } else if (p === 23) { + // not italic + attr.bg &= ~BgFlags.ITALIC; + } else if (p === 24) { + // not underlined + attr.fg &= ~FgFlags.UNDERLINE; + this._processUnderline(UnderlineStyle.NONE, attr); + } else if (p === 25) { + // not blink + attr.fg &= ~FgFlags.BLINK; + } else if (p === 27) { + // not inverse + attr.fg &= ~FgFlags.INVERSE; + } else if (p === 28) { + // not invisible + attr.fg &= ~FgFlags.INVISIBLE; + } else if (p === 29) { + // not strikethrough + attr.fg &= ~FgFlags.STRIKETHROUGH; + } else if (p === 39) { + // reset fg + attr.fg &= ~(Attributes.CM_MASK | Attributes.RGB_MASK); + attr.fg |= DEFAULT_ATTR_DATA.fg & (Attributes.PCOLOR_MASK | Attributes.RGB_MASK); + } else if (p === 49) { + // reset bg + attr.bg &= ~(Attributes.CM_MASK | Attributes.RGB_MASK); + attr.bg |= DEFAULT_ATTR_DATA.bg & (Attributes.PCOLOR_MASK | Attributes.RGB_MASK); + } else if (p === 38 || p === 48 || p === 58) { + // fg color 256 and RGB + i += this._extractColor(params, i, attr); + } else if (p === 53) { + // overline + attr.bg |= BgFlags.OVERLINE; + } else if (p === 55) { + // not overline + attr.bg &= ~BgFlags.OVERLINE; + } else if (p === 59) { + attr.extended = attr.extended.clone(); + attr.extended.underlineColor = -1; + attr.updateExtended(); + } else if (p === 100) { // FIXME: dead branch, p=100 already handled above! + // reset fg/bg + attr.fg &= ~(Attributes.CM_MASK | Attributes.RGB_MASK); + attr.fg |= DEFAULT_ATTR_DATA.fg & (Attributes.PCOLOR_MASK | Attributes.RGB_MASK); + attr.bg &= ~(Attributes.CM_MASK | Attributes.RGB_MASK); + attr.bg |= DEFAULT_ATTR_DATA.bg & (Attributes.PCOLOR_MASK | Attributes.RGB_MASK); + } else { + this._logService.debug('Unknown SGR attribute: %d.', p); + } + } + return true; + } + + /** + * CSI Ps n Device Status Report (DSR). + * Ps = 5 -> Status Report. Result (``OK'') is + * CSI 0 n + * Ps = 6 -> Report Cursor Position (CPR) [row;column]. + * Result is + * CSI r ; c R + * CSI ? Ps n + * Device Status Report (DSR, DEC-specific). + * Ps = 6 -> Report Cursor Position (CPR) [row;column] as CSI + * ? r ; c R (assumes page is zero). + * Ps = 1 5 -> Report Printer status as CSI ? 1 0 n (ready). + * or CSI ? 1 1 n (not ready). + * Ps = 2 5 -> Report UDK status as CSI ? 2 0 n (unlocked) + * or CSI ? 2 1 n (locked). + * Ps = 2 6 -> Report Keyboard status as + * CSI ? 2 7 ; 1 ; 0 ; 0 n (North American). + * The last two parameters apply to VT400 & up, and denote key- + * board ready and LK01 respectively. + * Ps = 5 3 -> Report Locator status as + * CSI ? 5 3 n Locator available, if compiled-in, or + * CSI ? 5 0 n No Locator, if not. + * + * @vt: #Y CSI DSR "Device Status Report" "CSI Ps n" "Request cursor position (CPR) with `Ps` = 6." + */ + public deviceStatus(params: IParams): boolean { + switch (params.params[0]) { + case 5: + // status report + this._coreService.triggerDataEvent(`${C0.ESC}[0n`); + break; + case 6: + // cursor position + const y = this._activeBuffer.y + 1; + const x = this._activeBuffer.x + 1; + this._coreService.triggerDataEvent(`${C0.ESC}[${y};${x}R`); + break; + } + return true; + } + + // @vt: #P[Only CPR is supported.] CSI DECDSR "DEC Device Status Report" "CSI ? Ps n" "Only CPR is supported (same as DSR)." + public deviceStatusPrivate(params: IParams): boolean { + // modern xterm doesnt seem to + // respond to any of these except ?6, 6, and 5 + switch (params.params[0]) { + case 6: + // cursor position + const y = this._activeBuffer.y + 1; + const x = this._activeBuffer.x + 1; + this._coreService.triggerDataEvent(`${C0.ESC}[?${y};${x}R`); + break; + case 15: + // no printer + // this.handler(C0.ESC + '[?11n'); + break; + case 25: + // dont support user defined keys + // this.handler(C0.ESC + '[?21n'); + break; + case 26: + // north american keyboard + // this.handler(C0.ESC + '[?27;1;0;0n'); + break; + case 53: + // no dec locator/mouse + // this.handler(C0.ESC + '[?50n'); + break; + } + return true; + } + + /** + * CSI ! p Soft terminal reset (DECSTR). + * http://vt100.net/docs/vt220-rm/table4-10.html + * + * @vt: #Y CSI DECSTR "Soft Terminal Reset" "CSI ! p" "Reset several terminal attributes to initial state." + * There are two terminal reset sequences - RIS and DECSTR. While RIS performs almost a full + * terminal bootstrap, DECSTR only resets certain attributes. For most needs DECSTR should be + * sufficient. + * + * The following terminal attributes are reset to default values: + * - IRM is reset (dafault = false) + * - scroll margins are reset (default = viewport size) + * - erase attributes are reset to default + * - charsets are reset + * - DECSC data is reset to initial values + * - DECOM is reset to absolute mode + * + * + * FIXME: there are several more attributes missing (see VT520 manual) + */ + public softReset(params: IParams): boolean { + this._coreService.isCursorHidden = false; + this._onRequestSyncScrollBar.fire(); + this._activeBuffer.scrollTop = 0; + this._activeBuffer.scrollBottom = this._bufferService.rows - 1; + this._curAttrData = DEFAULT_ATTR_DATA.clone(); + this._coreService.reset(); + this._charsetService.reset(); + + // reset DECSC data + this._activeBuffer.savedX = 0; + this._activeBuffer.savedY = this._activeBuffer.ybase; + this._activeBuffer.savedCurAttrData.fg = this._curAttrData.fg; + this._activeBuffer.savedCurAttrData.bg = this._curAttrData.bg; + this._activeBuffer.savedCharset = this._charsetService.charset; + + // reset DECOM + this._coreService.decPrivateModes.origin = false; + return true; + } + + /** + * CSI Ps SP q Set cursor style (DECSCUSR, VT520). + * Ps = 0 -> reset to option. + * Ps = 1 -> blinking block (default). + * Ps = 2 -> steady block. + * Ps = 3 -> blinking underline. + * Ps = 4 -> steady underline. + * Ps = 5 -> blinking bar (xterm). + * Ps = 6 -> steady bar (xterm). + * + * @vt: #Y CSI DECSCUSR "Set Cursor Style" "CSI Ps SP q" "Set cursor style." + * Supported cursor styles: + * - 0: reset to option + * - empty, 1: blinking block + * - 2: steady block + * - 3: blinking underline + * - 4: steady underline + * - 5: blinking bar + * - 6: steady bar + */ + public setCursorStyle(params: IParams): boolean { + const param = params.length === 0 ? 1 : params.params[0]; + if (param === 0) { + this._coreService.decPrivateModes.cursorStyle = undefined; + this._coreService.decPrivateModes.cursorBlink = undefined; + } else { + switch (param) { + case 1: + case 2: + this._coreService.decPrivateModes.cursorStyle = 'block'; + break; + case 3: + case 4: + this._coreService.decPrivateModes.cursorStyle = 'underline'; + break; + case 5: + case 6: + this._coreService.decPrivateModes.cursorStyle = 'bar'; + break; + } + const isBlinking = param % 2 === 1; + this._coreService.decPrivateModes.cursorBlink = isBlinking; + } + return true; + } + + /** + * CSI Ps ; Ps r + * Set Scrolling Region [top;bottom] (default = full size of win- + * dow) (DECSTBM). + * + * @vt: #Y CSI DECSTBM "Set Top and Bottom Margin" "CSI Ps ; Ps r" "Set top and bottom margins of the viewport [top;bottom] (default = viewport size)." + */ + public setScrollRegion(params: IParams): boolean { + const top = params.params[0] || 1; + let bottom: number; + + if (params.length < 2 || (bottom = params.params[1]) > this._bufferService.rows || bottom === 0) { + bottom = this._bufferService.rows; + } + + if (bottom > top) { + this._activeBuffer.scrollTop = top - 1; + this._activeBuffer.scrollBottom = bottom - 1; + this._setCursor(0, 0); + } + return true; + } + + /** + * CSI Ps ; Ps ; Ps t - Various window manipulations and reports (xterm) + * + * Note: Only those listed below are supported. All others are left to integrators and + * need special treatment based on the embedding environment. + * + * Ps = 1 4 supported + * Report xterm text area size in pixels. + * Result is CSI 4 ; height ; width t + * Ps = 14 ; 2 not implemented + * Ps = 16 supported + * Report xterm character cell size in pixels. + * Result is CSI 6 ; height ; width t + * Ps = 18 supported + * Report the size of the text area in characters. + * Result is CSI 8 ; height ; width t + * Ps = 20 supported + * Report xterm window's icon label. + * Result is OSC L label ST + * Ps = 21 supported + * Report xterm window's title. + * Result is OSC l label ST + * Ps = 22 ; 0 -> Save xterm icon and window title on stack. supported + * Ps = 22 ; 1 -> Save xterm icon title on stack. supported + * Ps = 22 ; 2 -> Save xterm window title on stack. supported + * Ps = 23 ; 0 -> Restore xterm icon and window title from stack. supported + * Ps = 23 ; 1 -> Restore xterm icon title from stack. supported + * Ps = 23 ; 2 -> Restore xterm window title from stack. supported + * Ps >= 24 not implemented + */ + public windowOptions(params: IParams): boolean { + if (!paramToWindowOption(params.params[0], this._optionsService.rawOptions.windowOptions)) { + return true; + } + const second = (params.length > 1) ? params.params[1] : 0; + switch (params.params[0]) { + case 14: // GetWinSizePixels, returns CSI 4 ; height ; width t + if (second !== 2) { + this._onRequestWindowsOptionsReport.fire(WindowsOptionsReportType.GET_WIN_SIZE_PIXELS); + } + break; + case 16: // GetCellSizePixels, returns CSI 6 ; height ; width t + this._onRequestWindowsOptionsReport.fire(WindowsOptionsReportType.GET_CELL_SIZE_PIXELS); + break; + case 18: // GetWinSizeChars, returns CSI 8 ; height ; width t + if (this._bufferService) { + this._coreService.triggerDataEvent(`${C0.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`); + } + break; + case 22: // PushTitle + if (second === 0 || second === 2) { + this._windowTitleStack.push(this._windowTitle); + if (this._windowTitleStack.length > STACK_LIMIT) { + this._windowTitleStack.shift(); + } + } + if (second === 0 || second === 1) { + this._iconNameStack.push(this._iconName); + if (this._iconNameStack.length > STACK_LIMIT) { + this._iconNameStack.shift(); + } + } + break; + case 23: // PopTitle + if (second === 0 || second === 2) { + if (this._windowTitleStack.length) { + this.setTitle(this._windowTitleStack.pop()!); + } + } + if (second === 0 || second === 1) { + if (this._iconNameStack.length) { + this.setIconName(this._iconNameStack.pop()!); + } + } + break; + } + return true; + } + + + /** + * CSI s + * ESC 7 + * Save cursor (ANSI.SYS). + * + * @vt: #P[TODO...] CSI SCOSC "Save Cursor" "CSI s" "Save cursor position, charmap and text attributes." + * @vt: #Y ESC SC "Save Cursor" "ESC 7" "Save cursor position, charmap and text attributes." + */ + public saveCursor(params?: IParams): boolean { + this._activeBuffer.savedX = this._activeBuffer.x; + this._activeBuffer.savedY = this._activeBuffer.ybase + this._activeBuffer.y; + this._activeBuffer.savedCurAttrData.fg = this._curAttrData.fg; + this._activeBuffer.savedCurAttrData.bg = this._curAttrData.bg; + this._activeBuffer.savedCharset = this._charsetService.charset; + return true; + } + + + /** + * CSI u + * ESC 8 + * Restore cursor (ANSI.SYS). + * + * @vt: #P[TODO...] CSI SCORC "Restore Cursor" "CSI u" "Restore cursor position, charmap and text attributes." + * @vt: #Y ESC RC "Restore Cursor" "ESC 8" "Restore cursor position, charmap and text attributes." + */ + public restoreCursor(params?: IParams): boolean { + this._activeBuffer.x = this._activeBuffer.savedX || 0; + this._activeBuffer.y = Math.max(this._activeBuffer.savedY - this._activeBuffer.ybase, 0); + this._curAttrData.fg = this._activeBuffer.savedCurAttrData.fg; + this._curAttrData.bg = this._activeBuffer.savedCurAttrData.bg; + this._charsetService.charset = (this as any)._savedCharset; + if (this._activeBuffer.savedCharset) { + this._charsetService.charset = this._activeBuffer.savedCharset; + } + this._restrictCursor(); + return true; + } + + + /** + * OSC 2; ST (set window title) + * Proxy to set window title. + * + * @vt: #P[Icon name is not exposed.] OSC 0 "Set Windows Title and Icon Name" "OSC 0 ; Pt BEL" "Set window title and icon name." + * Icon name is not supported. For Window Title see below. + * + * @vt: #Y OSC 2 "Set Windows Title" "OSC 2 ; Pt BEL" "Set window title." + * xterm.js does not manipulate the title directly, instead exposes changes via the event + * `Terminal.onTitleChange`. + */ + public setTitle(data: string): boolean { + this._windowTitle = data; + this._onTitleChange.fire(data); + return true; + } + + /** + * OSC 1; ST + * Note: Icon name is not exposed. + */ + public setIconName(data: string): boolean { + this._iconName = data; + return true; + } + + /** + * OSC 4; ; ST (set ANSI color to ) + * + * @vt: #Y OSC 4 "Set ANSI color" "OSC 4 ; c ; spec BEL" "Change color number `c` to the color specified by `spec`." + * `c` is the color index between 0 and 255. The color format of `spec` is derived from + * `XParseColor` (see OSC 10 for supported formats). There may be multipe `c ; spec` pairs present + * in the same instruction. If `spec` contains `?` the terminal returns a sequence with the + * currently set color. + */ + public setOrReportIndexedColor(data: string): boolean { + const event: IColorEvent = []; + const slots = data.split(';'); + while (slots.length > 1) { + const idx = slots.shift() as string; + const spec = slots.shift() as string; + if (/^\d+$/.exec(idx)) { + const index = parseInt(idx); + if (isValidColorIndex(index)) { + if (spec === '?') { + event.push({ type: ColorRequestType.REPORT, index }); + } else { + const color = parseColor(spec); + if (color) { + event.push({ type: ColorRequestType.SET, index, color }); + } + } + } + } + } + if (event.length) { + this._onColor.fire(event); + } + return true; + } + + /** + * OSC 8 ; ; ST - create hyperlink + * OSC 8 ; ; ST - finish hyperlink + * + * Test case: + * + * ```sh + * printf '\e]8;;http://example.com\e\\This is a link\e]8;;\e\\\n' + * ``` + * + * @vt: #Y OSC 8 "Create hyperlink" "OSC 8 ; params ; uri BEL" "Create a hyperlink to `uri` using `params`." + * `uri` is a hyperlink starting with `http://`, `https://`, `ftp://`, `file://` or `mailto://`. `params` is an + * optional list of key=value assignments, separated by the : character. + * Example: `id=xyz123:foo=bar:baz=quux`. + * Currently only the id key is defined. Cells that share the same ID and URI share hover + * feedback. Use `OSC 8 ; ; BEL` to finish the current hyperlink. + */ + public setHyperlink(data: string): boolean { + // Arg parsing is special cases to support unencoded semi-colons in the URIs (#4944) + const idx = data.indexOf(';'); + if (idx === -1) { + // malformed sequence, just return as handled + return true; + } + const id = data.slice(0, idx).trim(); + const uri = data.slice(idx + 1); + if (uri) { + return this._createHyperlink(id, uri); + } + if (id.trim()) { + return false; + } + return this._finishHyperlink(); + } + + private _createHyperlink(params: string, uri: string): boolean { + // It's legal to open a new hyperlink without explicitly finishing the previous one + if (this._getCurrentLinkId()) { + this._finishHyperlink(); + } + const parsedParams = params.split(':'); + let id: string | undefined; + const idParamIndex = parsedParams.findIndex(e => e.startsWith('id=')); + if (idParamIndex !== -1) { + id = parsedParams[idParamIndex].slice(3) || undefined; + } + this._curAttrData.extended = this._curAttrData.extended.clone(); + this._curAttrData.extended.urlId = this._oscLinkService.registerLink({ id, uri }); + this._curAttrData.updateExtended(); + return true; + } + + private _finishHyperlink(): boolean { + this._curAttrData.extended = this._curAttrData.extended.clone(); + this._curAttrData.extended.urlId = 0; + this._curAttrData.updateExtended(); + return true; + } + + // special colors - OSC 10 | 11 | 12 + private _specialColors = [SpecialColorIndex.FOREGROUND, SpecialColorIndex.BACKGROUND, SpecialColorIndex.CURSOR]; + + /** + * Apply colors requests for special colors in OSC 10 | 11 | 12. + * Since these commands are stacking from multiple parameters, + * we handle them in a loop with an entry offset to `_specialColors`. + */ + private _setOrReportSpecialColor(data: string, offset: number): boolean { + const slots = data.split(';'); + for (let i = 0; i < slots.length; ++i, ++offset) { + if (offset >= this._specialColors.length) break; + if (slots[i] === '?') { + this._onColor.fire([{ type: ColorRequestType.REPORT, index: this._specialColors[offset] }]); + } else { + const color = parseColor(slots[i]); + if (color) { + this._onColor.fire([{ type: ColorRequestType.SET, index: this._specialColors[offset], color }]); + } + } + } + return true; + } + + /** + * OSC 10 ; | ST - set or query default foreground color + * + * @vt: #Y OSC 10 "Set or query default foreground color" "OSC 10 ; Pt BEL" "Set or query default foreground color." + * To set the color, the following color specification formats are supported: + * - `rgb://` for `, , ` in `h | hh | hhh | hhhh`, where + * `h` is a single hexadecimal digit (case insignificant). The different widths scale + * from 4 bit (`h`) to 16 bit (`hhhh`) and get converted to 8 bit (`hh`). + * - `#RGB` - 4 bits per channel, expanded to `#R0G0B0` + * - `#RRGGBB` - 8 bits per channel + * - `#RRRGGGBBB` - 12 bits per channel, truncated to `#RRGGBB` + * - `#RRRRGGGGBBBB` - 16 bits per channel, truncated to `#RRGGBB` + * + * **Note:** X11 named colors are currently unsupported. + * + * If `Pt` contains `?` instead of a color specification, the terminal + * returns a sequence with the current default foreground color + * (use that sequence to restore the color after changes). + * + * **Note:** Other than xterm, xterm.js does not support OSC 12 - 19. + * Therefore stacking multiple `Pt` separated by `;` only works for the first two entries. + */ + public setOrReportFgColor(data: string): boolean { + return this._setOrReportSpecialColor(data, 0); + } + + /** + * OSC 11 ; | ST - set or query default background color + * + * @vt: #Y OSC 11 "Set or query default background color" "OSC 11 ; Pt BEL" "Same as OSC 10, but for default background." + */ + public setOrReportBgColor(data: string): boolean { + return this._setOrReportSpecialColor(data, 1); + } + + /** + * OSC 12 ; | ST - set or query default cursor color + * + * @vt: #Y OSC 12 "Set or query default cursor color" "OSC 12 ; Pt BEL" "Same as OSC 10, but for default cursor color." + */ + public setOrReportCursorColor(data: string): boolean { + return this._setOrReportSpecialColor(data, 2); + } + + /** + * OSC 104 ; ST - restore ANSI color + * + * @vt: #Y OSC 104 "Reset ANSI color" "OSC 104 ; c BEL" "Reset color number `c` to themed color." + * `c` is the color index between 0 and 255. This function restores the default color for `c` as + * specified by the loaded theme. Any number of `c` parameters may be given. + * If no parameters are given, the entire indexed color table will be reset. + */ + public restoreIndexedColor(data: string): boolean { + if (!data) { + this._onColor.fire([{ type: ColorRequestType.RESTORE }]); + return true; + } + const event: IColorEvent = []; + const slots = data.split(';'); + for (let i = 0; i < slots.length; ++i) { + if (/^\d+$/.exec(slots[i])) { + const index = parseInt(slots[i]); + if (isValidColorIndex(index)) { + event.push({ type: ColorRequestType.RESTORE, index }); + } + } + } + if (event.length) { + this._onColor.fire(event); + } + return true; + } + + /** + * OSC 110 ST - restore default foreground color + * + * @vt: #Y OSC 110 "Restore default foreground color" "OSC 110 BEL" "Restore default foreground to themed color." + */ + public restoreFgColor(data: string): boolean { + this._onColor.fire([{ type: ColorRequestType.RESTORE, index: SpecialColorIndex.FOREGROUND }]); + return true; + } + + /** + * OSC 111 ST - restore default background color + * + * @vt: #Y OSC 111 "Restore default background color" "OSC 111 BEL" "Restore default background to themed color." + */ + public restoreBgColor(data: string): boolean { + this._onColor.fire([{ type: ColorRequestType.RESTORE, index: SpecialColorIndex.BACKGROUND }]); + return true; + } + + /** + * OSC 112 ST - restore default cursor color + * + * @vt: #Y OSC 112 "Restore default cursor color" "OSC 112 BEL" "Restore default cursor to themed color." + */ + public restoreCursorColor(data: string): boolean { + this._onColor.fire([{ type: ColorRequestType.RESTORE, index: SpecialColorIndex.CURSOR }]); + return true; + } + + /** + * ESC E + * C1.NEL + * DEC mnemonic: NEL (https://vt100.net/docs/vt510-rm/NEL) + * Moves cursor to first position on next line. + * + * @vt: #Y C1 NEL "Next Line" "\x85" "Move the cursor to the beginning of the next row." + * @vt: #Y ESC NEL "Next Line" "ESC E" "Move the cursor to the beginning of the next row." + */ + public nextLine(): boolean { + this._activeBuffer.x = 0; + this.index(); + return true; + } + + /** + * ESC = + * DEC mnemonic: DECKPAM (https://vt100.net/docs/vt510-rm/DECKPAM.html) + * Enables the numeric keypad to send application sequences to the host. + */ + public keypadApplicationMode(): boolean { + this._logService.debug('Serial port requested application keypad.'); + this._coreService.decPrivateModes.applicationKeypad = true; + this._onRequestSyncScrollBar.fire(); + return true; + } + + /** + * ESC > + * DEC mnemonic: DECKPNM (https://vt100.net/docs/vt510-rm/DECKPNM.html) + * Enables the keypad to send numeric characters to the host. + */ + public keypadNumericMode(): boolean { + this._logService.debug('Switching back to normal keypad.'); + this._coreService.decPrivateModes.applicationKeypad = false; + this._onRequestSyncScrollBar.fire(); + return true; + } + + /** + * ESC % @ + * ESC % G + * Select default character set. UTF-8 is not supported (string are unicode anyways) + * therefore ESC % G does the same. + */ + public selectDefaultCharset(): boolean { + this._charsetService.setgLevel(0); + this._charsetService.setgCharset(0, DEFAULT_CHARSET); // US (default) + return true; + } + + /** + * ESC ( C + * Designate G0 Character Set, VT100, ISO 2022. + * ESC ) C + * Designate G1 Character Set (ISO 2022, VT100). + * ESC * C + * Designate G2 Character Set (ISO 2022, VT220). + * ESC + C + * Designate G3 Character Set (ISO 2022, VT220). + * ESC - C + * Designate G1 Character Set (VT300). + * ESC . C + * Designate G2 Character Set (VT300). + * ESC / C + * Designate G3 Character Set (VT300). C = A -> ISO Latin-1 Supplemental. - Supported? + */ + public selectCharset(collectAndFlag: string): boolean { + if (collectAndFlag.length !== 2) { + this.selectDefaultCharset(); + return true; + } + if (collectAndFlag[0] === '/') { + return true; // TODO: Is this supported? + } + this._charsetService.setgCharset(GLEVEL[collectAndFlag[0]], CHARSETS[collectAndFlag[1]] || DEFAULT_CHARSET); + return true; + } + + /** + * ESC D + * C1.IND + * DEC mnemonic: IND (https://vt100.net/docs/vt510-rm/IND.html) + * Moves the cursor down one line in the same column. + * + * @vt: #Y C1 IND "Index" "\x84" "Move the cursor one line down scrolling if needed." + * @vt: #Y ESC IND "Index" "ESC D" "Move the cursor one line down scrolling if needed." + */ + public index(): boolean { + this._restrictCursor(); + this._activeBuffer.y++; + if (this._activeBuffer.y === this._activeBuffer.scrollBottom + 1) { + this._activeBuffer.y--; + this._bufferService.scroll(this._eraseAttrData()); + } else if (this._activeBuffer.y >= this._bufferService.rows) { + this._activeBuffer.y = this._bufferService.rows - 1; + } + this._restrictCursor(); + return true; + } + + /** + * ESC H + * C1.HTS + * DEC mnemonic: HTS (https://vt100.net/docs/vt510-rm/HTS.html) + * Sets a horizontal tab stop at the column position indicated by + * the value of the active column when the terminal receives an HTS. + * + * @vt: #Y C1 HTS "Horizontal Tabulation Set" "\x88" "Places a tab stop at the current cursor position." + * @vt: #Y ESC HTS "Horizontal Tabulation Set" "ESC H" "Places a tab stop at the current cursor position." + */ + public tabSet(): boolean { + this._activeBuffer.tabs[this._activeBuffer.x] = true; + return true; + } + + /** + * ESC M + * C1.RI + * DEC mnemonic: HTS + * Moves the cursor up one line in the same column. If the cursor is at the top margin, + * the page scrolls down. + * + * @vt: #Y ESC IR "Reverse Index" "ESC M" "Move the cursor one line up scrolling if needed." + */ + public reverseIndex(): boolean { + this._restrictCursor(); + if (this._activeBuffer.y === this._activeBuffer.scrollTop) { + // possibly move the code below to term.reverseScroll(); + // test: echo -ne '\e[1;1H\e[44m\eM\e[0m' + // blankLine(true) is xterm/linux behavior + const scrollRegionHeight = this._activeBuffer.scrollBottom - this._activeBuffer.scrollTop; + this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase + this._activeBuffer.y, scrollRegionHeight, 1); + this._activeBuffer.lines.set(this._activeBuffer.ybase + this._activeBuffer.y, this._activeBuffer.getBlankLine(this._eraseAttrData())); + this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom); + } else { + this._activeBuffer.y--; + this._restrictCursor(); // quickfix to not run out of bounds + } + return true; + } + + /** + * ESC c + * DEC mnemonic: RIS (https://vt100.net/docs/vt510-rm/RIS.html) + * Reset to initial state. + */ + public fullReset(): boolean { + this._parser.reset(); + this._onRequestReset.fire(); + return true; + } + + public reset(): void { + this._curAttrData = DEFAULT_ATTR_DATA.clone(); + this._eraseAttrDataInternal = DEFAULT_ATTR_DATA.clone(); + } + + /** + * back_color_erase feature for xterm. + */ + private _eraseAttrData(): IAttributeData { + this._eraseAttrDataInternal.bg &= ~(Attributes.CM_MASK | 0xFFFFFF); + this._eraseAttrDataInternal.bg |= this._curAttrData.bg & ~0xFC000000; + return this._eraseAttrDataInternal; + } + + /** + * ESC n + * ESC o + * ESC | + * ESC } + * ESC ~ + * DEC mnemonic: LS (https://vt100.net/docs/vt510-rm/LS.html) + * When you use a locking shift, the character set remains in GL or GR until + * you use another locking shift. (partly supported) + */ + public setgLevel(level: number): boolean { + this._charsetService.setgLevel(level); + return true; + } + + /** + * ESC # 8 + * DEC mnemonic: DECALN (https://vt100.net/docs/vt510-rm/DECALN.html) + * This control function fills the complete screen area with + * a test pattern (E) used for adjusting screen alignment. + * + * @vt: #Y ESC DECALN "Screen Alignment Pattern" "ESC # 8" "Fill viewport with a test pattern (E)." + */ + public screenAlignmentPattern(): boolean { + // prepare cell data + const cell = new CellData(); + cell.content = 1 << Content.WIDTH_SHIFT | 'E'.charCodeAt(0); + cell.fg = this._curAttrData.fg; + cell.bg = this._curAttrData.bg; + + + this._setCursor(0, 0); + for (let yOffset = 0; yOffset < this._bufferService.rows; ++yOffset) { + const row = this._activeBuffer.ybase + this._activeBuffer.y + yOffset; + const line = this._activeBuffer.lines.get(row); + if (line) { + line.fill(cell); + line.isWrapped = false; + } + } + this._dirtyRowTracker.markAllDirty(); + this._setCursor(0, 0); + return true; + } + + + /** + * DCS $ q Pt ST + * DECRQSS (https://vt100.net/docs/vt510-rm/DECRQSS.html) + * Request Status String (DECRQSS), VT420 and up. + * Response: DECRPSS (https://vt100.net/docs/vt510-rm/DECRPSS.html) + * + * @vt: #P[Limited support, see below.] DCS DECRQSS "Request Selection or Setting" "DCS $ q Pt ST" "Request several terminal settings." + * Response is in the form `ESC P 1 $ r Pt ST` for valid requests, where `Pt` contains the + * corresponding CSI string, `ESC P 0 ST` for invalid requests. + * + * Supported requests and responses: + * + * | Type | Request | Response (`Pt`) | + * | -------------------------------- | ----------------- | ----------------------------------------------------- | + * | Graphic Rendition (SGR) | `DCS $ q m ST` | always reporting `0m` (currently broken) | + * | Top and Bottom Margins (DECSTBM) | `DCS $ q r ST` | `Ps ; Ps r` | + * | Cursor Style (DECSCUSR) | `DCS $ q SP q ST` | `Ps SP q` | + * | Protection Attribute (DECSCA) | `DCS $ q " q ST` | `Ps " q` (DECSCA 2 is reported as Ps = 0) | + * | Conformance Level (DECSCL) | `DCS $ q " p ST` | always reporting `61 ; 1 " p` (DECSCL is unsupported) | + * + * + * TODO: + * - fix SGR report + * - either check which conformance is better suited or remove the report completely + * --> we are currently a mixture of all up to VT400 but dont follow anyone strictly + */ + public requestStatusString(data: string, params: IParams): boolean { + const f = (s: string): boolean => { + this._coreService.triggerDataEvent(`${C0.ESC}${s}${C0.ESC}\\`); + return true; + }; + + // access helpers + const b = this._bufferService.buffer; + const opts = this._optionsService.rawOptions; + const STYLES: { [key: string]: number } = { 'block': 2, 'underline': 4, 'bar': 6 }; + + if (data === '"q') return f(`P1$r${this._curAttrData.isProtected() ? 1 : 0}"q`); + if (data === '"p') return f(`P1$r61;1"p`); + if (data === 'r') return f(`P1$r${b.scrollTop + 1};${b.scrollBottom + 1}r`); + // FIXME: report real SGR settings instead of 0m + if (data === 'm') return f(`P1$r0m`); + if (data === ' q') return f(`P1$r${STYLES[opts.cursorStyle] - (opts.cursorBlink ? 1 : 0)} q`); + return f(`P0$r`); + } + + public markRangeDirty(y1: number, y2: number): void { + this._dirtyRowTracker.markRangeDirty(y1, y2); + } +} + +export interface IDirtyRowTracker { + readonly start: number; + readonly end: number; + + clearRange(): void; + markDirty(y: number): void; + markRangeDirty(y1: number, y2: number): void; + markAllDirty(): void; +} + +class DirtyRowTracker implements IDirtyRowTracker { + public start!: number; + public end!: number; + + constructor( + @IBufferService private readonly _bufferService: IBufferService + ) { + this.clearRange(); + } + + public clearRange(): void { + this.start = this._bufferService.buffer.y; + this.end = this._bufferService.buffer.y; + } + + public markDirty(y: number): void { + if (y < this.start) { + this.start = y; + } else if (y > this.end) { + this.end = y; + } + } + + public markRangeDirty(y1: number, y2: number): void { + if (y1 > y2) { + $temp = y1; + y1 = y2; + y2 = $temp; + } + if (y1 < this.start) { + this.start = y1; + } + if (y2 > this.end) { + this.end = y2; + } + } + + public markAllDirty(): void { + this.markRangeDirty(0, this._bufferService.rows - 1); + } +} + +export function isValidColorIndex(value: number): value is ColorIndex { + return 0 <= value && value < 256; +} diff --git a/node_modules/@xterm/xterm/src/common/MultiKeyMap.ts b/node_modules/@xterm/xterm/src/common/MultiKeyMap.ts new file mode 100644 index 0000000..6287a8f --- /dev/null +++ b/node_modules/@xterm/xterm/src/common/MultiKeyMap.ts @@ -0,0 +1,42 @@ +/** + * Copyright (c) 2022 The xterm.js authors. All rights reserved. + * @license MIT + */ + +export class TwoKeyMap { + private _data: { [bg: string | number]: { [fg: string | number]: TValue | undefined } | undefined } = {}; + + public set(first: TFirst, second: TSecond, value: TValue): void { + if (!this._data[first]) { + this._data[first] = {}; + } + this._data[first as string | number]![second] = value; + } + + public get(first: TFirst, second: TSecond): TValue | undefined { + return this._data[first as string | number] ? this._data[first as string | number]![second] : undefined; + } + + public clear(): void { + this._data = {}; + } +} + +export class FourKeyMap { + private _data: TwoKeyMap> = new TwoKeyMap(); + + public set(first: TFirst, second: TSecond, third: TThird, fourth: TFourth, value: TValue): void { + if (!this._data.get(first, second)) { + this._data.set(first, second, new TwoKeyMap()); + } + this._data.get(first, second)!.set(third, fourth, value); + } + + public get(first: TFirst, second: TSecond, third: TThird, fourth: TFourth): TValue | undefined { + return this._data.get(first, second)?.get(third, fourth); + } + + public clear(): void { + this._data.clear(); + } +} diff --git a/node_modules/@xterm/xterm/src/common/Platform.ts b/node_modules/@xterm/xterm/src/common/Platform.ts new file mode 100644 index 0000000..4102f20 --- /dev/null +++ b/node_modules/@xterm/xterm/src/common/Platform.ts @@ -0,0 +1,44 @@ +/** + * Copyright (c) 2016 The xterm.js authors. All rights reserved. + * @license MIT + */ + +interface INavigator { + userAgent: string; + language: string; + platform: string; +} + +// We're declaring a navigator global here as we expect it in all runtimes (node and browser), but +// we want this module to live in common. +declare const navigator: INavigator; +declare const process: unknown; + +export const isNode = (typeof process !== 'undefined' && 'title' in (process as any)) ? true : false; +const userAgent = (isNode) ? 'node' : navigator.userAgent; +const platform = (isNode) ? 'node' : navigator.platform; + +export const isFirefox = userAgent.includes('Firefox'); +export const isLegacyEdge = userAgent.includes('Edge'); +export const isSafari = /^((?!chrome|android).)*safari/i.test(userAgent); +export function getSafariVersion(): number { + if (!isSafari) { + return 0; + } + const majorVersion = userAgent.match(/Version\/(\d+)/); + if (majorVersion === null || majorVersion.length < 2) { + return 0; + } + return parseInt(majorVersion[1]); +} + +// Find the users platform. We use this to interpret the meta key +// and ISO third level shifts. +// http://stackoverflow.com/q/19877924/577598 +export const isMac = ['Macintosh', 'MacIntel', 'MacPPC', 'Mac68K'].includes(platform); +export const isIpad = platform === 'iPad'; +export const isIphone = platform === 'iPhone'; +export const isWindows = ['Windows', 'Win16', 'Win32', 'WinCE'].includes(platform); +export const isLinux = platform.indexOf('Linux') >= 0; +// Note that when this is true, isLinux will also be true. +export const isChromeOS = /\bCrOS\b/.test(userAgent); diff --git a/node_modules/@xterm/xterm/src/common/SortedList.ts b/node_modules/@xterm/xterm/src/common/SortedList.ts new file mode 100644 index 0000000..82b6dfa --- /dev/null +++ b/node_modules/@xterm/xterm/src/common/SortedList.ts @@ -0,0 +1,194 @@ +/** + * Copyright (c) 2022 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { IdleTaskQueue } from 'common/TaskQueue'; + +// Work variables to avoid garbage collection. +let i = 0; + +/** + * A generic list that is maintained in sorted order and allows values with duplicate keys. Deferred + * batch insertion and deletion is used to significantly reduce the time it takes to insert and + * delete a large amount of items in succession. This list is based on binary search and as such + * locating a key will take O(log n) amortized, this includes the by key iterator. + */ +export class SortedList { + private _array: T[] = []; + + private readonly _insertedValues: T[] = []; + private readonly _flushInsertedTask = new IdleTaskQueue(); + private _isFlushingInserted = false; + + private readonly _deletedIndices: number[] = []; + private readonly _flushDeletedTask = new IdleTaskQueue(); + private _isFlushingDeleted = false; + + constructor( + private readonly _getKey: (value: T) => number + ) { + } + + public clear(): void { + this._array.length = 0; + this._insertedValues.length = 0; + this._flushInsertedTask.clear(); + this._isFlushingInserted = false; + this._deletedIndices.length = 0; + this._flushDeletedTask.clear(); + this._isFlushingDeleted = false; + } + + public insert(value: T): void { + this._flushCleanupDeleted(); + if (this._insertedValues.length === 0) { + this._flushInsertedTask.enqueue(() => this._flushInserted()); + } + this._insertedValues.push(value); + } + + private _flushInserted(): void { + const sortedAddedValues = this._insertedValues.sort((a, b) => this._getKey(a) - this._getKey(b)); + let sortedAddedValuesIndex = 0; + let arrayIndex = 0; + + const newArray = new Array(this._array.length + this._insertedValues.length); + + for (let newArrayIndex = 0; newArrayIndex < newArray.length; newArrayIndex++) { + if (arrayIndex >= this._array.length || this._getKey(sortedAddedValues[sortedAddedValuesIndex]) <= this._getKey(this._array[arrayIndex])) { + newArray[newArrayIndex] = sortedAddedValues[sortedAddedValuesIndex]; + sortedAddedValuesIndex++; + } else { + newArray[newArrayIndex] = this._array[arrayIndex++]; + } + } + + this._array = newArray; + this._insertedValues.length = 0; + } + + private _flushCleanupInserted(): void { + if (!this._isFlushingInserted && this._insertedValues.length > 0) { + this._flushInsertedTask.flush(); + } + } + + public delete(value: T): boolean { + this._flushCleanupInserted(); + if (this._array.length === 0) { + return false; + } + const key = this._getKey(value); + if (key === undefined) { + return false; + } + i = this._search(key); + if (i === -1) { + return false; + } + if (this._getKey(this._array[i]) !== key) { + return false; + } + do { + if (this._array[i] === value) { + if (this._deletedIndices.length === 0) { + this._flushDeletedTask.enqueue(() => this._flushDeleted()); + } + this._deletedIndices.push(i); + return true; + } + } while (++i < this._array.length && this._getKey(this._array[i]) === key); + return false; + } + + private _flushDeleted(): void { + this._isFlushingDeleted = true; + const sortedDeletedIndices = this._deletedIndices.sort((a, b) => a - b); + let sortedDeletedIndicesIndex = 0; + const newArray = new Array(this._array.length - sortedDeletedIndices.length); + let newArrayIndex = 0; + for (let i = 0; i < this._array.length; i++) { + if (sortedDeletedIndices[sortedDeletedIndicesIndex] === i) { + sortedDeletedIndicesIndex++; + } else { + newArray[newArrayIndex++] = this._array[i]; + } + } + this._array = newArray; + this._deletedIndices.length = 0; + this._isFlushingDeleted = false; + } + + private _flushCleanupDeleted(): void { + if (!this._isFlushingDeleted && this._deletedIndices.length > 0) { + this._flushDeletedTask.flush(); + } + } + + public *getKeyIterator(key: number): IterableIterator { + this._flushCleanupInserted(); + this._flushCleanupDeleted(); + if (this._array.length === 0) { + return; + } + i = this._search(key); + if (i < 0 || i >= this._array.length) { + return; + } + if (this._getKey(this._array[i]) !== key) { + return; + } + do { + yield this._array[i]; + } while (++i < this._array.length && this._getKey(this._array[i]) === key); + } + + public forEachByKey(key: number, callback: (value: T) => void): void { + this._flushCleanupInserted(); + this._flushCleanupDeleted(); + if (this._array.length === 0) { + return; + } + i = this._search(key); + if (i < 0 || i >= this._array.length) { + return; + } + if (this._getKey(this._array[i]) !== key) { + return; + } + do { + callback(this._array[i]); + } while (++i < this._array.length && this._getKey(this._array[i]) === key); + } + + public values(): IterableIterator { + this._flushCleanupInserted(); + this._flushCleanupDeleted(); + // Duplicate the array to avoid issues when _array changes while iterating + return [...this._array].values(); + } + + private _search(key: number): number { + let min = 0; + let max = this._array.length - 1; + while (max >= min) { + let mid = (min + max) >> 1; + const midKey = this._getKey(this._array[mid]); + if (midKey > key) { + max = mid - 1; + } else if (midKey < key) { + min = mid + 1; + } else { + // key in list, walk to lowest duplicate + while (mid > 0 && this._getKey(this._array[mid - 1]) === key) { + mid--; + } + return mid; + } + } + // key not in list + // still return closest min (also used as insert position) + return min; + } +} diff --git a/node_modules/@xterm/xterm/src/common/TaskQueue.ts b/node_modules/@xterm/xterm/src/common/TaskQueue.ts new file mode 100644 index 0000000..40cddff --- /dev/null +++ b/node_modules/@xterm/xterm/src/common/TaskQueue.ts @@ -0,0 +1,166 @@ +/** + * Copyright (c) 2022 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { isNode } from 'common/Platform'; + +interface ITaskQueue { + /** + * Adds a task to the queue which will run in a future idle callback. + * To avoid perceivable stalls on the mainthread, tasks with heavy workload + * should split their work into smaller pieces and return `true` to get + * called again until the work is done (on falsy return value). + */ + enqueue(task: () => boolean | void): void; + + /** + * Flushes the queue, running all remaining tasks synchronously. + */ + flush(): void; + + /** + * Clears any remaining tasks from the queue, these will not be run. + */ + clear(): void; +} + +interface ITaskDeadline { + timeRemaining(): number; +} +type CallbackWithDeadline = (deadline: ITaskDeadline) => void; + +abstract class TaskQueue implements ITaskQueue { + private _tasks: (() => boolean | void)[] = []; + private _idleCallback?: number; + private _i = 0; + + protected abstract _requestCallback(callback: CallbackWithDeadline): number; + protected abstract _cancelCallback(identifier: number): void; + + public enqueue(task: () => boolean | void): void { + this._tasks.push(task); + this._start(); + } + + public flush(): void { + while (this._i < this._tasks.length) { + if (!this._tasks[this._i]()) { + this._i++; + } + } + this.clear(); + } + + public clear(): void { + if (this._idleCallback) { + this._cancelCallback(this._idleCallback); + this._idleCallback = undefined; + } + this._i = 0; + this._tasks.length = 0; + } + + private _start(): void { + if (!this._idleCallback) { + this._idleCallback = this._requestCallback(this._process.bind(this)); + } + } + + private _process(deadline: ITaskDeadline): void { + this._idleCallback = undefined; + let taskDuration = 0; + let longestTask = 0; + let lastDeadlineRemaining = deadline.timeRemaining(); + let deadlineRemaining = 0; + while (this._i < this._tasks.length) { + taskDuration = performance.now(); + if (!this._tasks[this._i]()) { + this._i++; + } + // other than performance.now, performance.now might not be stable (changes on wall clock + // changes), this is not an issue here as a clock change during a short running task is very + // unlikely in case it still happened and leads to negative duration, simply assume 1 msec + taskDuration = Math.max(1, performance.now() - taskDuration); + longestTask = Math.max(taskDuration, longestTask); + // Guess the following task will take a similar time to the longest task in this batch, allow + // additional room to try avoid exceeding the deadline + deadlineRemaining = deadline.timeRemaining(); + if (longestTask * 1.5 > deadlineRemaining) { + // Warn when the time exceeding the deadline is over 20ms, if this happens in practice the + // task should be split into sub-tasks to ensure the UI remains responsive. + if (lastDeadlineRemaining - taskDuration < -20) { + console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(lastDeadlineRemaining - taskDuration))}ms`); + } + this._start(); + return; + } + lastDeadlineRemaining = deadlineRemaining; + } + this.clear(); + } +} + +/** + * A queue of that runs tasks over several tasks via setTimeout, trying to maintain above 60 frames + * per second. The tasks will run in the order they are enqueued, but they will run some time later, + * and care should be taken to ensure they're non-urgent and will not introduce race conditions. + */ +export class PriorityTaskQueue extends TaskQueue { + protected _requestCallback(callback: CallbackWithDeadline): number { + return setTimeout(() => callback(this._createDeadline(16))); + } + + protected _cancelCallback(identifier: number): void { + clearTimeout(identifier); + } + + private _createDeadline(duration: number): ITaskDeadline { + const end = performance.now() + duration; + return { + timeRemaining: () => Math.max(0, end - performance.now()) + }; + } +} + +class IdleTaskQueueInternal extends TaskQueue { + protected _requestCallback(callback: IdleRequestCallback): number { + return requestIdleCallback(callback); + } + + protected _cancelCallback(identifier: number): void { + cancelIdleCallback(identifier); + } +} + +/** + * A queue of that runs tasks over several idle callbacks, trying to respect the idle callback's + * deadline given by the environment. The tasks will run in the order they are enqueued, but they + * will run some time later, and care should be taken to ensure they're non-urgent and will not + * introduce race conditions. + * + * This reverts to a {@link PriorityTaskQueue} if the environment does not support idle callbacks. + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +export const IdleTaskQueue = (!isNode && 'requestIdleCallback' in window) ? IdleTaskQueueInternal : PriorityTaskQueue; + +/** + * An object that tracks a single debounced task that will run on the next idle frame. When called + * multiple times, only the last set task will run. + */ +export class DebouncedIdleTask { + private _queue: ITaskQueue; + + constructor() { + this._queue = new IdleTaskQueue(); + } + + public set(task: () => boolean | void): void { + this._queue.clear(); + this._queue.enqueue(task); + } + + public flush(): void { + this._queue.flush(); + } +} diff --git a/node_modules/@xterm/xterm/src/common/TypedArrayUtils.ts b/node_modules/@xterm/xterm/src/common/TypedArrayUtils.ts new file mode 100644 index 0000000..f3bacd5 --- /dev/null +++ b/node_modules/@xterm/xterm/src/common/TypedArrayUtils.ts @@ -0,0 +1,17 @@ +/** + * Copyright (c) 2018 The xterm.js authors. All rights reserved. + * @license MIT + */ + +export type TypedArray = Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Int8Array | Int16Array | Int32Array | Float32Array | Float64Array; + +/** + * Concat two typed arrays `a` and `b`. + * Returns a new typed array. + */ +export function concat(a: T, b: T): T { + const result = new (a.constructor as any)(a.length + b.length); + result.set(a); + result.set(b, a.length); + return result; +} diff --git a/node_modules/@xterm/xterm/src/common/Types.ts b/node_modules/@xterm/xterm/src/common/Types.ts new file mode 100644 index 0000000..3c147b8 --- /dev/null +++ b/node_modules/@xterm/xterm/src/common/Types.ts @@ -0,0 +1,552 @@ +/** + * Copyright (c) 2018 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { IDeleteEvent, IInsertEvent } from 'common/CircularList'; +import { Attributes, UnderlineStyle } from 'common/buffer/Constants'; // eslint-disable-line no-unused-vars +import { IBufferSet } from 'common/buffer/Types'; +import { IParams } from 'common/parser/Types'; +import { ICoreMouseService, ICoreService, IOptionsService, IUnicodeService } from 'common/services/Services'; +import { IFunctionIdentifier, ITerminalOptions as IPublicTerminalOptions } from '@xterm/xterm'; +import type { Emitter, Event } from 'vs/base/common/event'; + +export interface ICoreTerminal { + coreMouseService: ICoreMouseService; + coreService: ICoreService; + optionsService: IOptionsService; + unicodeService: IUnicodeService; + buffers: IBufferSet; + options: Required; + registerCsiHandler(id: IFunctionIdentifier, callback: (params: IParams) => boolean | Promise): IDisposable; + registerDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: IParams) => boolean | Promise): IDisposable; + registerEscHandler(id: IFunctionIdentifier, callback: () => boolean | Promise): IDisposable; + registerOscHandler(ident: number, callback: (data: string) => boolean | Promise): IDisposable; +} + +export interface IDisposable { + dispose(): void; +} + +// TODO: The options that are not in the public API should be reviewed +export interface ITerminalOptions extends IPublicTerminalOptions { + [key: string]: any; + cancelEvents?: boolean; + convertEol?: boolean; + termName?: string; +} + +export type CursorStyle = 'block' | 'underline' | 'bar'; + +export type CursorInactiveStyle = 'outline' | 'block' | 'bar' | 'underline' | 'none'; + +export type XtermListener = (...args: any[]) => void; + +/** + * A keyboard event interface which does not depend on the DOM, KeyboardEvent implicitly extends + * this event. + */ +export interface IKeyboardEvent { + altKey: boolean; + ctrlKey: boolean; + shiftKey: boolean; + metaKey: boolean; + /** @deprecated See KeyboardEvent.keyCode */ + keyCode: number; + key: string; + type: string; + code: string; +} + +export interface IScrollEvent { + position: number; +} + +export interface ICircularList { + length: number; + maxLength: number; + isFull: boolean; + + onDeleteEmitter: Emitter; + onDelete: Event; + onInsertEmitter: Emitter; + onInsert: Event; + onTrimEmitter: Emitter; + onTrim: Event; + + get(index: number): T | undefined; + set(index: number, value: T): void; + push(value: T): void; + recycle(): T; + pop(): T | undefined; + splice(start: number, deleteCount: number, ...items: T[]): void; + trimStart(count: number): void; + shiftElements(start: number, count: number, offset: number): void; +} + +export const enum KeyboardResultType { + SEND_KEY, + SELECT_ALL, + PAGE_UP, + PAGE_DOWN +} + +export interface IKeyboardResult { + type: KeyboardResultType; + cancel: boolean; + key: string | undefined; +} + +export interface ICharset { + [key: string]: string | undefined; +} + +export type CharData = [number, string, number, number]; + +export interface IColor { + readonly css: string; + readonly rgba: number; // 32-bit int with rgba in each byte +} +export type IColorRGB = [number, number, number]; + +export interface IExtendedAttrs { + ext: number; + underlineStyle: UnderlineStyle; + underlineColor: number; + underlineVariantOffset: number; + urlId: number; + clone(): IExtendedAttrs; + isEmpty(): boolean; +} + +/** + * Tracks the current hyperlink. Since these are treated as extended attirbutes, these get passed on + * to the linkifier when anything is printed. Doing it this way ensures that even when the cursor + * moves around unexpectedly the link is tracked, as opposed to using a start position and + * finalizing it at the end. + */ +export interface IOscLinkData { + id?: string; + uri: string; +} + +/** + * An object that represents all attributes of a cell. + */ +export interface IAttributeData { + /** + * "fg" is a 32-bit unsigned integer that stores the foreground color of the cell in the 24 least + * significant bits and additional flags in the remaining 8 bits. + */ + fg: number; + /** + * "bg" is a 32-bit unsigned integer that stores the background color of the cell in the 24 least + * significant bits and additional flags in the remaining 8 bits. + */ + bg: number; + /** + * "extended", aka "ext", stores extended attributes beyond those available in fg and bg. This + * data is optional on a cell and encodes less common data. + */ + extended: IExtendedAttrs; + + clone(): IAttributeData; + + // flags + isInverse(): number; + isBold(): number; + isUnderline(): number; + isBlink(): number; + isInvisible(): number; + isItalic(): number; + isDim(): number; + isStrikethrough(): number; + isProtected(): number; + isOverline(): number; + + /** + * The color mode of the foreground color which determines how to decode {@link getFgColor}, + * possible values include {@link Attributes.CM_DEFAULT}, {@link Attributes.CM_P16}, + * {@link Attributes.CM_P256} and {@link Attributes.CM_RGB}. + */ + getFgColorMode(): number; + /** + * The color mode of the background color which determines how to decode {@link getBgColor}, + * possible values include {@link Attributes.CM_DEFAULT}, {@link Attributes.CM_P16}, + * {@link Attributes.CM_P256} and {@link Attributes.CM_RGB}. + */ + getBgColorMode(): number; + isFgRGB(): boolean; + isBgRGB(): boolean; + isFgPalette(): boolean; + isBgPalette(): boolean; + isFgDefault(): boolean; + isBgDefault(): boolean; + isAttributeDefault(): boolean; + + /** + * Gets an integer representation of the foreground color, how to decode the color depends on the + * color mode {@link getFgColorMode}. + */ + getFgColor(): number; + /** + * Gets an integer representation of the background color, how to decode the color depends on the + * color mode {@link getBgColorMode}. + */ + getBgColor(): number; + + // extended attrs + hasExtendedAttrs(): number; + updateExtended(): void; + getUnderlineColor(): number; + getUnderlineColorMode(): number; + isUnderlineColorRGB(): boolean; + isUnderlineColorPalette(): boolean; + isUnderlineColorDefault(): boolean; + getUnderlineStyle(): number; + getUnderlineVariantOffset(): number; +} + +/** Cell data */ +export interface ICellData extends IAttributeData { + content: number; + combinedData: string; + isCombined(): number; + getWidth(): number; + getChars(): string; + getCode(): number; + setFromCharData(value: CharData): void; + getAsCharData(): CharData; +} + +/** + * Interface for a line in the terminal buffer. + */ +export interface IBufferLine { + length: number; + isWrapped: boolean; + get(index: number): CharData; + set(index: number, value: CharData): void; + loadCell(index: number, cell: ICellData): ICellData; + setCell(index: number, cell: ICellData): void; + setCellFromCodepoint(index: number, codePoint: number, width: number, attrs: IAttributeData): void; + addCodepointToCell(index: number, codePoint: number, width: number): void; + insertCells(pos: number, n: number, ch: ICellData): void; + deleteCells(pos: number, n: number, fill: ICellData): void; + replaceCells(start: number, end: number, fill: ICellData, respectProtect?: boolean): void; + resize(cols: number, fill: ICellData): boolean; + cleanupMemory(): number; + fill(fillCellData: ICellData, respectProtect?: boolean): void; + copyFrom(line: IBufferLine): void; + clone(): IBufferLine; + getTrimmedLength(): number; + getNoBgTrimmedLength(): number; + translateToString(trimRight?: boolean, startCol?: number, endCol?: number, outColumns?: number[]): string; + + /* direct access to cell attrs */ + getWidth(index: number): number; + hasWidth(index: number): number; + getFg(index: number): number; + getBg(index: number): number; + hasContent(index: number): number; + getCodePoint(index: number): number; + isCombined(index: number): number; + getString(index: number): string; +} + +export interface IMarker extends IDisposable { + readonly id: number; + readonly isDisposed: boolean; + readonly line: number; + onDispose: Event; +} +export interface IModes { + insertMode: boolean; +} + +export interface IDecPrivateModes { + applicationCursorKeys: boolean; + applicationKeypad: boolean; + bracketedPasteMode: boolean; + cursorBlink: boolean | undefined; + cursorStyle: CursorStyle | undefined; + origin: boolean; + reverseWraparound: boolean; + sendFocus: boolean; + synchronizedOutput: boolean; + wraparound: boolean; // defaults: xterm - true, vt100 - false +} + +export interface IRowRange { + start: number; + end: number; +} + +/** + * Interface for mouse events in the core. + */ +export const enum CoreMouseButton { + LEFT = 0, + MIDDLE = 1, + RIGHT = 2, + NONE = 3, + WHEEL = 4, + // additional buttons 1..8 + // untested! + AUX1 = 8, + AUX2 = 9, + AUX3 = 10, + AUX4 = 11, + AUX5 = 12, + AUX6 = 13, + AUX7 = 14, + AUX8 = 15 +} + +export const enum CoreMouseAction { + UP = 0, // buttons, wheel + DOWN = 1, // buttons, wheel + LEFT = 2, // wheel only + RIGHT = 3, // wheel only + MOVE = 32 // buttons only +} + +export interface ICoreMouseEvent { + /** column (zero based). */ + col: number; + /** row (zero based). */ + row: number; + /** xy pixel positions. */ + x: number; + y: number; + /** + * Button the action occured. Due to restrictions of the tracking protocols + * it is not possible to report multiple buttons at once. + * Wheel is treated as a button. + * There are invalid combinations of buttons and actions possible + * (like move + wheel), those are silently ignored by the CoreMouseService. + */ + button: CoreMouseButton; + action: CoreMouseAction; + /** + * Modifier states. + * Protocols will add/ignore those based on specific restrictions. + */ + ctrl?: boolean; + alt?: boolean; + shift?: boolean; +} + +/** + * CoreMouseEventType + * To be reported to the browser component which events a mouse + * protocol wants to be catched and forwarded as an ICoreMouseEvent + * to CoreMouseService. + */ +export const enum CoreMouseEventType { + NONE = 0, + /** any mousedown event */ + DOWN = 1, + /** any mouseup event */ + UP = 2, + /** any mousemove event while a button is held */ + DRAG = 4, + /** any mousemove event without a button */ + MOVE = 8, + /** any wheel event */ + WHEEL = 16 +} + +/** + * Mouse protocol interface. + * A mouse protocol can be registered and activated at the CoreMouseService. + * `events` should contain a list of needed events as a hint for the browser component + * to install/remove the appropriate event handlers. + * `restrict` applies further protocol specific restrictions like not allowed + * modifiers or filtering invalid event types. + */ +export interface ICoreMouseProtocol { + events: CoreMouseEventType; + restrict: (e: ICoreMouseEvent) => boolean; +} + +/** + * CoreMouseEncoding + * The tracking encoding can be registered and activated at the CoreMouseService. + * If a ICoreMouseEvent passes all procotol restrictions it will be encoded + * with the active encoding and sent out. + * Note: Returning an empty string will supress sending a mouse report, + * which can be used to skip creating falsey reports in limited encodings + * (DEFAULT only supports up to 223 1-based as coord value). + */ +export type CoreMouseEncoding = (event: ICoreMouseEvent) => string; + +/** + * windowOptions + */ +export interface IWindowOptions { + restoreWin?: boolean; + minimizeWin?: boolean; + setWinPosition?: boolean; + setWinSizePixels?: boolean; + raiseWin?: boolean; + lowerWin?: boolean; + refreshWin?: boolean; + setWinSizeChars?: boolean; + maximizeWin?: boolean; + fullscreenWin?: boolean; + getWinState?: boolean; + getWinPosition?: boolean; + getWinSizePixels?: boolean; + getScreenSizePixels?: boolean; + getCellSizePixels?: boolean; + getWinSizeChars?: boolean; + getScreenSizeChars?: boolean; + getIconTitle?: boolean; + getWinTitle?: boolean; + pushTitle?: boolean; + popTitle?: boolean; + setWinLines?: boolean; +} + +// color events from common, used for OSC 4/10/11/12 and 104/110/111/112 +export const enum ColorRequestType { + REPORT = 0, + SET = 1, + RESTORE = 2 +} + +// IntRange from https://stackoverflow.com/a/39495173 +type Enumerate = Acc['length'] extends N + ? Acc[number] + : Enumerate; +type IntRange = Exclude, Enumerate>; + +export type ColorIndex = IntRange<0, 256>; // number from 0 to 255 +export type AllColorIndex = ColorIndex | SpecialColorIndex; +export const enum SpecialColorIndex { + FOREGROUND = 256, + BACKGROUND = 257, + CURSOR = 258 +} +export interface IColorReportRequest { + type: ColorRequestType.REPORT; + index: AllColorIndex; +} +export interface IColorSetRequest { + type: ColorRequestType.SET; + index: AllColorIndex; + color: IColorRGB; +} +export interface IColorRestoreRequest { + type: ColorRequestType.RESTORE; + index?: AllColorIndex; +} +export type IColorEvent = (IColorReportRequest | IColorSetRequest | IColorRestoreRequest)[]; + + +/** + * Calls the parser and handles actions generated by the parser. + */ +export interface IInputHandler { + onTitleChange: Event; + + parse(data: string | Uint8Array, promiseResult?: boolean): void | Promise; + print(data: Uint32Array, start: number, end: number): void; + registerCsiHandler(id: IFunctionIdentifier, callback: (params: IParams) => boolean | Promise): IDisposable; + registerDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: IParams) => boolean | Promise): IDisposable; + registerEscHandler(id: IFunctionIdentifier, callback: () => boolean | Promise): IDisposable; + registerOscHandler(ident: number, callback: (data: string) => boolean | Promise): IDisposable; + + /** C0 BEL */ bell(): boolean; + /** C0 LF */ lineFeed(): boolean; + /** C0 CR */ carriageReturn(): boolean; + /** C0 BS */ backspace(): boolean; + /** C0 HT */ tab(): boolean; + /** C0 SO */ shiftOut(): boolean; + /** C0 SI */ shiftIn(): boolean; + + /** CSI @ */ insertChars(params: IParams): boolean; + /** CSI SP @ */ scrollLeft(params: IParams): boolean; + /** CSI A */ cursorUp(params: IParams): boolean; + /** CSI SP A */ scrollRight(params: IParams): boolean; + /** CSI B */ cursorDown(params: IParams): boolean; + /** CSI C */ cursorForward(params: IParams): boolean; + /** CSI D */ cursorBackward(params: IParams): boolean; + /** CSI E */ cursorNextLine(params: IParams): boolean; + /** CSI F */ cursorPrecedingLine(params: IParams): boolean; + /** CSI G */ cursorCharAbsolute(params: IParams): boolean; + /** CSI H */ cursorPosition(params: IParams): boolean; + /** CSI I */ cursorForwardTab(params: IParams): boolean; + /** CSI J */ eraseInDisplay(params: IParams): boolean; + /** CSI K */ eraseInLine(params: IParams): boolean; + /** CSI L */ insertLines(params: IParams): boolean; + /** CSI M */ deleteLines(params: IParams): boolean; + /** CSI P */ deleteChars(params: IParams): boolean; + /** CSI S */ scrollUp(params: IParams): boolean; + /** CSI T */ scrollDown(params: IParams, collect?: string): boolean; + /** CSI X */ eraseChars(params: IParams): boolean; + /** CSI Z */ cursorBackwardTab(params: IParams): boolean; + /** CSI ` */ charPosAbsolute(params: IParams): boolean; + /** CSI a */ hPositionRelative(params: IParams): boolean; + /** CSI b */ repeatPrecedingCharacter(params: IParams): boolean; + /** CSI c */ sendDeviceAttributesPrimary(params: IParams): boolean; + /** CSI > c */ sendDeviceAttributesSecondary(params: IParams): boolean; + /** CSI d */ linePosAbsolute(params: IParams): boolean; + /** CSI e */ vPositionRelative(params: IParams): boolean; + /** CSI f */ hVPosition(params: IParams): boolean; + /** CSI g */ tabClear(params: IParams): boolean; + /** CSI h */ setMode(params: IParams, collect?: string): boolean; + /** CSI l */ resetMode(params: IParams, collect?: string): boolean; + /** CSI m */ charAttributes(params: IParams): boolean; + /** CSI n */ deviceStatus(params: IParams, collect?: string): boolean; + /** CSI p */ softReset(params: IParams, collect?: string): boolean; + /** CSI q */ setCursorStyle(params: IParams, collect?: string): boolean; + /** CSI r */ setScrollRegion(params: IParams, collect?: string): boolean; + /** CSI s */ saveCursor(params: IParams): boolean; + /** CSI u */ restoreCursor(params: IParams): boolean; + /** CSI ' } */ insertColumns(params: IParams): boolean; + /** CSI ' ~ */ deleteColumns(params: IParams): boolean; + + /** OSC 0 + OSC 2 */ setTitle(data: string): boolean; + /** OSC 4 */ setOrReportIndexedColor(data: string): boolean; + /** OSC 10 */ setOrReportFgColor(data: string): boolean; + /** OSC 11 */ setOrReportBgColor(data: string): boolean; + /** OSC 12 */ setOrReportCursorColor(data: string): boolean; + /** OSC 104 */ restoreIndexedColor(data: string): boolean; + /** OSC 110 */ restoreFgColor(data: string): boolean; + /** OSC 111 */ restoreBgColor(data: string): boolean; + /** OSC 112 */ restoreCursorColor(data: string): boolean; + + /** ESC E */ nextLine(): boolean; + /** ESC = */ keypadApplicationMode(): boolean; + /** ESC > */ keypadNumericMode(): boolean; + /** ESC % G + ESC % @ */ selectDefaultCharset(): boolean; + /** ESC ( C + ESC ) C + ESC * C + ESC + C + ESC - C + ESC . C + ESC / C */ selectCharset(collectAndFlag: string): boolean; + /** ESC D */ index(): boolean; + /** ESC H */ tabSet(): boolean; + /** ESC M */ reverseIndex(): boolean; + /** ESC c */ fullReset(): boolean; + /** ESC n + ESC o + ESC | + ESC } + ESC ~ */ setgLevel(level: number): boolean; + /** ESC # 8 */ screenAlignmentPattern(): boolean; +} + +export interface IParseStack { + paused: boolean; + cursorStartX: number; + cursorStartY: number; + decodedLength: number; + position: number; +} diff --git a/node_modules/@xterm/xterm/src/common/WindowsMode.ts b/node_modules/@xterm/xterm/src/common/WindowsMode.ts new file mode 100644 index 0000000..7cff094 --- /dev/null +++ b/node_modules/@xterm/xterm/src/common/WindowsMode.ts @@ -0,0 +1,27 @@ +/** + * Copyright (c) 2019 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { CHAR_DATA_CODE_INDEX, NULL_CELL_CODE, WHITESPACE_CELL_CODE } from 'common/buffer/Constants'; +import { IBufferService } from 'common/services/Services'; + +export function updateWindowsModeWrappedState(bufferService: IBufferService): void { + // Winpty does not support wraparound mode which means that lines will never + // be marked as wrapped. This causes issues for things like copying a line + // retaining the wrapped new line characters or if consumers are listening + // in on the data stream. + // + // The workaround for this is to listen to every incoming line feed and mark + // the line as wrapped if the last character in the previous line is not a + // space. This is certainly not without its problems, but generally on + // Windows when text reaches the end of the terminal it's likely going to be + // wrapped. + const line = bufferService.buffer.lines.get(bufferService.buffer.ybase + bufferService.buffer.y - 1); + const lastChar = line?.get(bufferService.cols - 1); + + const nextLine = bufferService.buffer.lines.get(bufferService.buffer.ybase + bufferService.buffer.y); + if (nextLine && lastChar) { + nextLine.isWrapped = (lastChar[CHAR_DATA_CODE_INDEX] !== NULL_CELL_CODE && lastChar[CHAR_DATA_CODE_INDEX] !== WHITESPACE_CELL_CODE); + } +} diff --git a/node_modules/@xterm/xterm/src/common/buffer/AttributeData.ts b/node_modules/@xterm/xterm/src/common/buffer/AttributeData.ts new file mode 100644 index 0000000..6221fb8 --- /dev/null +++ b/node_modules/@xterm/xterm/src/common/buffer/AttributeData.ts @@ -0,0 +1,211 @@ +/** + * Copyright (c) 2018 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { IAttributeData, IColorRGB, IExtendedAttrs } from 'common/Types'; +import { Attributes, FgFlags, BgFlags, UnderlineStyle, ExtFlags } from 'common/buffer/Constants'; + +export class AttributeData implements IAttributeData { + public static toColorRGB(value: number): IColorRGB { + return [ + value >>> Attributes.RED_SHIFT & 255, + value >>> Attributes.GREEN_SHIFT & 255, + value & 255 + ]; + } + + public static fromColorRGB(value: IColorRGB): number { + return (value[0] & 255) << Attributes.RED_SHIFT | (value[1] & 255) << Attributes.GREEN_SHIFT | value[2] & 255; + } + + public clone(): IAttributeData { + const newObj = new AttributeData(); + newObj.fg = this.fg; + newObj.bg = this.bg; + newObj.extended = this.extended.clone(); + return newObj; + } + + // data + public fg = 0; + public bg = 0; + public extended: IExtendedAttrs = new ExtendedAttrs(); + + // flags + public isInverse(): number { return this.fg & FgFlags.INVERSE; } + public isBold(): number { return this.fg & FgFlags.BOLD; } + public isUnderline(): number { + if (this.hasExtendedAttrs() && this.extended.underlineStyle !== UnderlineStyle.NONE) { + return 1; + } + return this.fg & FgFlags.UNDERLINE; + } + public isBlink(): number { return this.fg & FgFlags.BLINK; } + public isInvisible(): number { return this.fg & FgFlags.INVISIBLE; } + public isItalic(): number { return this.bg & BgFlags.ITALIC; } + public isDim(): number { return this.bg & BgFlags.DIM; } + public isStrikethrough(): number { return this.fg & FgFlags.STRIKETHROUGH; } + public isProtected(): number { return this.bg & BgFlags.PROTECTED; } + public isOverline(): number { return this.bg & BgFlags.OVERLINE; } + + // color modes + public getFgColorMode(): number { return this.fg & Attributes.CM_MASK; } + public getBgColorMode(): number { return this.bg & Attributes.CM_MASK; } + public isFgRGB(): boolean { return (this.fg & Attributes.CM_MASK) === Attributes.CM_RGB; } + public isBgRGB(): boolean { return (this.bg & Attributes.CM_MASK) === Attributes.CM_RGB; } + public isFgPalette(): boolean { return (this.fg & Attributes.CM_MASK) === Attributes.CM_P16 || (this.fg & Attributes.CM_MASK) === Attributes.CM_P256; } + public isBgPalette(): boolean { return (this.bg & Attributes.CM_MASK) === Attributes.CM_P16 || (this.bg & Attributes.CM_MASK) === Attributes.CM_P256; } + public isFgDefault(): boolean { return (this.fg & Attributes.CM_MASK) === 0; } + public isBgDefault(): boolean { return (this.bg & Attributes.CM_MASK) === 0; } + public isAttributeDefault(): boolean { return this.fg === 0 && this.bg === 0; } + + // colors + public getFgColor(): number { + switch (this.fg & Attributes.CM_MASK) { + case Attributes.CM_P16: + case Attributes.CM_P256: return this.fg & Attributes.PCOLOR_MASK; + case Attributes.CM_RGB: return this.fg & Attributes.RGB_MASK; + default: return -1; // CM_DEFAULT defaults to -1 + } + } + public getBgColor(): number { + switch (this.bg & Attributes.CM_MASK) { + case Attributes.CM_P16: + case Attributes.CM_P256: return this.bg & Attributes.PCOLOR_MASK; + case Attributes.CM_RGB: return this.bg & Attributes.RGB_MASK; + default: return -1; // CM_DEFAULT defaults to -1 + } + } + + // extended attrs + public hasExtendedAttrs(): number { + return this.bg & BgFlags.HAS_EXTENDED; + } + public updateExtended(): void { + if (this.extended.isEmpty()) { + this.bg &= ~BgFlags.HAS_EXTENDED; + } else { + this.bg |= BgFlags.HAS_EXTENDED; + } + } + public getUnderlineColor(): number { + if ((this.bg & BgFlags.HAS_EXTENDED) && ~this.extended.underlineColor) { + switch (this.extended.underlineColor & Attributes.CM_MASK) { + case Attributes.CM_P16: + case Attributes.CM_P256: return this.extended.underlineColor & Attributes.PCOLOR_MASK; + case Attributes.CM_RGB: return this.extended.underlineColor & Attributes.RGB_MASK; + default: return this.getFgColor(); + } + } + return this.getFgColor(); + } + public getUnderlineColorMode(): number { + return (this.bg & BgFlags.HAS_EXTENDED) && ~this.extended.underlineColor + ? this.extended.underlineColor & Attributes.CM_MASK + : this.getFgColorMode(); + } + public isUnderlineColorRGB(): boolean { + return (this.bg & BgFlags.HAS_EXTENDED) && ~this.extended.underlineColor + ? (this.extended.underlineColor & Attributes.CM_MASK) === Attributes.CM_RGB + : this.isFgRGB(); + } + public isUnderlineColorPalette(): boolean { + return (this.bg & BgFlags.HAS_EXTENDED) && ~this.extended.underlineColor + ? (this.extended.underlineColor & Attributes.CM_MASK) === Attributes.CM_P16 + || (this.extended.underlineColor & Attributes.CM_MASK) === Attributes.CM_P256 + : this.isFgPalette(); + } + public isUnderlineColorDefault(): boolean { + return (this.bg & BgFlags.HAS_EXTENDED) && ~this.extended.underlineColor + ? (this.extended.underlineColor & Attributes.CM_MASK) === 0 + : this.isFgDefault(); + } + public getUnderlineStyle(): UnderlineStyle { + return this.fg & FgFlags.UNDERLINE + ? (this.bg & BgFlags.HAS_EXTENDED ? this.extended.underlineStyle : UnderlineStyle.SINGLE) + : UnderlineStyle.NONE; + } + public getUnderlineVariantOffset(): number { + return this.extended.underlineVariantOffset; + } +} + + +/** + * Extended attributes for a cell. + * Holds information about different underline styles and color. + */ +export class ExtendedAttrs implements IExtendedAttrs { + private _ext: number = 0; + public get ext(): number { + if (this._urlId) { + return ( + (this._ext & ~ExtFlags.UNDERLINE_STYLE) | + (this.underlineStyle << 26) + ); + } + return this._ext; + } + public set ext(value: number) { this._ext = value; } + + public get underlineStyle(): UnderlineStyle { + // Always return the URL style if it has one + if (this._urlId) { + return UnderlineStyle.DASHED; + } + return (this._ext & ExtFlags.UNDERLINE_STYLE) >> 26; + } + public set underlineStyle(value: UnderlineStyle) { + this._ext &= ~ExtFlags.UNDERLINE_STYLE; + this._ext |= (value << 26) & ExtFlags.UNDERLINE_STYLE; + } + + public get underlineColor(): number { + return this._ext & (Attributes.CM_MASK | Attributes.RGB_MASK); + } + public set underlineColor(value: number) { + this._ext &= ~(Attributes.CM_MASK | Attributes.RGB_MASK); + this._ext |= value & (Attributes.CM_MASK | Attributes.RGB_MASK); + } + + private _urlId: number = 0; + public get urlId(): number { + return this._urlId; + } + public set urlId(value: number) { + this._urlId = value; + } + + public get underlineVariantOffset(): number { + const val = (this._ext & ExtFlags.VARIANT_OFFSET) >> 29; + if (val < 0) { + return val ^ 0xFFFFFFF8; + } + return val; + } + public set underlineVariantOffset(value: number) { + this._ext &= ~ExtFlags.VARIANT_OFFSET; + this._ext |= (value << 29) & ExtFlags.VARIANT_OFFSET; + } + + constructor( + ext: number = 0, + urlId: number = 0 + ) { + this._ext = ext; + this._urlId = urlId; + } + + public clone(): IExtendedAttrs { + return new ExtendedAttrs(this._ext, this._urlId); + } + + /** + * Convenient method to indicate whether the object holds no additional information, + * that needs to be persistant in the buffer. + */ + public isEmpty(): boolean { + return this.underlineStyle === UnderlineStyle.NONE && this._urlId === 0; + } +} diff --git a/node_modules/@xterm/xterm/src/common/buffer/Buffer.ts b/node_modules/@xterm/xterm/src/common/buffer/Buffer.ts new file mode 100644 index 0000000..81ab156 --- /dev/null +++ b/node_modules/@xterm/xterm/src/common/buffer/Buffer.ts @@ -0,0 +1,662 @@ +/** + * Copyright (c) 2017 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { CircularList, IInsertEvent } from 'common/CircularList'; +import { IdleTaskQueue } from 'common/TaskQueue'; +import { IAttributeData, IBufferLine, ICellData, ICharset } from 'common/Types'; +import { ExtendedAttrs } from 'common/buffer/AttributeData'; +import { BufferLine, DEFAULT_ATTR_DATA } from 'common/buffer/BufferLine'; +import { getWrappedLineTrimmedLength, reflowLargerApplyNewLayout, reflowLargerCreateNewLayout, reflowLargerGetLinesToRemove, reflowSmallerGetNewLineLengths } from 'common/buffer/BufferReflow'; +import { CellData } from 'common/buffer/CellData'; +import { NULL_CELL_CHAR, NULL_CELL_CODE, NULL_CELL_WIDTH, WHITESPACE_CELL_CHAR, WHITESPACE_CELL_CODE, WHITESPACE_CELL_WIDTH } from 'common/buffer/Constants'; +import { Marker } from 'common/buffer/Marker'; +import { IBuffer } from 'common/buffer/Types'; +import { DEFAULT_CHARSET } from 'common/data/Charsets'; +import { IBufferService, IOptionsService } from 'common/services/Services'; + +export const MAX_BUFFER_SIZE = 4294967295; // 2^32 - 1 + +/** + * This class represents a terminal buffer (an internal state of the terminal), where the + * following information is stored (in high-level): + * - text content of this particular buffer + * - cursor position + * - scroll position + */ +export class Buffer implements IBuffer { + public lines: CircularList; + public ydisp: number = 0; + public ybase: number = 0; + public y: number = 0; + public x: number = 0; + public scrollBottom: number; + public scrollTop: number; + public tabs: { [column: number]: boolean | undefined } = {}; + public savedY: number = 0; + public savedX: number = 0; + public savedCurAttrData = DEFAULT_ATTR_DATA.clone(); + public savedCharset: ICharset | undefined = DEFAULT_CHARSET; + public markers: Marker[] = []; + private _nullCell: ICellData = CellData.fromCharData([0, NULL_CELL_CHAR, NULL_CELL_WIDTH, NULL_CELL_CODE]); + private _whitespaceCell: ICellData = CellData.fromCharData([0, WHITESPACE_CELL_CHAR, WHITESPACE_CELL_WIDTH, WHITESPACE_CELL_CODE]); + private _cols: number; + private _rows: number; + private _isClearing: boolean = false; + + constructor( + private _hasScrollback: boolean, + private _optionsService: IOptionsService, + private _bufferService: IBufferService + ) { + this._cols = this._bufferService.cols; + this._rows = this._bufferService.rows; + this.lines = new CircularList(this._getCorrectBufferLength(this._rows)); + this.scrollTop = 0; + this.scrollBottom = this._rows - 1; + this.setupTabStops(); + } + + public getNullCell(attr?: IAttributeData): ICellData { + if (attr) { + this._nullCell.fg = attr.fg; + this._nullCell.bg = attr.bg; + this._nullCell.extended = attr.extended; + } else { + this._nullCell.fg = 0; + this._nullCell.bg = 0; + this._nullCell.extended = new ExtendedAttrs(); + } + return this._nullCell; + } + + public getWhitespaceCell(attr?: IAttributeData): ICellData { + if (attr) { + this._whitespaceCell.fg = attr.fg; + this._whitespaceCell.bg = attr.bg; + this._whitespaceCell.extended = attr.extended; + } else { + this._whitespaceCell.fg = 0; + this._whitespaceCell.bg = 0; + this._whitespaceCell.extended = new ExtendedAttrs(); + } + return this._whitespaceCell; + } + + public getBlankLine(attr: IAttributeData, isWrapped?: boolean): IBufferLine { + return new BufferLine(this._bufferService.cols, this.getNullCell(attr), isWrapped); + } + + public get hasScrollback(): boolean { + return this._hasScrollback && this.lines.maxLength > this._rows; + } + + public get isCursorInViewport(): boolean { + const absoluteY = this.ybase + this.y; + const relativeY = absoluteY - this.ydisp; + return (relativeY >= 0 && relativeY < this._rows); + } + + /** + * Gets the correct buffer length based on the rows provided, the terminal's + * scrollback and whether this buffer is flagged to have scrollback or not. + * @param rows The terminal rows to use in the calculation. + */ + private _getCorrectBufferLength(rows: number): number { + if (!this._hasScrollback) { + return rows; + } + + const correctBufferLength = rows + this._optionsService.rawOptions.scrollback; + + return correctBufferLength > MAX_BUFFER_SIZE ? MAX_BUFFER_SIZE : correctBufferLength; + } + + /** + * Fills the buffer's viewport with blank lines. + */ + public fillViewportRows(fillAttr?: IAttributeData): void { + if (this.lines.length === 0) { + if (fillAttr === undefined) { + fillAttr = DEFAULT_ATTR_DATA; + } + let i = this._rows; + while (i--) { + this.lines.push(this.getBlankLine(fillAttr)); + } + } + } + + /** + * Clears the buffer to it's initial state, discarding all previous data. + */ + public clear(): void { + this.ydisp = 0; + this.ybase = 0; + this.y = 0; + this.x = 0; + this.lines = new CircularList(this._getCorrectBufferLength(this._rows)); + this.scrollTop = 0; + this.scrollBottom = this._rows - 1; + this.setupTabStops(); + } + + /** + * Resizes the buffer, adjusting its data accordingly. + * @param newCols The new number of columns. + * @param newRows The new number of rows. + */ + public resize(newCols: number, newRows: number): void { + // store reference to null cell with default attrs + const nullCell = this.getNullCell(DEFAULT_ATTR_DATA); + + // count bufferlines with overly big memory to be cleaned afterwards + let dirtyMemoryLines = 0; + + // Increase max length if needed before adjustments to allow space to fill + // as required. + const newMaxLength = this._getCorrectBufferLength(newRows); + if (newMaxLength > this.lines.maxLength) { + this.lines.maxLength = newMaxLength; + } + + // if (this._cols > newCols) { + // console.log('increase!'); + // } + + // The following adjustments should only happen if the buffer has been + // initialized/filled. + if (this.lines.length > 0) { + // Deal with columns increasing (reducing needs to happen after reflow) + if (this._cols < newCols) { + for (let i = 0; i < this.lines.length; i++) { + // +boolean for fast 0 or 1 conversion + dirtyMemoryLines += +this.lines.get(i)!.resize(newCols, nullCell); + } + } + + // Resize rows in both directions as needed + let addToY = 0; + if (this._rows < newRows) { + for (let y = this._rows; y < newRows; y++) { + if (this.lines.length < newRows + this.ybase) { + if (this._optionsService.rawOptions.windowsMode || this._optionsService.rawOptions.windowsPty.backend !== undefined || this._optionsService.rawOptions.windowsPty.buildNumber !== undefined) { + // Just add the new missing rows on Windows as conpty reprints the screen with it's + // view of the world. Once a line enters scrollback for conpty it remains there + this.lines.push(new BufferLine(newCols, nullCell)); + } else { + if (this.ybase > 0 && this.lines.length <= this.ybase + this.y + addToY + 1) { + // There is room above the buffer and there are no empty elements below the line, + // scroll up + this.ybase--; + addToY++; + if (this.ydisp > 0) { + // Viewport is at the top of the buffer, must increase downwards + this.ydisp--; + } + } else { + // Add a blank line if there is no buffer left at the top to scroll to, or if there + // are blank lines after the cursor + this.lines.push(new BufferLine(newCols, nullCell)); + } + } + } + } + } else { // (this._rows >= newRows) + for (let y = this._rows; y > newRows; y--) { + if (this.lines.length > newRows + this.ybase) { + if (this.lines.length > this.ybase + this.y + 1) { + // The line is a blank line below the cursor, remove it + this.lines.pop(); + } else { + // The line is the cursor, scroll down + this.ybase++; + this.ydisp++; + } + } + } + } + + // Reduce max length if needed after adjustments, this is done after as it + // would otherwise cut data from the bottom of the buffer. + if (newMaxLength < this.lines.maxLength) { + // Trim from the top of the buffer and adjust ybase and ydisp. + const amountToTrim = this.lines.length - newMaxLength; + if (amountToTrim > 0) { + this.lines.trimStart(amountToTrim); + this.ybase = Math.max(this.ybase - amountToTrim, 0); + this.ydisp = Math.max(this.ydisp - amountToTrim, 0); + this.savedY = Math.max(this.savedY - amountToTrim, 0); + } + this.lines.maxLength = newMaxLength; + } + + // Make sure that the cursor stays on screen + this.x = Math.min(this.x, newCols - 1); + this.y = Math.min(this.y, newRows - 1); + if (addToY) { + this.y += addToY; + } + this.savedX = Math.min(this.savedX, newCols - 1); + + this.scrollTop = 0; + } + + this.scrollBottom = newRows - 1; + + if (this._isReflowEnabled) { + this._reflow(newCols, newRows); + + // Trim the end of the line off if cols shrunk + if (this._cols > newCols) { + for (let i = 0; i < this.lines.length; i++) { + // +boolean for fast 0 or 1 conversion + dirtyMemoryLines += +this.lines.get(i)!.resize(newCols, nullCell); + } + } + } + + this._cols = newCols; + this._rows = newRows; + + this._memoryCleanupQueue.clear(); + // schedule memory cleanup only, if more than 10% of the lines are affected + if (dirtyMemoryLines > 0.1 * this.lines.length) { + this._memoryCleanupPosition = 0; + this._memoryCleanupQueue.enqueue(() => this._batchedMemoryCleanup()); + } + } + + private _memoryCleanupQueue = new IdleTaskQueue(); + private _memoryCleanupPosition = 0; + + private _batchedMemoryCleanup(): boolean { + let normalRun = true; + if (this._memoryCleanupPosition >= this.lines.length) { + // cleanup made it once through all lines, thus rescan in loop below to also catch shifted + // lines, which should finish rather quick if there are no more cleanups pending + this._memoryCleanupPosition = 0; + normalRun = false; + } + let counted = 0; + while (this._memoryCleanupPosition < this.lines.length) { + counted += this.lines.get(this._memoryCleanupPosition++)!.cleanupMemory(); + // cleanup max 100 lines per batch + if (counted > 100) { + return true; + } + } + // normal runs always need another rescan afterwards + // if we made it here with normalRun=false, we are in a final run + // and can end the cleanup task for sure + return normalRun; + } + + private get _isReflowEnabled(): boolean { + const windowsPty = this._optionsService.rawOptions.windowsPty; + if (windowsPty && windowsPty.buildNumber) { + return this._hasScrollback && windowsPty.backend === 'conpty' && windowsPty.buildNumber >= 21376; + } + return this._hasScrollback && !this._optionsService.rawOptions.windowsMode; + } + + private _reflow(newCols: number, newRows: number): void { + if (this._cols === newCols) { + return; + } + + // Iterate through rows, ignore the last one as it cannot be wrapped + if (newCols > this._cols) { + this._reflowLarger(newCols, newRows); + } else { + this._reflowSmaller(newCols, newRows); + } + } + + private _reflowLarger(newCols: number, newRows: number): void { + const reflowCursorLine = this._optionsService.rawOptions.reflowCursorLine; + const toRemove: number[] = reflowLargerGetLinesToRemove(this.lines, this._cols, newCols, this.ybase + this.y, this.getNullCell(DEFAULT_ATTR_DATA), reflowCursorLine); + if (toRemove.length > 0) { + const newLayoutResult = reflowLargerCreateNewLayout(this.lines, toRemove); + reflowLargerApplyNewLayout(this.lines, newLayoutResult.layout); + this._reflowLargerAdjustViewport(newCols, newRows, newLayoutResult.countRemoved); + } + } + + private _reflowLargerAdjustViewport(newCols: number, newRows: number, countRemoved: number): void { + const nullCell = this.getNullCell(DEFAULT_ATTR_DATA); + // Adjust viewport based on number of items removed + let viewportAdjustments = countRemoved; + while (viewportAdjustments-- > 0) { + if (this.ybase === 0) { + if (this.y > 0) { + this.y--; + } + if (this.lines.length < newRows) { + // Add an extra row at the bottom of the viewport + this.lines.push(new BufferLine(newCols, nullCell)); + } + } else { + if (this.ydisp === this.ybase) { + this.ydisp--; + } + this.ybase--; + } + } + this.savedY = Math.max(this.savedY - countRemoved, 0); + } + + private _reflowSmaller(newCols: number, newRows: number): void { + const reflowCursorLine = this._optionsService.rawOptions.reflowCursorLine; + const nullCell = this.getNullCell(DEFAULT_ATTR_DATA); + // Gather all BufferLines that need to be inserted into the Buffer here so that they can be + // batched up and only committed once + const toInsert = []; + let countToInsert = 0; + // Go backwards as many lines may be trimmed and this will avoid considering them + for (let y = this.lines.length - 1; y >= 0; y--) { + // Check whether this line is a problem + let nextLine = this.lines.get(y) as BufferLine; + if (!nextLine || !nextLine.isWrapped && nextLine.getTrimmedLength() <= newCols) { + continue; + } + + // Gather wrapped lines and adjust y to be the starting line + const wrappedLines: BufferLine[] = [nextLine]; + while (nextLine.isWrapped && y > 0) { + nextLine = this.lines.get(--y) as BufferLine; + wrappedLines.unshift(nextLine); + } + + if (!reflowCursorLine) { + // If these lines contain the cursor don't touch them, the program will handle fixing up + // wrapped lines with the cursor + const absoluteY = this.ybase + this.y; + if (absoluteY >= y && absoluteY < y + wrappedLines.length) { + continue; + } + } + + const lastLineLength = wrappedLines[wrappedLines.length - 1].getTrimmedLength(); + const destLineLengths = reflowSmallerGetNewLineLengths(wrappedLines, this._cols, newCols); + const linesToAdd = destLineLengths.length - wrappedLines.length; + let trimmedLines: number; + if (this.ybase === 0 && this.y !== this.lines.length - 1) { + // If the top section of the buffer is not yet filled + trimmedLines = Math.max(0, this.y - this.lines.maxLength + linesToAdd); + } else { + trimmedLines = Math.max(0, this.lines.length - this.lines.maxLength + linesToAdd); + } + + // Add the new lines + const newLines: BufferLine[] = []; + for (let i = 0; i < linesToAdd; i++) { + const newLine = this.getBlankLine(DEFAULT_ATTR_DATA, true) as BufferLine; + newLines.push(newLine); + } + if (newLines.length > 0) { + toInsert.push({ + // countToInsert here gets the actual index, taking into account other inserted items. + // using this we can iterate through the list forwards + start: y + wrappedLines.length + countToInsert, + newLines + }); + countToInsert += newLines.length; + } + wrappedLines.push(...newLines); + + // Copy buffer data to new locations, this needs to happen backwards to do in-place + let destLineIndex = destLineLengths.length - 1; // Math.floor(cellsNeeded / newCols); + let destCol = destLineLengths[destLineIndex]; // cellsNeeded % newCols; + if (destCol === 0) { + destLineIndex--; + destCol = destLineLengths[destLineIndex]; + } + let srcLineIndex = wrappedLines.length - linesToAdd - 1; + let srcCol = lastLineLength; + while (srcLineIndex >= 0) { + const cellsToCopy = Math.min(srcCol, destCol); + if (wrappedLines[destLineIndex] === undefined) { + // Sanity check that the line exists, this has been known to fail for an unknown reason + // which would stop the reflow from happening if an exception would throw. + break; + } + wrappedLines[destLineIndex].copyCellsFrom(wrappedLines[srcLineIndex], srcCol - cellsToCopy, destCol - cellsToCopy, cellsToCopy, true); + destCol -= cellsToCopy; + if (destCol === 0) { + destLineIndex--; + destCol = destLineLengths[destLineIndex]; + } + srcCol -= cellsToCopy; + if (srcCol === 0) { + srcLineIndex--; + const wrappedLinesIndex = Math.max(srcLineIndex, 0); + srcCol = getWrappedLineTrimmedLength(wrappedLines, wrappedLinesIndex, this._cols); + } + } + + // Null out the end of the line ends if a wide character wrapped to the following line + for (let i = 0; i < wrappedLines.length; i++) { + if (destLineLengths[i] < newCols) { + wrappedLines[i].setCell(destLineLengths[i], nullCell); + } + } + + // Adjust viewport as needed + let viewportAdjustments = linesToAdd - trimmedLines; + while (viewportAdjustments-- > 0) { + if (this.ybase === 0) { + if (this.y < newRows - 1) { + this.y++; + this.lines.pop(); + } else { + this.ybase++; + this.ydisp++; + } + } else { + // Ensure ybase does not exceed its maximum value + if (this.ybase < Math.min(this.lines.maxLength, this.lines.length + countToInsert) - newRows) { + if (this.ybase === this.ydisp) { + this.ydisp++; + } + this.ybase++; + } + } + } + this.savedY = Math.min(this.savedY + linesToAdd, this.ybase + newRows - 1); + } + + // Rearrange lines in the buffer if there are any insertions, this is done at the end rather + // than earlier so that it's a single O(n) pass through the buffer, instead of O(n^2) from many + // costly calls to CircularList.splice. + if (toInsert.length > 0) { + // Record buffer insert events and then play them back backwards so that the indexes are + // correct + const insertEvents: IInsertEvent[] = []; + + // Record original lines so they don't get overridden when we rearrange the list + const originalLines: BufferLine[] = []; + for (let i = 0; i < this.lines.length; i++) { + originalLines.push(this.lines.get(i) as BufferLine); + } + const originalLinesLength = this.lines.length; + + let originalLineIndex = originalLinesLength - 1; + let nextToInsertIndex = 0; + let nextToInsert = toInsert[nextToInsertIndex]; + this.lines.length = Math.min(this.lines.maxLength, this.lines.length + countToInsert); + let countInsertedSoFar = 0; + for (let i = Math.min(this.lines.maxLength - 1, originalLinesLength + countToInsert - 1); i >= 0; i--) { + if (nextToInsert && nextToInsert.start > originalLineIndex + countInsertedSoFar) { + // Insert extra lines here, adjusting i as needed + for (let nextI = nextToInsert.newLines.length - 1; nextI >= 0; nextI--) { + this.lines.set(i--, nextToInsert.newLines[nextI]); + } + i++; + + // Create insert events for later + insertEvents.push({ + index: originalLineIndex + 1, + amount: nextToInsert.newLines.length + }); + + countInsertedSoFar += nextToInsert.newLines.length; + nextToInsert = toInsert[++nextToInsertIndex]; + } else { + this.lines.set(i, originalLines[originalLineIndex--]); + } + } + + // Update markers + let insertCountEmitted = 0; + for (let i = insertEvents.length - 1; i >= 0; i--) { + insertEvents[i].index += insertCountEmitted; + this.lines.onInsertEmitter.fire(insertEvents[i]); + insertCountEmitted += insertEvents[i].amount; + } + const amountToTrim = Math.max(0, originalLinesLength + countToInsert - this.lines.maxLength); + if (amountToTrim > 0) { + this.lines.onTrimEmitter.fire(amountToTrim); + } + } + } + + /** + * Translates a buffer line to a string, with optional start and end columns. + * Wide characters will count as two columns in the resulting string. This + * function is useful for getting the actual text underneath the raw selection + * position. + * @param lineIndex The absolute index of the line being translated. + * @param trimRight Whether to trim whitespace to the right. + * @param startCol The column to start at. + * @param endCol The column to end at. + */ + public translateBufferLineToString(lineIndex: number, trimRight: boolean, startCol: number = 0, endCol?: number): string { + const line = this.lines.get(lineIndex); + if (!line) { + return ''; + } + return line.translateToString(trimRight, startCol, endCol); + } + + public getWrappedRangeForLine(y: number): { first: number, last: number } { + let first = y; + let last = y; + // Scan upwards for wrapped lines + while (first > 0 && this.lines.get(first)!.isWrapped) { + first--; + } + // Scan downwards for wrapped lines + while (last + 1 < this.lines.length && this.lines.get(last + 1)!.isWrapped) { + last++; + } + return { first, last }; + } + + /** + * Setup the tab stops. + * @param i The index to start setting up tab stops from. + */ + public setupTabStops(i?: number): void { + if (i !== null && i !== undefined) { + if (!this.tabs[i]) { + i = this.prevStop(i); + } + } else { + this.tabs = {}; + i = 0; + } + + for (; i < this._cols; i += this._optionsService.rawOptions.tabStopWidth) { + this.tabs[i] = true; + } + } + + /** + * Move the cursor to the previous tab stop from the given position (default is current). + * @param x The position to move the cursor to the previous tab stop. + */ + public prevStop(x?: number): number { + if (x === null || x === undefined) { + x = this.x; + } + while (!this.tabs[--x] && x > 0); + return x >= this._cols ? this._cols - 1 : x < 0 ? 0 : x; + } + + /** + * Move the cursor one tab stop forward from the given position (default is current). + * @param x The position to move the cursor one tab stop forward. + */ + public nextStop(x?: number): number { + if (x === null || x === undefined) { + x = this.x; + } + while (!this.tabs[++x] && x < this._cols); + return x >= this._cols ? this._cols - 1 : x < 0 ? 0 : x; + } + + /** + * Clears markers on single line. + * @param y The line to clear. + */ + public clearMarkers(y: number): void { + this._isClearing = true; + for (let i = 0; i < this.markers.length; i++) { + if (this.markers[i].line === y) { + this.markers[i].dispose(); + this.markers.splice(i--, 1); + } + } + this._isClearing = false; + } + + /** + * Clears markers on all lines + */ + public clearAllMarkers(): void { + this._isClearing = true; + for (let i = 0; i < this.markers.length; i++) { + this.markers[i].dispose(); + } + this.markers.length = 0; + this._isClearing = false; + } + + public addMarker(y: number): Marker { + const marker = new Marker(y); + this.markers.push(marker); + marker.register(this.lines.onTrim(amount => { + marker.line -= amount; + // The marker should be disposed when the line is trimmed from the buffer + if (marker.line < 0) { + marker.dispose(); + } + })); + marker.register(this.lines.onInsert(event => { + if (marker.line >= event.index) { + marker.line += event.amount; + } + })); + marker.register(this.lines.onDelete(event => { + // Delete the marker if it's within the range + if (marker.line >= event.index && marker.line < event.index + event.amount) { + marker.dispose(); + } + + // Shift the marker if it's after the deleted range + if (marker.line > event.index) { + marker.line -= event.amount; + } + })); + marker.register(marker.onDispose(() => this._removeMarker(marker))); + return marker; + } + + private _removeMarker(marker: Marker): void { + if (!this._isClearing) { + this.markers.splice(this.markers.indexOf(marker), 1); + } + } +} diff --git a/node_modules/@xterm/xterm/src/common/buffer/BufferLine.ts b/node_modules/@xterm/xterm/src/common/buffer/BufferLine.ts new file mode 100644 index 0000000..ee3481a --- /dev/null +++ b/node_modules/@xterm/xterm/src/common/buffer/BufferLine.ts @@ -0,0 +1,551 @@ +/** + * Copyright (c) 2018 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { CharData, IAttributeData, IBufferLine, ICellData, IExtendedAttrs } from 'common/Types'; +import { AttributeData } from 'common/buffer/AttributeData'; +import { CellData } from 'common/buffer/CellData'; +import { Attributes, BgFlags, CHAR_DATA_ATTR_INDEX, CHAR_DATA_CHAR_INDEX, CHAR_DATA_WIDTH_INDEX, Content, NULL_CELL_CHAR, NULL_CELL_CODE, NULL_CELL_WIDTH, WHITESPACE_CELL_CHAR } from 'common/buffer/Constants'; +import { stringFromCodePoint } from 'common/input/TextDecoder'; + +/** + * buffer memory layout: + * + * | uint32_t | uint32_t | uint32_t | + * | `content` | `FG` | `BG` | + * | wcwidth(2) comb(1) codepoint(21) | flags(8) R(8) G(8) B(8) | flags(8) R(8) G(8) B(8) | + */ + + +/** typed array slots taken by one cell */ +const CELL_SIZE = 3; + +/** + * Cell member indices. + * + * Direct access: + * `content = data[column * CELL_SIZE + Cell.CONTENT];` + * `fg = data[column * CELL_SIZE + Cell.FG];` + * `bg = data[column * CELL_SIZE + Cell.BG];` + */ +const enum Cell { + CONTENT = 0, + FG = 1, // currently simply holds all known attrs + BG = 2 // currently unused +} + +export const DEFAULT_ATTR_DATA = Object.freeze(new AttributeData()); + +// Work variables to avoid garbage collection +let $startIndex = 0; + +/** Factor when to cleanup underlying array buffer after shrinking. */ +const CLEANUP_THRESHOLD = 2; + +/** + * Typed array based bufferline implementation. + * + * There are 2 ways to insert data into the cell buffer: + * - `setCellFromCodepoint` + `addCodepointToCell` + * Use these for data that is already UTF32. + * Used during normal input in `InputHandler` for faster buffer access. + * - `setCell` + * This method takes a CellData object and stores the data in the buffer. + * Use `CellData.fromCharData` to create the CellData object (e.g. from JS string). + * + * To retrieve data from the buffer use either one of the primitive methods + * (if only one particular value is needed) or `loadCell`. For `loadCell` in a loop + * memory allocs / GC pressure can be greatly reduced by reusing the CellData object. + */ +export class BufferLine implements IBufferLine { + protected _data: Uint32Array; + protected _combined: {[index: number]: string} = {}; + protected _extendedAttrs: {[index: number]: IExtendedAttrs | undefined} = {}; + public length: number; + + constructor(cols: number, fillCellData?: ICellData, public isWrapped: boolean = false) { + this._data = new Uint32Array(cols * CELL_SIZE); + const cell = fillCellData || CellData.fromCharData([0, NULL_CELL_CHAR, NULL_CELL_WIDTH, NULL_CELL_CODE]); + for (let i = 0; i < cols; ++i) { + this.setCell(i, cell); + } + this.length = cols; + } + + /** + * Get cell data CharData. + * @deprecated + */ + public get(index: number): CharData { + const content = this._data[index * CELL_SIZE + Cell.CONTENT]; + const cp = content & Content.CODEPOINT_MASK; + return [ + this._data[index * CELL_SIZE + Cell.FG], + (content & Content.IS_COMBINED_MASK) + ? this._combined[index] + : (cp) ? stringFromCodePoint(cp) : '', + content >> Content.WIDTH_SHIFT, + (content & Content.IS_COMBINED_MASK) + ? this._combined[index].charCodeAt(this._combined[index].length - 1) + : cp + ]; + } + + /** + * Set cell data from CharData. + * @deprecated + */ + public set(index: number, value: CharData): void { + this._data[index * CELL_SIZE + Cell.FG] = value[CHAR_DATA_ATTR_INDEX]; + if (value[CHAR_DATA_CHAR_INDEX].length > 1) { + this._combined[index] = value[1]; + this._data[index * CELL_SIZE + Cell.CONTENT] = index | Content.IS_COMBINED_MASK | (value[CHAR_DATA_WIDTH_INDEX] << Content.WIDTH_SHIFT); + } else { + this._data[index * CELL_SIZE + Cell.CONTENT] = value[CHAR_DATA_CHAR_INDEX].charCodeAt(0) | (value[CHAR_DATA_WIDTH_INDEX] << Content.WIDTH_SHIFT); + } + } + + /** + * primitive getters + * use these when only one value is needed, otherwise use `loadCell` + */ + public getWidth(index: number): number { + return this._data[index * CELL_SIZE + Cell.CONTENT] >> Content.WIDTH_SHIFT; + } + + /** Test whether content has width. */ + public hasWidth(index: number): number { + return this._data[index * CELL_SIZE + Cell.CONTENT] & Content.WIDTH_MASK; + } + + /** Get FG cell component. */ + public getFg(index: number): number { + return this._data[index * CELL_SIZE + Cell.FG]; + } + + /** Get BG cell component. */ + public getBg(index: number): number { + return this._data[index * CELL_SIZE + Cell.BG]; + } + + /** + * Test whether contains any chars. + * Basically an empty has no content, but other cells might differ in FG/BG + * from real empty cells. + */ + public hasContent(index: number): number { + return this._data[index * CELL_SIZE + Cell.CONTENT] & Content.HAS_CONTENT_MASK; + } + + /** + * Get codepoint of the cell. + * To be in line with `code` in CharData this either returns + * a single UTF32 codepoint or the last codepoint of a combined string. + */ + public getCodePoint(index: number): number { + const content = this._data[index * CELL_SIZE + Cell.CONTENT]; + if (content & Content.IS_COMBINED_MASK) { + return this._combined[index].charCodeAt(this._combined[index].length - 1); + } + return content & Content.CODEPOINT_MASK; + } + + /** Test whether the cell contains a combined string. */ + public isCombined(index: number): number { + return this._data[index * CELL_SIZE + Cell.CONTENT] & Content.IS_COMBINED_MASK; + } + + /** Returns the string content of the cell. */ + public getString(index: number): string { + const content = this._data[index * CELL_SIZE + Cell.CONTENT]; + if (content & Content.IS_COMBINED_MASK) { + return this._combined[index]; + } + if (content & Content.CODEPOINT_MASK) { + return stringFromCodePoint(content & Content.CODEPOINT_MASK); + } + // return empty string for empty cells + return ''; + } + + /** Get state of protected flag. */ + public isProtected(index: number): number { + return this._data[index * CELL_SIZE + Cell.BG] & BgFlags.PROTECTED; + } + + /** + * Load data at `index` into `cell`. This is used to access cells in a way that's more friendly + * to GC as it significantly reduced the amount of new objects/references needed. + */ + public loadCell(index: number, cell: ICellData): ICellData { + $startIndex = index * CELL_SIZE; + cell.content = this._data[$startIndex + Cell.CONTENT]; + cell.fg = this._data[$startIndex + Cell.FG]; + cell.bg = this._data[$startIndex + Cell.BG]; + if (cell.content & Content.IS_COMBINED_MASK) { + cell.combinedData = this._combined[index]; + } + if (cell.bg & BgFlags.HAS_EXTENDED) { + cell.extended = this._extendedAttrs[index]!; + } + return cell; + } + + /** + * Set data at `index` to `cell`. + */ + public setCell(index: number, cell: ICellData): void { + if (cell.content & Content.IS_COMBINED_MASK) { + this._combined[index] = cell.combinedData; + } + if (cell.bg & BgFlags.HAS_EXTENDED) { + this._extendedAttrs[index] = cell.extended; + } + this._data[index * CELL_SIZE + Cell.CONTENT] = cell.content; + this._data[index * CELL_SIZE + Cell.FG] = cell.fg; + this._data[index * CELL_SIZE + Cell.BG] = cell.bg; + } + + /** + * Set cell data from input handler. + * Since the input handler see the incoming chars as UTF32 codepoints, + * it gets an optimized access method. + */ + public setCellFromCodepoint(index: number, codePoint: number, width: number, attrs: IAttributeData): void { + if (attrs.bg & BgFlags.HAS_EXTENDED) { + this._extendedAttrs[index] = attrs.extended; + } + this._data[index * CELL_SIZE + Cell.CONTENT] = codePoint | (width << Content.WIDTH_SHIFT); + this._data[index * CELL_SIZE + Cell.FG] = attrs.fg; + this._data[index * CELL_SIZE + Cell.BG] = attrs.bg; + } + + /** + * Add a codepoint to a cell from input handler. + * During input stage combining chars with a width of 0 follow and stack + * onto a leading char. Since we already set the attrs + * by the previous `setDataFromCodePoint` call, we can omit it here. + */ + public addCodepointToCell(index: number, codePoint: number, width: number): void { + let content = this._data[index * CELL_SIZE + Cell.CONTENT]; + if (content & Content.IS_COMBINED_MASK) { + // we already have a combined string, simply add + this._combined[index] += stringFromCodePoint(codePoint); + } else { + if (content & Content.CODEPOINT_MASK) { + // normal case for combining chars: + // - move current leading char + new one into combined string + // - set combined flag + this._combined[index] = stringFromCodePoint(content & Content.CODEPOINT_MASK) + stringFromCodePoint(codePoint); + content &= ~Content.CODEPOINT_MASK; // set codepoint in buffer to 0 + content |= Content.IS_COMBINED_MASK; + } else { + // should not happen - we actually have no data in the cell yet + // simply set the data in the cell buffer with a width of 1 + content = codePoint | (1 << Content.WIDTH_SHIFT); + } + } + if (width) { + content &= ~Content.WIDTH_MASK; + content |= width << Content.WIDTH_SHIFT; + } + this._data[index * CELL_SIZE + Cell.CONTENT] = content; + } + + public insertCells(pos: number, n: number, fillCellData: ICellData): void { + pos %= this.length; + + // handle fullwidth at pos: reset cell one to the left if pos is second cell of a wide char + if (pos && this.getWidth(pos - 1) === 2) { + this.setCellFromCodepoint(pos - 1, 0, 1, fillCellData); + } + + if (n < this.length - pos) { + const cell = new CellData(); + for (let i = this.length - pos - n - 1; i >= 0; --i) { + this.setCell(pos + n + i, this.loadCell(pos + i, cell)); + } + for (let i = 0; i < n; ++i) { + this.setCell(pos + i, fillCellData); + } + } else { + for (let i = pos; i < this.length; ++i) { + this.setCell(i, fillCellData); + } + } + + // handle fullwidth at line end: reset last cell if it is first cell of a wide char + if (this.getWidth(this.length - 1) === 2) { + this.setCellFromCodepoint(this.length - 1, 0, 1, fillCellData); + } + } + + public deleteCells(pos: number, n: number, fillCellData: ICellData): void { + pos %= this.length; + if (n < this.length - pos) { + const cell = new CellData(); + for (let i = 0; i < this.length - pos - n; ++i) { + this.setCell(pos + i, this.loadCell(pos + n + i, cell)); + } + for (let i = this.length - n; i < this.length; ++i) { + this.setCell(i, fillCellData); + } + } else { + for (let i = pos; i < this.length; ++i) { + this.setCell(i, fillCellData); + } + } + + // handle fullwidth at pos: + // - reset pos-1 if wide char + // - reset pos if width==0 (previous second cell of a wide char) + if (pos && this.getWidth(pos - 1) === 2) { + this.setCellFromCodepoint(pos - 1, 0, 1, fillCellData); + } + if (this.getWidth(pos) === 0 && !this.hasContent(pos)) { + this.setCellFromCodepoint(pos, 0, 1, fillCellData); + } + } + + public replaceCells(start: number, end: number, fillCellData: ICellData, respectProtect: boolean = false): void { + // full branching on respectProtect==true, hopefully getting fast JIT for standard case + if (respectProtect) { + if (start && this.getWidth(start - 1) === 2 && !this.isProtected(start - 1)) { + this.setCellFromCodepoint(start - 1, 0, 1, fillCellData); + } + if (end < this.length && this.getWidth(end - 1) === 2 && !this.isProtected(end)) { + this.setCellFromCodepoint(end, 0, 1, fillCellData); + } + while (start < end && start < this.length) { + if (!this.isProtected(start)) { + this.setCell(start, fillCellData); + } + start++; + } + return; + } + + // handle fullwidth at start: reset cell one to the left if start is second cell of a wide char + if (start && this.getWidth(start - 1) === 2) { + this.setCellFromCodepoint(start - 1, 0, 1, fillCellData); + } + // handle fullwidth at last cell + 1: reset to empty cell if it is second part of a wide char + if (end < this.length && this.getWidth(end - 1) === 2) { + this.setCellFromCodepoint(end, 0, 1, fillCellData); + } + + while (start < end && start < this.length) { + this.setCell(start++, fillCellData); + } + } + + /** + * Resize BufferLine to `cols` filling excess cells with `fillCellData`. + * The underlying array buffer will not change if there is still enough space + * to hold the new buffer line data. + * Returns a boolean indicating, whether a `cleanupMemory` call would free + * excess memory (true after shrinking > CLEANUP_THRESHOLD). + */ + public resize(cols: number, fillCellData: ICellData): boolean { + if (cols === this.length) { + return this._data.length * 4 * CLEANUP_THRESHOLD < this._data.buffer.byteLength; + } + const uint32Cells = cols * CELL_SIZE; + if (cols > this.length) { + if (this._data.buffer.byteLength >= uint32Cells * 4) { + // optimization: avoid alloc and data copy if buffer has enough room + this._data = new Uint32Array(this._data.buffer, 0, uint32Cells); + } else { + // slow path: new alloc and full data copy + const data = new Uint32Array(uint32Cells); + data.set(this._data); + this._data = data; + } + for (let i = this.length; i < cols; ++i) { + this.setCell(i, fillCellData); + } + } else { + // optimization: just shrink the view on existing buffer + this._data = this._data.subarray(0, uint32Cells); + // Remove any cut off combined data + const keys = Object.keys(this._combined); + for (let i = 0; i < keys.length; i++) { + const key = parseInt(keys[i], 10); + if (key >= cols) { + delete this._combined[key]; + } + } + // remove any cut off extended attributes + const extKeys = Object.keys(this._extendedAttrs); + for (let i = 0; i < extKeys.length; i++) { + const key = parseInt(extKeys[i], 10); + if (key >= cols) { + delete this._extendedAttrs[key]; + } + } + } + this.length = cols; + return uint32Cells * 4 * CLEANUP_THRESHOLD < this._data.buffer.byteLength; + } + + /** + * Cleanup underlying array buffer. + * A cleanup will be triggered if the array buffer exceeds the actual used + * memory by a factor of CLEANUP_THRESHOLD. + * Returns 0 or 1 indicating whether a cleanup happened. + */ + public cleanupMemory(): number { + if (this._data.length * 4 * CLEANUP_THRESHOLD < this._data.buffer.byteLength) { + const data = new Uint32Array(this._data.length); + data.set(this._data); + this._data = data; + return 1; + } + return 0; + } + + /** fill a line with fillCharData */ + public fill(fillCellData: ICellData, respectProtect: boolean = false): void { + // full branching on respectProtect==true, hopefully getting fast JIT for standard case + if (respectProtect) { + for (let i = 0; i < this.length; ++i) { + if (!this.isProtected(i)) { + this.setCell(i, fillCellData); + } + } + return; + } + this._combined = {}; + this._extendedAttrs = {}; + for (let i = 0; i < this.length; ++i) { + this.setCell(i, fillCellData); + } + } + + /** alter to a full copy of line */ + public copyFrom(line: BufferLine): void { + if (this.length !== line.length) { + this._data = new Uint32Array(line._data); + } else { + // use high speed copy if lengths are equal + this._data.set(line._data); + } + this.length = line.length; + this._combined = {}; + for (const el in line._combined) { + this._combined[el] = line._combined[el]; + } + this._extendedAttrs = {}; + for (const el in line._extendedAttrs) { + this._extendedAttrs[el] = line._extendedAttrs[el]; + } + this.isWrapped = line.isWrapped; + } + + /** create a new clone */ + public clone(): IBufferLine { + const newLine = new BufferLine(0); + newLine._data = new Uint32Array(this._data); + newLine.length = this.length; + for (const el in this._combined) { + newLine._combined[el] = this._combined[el]; + } + for (const el in this._extendedAttrs) { + newLine._extendedAttrs[el] = this._extendedAttrs[el]; + } + newLine.isWrapped = this.isWrapped; + return newLine; + } + + public getTrimmedLength(): number { + for (let i = this.length - 1; i >= 0; --i) { + if ((this._data[i * CELL_SIZE + Cell.CONTENT] & Content.HAS_CONTENT_MASK)) { + return i + (this._data[i * CELL_SIZE + Cell.CONTENT] >> Content.WIDTH_SHIFT); + } + } + return 0; + } + + public getNoBgTrimmedLength(): number { + for (let i = this.length - 1; i >= 0; --i) { + if ((this._data[i * CELL_SIZE + Cell.CONTENT] & Content.HAS_CONTENT_MASK) || (this._data[i * CELL_SIZE + Cell.BG] & Attributes.CM_MASK)) { + return i + (this._data[i * CELL_SIZE + Cell.CONTENT] >> Content.WIDTH_SHIFT); + } + } + return 0; + } + + public copyCellsFrom(src: BufferLine, srcCol: number, destCol: number, length: number, applyInReverse: boolean): void { + const srcData = src._data; + if (applyInReverse) { + for (let cell = length - 1; cell >= 0; cell--) { + for (let i = 0; i < CELL_SIZE; i++) { + this._data[(destCol + cell) * CELL_SIZE + i] = srcData[(srcCol + cell) * CELL_SIZE + i]; + } + if (srcData[(srcCol + cell) * CELL_SIZE + Cell.BG] & BgFlags.HAS_EXTENDED) { + this._extendedAttrs[destCol + cell] = src._extendedAttrs[srcCol + cell]; + } + } + } else { + for (let cell = 0; cell < length; cell++) { + for (let i = 0; i < CELL_SIZE; i++) { + this._data[(destCol + cell) * CELL_SIZE + i] = srcData[(srcCol + cell) * CELL_SIZE + i]; + } + if (srcData[(srcCol + cell) * CELL_SIZE + Cell.BG] & BgFlags.HAS_EXTENDED) { + this._extendedAttrs[destCol + cell] = src._extendedAttrs[srcCol + cell]; + } + } + } + + // Move any combined data over as needed, FIXME: repeat for extended attrs + const srcCombinedKeys = Object.keys(src._combined); + for (let i = 0; i < srcCombinedKeys.length; i++) { + const key = parseInt(srcCombinedKeys[i], 10); + if (key >= srcCol) { + this._combined[key - srcCol + destCol] = src._combined[key]; + } + } + } + + /** + * Translates the buffer line to a string. + * + * @param trimRight Whether to trim any empty cells on the right. + * @param startCol The column to start the string (0-based inclusive). + * @param endCol The column to end the string (0-based exclusive). + * @param outColumns if specified, this array will be filled with column numbers such that + * `returnedString[i]` is displayed at `outColumns[i]` column. `outColumns[returnedString.length]` + * is where the character following `returnedString` will be displayed. + * + * When a single cell is translated to multiple UTF-16 code units (e.g. surrogate pair) in the + * returned string, the corresponding entries in `outColumns` will have the same column number. + */ + public translateToString(trimRight?: boolean, startCol?: number, endCol?: number, outColumns?: number[]): string { + startCol = startCol ?? 0; + endCol = endCol ?? this.length; + if (trimRight) { + endCol = Math.min(endCol, this.getTrimmedLength()); + } + if (outColumns) { + outColumns.length = 0; + } + let result = ''; + while (startCol < endCol) { + const content = this._data[startCol * CELL_SIZE + Cell.CONTENT]; + const cp = content & Content.CODEPOINT_MASK; + const chars = (content & Content.IS_COMBINED_MASK) ? this._combined[startCol] : (cp) ? stringFromCodePoint(cp) : WHITESPACE_CELL_CHAR; + result += chars; + if (outColumns) { + for (let i = 0; i < chars.length; ++i) { + outColumns.push(startCol); + } + } + startCol += (content >> Content.WIDTH_SHIFT) || 1; // always advance by at least 1 + } + if (outColumns) { + outColumns.push(startCol); + } + return result; + } +} diff --git a/node_modules/@xterm/xterm/src/common/buffer/BufferRange.ts b/node_modules/@xterm/xterm/src/common/buffer/BufferRange.ts new file mode 100644 index 0000000..aa7ee40 --- /dev/null +++ b/node_modules/@xterm/xterm/src/common/buffer/BufferRange.ts @@ -0,0 +1,13 @@ +/** + * Copyright (c) 2021 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { IBufferRange } from '@xterm/xterm'; + +export function getRangeLength(range: IBufferRange, bufferCols: number): number { + if (range.start.y > range.end.y) { + throw new Error(`Buffer range end (${range.end.x}, ${range.end.y}) cannot be before start (${range.start.x}, ${range.start.y})`); + } + return bufferCols * (range.end.y - range.start.y) + (range.end.x - range.start.x + 1); +} diff --git a/node_modules/@xterm/xterm/src/common/buffer/BufferReflow.ts b/node_modules/@xterm/xterm/src/common/buffer/BufferReflow.ts new file mode 100644 index 0000000..44aa097 --- /dev/null +++ b/node_modules/@xterm/xterm/src/common/buffer/BufferReflow.ts @@ -0,0 +1,226 @@ +/** + * Copyright (c) 2019 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { BufferLine } from 'common/buffer/BufferLine'; +import { CircularList } from 'common/CircularList'; +import { IBufferLine, ICellData } from 'common/Types'; + +export interface INewLayoutResult { + layout: number[]; + countRemoved: number; +} + +/** + * Evaluates and returns indexes to be removed after a reflow larger occurs. Lines will be removed + * when a wrapped line unwraps. + * @param lines The buffer lines. + * @param oldCols The columns before resize + * @param newCols The columns after resize. + * @param bufferAbsoluteY The absolute y position of the cursor (baseY + cursorY). + * @param nullCell The cell data to use when filling in empty cells. + * @param reflowCursorLine Whether to reflow the line containing the cursor. + */ +export function reflowLargerGetLinesToRemove(lines: CircularList, oldCols: number, newCols: number, bufferAbsoluteY: number, nullCell: ICellData, reflowCursorLine: boolean): number[] { + // Gather all BufferLines that need to be removed from the Buffer here so that they can be + // batched up and only committed once + const toRemove: number[] = []; + + for (let y = 0; y < lines.length - 1; y++) { + // Check if this row is wrapped + let i = y; + let nextLine = lines.get(++i) as BufferLine; + if (!nextLine.isWrapped) { + continue; + } + + // Check how many lines it's wrapped for + const wrappedLines: BufferLine[] = [lines.get(y) as BufferLine]; + while (i < lines.length && nextLine.isWrapped) { + wrappedLines.push(nextLine); + nextLine = lines.get(++i) as BufferLine; + } + + if (!reflowCursorLine) { + // If these lines contain the cursor don't touch them, the program will handle fixing up + // wrapped lines with the cursor + if (bufferAbsoluteY >= y && bufferAbsoluteY < i) { + y += wrappedLines.length - 1; + continue; + } + } + + // Copy buffer data to new locations + let destLineIndex = 0; + let destCol = getWrappedLineTrimmedLength(wrappedLines, destLineIndex, oldCols); + let srcLineIndex = 1; + let srcCol = 0; + while (srcLineIndex < wrappedLines.length) { + const srcTrimmedTineLength = getWrappedLineTrimmedLength(wrappedLines, srcLineIndex, oldCols); + const srcRemainingCells = srcTrimmedTineLength - srcCol; + const destRemainingCells = newCols - destCol; + const cellsToCopy = Math.min(srcRemainingCells, destRemainingCells); + + wrappedLines[destLineIndex].copyCellsFrom(wrappedLines[srcLineIndex], srcCol, destCol, cellsToCopy, false); + + destCol += cellsToCopy; + if (destCol === newCols) { + destLineIndex++; + destCol = 0; + } + srcCol += cellsToCopy; + if (srcCol === srcTrimmedTineLength) { + srcLineIndex++; + srcCol = 0; + } + + // Make sure the last cell isn't wide, if it is copy it to the current dest + if (destCol === 0 && destLineIndex !== 0) { + if (wrappedLines[destLineIndex - 1].getWidth(newCols - 1) === 2) { + wrappedLines[destLineIndex].copyCellsFrom(wrappedLines[destLineIndex - 1], newCols - 1, destCol++, 1, false); + // Null out the end of the last row + wrappedLines[destLineIndex - 1].setCell(newCols - 1, nullCell); + } + } + } + + // Clear out remaining cells or fragments could remain; + wrappedLines[destLineIndex].replaceCells(destCol, newCols, nullCell); + + // Work backwards and remove any rows at the end that only contain null cells + let countToRemove = 0; + for (let i = wrappedLines.length - 1; i > 0; i--) { + if (i > destLineIndex || wrappedLines[i].getTrimmedLength() === 0) { + countToRemove++; + } else { + break; + } + } + + if (countToRemove > 0) { + toRemove.push(y + wrappedLines.length - countToRemove); // index + toRemove.push(countToRemove); + } + + y += wrappedLines.length - 1; + } + return toRemove; +} + +/** + * Creates and return the new layout for lines given an array of indexes to be removed. + * @param lines The buffer lines. + * @param toRemove The indexes to remove. + */ +export function reflowLargerCreateNewLayout(lines: CircularList, toRemove: number[]): INewLayoutResult { + const layout: number[] = []; + // First iterate through the list and get the actual indexes to use for rows + let nextToRemoveIndex = 0; + let nextToRemoveStart = toRemove[nextToRemoveIndex]; + let countRemovedSoFar = 0; + for (let i = 0; i < lines.length; i++) { + if (nextToRemoveStart === i) { + const countToRemove = toRemove[++nextToRemoveIndex]; + + // Tell markers that there was a deletion + lines.onDeleteEmitter.fire({ + index: i - countRemovedSoFar, + amount: countToRemove + }); + + i += countToRemove - 1; + countRemovedSoFar += countToRemove; + nextToRemoveStart = toRemove[++nextToRemoveIndex]; + } else { + layout.push(i); + } + } + return { + layout, + countRemoved: countRemovedSoFar + }; +} + +/** + * Applies a new layout to the buffer. This essentially does the same as many splice calls but it's + * done all at once in a single iteration through the list since splice is very expensive. + * @param lines The buffer lines. + * @param newLayout The new layout to apply. + */ +export function reflowLargerApplyNewLayout(lines: CircularList, newLayout: number[]): void { + // Record original lines so they don't get overridden when we rearrange the list + const newLayoutLines: BufferLine[] = []; + for (let i = 0; i < newLayout.length; i++) { + newLayoutLines.push(lines.get(newLayout[i]) as BufferLine); + } + + // Rearrange the list + for (let i = 0; i < newLayoutLines.length; i++) { + lines.set(i, newLayoutLines[i]); + } + lines.length = newLayout.length; +} + +/** + * Gets the new line lengths for a given wrapped line. The purpose of this function it to pre- + * compute the wrapping points since wide characters may need to be wrapped onto the following line. + * This function will return an array of numbers of where each line wraps to, the resulting array + * will only contain the values `newCols` (when the line does not end with a wide character) and + * `newCols - 1` (when the line does end with a wide character), except for the last value which + * will contain the remaining items to fill the line. + * + * Calling this with a `newCols` value of `1` will lock up. + * + * @param wrappedLines The wrapped lines to evaluate. + * @param oldCols The columns before resize. + * @param newCols The columns after resize. + */ +export function reflowSmallerGetNewLineLengths(wrappedLines: BufferLine[], oldCols: number, newCols: number): number[] { + const newLineLengths: number[] = []; + const cellsNeeded = wrappedLines.map((l, i) => getWrappedLineTrimmedLength(wrappedLines, i, oldCols)).reduce((p, c) => p + c); + + // Use srcCol and srcLine to find the new wrapping point, use that to get the cellsAvailable and + // linesNeeded + let srcCol = 0; + let srcLine = 0; + let cellsAvailable = 0; + while (cellsAvailable < cellsNeeded) { + if (cellsNeeded - cellsAvailable < newCols) { + // Add the final line and exit the loop + newLineLengths.push(cellsNeeded - cellsAvailable); + break; + } + srcCol += newCols; + const oldTrimmedLength = getWrappedLineTrimmedLength(wrappedLines, srcLine, oldCols); + if (srcCol > oldTrimmedLength) { + srcCol -= oldTrimmedLength; + srcLine++; + } + const endsWithWide = wrappedLines[srcLine].getWidth(srcCol - 1) === 2; + if (endsWithWide) { + srcCol--; + } + const lineLength = endsWithWide ? newCols - 1 : newCols; + newLineLengths.push(lineLength); + cellsAvailable += lineLength; + } + + return newLineLengths; +} + +export function getWrappedLineTrimmedLength(lines: BufferLine[], i: number, cols: number): number { + // If this is the last row in the wrapped line, get the actual trimmed length + if (i === lines.length - 1) { + return lines[i].getTrimmedLength(); + } + // Detect whether the following line starts with a wide character and the end of the current line + // is null, if so then we can be pretty sure the null character should be excluded from the line + // length] + const endsInNull = !(lines[i].hasContent(cols - 1)) && lines[i].getWidth(cols - 1) === 1; + const followingLineStartsWithWide = lines[i + 1].getWidth(0) === 2; + if (endsInNull && followingLineStartsWithWide) { + return cols - 1; + } + return cols; +} diff --git a/node_modules/@xterm/xterm/src/common/buffer/BufferSet.ts b/node_modules/@xterm/xterm/src/common/buffer/BufferSet.ts new file mode 100644 index 0000000..8f3a6ae --- /dev/null +++ b/node_modules/@xterm/xterm/src/common/buffer/BufferSet.ts @@ -0,0 +1,134 @@ +/** + * Copyright (c) 2017 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { Disposable } from 'vs/base/common/lifecycle'; +import { IAttributeData } from 'common/Types'; +import { Buffer } from 'common/buffer/Buffer'; +import { IBuffer, IBufferSet } from 'common/buffer/Types'; +import { IBufferService, IOptionsService } from 'common/services/Services'; +import { Emitter } from 'vs/base/common/event'; + +/** + * The BufferSet represents the set of two buffers used by xterm terminals (normal and alt) and + * provides also utilities for working with them. + */ +export class BufferSet extends Disposable implements IBufferSet { + private _normal!: Buffer; + private _alt!: Buffer; + private _activeBuffer!: Buffer; + + private readonly _onBufferActivate = this._register(new Emitter<{ activeBuffer: IBuffer, inactiveBuffer: IBuffer }>()); + public readonly onBufferActivate = this._onBufferActivate.event; + + /** + * Create a new BufferSet for the given terminal. + */ + constructor( + private readonly _optionsService: IOptionsService, + private readonly _bufferService: IBufferService + ) { + super(); + this.reset(); + this._register(this._optionsService.onSpecificOptionChange('scrollback', () => this.resize(this._bufferService.cols, this._bufferService.rows))); + this._register(this._optionsService.onSpecificOptionChange('tabStopWidth', () => this.setupTabStops())); + } + + public reset(): void { + this._normal = new Buffer(true, this._optionsService, this._bufferService); + this._normal.fillViewportRows(); + + // The alt buffer should never have scrollback. + // See http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h2-The-Alternate-Screen-Buffer + this._alt = new Buffer(false, this._optionsService, this._bufferService); + this._activeBuffer = this._normal; + this._onBufferActivate.fire({ + activeBuffer: this._normal, + inactiveBuffer: this._alt + }); + + this.setupTabStops(); + } + + /** + * Returns the alt Buffer of the BufferSet + */ + public get alt(): Buffer { + return this._alt; + } + + /** + * Returns the currently active Buffer of the BufferSet + */ + public get active(): Buffer { + return this._activeBuffer; + } + + /** + * Returns the normal Buffer of the BufferSet + */ + public get normal(): Buffer { + return this._normal; + } + + /** + * Sets the normal Buffer of the BufferSet as its currently active Buffer + */ + public activateNormalBuffer(): void { + if (this._activeBuffer === this._normal) { + return; + } + this._normal.x = this._alt.x; + this._normal.y = this._alt.y; + // The alt buffer should always be cleared when we switch to the normal + // buffer. This frees up memory since the alt buffer should always be new + // when activated. + this._alt.clearAllMarkers(); + this._alt.clear(); + this._activeBuffer = this._normal; + this._onBufferActivate.fire({ + activeBuffer: this._normal, + inactiveBuffer: this._alt + }); + } + + /** + * Sets the alt Buffer of the BufferSet as its currently active Buffer + */ + public activateAltBuffer(fillAttr?: IAttributeData): void { + if (this._activeBuffer === this._alt) { + return; + } + // Since the alt buffer is always cleared when the normal buffer is + // activated, we want to fill it when switching to it. + this._alt.fillViewportRows(fillAttr); + this._alt.x = this._normal.x; + this._alt.y = this._normal.y; + this._activeBuffer = this._alt; + this._onBufferActivate.fire({ + activeBuffer: this._alt, + inactiveBuffer: this._normal + }); + } + + /** + * Resizes both normal and alt buffers, adjusting their data accordingly. + * @param newCols The new number of columns. + * @param newRows The new number of rows. + */ + public resize(newCols: number, newRows: number): void { + this._normal.resize(newCols, newRows); + this._alt.resize(newCols, newRows); + this.setupTabStops(newCols); + } + + /** + * Setup the tab stops. + * @param i The index to start setting up tab stops from. + */ + public setupTabStops(i?: number): void { + this._normal.setupTabStops(i); + this._alt.setupTabStops(i); + } +} diff --git a/node_modules/@xterm/xterm/src/common/buffer/CellData.ts b/node_modules/@xterm/xterm/src/common/buffer/CellData.ts new file mode 100644 index 0000000..9454c55 --- /dev/null +++ b/node_modules/@xterm/xterm/src/common/buffer/CellData.ts @@ -0,0 +1,94 @@ +/** + * Copyright (c) 2018 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { CharData, ICellData, IExtendedAttrs } from 'common/Types'; +import { stringFromCodePoint } from 'common/input/TextDecoder'; +import { CHAR_DATA_CHAR_INDEX, CHAR_DATA_WIDTH_INDEX, CHAR_DATA_ATTR_INDEX, Content } from 'common/buffer/Constants'; +import { AttributeData, ExtendedAttrs } from 'common/buffer/AttributeData'; + +/** + * CellData - represents a single Cell in the terminal buffer. + */ +export class CellData extends AttributeData implements ICellData { + /** Helper to create CellData from CharData. */ + public static fromCharData(value: CharData): CellData { + const obj = new CellData(); + obj.setFromCharData(value); + return obj; + } + /** Primitives from terminal buffer. */ + public content = 0; + public fg = 0; + public bg = 0; + public extended: IExtendedAttrs = new ExtendedAttrs(); + public combinedData = ''; + /** Whether cell contains a combined string. */ + public isCombined(): number { + return this.content & Content.IS_COMBINED_MASK; + } + /** Width of the cell. */ + public getWidth(): number { + return this.content >> Content.WIDTH_SHIFT; + } + /** JS string of the content. */ + public getChars(): string { + if (this.content & Content.IS_COMBINED_MASK) { + return this.combinedData; + } + if (this.content & Content.CODEPOINT_MASK) { + return stringFromCodePoint(this.content & Content.CODEPOINT_MASK); + } + return ''; + } + /** + * Codepoint of cell + * Note this returns the UTF32 codepoint of single chars, + * if content is a combined string it returns the codepoint + * of the last char in string to be in line with code in CharData. + */ + public getCode(): number { + return (this.isCombined()) + ? this.combinedData.charCodeAt(this.combinedData.length - 1) + : this.content & Content.CODEPOINT_MASK; + } + /** Set data from CharData */ + public setFromCharData(value: CharData): void { + this.fg = value[CHAR_DATA_ATTR_INDEX]; + this.bg = 0; + let combined = false; + // surrogates and combined strings need special treatment + if (value[CHAR_DATA_CHAR_INDEX].length > 2) { + combined = true; + } + else if (value[CHAR_DATA_CHAR_INDEX].length === 2) { + const code = value[CHAR_DATA_CHAR_INDEX].charCodeAt(0); + // if the 2-char string is a surrogate create single codepoint + // everything else is combined + if (0xD800 <= code && code <= 0xDBFF) { + const second = value[CHAR_DATA_CHAR_INDEX].charCodeAt(1); + if (0xDC00 <= second && second <= 0xDFFF) { + this.content = ((code - 0xD800) * 0x400 + second - 0xDC00 + 0x10000) | (value[CHAR_DATA_WIDTH_INDEX] << Content.WIDTH_SHIFT); + } + else { + combined = true; + } + } + else { + combined = true; + } + } + else { + this.content = value[CHAR_DATA_CHAR_INDEX].charCodeAt(0) | (value[CHAR_DATA_WIDTH_INDEX] << Content.WIDTH_SHIFT); + } + if (combined) { + this.combinedData = value[CHAR_DATA_CHAR_INDEX]; + this.content = Content.IS_COMBINED_MASK | (value[CHAR_DATA_WIDTH_INDEX] << Content.WIDTH_SHIFT); + } + } + /** Get data as CharData. */ + public getAsCharData(): CharData { + return [this.fg, this.getChars(), this.getWidth(), this.getCode()]; + } +} diff --git a/node_modules/@xterm/xterm/src/common/buffer/Constants.ts b/node_modules/@xterm/xterm/src/common/buffer/Constants.ts new file mode 100644 index 0000000..5ce075c --- /dev/null +++ b/node_modules/@xterm/xterm/src/common/buffer/Constants.ts @@ -0,0 +1,157 @@ +/** + * Copyright (c) 2019 The xterm.js authors. All rights reserved. + * @license MIT + */ + +export const DEFAULT_COLOR = 0; +export const DEFAULT_ATTR = (0 << 18) | (DEFAULT_COLOR << 9) | (256 << 0); +export const DEFAULT_EXT = 0; + +export const CHAR_DATA_ATTR_INDEX = 0; +export const CHAR_DATA_CHAR_INDEX = 1; +export const CHAR_DATA_WIDTH_INDEX = 2; +export const CHAR_DATA_CODE_INDEX = 3; + +/** + * Null cell - a real empty cell (containing nothing). + * Note that code should always be 0 for a null cell as + * several test condition of the buffer line rely on this. + */ +export const NULL_CELL_CHAR = ''; +export const NULL_CELL_WIDTH = 1; +export const NULL_CELL_CODE = 0; + +/** + * Whitespace cell. + * This is meant as a replacement for empty cells when needed + * during rendering lines to preserve correct aligment. + */ +export const WHITESPACE_CELL_CHAR = ' '; +export const WHITESPACE_CELL_WIDTH = 1; +export const WHITESPACE_CELL_CODE = 32; + +/** + * Bitmasks for accessing data in `content`. + */ +export const enum Content { + /** + * bit 1..21 codepoint, max allowed in UTF32 is 0x10FFFF (21 bits taken) + * read: `codepoint = content & Content.codepointMask;` + * write: `content |= codepoint & Content.codepointMask;` + * shortcut if precondition `codepoint <= 0x10FFFF` is met: + * `content |= codepoint;` + */ + CODEPOINT_MASK = 0x1FFFFF, + + /** + * bit 22 flag indication whether a cell contains combined content + * read: `isCombined = content & Content.isCombined;` + * set: `content |= Content.isCombined;` + * clear: `content &= ~Content.isCombined;` + */ + IS_COMBINED_MASK = 0x200000, // 1 << 21 + + /** + * bit 1..22 mask to check whether a cell contains any string data + * we need to check for codepoint and isCombined bits to see + * whether a cell contains anything + * read: `isEmpty = !(content & Content.hasContent)` + */ + HAS_CONTENT_MASK = 0x3FFFFF, + + /** + * bit 23..24 wcwidth value of cell, takes 2 bits (ranges from 0..2) + * read: `width = (content & Content.widthMask) >> Content.widthShift;` + * `hasWidth = content & Content.widthMask;` + * as long as wcwidth is highest value in `content`: + * `width = content >> Content.widthShift;` + * write: `content |= (width << Content.widthShift) & Content.widthMask;` + * shortcut if precondition `0 <= width <= 3` is met: + * `content |= width << Content.widthShift;` + */ + WIDTH_MASK = 0xC00000, // 3 << 22 + WIDTH_SHIFT = 22 +} + +export const enum Attributes { + /** + * bit 1..8 blue in RGB, color in P256 and P16 + */ + BLUE_MASK = 0xFF, + BLUE_SHIFT = 0, + PCOLOR_MASK = 0xFF, + PCOLOR_SHIFT = 0, + + /** + * bit 9..16 green in RGB + */ + GREEN_MASK = 0xFF00, + GREEN_SHIFT = 8, + + /** + * bit 17..24 red in RGB + */ + RED_MASK = 0xFF0000, + RED_SHIFT = 16, + + /** + * bit 25..26 color mode: DEFAULT (0) | P16 (1) | P256 (2) | RGB (3) + */ + CM_MASK = 0x3000000, + CM_DEFAULT = 0, + CM_P16 = 0x1000000, + CM_P256 = 0x2000000, + CM_RGB = 0x3000000, + + /** + * bit 1..24 RGB room + */ + RGB_MASK = 0xFFFFFF +} + +export const enum FgFlags { + /** + * bit 27..32 + */ + INVERSE = 0x4000000, + BOLD = 0x8000000, + UNDERLINE = 0x10000000, + BLINK = 0x20000000, + INVISIBLE = 0x40000000, + STRIKETHROUGH = 0x80000000, +} + +export const enum BgFlags { + /** + * bit 27..32 (upper 2 unused) + */ + ITALIC = 0x4000000, + DIM = 0x8000000, + HAS_EXTENDED = 0x10000000, + PROTECTED = 0x20000000, + OVERLINE = 0x40000000 +} + +export const enum ExtFlags { + /** + * bit 27..29 + */ + UNDERLINE_STYLE = 0x1C000000, + + /** + * bit 30..32 + * + * An optional variant for the glyph, this can be used for example to offset underlines by a + * number of pixels to create a perfect pattern. + */ + VARIANT_OFFSET = 0xE0000000 +} + +export const enum UnderlineStyle { + NONE = 0, + SINGLE = 1, + DOUBLE = 2, + CURLY = 3, + DOTTED = 4, + DASHED = 5 +} diff --git a/node_modules/@xterm/xterm/src/common/buffer/Marker.ts b/node_modules/@xterm/xterm/src/common/buffer/Marker.ts new file mode 100644 index 0000000..a83cf87 --- /dev/null +++ b/node_modules/@xterm/xterm/src/common/buffer/Marker.ts @@ -0,0 +1,43 @@ +/** + * Copyright (c) 2018 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { IDisposable, IMarker } from 'common/Types'; +import { Emitter } from 'vs/base/common/event'; +import { dispose } from 'vs/base/common/lifecycle'; + +export class Marker implements IMarker { + private static _nextId = 1; + + public isDisposed: boolean = false; + private readonly _disposables: IDisposable[] = []; + + private readonly _id: number = Marker._nextId++; + public get id(): number { return this._id; } + + private readonly _onDispose = this.register(new Emitter()); + public readonly onDispose = this._onDispose.event; + + constructor( + public line: number + ) { + } + + public dispose(): void { + if (this.isDisposed) { + return; + } + this.isDisposed = true; + this.line = -1; + // Emit before super.dispose such that dispose listeners get a change to react + this._onDispose.fire(); + dispose(this._disposables); + this._disposables.length = 0; + } + + public register(disposable: T): T { + this._disposables.push(disposable); + return disposable; + } +} diff --git a/node_modules/@xterm/xterm/src/common/buffer/Types.ts b/node_modules/@xterm/xterm/src/common/buffer/Types.ts new file mode 100644 index 0000000..a59c0e1 --- /dev/null +++ b/node_modules/@xterm/xterm/src/common/buffer/Types.ts @@ -0,0 +1,52 @@ +/** + * Copyright (c) 2019 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { IAttributeData, ICircularList, IBufferLine, ICellData, IMarker, ICharset, IDisposable } from 'common/Types'; +import type { Event } from 'vs/base/common/event'; + +// BufferIndex denotes a position in the buffer: [rowIndex, colIndex] +export type BufferIndex = [number, number]; + +export interface IBuffer { + readonly lines: ICircularList; + ydisp: number; + ybase: number; + y: number; + x: number; + tabs: any; + scrollBottom: number; + scrollTop: number; + hasScrollback: boolean; + savedY: number; + savedX: number; + savedCharset: ICharset | undefined; + savedCurAttrData: IAttributeData; + isCursorInViewport: boolean; + markers: IMarker[]; + translateBufferLineToString(lineIndex: number, trimRight: boolean, startCol?: number, endCol?: number): string; + getWrappedRangeForLine(y: number): { first: number, last: number }; + nextStop(x?: number): number; + prevStop(x?: number): number; + getBlankLine(attr: IAttributeData, isWrapped?: boolean): IBufferLine; + getNullCell(attr?: IAttributeData): ICellData; + getWhitespaceCell(attr?: IAttributeData): ICellData; + addMarker(y: number): IMarker; + clearMarkers(y: number): void; + clearAllMarkers(): void; +} + +export interface IBufferSet extends IDisposable { + alt: IBuffer; + normal: IBuffer; + active: IBuffer; + + onBufferActivate: Event<{ activeBuffer: IBuffer, inactiveBuffer: IBuffer }>; + + activateNormalBuffer(): void; + activateAltBuffer(fillAttr?: IAttributeData): void; + reset(): void; + resize(newCols: number, newRows: number): void; + setupTabStops(i?: number): void; +} diff --git a/node_modules/@xterm/xterm/src/common/data/Charsets.ts b/node_modules/@xterm/xterm/src/common/data/Charsets.ts new file mode 100644 index 0000000..c72d5a2 --- /dev/null +++ b/node_modules/@xterm/xterm/src/common/data/Charsets.ts @@ -0,0 +1,256 @@ +/** + * Copyright (c) 2016 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { ICharset } from 'common/Types'; + +/** + * The character sets supported by the terminal. These enable several languages + * to be represented within the terminal with only 8-bit encoding. See ISO 2022 + * for a discussion on character sets. Only VT100 character sets are supported. + */ +export const CHARSETS: { [key: string]: ICharset | undefined } = {}; + +/** + * The default character set, US. + */ +export const DEFAULT_CHARSET: ICharset | undefined = CHARSETS['B']; + +/** + * DEC Special Character and Line Drawing Set. + * Reference: http://vt100.net/docs/vt102-ug/table5-13.html + * A lot of curses apps use this if they see TERM=xterm. + * testing: echo -e '\e(0a\e(B' + * The xterm output sometimes seems to conflict with the + * reference above. xterm seems in line with the reference + * when running vttest however. + * The table below now uses xterm's output from vttest. + */ +CHARSETS['0'] = { + '`': '\u25c6', // '◆' + 'a': '\u2592', // '▒' + 'b': '\u2409', // '␉' (HT) + 'c': '\u240c', // '␌' (FF) + 'd': '\u240d', // '␍' (CR) + 'e': '\u240a', // '␊' (LF) + 'f': '\u00b0', // '°' + 'g': '\u00b1', // '±' + 'h': '\u2424', // '␤' (NL) + 'i': '\u240b', // '␋' (VT) + 'j': '\u2518', // '┘' + 'k': '\u2510', // '┐' + 'l': '\u250c', // '┌' + 'm': '\u2514', // '└' + 'n': '\u253c', // '┼' + 'o': '\u23ba', // '⎺' + 'p': '\u23bb', // '⎻' + 'q': '\u2500', // '─' + 'r': '\u23bc', // '⎼' + 's': '\u23bd', // '⎽' + 't': '\u251c', // '├' + 'u': '\u2524', // '┤' + 'v': '\u2534', // '┴' + 'w': '\u252c', // '┬' + 'x': '\u2502', // '│' + 'y': '\u2264', // '≤' + 'z': '\u2265', // '≥' + '{': '\u03c0', // 'π' + '|': '\u2260', // '≠' + '}': '\u00a3', // '£' + '~': '\u00b7' // '·' +}; + +/** + * British character set + * ESC (A + * Reference: http://vt100.net/docs/vt220-rm/table2-5.html + */ +CHARSETS['A'] = { + '#': '£' +}; + +/** + * United States character set + * ESC (B + */ +CHARSETS['B'] = undefined; + +/** + * Dutch character set + * ESC (4 + * Reference: http://vt100.net/docs/vt220-rm/table2-6.html + */ +CHARSETS['4'] = { + '#': '£', + '@': '¾', + '[': 'ij', + '\\': '½', + ']': '|', + '{': '¨', + '|': 'f', + '}': '¼', + '~': '´' +}; + +/** + * Finnish character set + * ESC (C or ESC (5 + * Reference: http://vt100.net/docs/vt220-rm/table2-7.html + */ +CHARSETS['C'] = +CHARSETS['5'] = { + '[': 'Ä', + '\\': 'Ö', + ']': 'Å', + '^': 'Ü', + '`': 'é', + '{': 'ä', + '|': 'ö', + '}': 'å', + '~': 'ü' +}; + +/** + * French character set + * ESC (R + * Reference: http://vt100.net/docs/vt220-rm/table2-8.html + */ +CHARSETS['R'] = { + '#': '£', + '@': 'à', + '[': '°', + '\\': 'ç', + ']': '§', + '{': 'é', + '|': 'ù', + '}': 'è', + '~': '¨' +}; + +/** + * French Canadian character set + * ESC (Q + * Reference: http://vt100.net/docs/vt220-rm/table2-9.html + */ +CHARSETS['Q'] = { + '@': 'à', + '[': 'â', + '\\': 'ç', + ']': 'ê', + '^': 'î', + '`': 'ô', + '{': 'é', + '|': 'ù', + '}': 'è', + '~': 'û' +}; + +/** + * German character set + * ESC (K + * Reference: http://vt100.net/docs/vt220-rm/table2-10.html + */ +CHARSETS['K'] = { + '@': '§', + '[': 'Ä', + '\\': 'Ö', + ']': 'Ü', + '{': 'ä', + '|': 'ö', + '}': 'ü', + '~': 'ß' +}; + +/** + * Italian character set + * ESC (Y + * Reference: http://vt100.net/docs/vt220-rm/table2-11.html + */ +CHARSETS['Y'] = { + '#': '£', + '@': '§', + '[': '°', + '\\': 'ç', + ']': 'é', + '`': 'ù', + '{': 'à', + '|': 'ò', + '}': 'è', + '~': 'ì' +}; + +/** + * Norwegian/Danish character set + * ESC (E or ESC (6 + * Reference: http://vt100.net/docs/vt220-rm/table2-12.html + */ +CHARSETS['E'] = +CHARSETS['6'] = { + '@': 'Ä', + '[': 'Æ', + '\\': 'Ø', + ']': 'Å', + '^': 'Ü', + '`': 'ä', + '{': 'æ', + '|': 'ø', + '}': 'å', + '~': 'ü' +}; + +/** + * Spanish character set + * ESC (Z + * Reference: http://vt100.net/docs/vt220-rm/table2-13.html + */ +CHARSETS['Z'] = { + '#': '£', + '@': '§', + '[': '¡', + '\\': 'Ñ', + ']': '¿', + '{': '°', + '|': 'ñ', + '}': 'ç' +}; + +/** + * Swedish character set + * ESC (H or ESC (7 + * Reference: http://vt100.net/docs/vt220-rm/table2-14.html + */ +CHARSETS['H'] = +CHARSETS['7'] = { + '@': 'É', + '[': 'Ä', + '\\': 'Ö', + ']': 'Å', + '^': 'Ü', + '`': 'é', + '{': 'ä', + '|': 'ö', + '}': 'å', + '~': 'ü' +}; + +/** + * Swiss character set + * ESC (= + * Reference: http://vt100.net/docs/vt220-rm/table2-15.html + */ +CHARSETS['='] = { + '#': 'ù', + '@': 'à', + '[': 'é', + '\\': 'ç', + ']': 'ê', + '^': 'î', + // eslint-disable-next-line @typescript-eslint/naming-convention + '_': 'è', + '`': 'ô', + '{': 'ä', + '|': 'ö', + '}': 'ü', + '~': 'û' +}; diff --git a/node_modules/@xterm/xterm/src/common/data/EscapeSequences.ts b/node_modules/@xterm/xterm/src/common/data/EscapeSequences.ts new file mode 100644 index 0000000..0e03462 --- /dev/null +++ b/node_modules/@xterm/xterm/src/common/data/EscapeSequences.ts @@ -0,0 +1,153 @@ +/** + * Copyright (c) 2017 The xterm.js authors. All rights reserved. + * @license MIT + */ + +/** + * C0 control codes + * See = https://en.wikipedia.org/wiki/C0_and_C1_control_codes + */ +export namespace C0 { + /** Null (Caret = ^@, C = \0) */ + export const NUL = '\x00'; + /** Start of Heading (Caret = ^A) */ + export const SOH = '\x01'; + /** Start of Text (Caret = ^B) */ + export const STX = '\x02'; + /** End of Text (Caret = ^C) */ + export const ETX = '\x03'; + /** End of Transmission (Caret = ^D) */ + export const EOT = '\x04'; + /** Enquiry (Caret = ^E) */ + export const ENQ = '\x05'; + /** Acknowledge (Caret = ^F) */ + export const ACK = '\x06'; + /** Bell (Caret = ^G, C = \a) */ + export const BEL = '\x07'; + /** Backspace (Caret = ^H, C = \b) */ + export const BS = '\x08'; + /** Character Tabulation, Horizontal Tabulation (Caret = ^I, C = \t) */ + export const HT = '\x09'; + /** Line Feed (Caret = ^J, C = \n) */ + export const LF = '\x0a'; + /** Line Tabulation, Vertical Tabulation (Caret = ^K, C = \v) */ + export const VT = '\x0b'; + /** Form Feed (Caret = ^L, C = \f) */ + export const FF = '\x0c'; + /** Carriage Return (Caret = ^M, C = \r) */ + export const CR = '\x0d'; + /** Shift Out (Caret = ^N) */ + export const SO = '\x0e'; + /** Shift In (Caret = ^O) */ + export const SI = '\x0f'; + /** Data Link Escape (Caret = ^P) */ + export const DLE = '\x10'; + /** Device Control One (XON) (Caret = ^Q) */ + export const DC1 = '\x11'; + /** Device Control Two (Caret = ^R) */ + export const DC2 = '\x12'; + /** Device Control Three (XOFF) (Caret = ^S) */ + export const DC3 = '\x13'; + /** Device Control Four (Caret = ^T) */ + export const DC4 = '\x14'; + /** Negative Acknowledge (Caret = ^U) */ + export const NAK = '\x15'; + /** Synchronous Idle (Caret = ^V) */ + export const SYN = '\x16'; + /** End of Transmission Block (Caret = ^W) */ + export const ETB = '\x17'; + /** Cancel (Caret = ^X) */ + export const CAN = '\x18'; + /** End of Medium (Caret = ^Y) */ + export const EM = '\x19'; + /** Substitute (Caret = ^Z) */ + export const SUB = '\x1a'; + /** Escape (Caret = ^[, C = \e) */ + export const ESC = '\x1b'; + /** File Separator (Caret = ^\) */ + export const FS = '\x1c'; + /** Group Separator (Caret = ^]) */ + export const GS = '\x1d'; + /** Record Separator (Caret = ^^) */ + export const RS = '\x1e'; + /** Unit Separator (Caret = ^_) */ + export const US = '\x1f'; + /** Space */ + export const SP = '\x20'; + /** Delete (Caret = ^?) */ + export const DEL = '\x7f'; +} + +/** + * C1 control codes + * See = https://en.wikipedia.org/wiki/C0_and_C1_control_codes + */ +export namespace C1 { + /** padding character */ + export const PAD = '\x80'; + /** High Octet Preset */ + export const HOP = '\x81'; + /** Break Permitted Here */ + export const BPH = '\x82'; + /** No Break Here */ + export const NBH = '\x83'; + /** Index */ + export const IND = '\x84'; + /** Next Line */ + export const NEL = '\x85'; + /** Start of Selected Area */ + export const SSA = '\x86'; + /** End of Selected Area */ + export const ESA = '\x87'; + /** Horizontal Tabulation Set */ + export const HTS = '\x88'; + /** Horizontal Tabulation With Justification */ + export const HTJ = '\x89'; + /** Vertical Tabulation Set */ + export const VTS = '\x8a'; + /** Partial Line Down */ + export const PLD = '\x8b'; + /** Partial Line Up */ + export const PLU = '\x8c'; + /** Reverse Index */ + export const RI = '\x8d'; + /** Single-Shift 2 */ + export const SS2 = '\x8e'; + /** Single-Shift 3 */ + export const SS3 = '\x8f'; + /** Device Control String */ + export const DCS = '\x90'; + /** Private Use 1 */ + export const PU1 = '\x91'; + /** Private Use 2 */ + export const PU2 = '\x92'; + /** Set Transmit State */ + export const STS = '\x93'; + /** Destructive backspace, intended to eliminate ambiguity about meaning of BS. */ + export const CCH = '\x94'; + /** Message Waiting */ + export const MW = '\x95'; + /** Start of Protected Area */ + export const SPA = '\x96'; + /** End of Protected Area */ + export const EPA = '\x97'; + /** Start of String */ + export const SOS = '\x98'; + /** Single Graphic Character Introducer */ + export const SGCI = '\x99'; + /** Single Character Introducer */ + export const SCI = '\x9a'; + /** Control Sequence Introducer */ + export const CSI = '\x9b'; + /** String Terminator */ + export const ST = '\x9c'; + /** Operating System Command */ + export const OSC = '\x9d'; + /** Privacy Message */ + export const PM = '\x9e'; + /** Application Program Command */ + export const APC = '\x9f'; +} +export namespace C1_ESCAPED { + export const ST = `${C0.ESC}\\`; +} diff --git a/node_modules/@xterm/xterm/src/common/input/Keyboard.ts b/node_modules/@xterm/xterm/src/common/input/Keyboard.ts new file mode 100644 index 0000000..c825b41 --- /dev/null +++ b/node_modules/@xterm/xterm/src/common/input/Keyboard.ts @@ -0,0 +1,373 @@ +/** + * Copyright (c) 2014 The xterm.js authors. All rights reserved. + * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License) + * @license MIT + */ + +import { IKeyboardEvent, IKeyboardResult, KeyboardResultType } from 'common/Types'; +import { C0 } from 'common/data/EscapeSequences'; + +// reg + shift key mappings for digits and special chars +const KEYCODE_KEY_MAPPINGS: { [key: number]: [string, string]} = { + // digits 0-9 + 48: ['0', ')'], + 49: ['1', '!'], + 50: ['2', '@'], + 51: ['3', '#'], + 52: ['4', '$'], + 53: ['5', '%'], + 54: ['6', '^'], + 55: ['7', '&'], + 56: ['8', '*'], + 57: ['9', '('], + + // special chars + 186: [';', ':'], + 187: ['=', '+'], + 188: [',', '<'], + 189: ['-', '_'], + 190: ['.', '>'], + 191: ['/', '?'], + 192: ['`', '~'], + 219: ['[', '{'], + 220: ['\\', '|'], + 221: [']', '}'], + 222: ['\'', '"'] +}; + +export function evaluateKeyboardEvent( + ev: IKeyboardEvent, + applicationCursorMode: boolean, + isMac: boolean, + macOptionIsMeta: boolean +): IKeyboardResult { + const result: IKeyboardResult = { + type: KeyboardResultType.SEND_KEY, + // Whether to cancel event propagation (NOTE: this may not be needed since the event is + // canceled at the end of keyDown + cancel: false, + // The new key even to emit + key: undefined + }; + const modifiers = (ev.shiftKey ? 1 : 0) | (ev.altKey ? 2 : 0) | (ev.ctrlKey ? 4 : 0) | (ev.metaKey ? 8 : 0); + switch (ev.keyCode) { + case 0: + if (ev.key === 'UIKeyInputUpArrow') { + if (applicationCursorMode) { + result.key = C0.ESC + 'OA'; + } else { + result.key = C0.ESC + '[A'; + } + } + else if (ev.key === 'UIKeyInputLeftArrow') { + if (applicationCursorMode) { + result.key = C0.ESC + 'OD'; + } else { + result.key = C0.ESC + '[D'; + } + } + else if (ev.key === 'UIKeyInputRightArrow') { + if (applicationCursorMode) { + result.key = C0.ESC + 'OC'; + } else { + result.key = C0.ESC + '[C'; + } + } + else if (ev.key === 'UIKeyInputDownArrow') { + if (applicationCursorMode) { + result.key = C0.ESC + 'OB'; + } else { + result.key = C0.ESC + '[B'; + } + } + break; + case 8: + // backspace + result.key = ev.ctrlKey ? '\b' : C0.DEL; // ^H or ^? + if (ev.altKey) { + result.key = C0.ESC + result.key; + } + break; + case 9: + // tab + if (ev.shiftKey) { + result.key = C0.ESC + '[Z'; + break; + } + result.key = C0.HT; + result.cancel = true; + break; + case 13: + // return/enter + result.key = ev.altKey ? C0.ESC + C0.CR : C0.CR; + result.cancel = true; + break; + case 27: + // escape + result.key = C0.ESC; + if (ev.altKey) { + result.key = C0.ESC + C0.ESC; + } + result.cancel = true; + break; + case 37: + // left-arrow + if (ev.metaKey) { + break; + } + if (modifiers) { + result.key = C0.ESC + '[1;' + (modifiers + 1) + 'D'; + } else if (applicationCursorMode) { + result.key = C0.ESC + 'OD'; + } else { + result.key = C0.ESC + '[D'; + } + break; + case 39: + // right-arrow + if (ev.metaKey) { + break; + } + if (modifiers) { + result.key = C0.ESC + '[1;' + (modifiers + 1) + 'C'; + } else if (applicationCursorMode) { + result.key = C0.ESC + 'OC'; + } else { + result.key = C0.ESC + '[C'; + } + break; + case 38: + // up-arrow + if (ev.metaKey) { + break; + } + if (modifiers) { + result.key = C0.ESC + '[1;' + (modifiers + 1) + 'A'; + } else if (applicationCursorMode) { + result.key = C0.ESC + 'OA'; + } else { + result.key = C0.ESC + '[A'; + } + break; + case 40: + // down-arrow + if (ev.metaKey) { + break; + } + if (modifiers) { + result.key = C0.ESC + '[1;' + (modifiers + 1) + 'B'; + } else if (applicationCursorMode) { + result.key = C0.ESC + 'OB'; + } else { + result.key = C0.ESC + '[B'; + } + break; + case 45: + // insert + if (!ev.shiftKey && !ev.ctrlKey) { + // or + are used to + // copy-paste on some systems. + result.key = C0.ESC + '[2~'; + } + break; + case 46: + // delete + if (modifiers) { + result.key = C0.ESC + '[3;' + (modifiers + 1) + '~'; + } else { + result.key = C0.ESC + '[3~'; + } + break; + case 36: + // home + if (modifiers) { + result.key = C0.ESC + '[1;' + (modifiers + 1) + 'H'; + } else if (applicationCursorMode) { + result.key = C0.ESC + 'OH'; + } else { + result.key = C0.ESC + '[H'; + } + break; + case 35: + // end + if (modifiers) { + result.key = C0.ESC + '[1;' + (modifiers + 1) + 'F'; + } else if (applicationCursorMode) { + result.key = C0.ESC + 'OF'; + } else { + result.key = C0.ESC + '[F'; + } + break; + case 33: + // page up + if (ev.shiftKey) { + result.type = KeyboardResultType.PAGE_UP; + } else if (ev.ctrlKey) { + result.key = C0.ESC + '[5;' + (modifiers + 1) + '~'; + } else { + result.key = C0.ESC + '[5~'; + } + break; + case 34: + // page down + if (ev.shiftKey) { + result.type = KeyboardResultType.PAGE_DOWN; + } else if (ev.ctrlKey) { + result.key = C0.ESC + '[6;' + (modifiers + 1) + '~'; + } else { + result.key = C0.ESC + '[6~'; + } + break; + case 112: + // F1-F12 + if (modifiers) { + result.key = C0.ESC + '[1;' + (modifiers + 1) + 'P'; + } else { + result.key = C0.ESC + 'OP'; + } + break; + case 113: + if (modifiers) { + result.key = C0.ESC + '[1;' + (modifiers + 1) + 'Q'; + } else { + result.key = C0.ESC + 'OQ'; + } + break; + case 114: + if (modifiers) { + result.key = C0.ESC + '[1;' + (modifiers + 1) + 'R'; + } else { + result.key = C0.ESC + 'OR'; + } + break; + case 115: + if (modifiers) { + result.key = C0.ESC + '[1;' + (modifiers + 1) + 'S'; + } else { + result.key = C0.ESC + 'OS'; + } + break; + case 116: + if (modifiers) { + result.key = C0.ESC + '[15;' + (modifiers + 1) + '~'; + } else { + result.key = C0.ESC + '[15~'; + } + break; + case 117: + if (modifiers) { + result.key = C0.ESC + '[17;' + (modifiers + 1) + '~'; + } else { + result.key = C0.ESC + '[17~'; + } + break; + case 118: + if (modifiers) { + result.key = C0.ESC + '[18;' + (modifiers + 1) + '~'; + } else { + result.key = C0.ESC + '[18~'; + } + break; + case 119: + if (modifiers) { + result.key = C0.ESC + '[19;' + (modifiers + 1) + '~'; + } else { + result.key = C0.ESC + '[19~'; + } + break; + case 120: + if (modifiers) { + result.key = C0.ESC + '[20;' + (modifiers + 1) + '~'; + } else { + result.key = C0.ESC + '[20~'; + } + break; + case 121: + if (modifiers) { + result.key = C0.ESC + '[21;' + (modifiers + 1) + '~'; + } else { + result.key = C0.ESC + '[21~'; + } + break; + case 122: + if (modifiers) { + result.key = C0.ESC + '[23;' + (modifiers + 1) + '~'; + } else { + result.key = C0.ESC + '[23~'; + } + break; + case 123: + if (modifiers) { + result.key = C0.ESC + '[24;' + (modifiers + 1) + '~'; + } else { + result.key = C0.ESC + '[24~'; + } + break; + default: + // a-z and space + if (ev.ctrlKey && !ev.shiftKey && !ev.altKey && !ev.metaKey) { + if (ev.keyCode >= 65 && ev.keyCode <= 90) { + result.key = String.fromCharCode(ev.keyCode - 64); + } else if (ev.keyCode === 32) { + result.key = C0.NUL; + } else if (ev.keyCode >= 51 && ev.keyCode <= 55) { + // escape, file sep, group sep, record sep, unit sep + result.key = String.fromCharCode(ev.keyCode - 51 + 27); + } else if (ev.keyCode === 56) { + result.key = C0.DEL; + } else if (ev.keyCode === 219) { + result.key = C0.ESC; + } else if (ev.keyCode === 220) { + result.key = C0.FS; + } else if (ev.keyCode === 221) { + result.key = C0.GS; + } + } else if ((!isMac || macOptionIsMeta) && ev.altKey && !ev.metaKey) { + // On macOS this is a third level shift when !macOptionIsMeta. Use instead. + const keyMapping = KEYCODE_KEY_MAPPINGS[ev.keyCode]; + const key = keyMapping?.[!ev.shiftKey ? 0 : 1]; + if (key) { + result.key = C0.ESC + key; + } else if (ev.keyCode >= 65 && ev.keyCode <= 90) { + const keyCode = ev.ctrlKey ? ev.keyCode - 64 : ev.keyCode + 32; + let keyString = String.fromCharCode(keyCode); + if (ev.shiftKey) { + keyString = keyString.toUpperCase(); + } + result.key = C0.ESC + keyString; + } else if (ev.keyCode === 32) { + result.key = C0.ESC + (ev.ctrlKey ? C0.NUL : ' '); + } else if (ev.key === 'Dead' && ev.code.startsWith('Key')) { + // Reference: https://github.com/xtermjs/xterm.js/issues/3725 + // Alt will produce a "dead key" (initate composition) with some + // of the letters in US layout (e.g. N/E/U). + // It's safe to match against Key* since no other `code` values begin with "Key". + // https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code/code_values#code_values_on_mac + let keyString = ev.code.slice(3, 4); + if (!ev.shiftKey) { + keyString = keyString.toLowerCase(); + } + result.key = C0.ESC + keyString; + result.cancel = true; + } + } else if (isMac && !ev.altKey && !ev.ctrlKey && !ev.shiftKey && ev.metaKey) { + if (ev.keyCode === 65) { // cmd + a + result.type = KeyboardResultType.SELECT_ALL; + } + } else if (ev.key && !ev.ctrlKey && !ev.altKey && !ev.metaKey && ev.keyCode >= 48 && ev.key.length === 1) { + // Include only keys that that result in a _single_ character; don't include num lock, + // volume up, etc. + result.key = ev.key; + } else if (ev.key && ev.ctrlKey) { + if (ev.key === '_') { // ^_ + result.key = C0.US; + } + if (ev.key === '@') { // ^ + shift + 2 = ^ + @ + result.key = C0.NUL; + } + } + break; + } + + return result; +} diff --git a/node_modules/@xterm/xterm/src/common/input/TextDecoder.ts b/node_modules/@xterm/xterm/src/common/input/TextDecoder.ts new file mode 100644 index 0000000..7ec9c7c --- /dev/null +++ b/node_modules/@xterm/xterm/src/common/input/TextDecoder.ts @@ -0,0 +1,346 @@ +/** + * Copyright (c) 2019 The xterm.js authors. All rights reserved. + * @license MIT + */ + +/** + * Polyfill - Convert UTF32 codepoint into JS string. + * Note: The built-in String.fromCodePoint happens to be much slower + * due to additional sanity checks. We can avoid them since + * we always operate on legal UTF32 (granted by the input decoders) + * and use this faster version instead. + */ +export function stringFromCodePoint(codePoint: number): string { + if (codePoint > 0xFFFF) { + codePoint -= 0x10000; + return String.fromCharCode((codePoint >> 10) + 0xD800) + String.fromCharCode((codePoint % 0x400) + 0xDC00); + } + return String.fromCharCode(codePoint); +} + +/** + * Convert UTF32 char codes into JS string. + * Basically the same as `stringFromCodePoint` but for multiple codepoints + * in a loop (which is a lot faster). + */ +export function utf32ToString(data: Uint32Array, start: number = 0, end: number = data.length): string { + let result = ''; + for (let i = start; i < end; ++i) { + let codepoint = data[i]; + if (codepoint > 0xFFFF) { + // JS strings are encoded as UTF16, thus a non BMP codepoint gets converted into a surrogate + // pair conversion rules: + // - subtract 0x10000 from code point, leaving a 20 bit number + // - add high 10 bits to 0xD800 --> first surrogate + // - add low 10 bits to 0xDC00 --> second surrogate + codepoint -= 0x10000; + result += String.fromCharCode((codepoint >> 10) + 0xD800) + String.fromCharCode((codepoint % 0x400) + 0xDC00); + } else { + result += String.fromCharCode(codepoint); + } + } + return result; +} + +/** + * StringToUtf32 - decodes UTF16 sequences into UTF32 codepoints. + * To keep the decoder in line with JS strings it handles single surrogates as UCS2. + */ +export class StringToUtf32 { + private _interim: number = 0; + + /** + * Clears interim and resets decoder to clean state. + */ + public clear(): void { + this._interim = 0; + } + + /** + * Decode JS string to UTF32 codepoints. + * The methods assumes stream input and will store partly transmitted + * surrogate pairs and decode them with the next data chunk. + * Note: The method does no bound checks for target, therefore make sure + * the provided input data does not exceed the size of `target`. + * Returns the number of written codepoints in `target`. + */ + public decode(input: string, target: Uint32Array): number { + const length = input.length; + + if (!length) { + return 0; + } + + let size = 0; + let startPos = 0; + + // handle leftover surrogate high + if (this._interim) { + const second = input.charCodeAt(startPos++); + if (0xDC00 <= second && second <= 0xDFFF) { + target[size++] = (this._interim - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; + } else { + // illegal codepoint (USC2 handling) + target[size++] = this._interim; + target[size++] = second; + } + this._interim = 0; + } + + for (let i = startPos; i < length; ++i) { + const code = input.charCodeAt(i); + // surrogate pair first + if (0xD800 <= code && code <= 0xDBFF) { + if (++i >= length) { + this._interim = code; + return size; + } + const second = input.charCodeAt(i); + if (0xDC00 <= second && second <= 0xDFFF) { + target[size++] = (code - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; + } else { + // illegal codepoint (USC2 handling) + target[size++] = code; + target[size++] = second; + } + continue; + } + if (code === 0xFEFF) { + // BOM + continue; + } + target[size++] = code; + } + return size; + } +} + +/** + * Utf8Decoder - decodes UTF8 byte sequences into UTF32 codepoints. + */ +export class Utf8ToUtf32 { + public interim: Uint8Array = new Uint8Array(3); + + /** + * Clears interim bytes and resets decoder to clean state. + */ + public clear(): void { + this.interim.fill(0); + } + + /** + * Decodes UTF8 byte sequences in `input` to UTF32 codepoints in `target`. + * The methods assumes stream input and will store partly transmitted bytes + * and decode them with the next data chunk. + * Note: The method does no bound checks for target, therefore make sure + * the provided data chunk does not exceed the size of `target`. + * Returns the number of written codepoints in `target`. + */ + public decode(input: Uint8Array, target: Uint32Array): number { + const length = input.length; + + if (!length) { + return 0; + } + + let size = 0; + let byte1: number; + let byte2: number; + let byte3: number; + let byte4: number; + let codepoint = 0; + let startPos = 0; + + // handle leftover bytes + if (this.interim[0]) { + let discardInterim = false; + let cp = this.interim[0]; + cp &= ((((cp & 0xE0) === 0xC0)) ? 0x1F : (((cp & 0xF0) === 0xE0)) ? 0x0F : 0x07); + let pos = 0; + let tmp: number; + while ((tmp = this.interim[++pos] & 0x3F) && pos < 4) { + cp <<= 6; + cp |= tmp; + } + // missing bytes - read ahead from input + const type = (((this.interim[0] & 0xE0) === 0xC0)) ? 2 : (((this.interim[0] & 0xF0) === 0xE0)) ? 3 : 4; + const missing = type - pos; + while (startPos < missing) { + if (startPos >= length) { + return 0; + } + tmp = input[startPos++]; + if ((tmp & 0xC0) !== 0x80) { + // wrong continuation, discard interim bytes completely + startPos--; + discardInterim = true; + break; + } else { + // need to save so we can continue short inputs in next call + this.interim[pos++] = tmp; + cp <<= 6; + cp |= tmp & 0x3F; + } + } + if (!discardInterim) { + // final test is type dependent + if (type === 2) { + if (cp < 0x80) { + // wrong starter byte + startPos--; + } else { + target[size++] = cp; + } + } else if (type === 3) { + if (cp < 0x0800 || (cp >= 0xD800 && cp <= 0xDFFF) || cp === 0xFEFF) { + // illegal codepoint or BOM + } else { + target[size++] = cp; + } + } else { + if (cp < 0x010000 || cp > 0x10FFFF) { + // illegal codepoint + } else { + target[size++] = cp; + } + } + } + this.interim.fill(0); + } + + // loop through input + const fourStop = length - 4; + let i = startPos; + while (i < length) { + /** + * ASCII shortcut with loop unrolled to 4 consecutive ASCII chars. + * This is a compromise between speed gain for ASCII + * and penalty for non ASCII: + * For best ASCII performance the char should be stored directly into target, + * but even a single attempt to write to target and compare afterwards + * penalizes non ASCII really bad (-50%), thus we load the char into byteX first, + * which reduces ASCII performance by ~15%. + * This trial for ASCII reduces non ASCII performance by ~10% which seems acceptible + * compared to the gains. + * Note that this optimization only takes place for 4 consecutive ASCII chars, + * for any shorter it bails out. Worst case - all 4 bytes being read but + * thrown away due to the last being a non ASCII char (-10% performance). + */ + while (i < fourStop + && !((byte1 = input[i]) & 0x80) + && !((byte2 = input[i + 1]) & 0x80) + && !((byte3 = input[i + 2]) & 0x80) + && !((byte4 = input[i + 3]) & 0x80)) + { + target[size++] = byte1; + target[size++] = byte2; + target[size++] = byte3; + target[size++] = byte4; + i += 4; + } + + // reread byte1 + byte1 = input[i++]; + + // 1 byte + if (byte1 < 0x80) { + target[size++] = byte1; + + // 2 bytes + } else if ((byte1 & 0xE0) === 0xC0) { + if (i >= length) { + this.interim[0] = byte1; + return size; + } + byte2 = input[i++]; + if ((byte2 & 0xC0) !== 0x80) { + // wrong continuation + i--; + continue; + } + codepoint = (byte1 & 0x1F) << 6 | (byte2 & 0x3F); + if (codepoint < 0x80) { + // wrong starter byte + i--; + continue; + } + target[size++] = codepoint; + + // 3 bytes + } else if ((byte1 & 0xF0) === 0xE0) { + if (i >= length) { + this.interim[0] = byte1; + return size; + } + byte2 = input[i++]; + if ((byte2 & 0xC0) !== 0x80) { + // wrong continuation + i--; + continue; + } + if (i >= length) { + this.interim[0] = byte1; + this.interim[1] = byte2; + return size; + } + byte3 = input[i++]; + if ((byte3 & 0xC0) !== 0x80) { + // wrong continuation + i--; + continue; + } + codepoint = (byte1 & 0x0F) << 12 | (byte2 & 0x3F) << 6 | (byte3 & 0x3F); + if (codepoint < 0x0800 || (codepoint >= 0xD800 && codepoint <= 0xDFFF) || codepoint === 0xFEFF) { + // illegal codepoint or BOM, no i-- here + continue; + } + target[size++] = codepoint; + + // 4 bytes + } else if ((byte1 & 0xF8) === 0xF0) { + if (i >= length) { + this.interim[0] = byte1; + return size; + } + byte2 = input[i++]; + if ((byte2 & 0xC0) !== 0x80) { + // wrong continuation + i--; + continue; + } + if (i >= length) { + this.interim[0] = byte1; + this.interim[1] = byte2; + return size; + } + byte3 = input[i++]; + if ((byte3 & 0xC0) !== 0x80) { + // wrong continuation + i--; + continue; + } + if (i >= length) { + this.interim[0] = byte1; + this.interim[1] = byte2; + this.interim[2] = byte3; + return size; + } + byte4 = input[i++]; + if ((byte4 & 0xC0) !== 0x80) { + // wrong continuation + i--; + continue; + } + codepoint = (byte1 & 0x07) << 18 | (byte2 & 0x3F) << 12 | (byte3 & 0x3F) << 6 | (byte4 & 0x3F); + if (codepoint < 0x010000 || codepoint > 0x10FFFF) { + // illegal codepoint, no i-- here + continue; + } + target[size++] = codepoint; + } else { + // illegal byte, just skip + } + } + return size; + } +} diff --git a/node_modules/@xterm/xterm/src/common/input/UnicodeV6.ts b/node_modules/@xterm/xterm/src/common/input/UnicodeV6.ts new file mode 100644 index 0000000..83265f7 --- /dev/null +++ b/node_modules/@xterm/xterm/src/common/input/UnicodeV6.ts @@ -0,0 +1,145 @@ +/** + * Copyright (c) 2019 The xterm.js authors. All rights reserved. + * @license MIT + */ +import { IUnicodeVersionProvider, UnicodeCharProperties, UnicodeCharWidth } from 'common/services/Services'; +import { UnicodeService } from 'common/services/UnicodeService'; + +const BMP_COMBINING = [ + [0x0300, 0x036F], [0x0483, 0x0486], [0x0488, 0x0489], + [0x0591, 0x05BD], [0x05BF, 0x05BF], [0x05C1, 0x05C2], + [0x05C4, 0x05C5], [0x05C7, 0x05C7], [0x0600, 0x0603], + [0x0610, 0x0615], [0x064B, 0x065E], [0x0670, 0x0670], + [0x06D6, 0x06E4], [0x06E7, 0x06E8], [0x06EA, 0x06ED], + [0x070F, 0x070F], [0x0711, 0x0711], [0x0730, 0x074A], + [0x07A6, 0x07B0], [0x07EB, 0x07F3], [0x0901, 0x0902], + [0x093C, 0x093C], [0x0941, 0x0948], [0x094D, 0x094D], + [0x0951, 0x0954], [0x0962, 0x0963], [0x0981, 0x0981], + [0x09BC, 0x09BC], [0x09C1, 0x09C4], [0x09CD, 0x09CD], + [0x09E2, 0x09E3], [0x0A01, 0x0A02], [0x0A3C, 0x0A3C], + [0x0A41, 0x0A42], [0x0A47, 0x0A48], [0x0A4B, 0x0A4D], + [0x0A70, 0x0A71], [0x0A81, 0x0A82], [0x0ABC, 0x0ABC], + [0x0AC1, 0x0AC5], [0x0AC7, 0x0AC8], [0x0ACD, 0x0ACD], + [0x0AE2, 0x0AE3], [0x0B01, 0x0B01], [0x0B3C, 0x0B3C], + [0x0B3F, 0x0B3F], [0x0B41, 0x0B43], [0x0B4D, 0x0B4D], + [0x0B56, 0x0B56], [0x0B82, 0x0B82], [0x0BC0, 0x0BC0], + [0x0BCD, 0x0BCD], [0x0C3E, 0x0C40], [0x0C46, 0x0C48], + [0x0C4A, 0x0C4D], [0x0C55, 0x0C56], [0x0CBC, 0x0CBC], + [0x0CBF, 0x0CBF], [0x0CC6, 0x0CC6], [0x0CCC, 0x0CCD], + [0x0CE2, 0x0CE3], [0x0D41, 0x0D43], [0x0D4D, 0x0D4D], + [0x0DCA, 0x0DCA], [0x0DD2, 0x0DD4], [0x0DD6, 0x0DD6], + [0x0E31, 0x0E31], [0x0E34, 0x0E3A], [0x0E47, 0x0E4E], + [0x0EB1, 0x0EB1], [0x0EB4, 0x0EB9], [0x0EBB, 0x0EBC], + [0x0EC8, 0x0ECD], [0x0F18, 0x0F19], [0x0F35, 0x0F35], + [0x0F37, 0x0F37], [0x0F39, 0x0F39], [0x0F71, 0x0F7E], + [0x0F80, 0x0F84], [0x0F86, 0x0F87], [0x0F90, 0x0F97], + [0x0F99, 0x0FBC], [0x0FC6, 0x0FC6], [0x102D, 0x1030], + [0x1032, 0x1032], [0x1036, 0x1037], [0x1039, 0x1039], + [0x1058, 0x1059], [0x1160, 0x11FF], [0x135F, 0x135F], + [0x1712, 0x1714], [0x1732, 0x1734], [0x1752, 0x1753], + [0x1772, 0x1773], [0x17B4, 0x17B5], [0x17B7, 0x17BD], + [0x17C6, 0x17C6], [0x17C9, 0x17D3], [0x17DD, 0x17DD], + [0x180B, 0x180D], [0x18A9, 0x18A9], [0x1920, 0x1922], + [0x1927, 0x1928], [0x1932, 0x1932], [0x1939, 0x193B], + [0x1A17, 0x1A18], [0x1B00, 0x1B03], [0x1B34, 0x1B34], + [0x1B36, 0x1B3A], [0x1B3C, 0x1B3C], [0x1B42, 0x1B42], + [0x1B6B, 0x1B73], [0x1DC0, 0x1DCA], [0x1DFE, 0x1DFF], + [0x200B, 0x200F], [0x202A, 0x202E], [0x2060, 0x2063], + [0x206A, 0x206F], [0x20D0, 0x20EF], [0x302A, 0x302F], + [0x3099, 0x309A], [0xA806, 0xA806], [0xA80B, 0xA80B], + [0xA825, 0xA826], [0xFB1E, 0xFB1E], [0xFE00, 0xFE0F], + [0xFE20, 0xFE23], [0xFEFF, 0xFEFF], [0xFFF9, 0xFFFB] +]; +const HIGH_COMBINING = [ + [0x10A01, 0x10A03], [0x10A05, 0x10A06], [0x10A0C, 0x10A0F], + [0x10A38, 0x10A3A], [0x10A3F, 0x10A3F], [0x1D167, 0x1D169], + [0x1D173, 0x1D182], [0x1D185, 0x1D18B], [0x1D1AA, 0x1D1AD], + [0x1D242, 0x1D244], [0xE0001, 0xE0001], [0xE0020, 0xE007F], + [0xE0100, 0xE01EF] +]; + +// BMP lookup table, lazy initialized during first addon loading +let table: Uint8Array; + +function bisearch(ucs: number, data: number[][]): boolean { + let min = 0; + let max = data.length - 1; + let mid; + if (ucs < data[0][0] || ucs > data[max][1]) { + return false; + } + while (max >= min) { + mid = (min + max) >> 1; + if (ucs > data[mid][1]) { + min = mid + 1; + } else if (ucs < data[mid][0]) { + max = mid - 1; + } else { + return true; + } + } + return false; +} + +export class UnicodeV6 implements IUnicodeVersionProvider { + public readonly version = '6'; + + constructor() { + // init lookup table once + if (!table) { + table = new Uint8Array(65536); + table.fill(1); + table[0] = 0; + // control chars + table.fill(0, 1, 32); + table.fill(0, 0x7f, 0xa0); + + // apply wide char rules first + // wide chars + table.fill(2, 0x1100, 0x1160); + table[0x2329] = 2; + table[0x232a] = 2; + table.fill(2, 0x2e80, 0xa4d0); + table[0x303f] = 1; // wrongly in last line + + table.fill(2, 0xac00, 0xd7a4); + table.fill(2, 0xf900, 0xfb00); + table.fill(2, 0xfe10, 0xfe1a); + table.fill(2, 0xfe30, 0xfe70); + table.fill(2, 0xff00, 0xff61); + table.fill(2, 0xffe0, 0xffe7); + + // apply combining last to ensure we overwrite + // wrongly wide set chars: + // the original algo evals combining first and falls + // through to wide check so we simply do here the opposite + // combining 0 + for (let r = 0; r < BMP_COMBINING.length; ++r) { + table.fill(0, BMP_COMBINING[r][0], BMP_COMBINING[r][1] + 1); + } + } + } + + public wcwidth(num: number): UnicodeCharWidth { + if (num < 32) return 0; + if (num < 127) return 1; + if (num < 65536) return table[num] as UnicodeCharWidth; + if (bisearch(num, HIGH_COMBINING)) return 0; + if ((num >= 0x20000 && num <= 0x2fffd) || (num >= 0x30000 && num <= 0x3fffd)) return 2; + return 1; + } + + public charProperties(codepoint: number, preceding: UnicodeCharProperties): UnicodeCharProperties { + let width = this.wcwidth(codepoint); + let shouldJoin = width === 0 && preceding !== 0; + if (shouldJoin) { + const oldWidth = UnicodeService.extractWidth(preceding); + if (oldWidth === 0) { + shouldJoin = false; + } else if (oldWidth > width) { + width = oldWidth; + } + } + return UnicodeService.createPropertyValue(0, width, shouldJoin); + } +} diff --git a/node_modules/@xterm/xterm/src/common/input/WriteBuffer.ts b/node_modules/@xterm/xterm/src/common/input/WriteBuffer.ts new file mode 100644 index 0000000..801cf3e --- /dev/null +++ b/node_modules/@xterm/xterm/src/common/input/WriteBuffer.ts @@ -0,0 +1,247 @@ + +/** + * Copyright (c) 2019 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { Disposable } from 'vs/base/common/lifecycle'; +import { Emitter } from 'vs/base/common/event'; + +declare const setTimeout: (handler: () => void, timeout?: number) => void; + +/** + * Safety watermark to avoid memory exhaustion and browser engine crash on fast data input. + * Enable flow control to avoid this limit and make sure that your backend correctly + * propagates this to the underlying pty. (see docs for further instructions) + * Since this limit is meant as a safety parachute to prevent browser crashs, + * it is set to a very high number. Typically xterm.js gets unresponsive with + * a 100 times lower number (>500 kB). + */ +const DISCARD_WATERMARK = 50000000; // ~50 MB + +/** + * The max number of ms to spend on writes before allowing the renderer to + * catch up with a 0ms setTimeout. A value of < 33 to keep us close to + * 30fps, and a value of < 16 to try to run at 60fps. Of course, the real FPS + * depends on the time it takes for the renderer to draw the frame. + */ +const WRITE_TIMEOUT_MS = 12; + +/** + * Threshold of max held chunks in the write buffer, that were already processed. + * This is a tradeoff between extensive write buffer shifts (bad runtime) and high + * memory consumption by data thats not used anymore. + */ +const WRITE_BUFFER_LENGTH_THRESHOLD = 50; + +export class WriteBuffer extends Disposable { + private _writeBuffer: (string | Uint8Array)[] = []; + private _callbacks: ((() => void) | undefined)[] = []; + private _pendingData = 0; + private _bufferOffset = 0; + private _isSyncWriting = false; + private _syncCalls = 0; + private _didUserInput = false; + + private readonly _onWriteParsed = this._register(new Emitter()); + public readonly onWriteParsed = this._onWriteParsed.event; + + constructor(private _action: (data: string | Uint8Array, promiseResult?: boolean) => void | Promise) { + super(); + } + + public handleUserInput(): void { + this._didUserInput = true; + } + + /** + * @deprecated Unreliable, to be removed soon. + */ + public writeSync(data: string | Uint8Array, maxSubsequentCalls?: number): void { + // stop writeSync recursions with maxSubsequentCalls argument + // This is dangerous to use as it will lose the current data chunk + // and return immediately. + if (maxSubsequentCalls !== undefined && this._syncCalls > maxSubsequentCalls) { + // comment next line if a whole loop block should only contain x `writeSync` calls + // (total flat vs. deep nested limit) + this._syncCalls = 0; + return; + } + // append chunk to buffer + this._pendingData += data.length; + this._writeBuffer.push(data); + this._callbacks.push(undefined); + + // increase recursion counter + this._syncCalls++; + // exit early if another writeSync loop is active + if (this._isSyncWriting) { + return; + } + this._isSyncWriting = true; + + // force sync processing on pending data chunks to avoid in-band data scrambling + // does the same as innerWrite but without event loop + // we have to do it here as single loop steps to not corrupt loop subject + // by another writeSync call triggered from _action + let chunk: string | Uint8Array | undefined; + while (chunk = this._writeBuffer.shift()) { + this._action(chunk); + const cb = this._callbacks.shift(); + if (cb) cb(); + } + // reset to avoid reprocessing of chunks with scheduled innerWrite call + // stopping scheduled innerWrite by offset > length condition + this._pendingData = 0; + this._bufferOffset = 0x7FFFFFFF; + + // allow another writeSync to loop + this._isSyncWriting = false; + this._syncCalls = 0; + } + + public write(data: string | Uint8Array, callback?: () => void): void { + if (this._pendingData > DISCARD_WATERMARK) { + throw new Error('write data discarded, use flow control to avoid losing data'); + } + + // schedule chunk processing for next event loop run + if (!this._writeBuffer.length) { + this._bufferOffset = 0; + + // If this is the first write call after the user has done some input, + // parse it immediately to minimize input latency, + // otherwise schedule for the next event + if (this._didUserInput) { + this._didUserInput = false; + this._pendingData += data.length; + this._writeBuffer.push(data); + this._callbacks.push(callback); + this._innerWrite(); + return; + } + + setTimeout(() => this._innerWrite()); + } + + this._pendingData += data.length; + this._writeBuffer.push(data); + this._callbacks.push(callback); + } + + /** + * Inner write call, that enters the sliced chunk processing by timing. + * + * `lastTime` indicates, when the last _innerWrite call had started. + * It is used to aggregate async handler execution under a timeout constraint + * effectively lowering the redrawing needs, schematically: + * + * macroTask _innerWrite: + * if (performance.now() - (lastTime | 0) < WRITE_TIMEOUT_MS): + * schedule microTask _innerWrite(lastTime) + * else: + * schedule macroTask _innerWrite(0) + * + * overall execution order on task queues: + * + * macrotasks: [...] --> _innerWrite(0) --> [...] --> screenUpdate --> [...] + * m t: | + * i a: [...] + * c s: | + * r k: while < timeout: + * o s: _innerWrite(timeout) + * + * `promiseResult` depicts the promise resolve value of an async handler. + * This value gets carried forward through all saved stack states of the + * paused parser for proper continuation. + * + * Note, for pure sync code `lastTime` and `promiseResult` have no meaning. + */ + protected _innerWrite(lastTime: number = 0, promiseResult: boolean = true): void { + const startTime = lastTime || performance.now(); + while (this._writeBuffer.length > this._bufferOffset) { + const data = this._writeBuffer[this._bufferOffset]; + const result = this._action(data, promiseResult); + if (result) { + /** + * If we get a promise as return value, we re-schedule the continuation + * as thenable on the promise and exit right away. + * + * The exit here means, that we block input processing at the current active chunk, + * the exact execution position within the chunk is preserved by the saved + * stack content in InputHandler and EscapeSequenceParser. + * + * Resuming happens automatically from that saved stack state. + * Also the resolved promise value is passed along the callstack to + * `EscapeSequenceParser.parse` to correctly resume the stopped handler loop. + * + * Exceptions on async handlers will be logged to console async, but do not interrupt + * the input processing (continues with next handler at the current input position). + */ + + /** + * If a promise takes long to resolve, we should schedule continuation behind setTimeout. + * This might already be too late, if our .then enters really late (executor + prev thens + * took very long). This cannot be solved here for the handler itself (it is the handlers + * responsibility to slice hard work), but we can at least schedule a screen update as we + * gain control. + */ + const continuation: (r: boolean) => void = (r: boolean) => performance.now() - startTime >= WRITE_TIMEOUT_MS + ? setTimeout(() => this._innerWrite(0, r)) + : this._innerWrite(startTime, r); + + /** + * Optimization considerations: + * The continuation above favors FPS over throughput by eval'ing `startTime` on resolve. + * This might schedule too many screen updates with bad throughput drops (in case a slow + * resolving handler sliced its work properly behind setTimeout calls). We cannot spot + * this condition here, also the renderer has no way to spot nonsense updates either. + * FIXME: A proper fix for this would track the FPS at the renderer entry level separately. + * + * If favoring of FPS shows bad throughtput impact, use the following instead. It favors + * throughput by eval'ing `startTime` upfront pulling at least one more chunk into the + * current microtask queue (executed before setTimeout). + */ + // const continuation: (r: boolean) => void = performance.now() - startTime >= + // WRITE_TIMEOUT_MS + // ? r => setTimeout(() => this._innerWrite(0, r)) + // : r => this._innerWrite(startTime, r); + + // Handle exceptions synchronously to current band position, idea: + // 1. spawn a single microtask which we allow to throw hard + // 2. spawn a promise immediately resolving to `true` + // (executed on the same queue, thus properly aligned before continuation happens) + result.catch(err => { + queueMicrotask(() => {throw err;}); + return Promise.resolve(false); + }).then(continuation); + return; + } + + const cb = this._callbacks[this._bufferOffset]; + if (cb) cb(); + this._bufferOffset++; + this._pendingData -= data.length; + + if (performance.now() - startTime >= WRITE_TIMEOUT_MS) { + break; + } + } + if (this._writeBuffer.length > this._bufferOffset) { + // Allow renderer to catch up before processing the next batch + // trim already processed chunks if we are above threshold + if (this._bufferOffset > WRITE_BUFFER_LENGTH_THRESHOLD) { + this._writeBuffer = this._writeBuffer.slice(this._bufferOffset); + this._callbacks = this._callbacks.slice(this._bufferOffset); + this._bufferOffset = 0; + } + setTimeout(() => this._innerWrite()); + } else { + this._writeBuffer.length = 0; + this._callbacks.length = 0; + this._pendingData = 0; + this._bufferOffset = 0; + } + this._onWriteParsed.fire(); + } +} diff --git a/node_modules/@xterm/xterm/src/common/input/XParseColor.ts b/node_modules/@xterm/xterm/src/common/input/XParseColor.ts new file mode 100644 index 0000000..fd23ec4 --- /dev/null +++ b/node_modules/@xterm/xterm/src/common/input/XParseColor.ts @@ -0,0 +1,80 @@ +/** + * Copyright (c) 2021 The xterm.js authors. All rights reserved. + * @license MIT + */ + + +// 'rgb:' rule - matching: r/g/b | rr/gg/bb | rrr/ggg/bbb | rrrr/gggg/bbbb (hex digits) +const RGB_REX = /^([\da-f])\/([\da-f])\/([\da-f])$|^([\da-f]{2})\/([\da-f]{2})\/([\da-f]{2})$|^([\da-f]{3})\/([\da-f]{3})\/([\da-f]{3})$|^([\da-f]{4})\/([\da-f]{4})\/([\da-f]{4})$/; +// '#...' rule - matching any hex digits +const HASH_REX = /^[\da-f]+$/; + +/** + * Parse color spec to RGB values (8 bit per channel). + * See `man xparsecolor` for details about certain format specifications. + * + * Supported formats: + * - rgb:// with , , in h | hh | hhh | hhhh + * - #RGB, #RRGGBB, #RRRGGGBBB, #RRRRGGGGBBBB + * + * All other formats like rgbi: or device-independent string specifications + * with float numbering are not supported. + */ +export function parseColor(data: string): [number, number, number] | undefined { + if (!data) return; + // also handle uppercases + let low = data.toLowerCase(); + if (low.indexOf('rgb:') === 0) { + // 'rgb:' specifier + low = low.slice(4); + const m = RGB_REX.exec(low); + if (m) { + const base = m[1] ? 15 : m[4] ? 255 : m[7] ? 4095 : 65535; + return [ + Math.round(parseInt(m[1] || m[4] || m[7] || m[10], 16) / base * 255), + Math.round(parseInt(m[2] || m[5] || m[8] || m[11], 16) / base * 255), + Math.round(parseInt(m[3] || m[6] || m[9] || m[12], 16) / base * 255) + ]; + } + } else if (low.indexOf('#') === 0) { + // '#' specifier + low = low.slice(1); + if (HASH_REX.exec(low) && [3, 6, 9, 12].includes(low.length)) { + const adv = low.length / 3; + const result: [number, number, number] = [0, 0, 0]; + for (let i = 0; i < 3; ++i) { + const c = parseInt(low.slice(adv * i, adv * i + adv), 16); + result[i] = adv === 1 ? c << 4 : adv === 2 ? c : adv === 3 ? c >> 4 : c >> 8; + } + return result; + } + } + + // Named colors are currently not supported due to the large addition to the xterm.js bundle size + // they would add. In order to support named colors, we would need some way of optionally loading + // additional payloads so startup/download time is not bloated (see #3530). +} + +// pad hex output to requested bit width +function pad(n: number, bits: number): string { + const s = n.toString(16); + const s2 = s.length < 2 ? '0' + s : s; + switch (bits) { + case 4: + return s[0]; + case 8: + return s2; + case 12: + return (s2 + s2).slice(0, 3); + default: + return s2 + s2; + } +} + +/** + * Convert a given color to rgb:../../.. string of `bits` depth. + */ +export function toRgbString(color: [number, number, number], bits: number = 16): string { + const [r, g, b] = color; + return `rgb:${pad(r, bits)}/${pad(g, bits)}/${pad(b, bits)}`; +} diff --git a/node_modules/@xterm/xterm/src/common/parser/Constants.ts b/node_modules/@xterm/xterm/src/common/parser/Constants.ts new file mode 100644 index 0000000..7fe24f3 --- /dev/null +++ b/node_modules/@xterm/xterm/src/common/parser/Constants.ts @@ -0,0 +1,58 @@ +/** + * Copyright (c) 2017 The xterm.js authors. All rights reserved. + * @license MIT + */ + +/** + * Internal states of EscapeSequenceParser. + */ +export const enum ParserState { + GROUND = 0, + ESCAPE = 1, + ESCAPE_INTERMEDIATE = 2, + CSI_ENTRY = 3, + CSI_PARAM = 4, + CSI_INTERMEDIATE = 5, + CSI_IGNORE = 6, + SOS_PM_APC_STRING = 7, + OSC_STRING = 8, + DCS_ENTRY = 9, + DCS_PARAM = 10, + DCS_IGNORE = 11, + DCS_INTERMEDIATE = 12, + DCS_PASSTHROUGH = 13 +} + +/** + * Internal actions of EscapeSequenceParser. + */ +export const enum ParserAction { + IGNORE = 0, + ERROR = 1, + PRINT = 2, + EXECUTE = 3, + OSC_START = 4, + OSC_PUT = 5, + OSC_END = 6, + CSI_DISPATCH = 7, + PARAM = 8, + COLLECT = 9, + ESC_DISPATCH = 10, + CLEAR = 11, + DCS_HOOK = 12, + DCS_PUT = 13, + DCS_UNHOOK = 14 +} + +/** + * Internal states of OscParser. + */ +export const enum OscState { + START = 0, + ID = 1, + PAYLOAD = 2, + ABORT = 3 +} + +// payload limit for OSC and DCS +export const PAYLOAD_LIMIT = 10000000; diff --git a/node_modules/@xterm/xterm/src/common/parser/DcsParser.ts b/node_modules/@xterm/xterm/src/common/parser/DcsParser.ts new file mode 100644 index 0000000..b66524b --- /dev/null +++ b/node_modules/@xterm/xterm/src/common/parser/DcsParser.ts @@ -0,0 +1,192 @@ +/** + * Copyright (c) 2019 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { IDisposable } from 'common/Types'; +import { IDcsHandler, IParams, IHandlerCollection, IDcsParser, DcsFallbackHandlerType, ISubParserStackState } from 'common/parser/Types'; +import { utf32ToString } from 'common/input/TextDecoder'; +import { Params } from 'common/parser/Params'; +import { PAYLOAD_LIMIT } from 'common/parser/Constants'; + +const EMPTY_HANDLERS: IDcsHandler[] = []; + +export class DcsParser implements IDcsParser { + private _handlers: IHandlerCollection = Object.create(null); + private _active: IDcsHandler[] = EMPTY_HANDLERS; + private _ident: number = 0; + private _handlerFb: DcsFallbackHandlerType = () => { }; + private _stack: ISubParserStackState = { + paused: false, + loopPosition: 0, + fallThrough: false + }; + + public dispose(): void { + this._handlers = Object.create(null); + this._handlerFb = () => { }; + this._active = EMPTY_HANDLERS; + } + + public registerHandler(ident: number, handler: IDcsHandler): IDisposable { + if (this._handlers[ident] === undefined) { + this._handlers[ident] = []; + } + const handlerList = this._handlers[ident]; + handlerList.push(handler); + return { + dispose: () => { + const handlerIndex = handlerList.indexOf(handler); + if (handlerIndex !== -1) { + handlerList.splice(handlerIndex, 1); + } + } + }; + } + + public clearHandler(ident: number): void { + if (this._handlers[ident]) delete this._handlers[ident]; + } + + public setHandlerFallback(handler: DcsFallbackHandlerType): void { + this._handlerFb = handler; + } + + public reset(): void { + // force cleanup leftover handlers + if (this._active.length) { + for (let j = this._stack.paused ? this._stack.loopPosition - 1 : this._active.length - 1; j >= 0; --j) { + this._active[j].unhook(false); + } + } + this._stack.paused = false; + this._active = EMPTY_HANDLERS; + this._ident = 0; + } + + public hook(ident: number, params: IParams): void { + // always reset leftover handlers + this.reset(); + this._ident = ident; + this._active = this._handlers[ident] || EMPTY_HANDLERS; + if (!this._active.length) { + this._handlerFb(this._ident, 'HOOK', params); + } else { + for (let j = this._active.length - 1; j >= 0; j--) { + this._active[j].hook(params); + } + } + } + + public put(data: Uint32Array, start: number, end: number): void { + if (!this._active.length) { + this._handlerFb(this._ident, 'PUT', utf32ToString(data, start, end)); + } else { + for (let j = this._active.length - 1; j >= 0; j--) { + this._active[j].put(data, start, end); + } + } + } + + public unhook(success: boolean, promiseResult: boolean = true): void | Promise { + if (!this._active.length) { + this._handlerFb(this._ident, 'UNHOOK', success); + } else { + let handlerResult: boolean | Promise = false; + let j = this._active.length - 1; + let fallThrough = false; + if (this._stack.paused) { + j = this._stack.loopPosition - 1; + handlerResult = promiseResult; + fallThrough = this._stack.fallThrough; + this._stack.paused = false; + } + if (!fallThrough && handlerResult === false) { + for (; j >= 0; j--) { + handlerResult = this._active[j].unhook(success); + if (handlerResult === true) { + break; + } else if (handlerResult instanceof Promise) { + this._stack.paused = true; + this._stack.loopPosition = j; + this._stack.fallThrough = false; + return handlerResult; + } + } + j--; + } + // cleanup left over handlers (fallThrough for async) + for (; j >= 0; j--) { + handlerResult = this._active[j].unhook(false); + if (handlerResult instanceof Promise) { + this._stack.paused = true; + this._stack.loopPosition = j; + this._stack.fallThrough = true; + return handlerResult; + } + } + } + this._active = EMPTY_HANDLERS; + this._ident = 0; + } +} + +// predefine empty params as [0] (ZDM) +const EMPTY_PARAMS = new Params(); +EMPTY_PARAMS.addParam(0); + +/** + * Convenient class to create a DCS handler from a single callback function. + * Note: The payload is currently limited to 50 MB (hardcoded). + */ +export class DcsHandler implements IDcsHandler { + private _data = ''; + private _params: IParams = EMPTY_PARAMS; + private _hitLimit: boolean = false; + + constructor(private _handler: (data: string, params: IParams) => boolean | Promise) { } + + public hook(params: IParams): void { + // since we need to preserve params until `unhook`, we have to clone it + // (only borrowed from parser and spans multiple parser states) + // perf optimization: + // clone only, if we have non empty params, otherwise stick with default + this._params = (params.length > 1 || params.params[0]) ? params.clone() : EMPTY_PARAMS; + this._data = ''; + this._hitLimit = false; + } + + public put(data: Uint32Array, start: number, end: number): void { + if (this._hitLimit) { + return; + } + this._data += utf32ToString(data, start, end); + if (this._data.length > PAYLOAD_LIMIT) { + this._data = ''; + this._hitLimit = true; + } + } + + public unhook(success: boolean): boolean | Promise { + let ret: boolean | Promise = false; + if (this._hitLimit) { + ret = false; + } else if (success) { + ret = this._handler(this._data, this._params); + if (ret instanceof Promise) { + // need to hold data and params until `ret` got resolved + // dont care for errors, data will be freed anyway on next start + return ret.then(res => { + this._params = EMPTY_PARAMS; + this._data = ''; + this._hitLimit = false; + return res; + }); + } + } + this._params = EMPTY_PARAMS; + this._data = ''; + this._hitLimit = false; + return ret; + } +} diff --git a/node_modules/@xterm/xterm/src/common/parser/EscapeSequenceParser.ts b/node_modules/@xterm/xterm/src/common/parser/EscapeSequenceParser.ts new file mode 100644 index 0000000..e13d67f --- /dev/null +++ b/node_modules/@xterm/xterm/src/common/parser/EscapeSequenceParser.ts @@ -0,0 +1,792 @@ +/** + * Copyright (c) 2018 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { IParsingState, IDcsHandler, IEscapeSequenceParser, IParams, IOscHandler, IHandlerCollection, CsiHandlerType, OscFallbackHandlerType, IOscParser, EscHandlerType, IDcsParser, DcsFallbackHandlerType, IFunctionIdentifier, ExecuteFallbackHandlerType, CsiFallbackHandlerType, EscFallbackHandlerType, PrintHandlerType, PrintFallbackHandlerType, ExecuteHandlerType, IParserStackState, ParserStackType, ResumableHandlersType } from 'common/parser/Types'; +import { ParserState, ParserAction } from 'common/parser/Constants'; +import { Disposable, toDisposable } from 'vs/base/common/lifecycle'; +import { IDisposable } from 'common/Types'; +import { Params } from 'common/parser/Params'; +import { OscParser } from 'common/parser/OscParser'; +import { DcsParser } from 'common/parser/DcsParser'; + +/** + * Table values are generated like this: + * index: currentState << TableValue.INDEX_STATE_SHIFT | charCode + * value: action << TableValue.TRANSITION_ACTION_SHIFT | nextState + */ +const enum TableAccess { + TRANSITION_ACTION_SHIFT = 4, + TRANSITION_STATE_MASK = 15, + INDEX_STATE_SHIFT = 8 +} + +/** + * Transition table for EscapeSequenceParser. + */ +export class TransitionTable { + public table: Uint8Array; + + constructor(length: number) { + this.table = new Uint8Array(length); + } + + /** + * Set default transition. + * @param action default action + * @param next default next state + */ + public setDefault(action: ParserAction, next: ParserState): void { + this.table.fill(action << TableAccess.TRANSITION_ACTION_SHIFT | next); + } + + /** + * Add a transition to the transition table. + * @param code input character code + * @param state current parser state + * @param action parser action to be done + * @param next next parser state + */ + public add(code: number, state: ParserState, action: ParserAction, next: ParserState): void { + this.table[state << TableAccess.INDEX_STATE_SHIFT | code] = action << TableAccess.TRANSITION_ACTION_SHIFT | next; + } + + /** + * Add transitions for multiple input character codes. + * @param codes input character code array + * @param state current parser state + * @param action parser action to be done + * @param next next parser state + */ + public addMany(codes: number[], state: ParserState, action: ParserAction, next: ParserState): void { + for (let i = 0; i < codes.length; i++) { + this.table[state << TableAccess.INDEX_STATE_SHIFT | codes[i]] = action << TableAccess.TRANSITION_ACTION_SHIFT | next; + } + } +} + + +// Pseudo-character placeholder for printable non-ascii characters (unicode). +const NON_ASCII_PRINTABLE = 0xA0; + + +/** + * VT500 compatible transition table. + * Taken from https://vt100.net/emu/dec_ansi_parser. + */ +export const VT500_TRANSITION_TABLE = (function (): TransitionTable { + const table: TransitionTable = new TransitionTable(4095); + + // range macro for byte + const BYTE_VALUES = 256; + const blueprint = Array.apply(null, Array(BYTE_VALUES)).map((unused: any, i: number) => i); + const r = (start: number, end: number): number[] => blueprint.slice(start, end); + + // Default definitions. + const PRINTABLES = r(0x20, 0x7f); // 0x20 (SP) included, 0x7F (DEL) excluded + const EXECUTABLES = r(0x00, 0x18); + EXECUTABLES.push(0x19); + EXECUTABLES.push.apply(EXECUTABLES, r(0x1c, 0x20)); + + const states: number[] = r(ParserState.GROUND, ParserState.DCS_PASSTHROUGH + 1); + let state: any; + + // set default transition + table.setDefault(ParserAction.ERROR, ParserState.GROUND); + // printables + table.addMany(PRINTABLES, ParserState.GROUND, ParserAction.PRINT, ParserState.GROUND); + // global anywhere rules + for (state in states) { + table.addMany([0x18, 0x1a, 0x99, 0x9a], state, ParserAction.EXECUTE, ParserState.GROUND); + table.addMany(r(0x80, 0x90), state, ParserAction.EXECUTE, ParserState.GROUND); + table.addMany(r(0x90, 0x98), state, ParserAction.EXECUTE, ParserState.GROUND); + table.add(0x9c, state, ParserAction.IGNORE, ParserState.GROUND); // ST as terminator + table.add(0x1b, state, ParserAction.CLEAR, ParserState.ESCAPE); // ESC + table.add(0x9d, state, ParserAction.OSC_START, ParserState.OSC_STRING); // OSC + table.addMany([0x98, 0x9e, 0x9f], state, ParserAction.IGNORE, ParserState.SOS_PM_APC_STRING); + table.add(0x9b, state, ParserAction.CLEAR, ParserState.CSI_ENTRY); // CSI + table.add(0x90, state, ParserAction.CLEAR, ParserState.DCS_ENTRY); // DCS + } + // rules for executables and 7f + table.addMany(EXECUTABLES, ParserState.GROUND, ParserAction.EXECUTE, ParserState.GROUND); + table.addMany(EXECUTABLES, ParserState.ESCAPE, ParserAction.EXECUTE, ParserState.ESCAPE); + table.add(0x7f, ParserState.ESCAPE, ParserAction.IGNORE, ParserState.ESCAPE); + table.addMany(EXECUTABLES, ParserState.OSC_STRING, ParserAction.IGNORE, ParserState.OSC_STRING); + table.addMany(EXECUTABLES, ParserState.CSI_ENTRY, ParserAction.EXECUTE, ParserState.CSI_ENTRY); + table.add(0x7f, ParserState.CSI_ENTRY, ParserAction.IGNORE, ParserState.CSI_ENTRY); + table.addMany(EXECUTABLES, ParserState.CSI_PARAM, ParserAction.EXECUTE, ParserState.CSI_PARAM); + table.add(0x7f, ParserState.CSI_PARAM, ParserAction.IGNORE, ParserState.CSI_PARAM); + table.addMany(EXECUTABLES, ParserState.CSI_IGNORE, ParserAction.EXECUTE, ParserState.CSI_IGNORE); + table.addMany(EXECUTABLES, ParserState.CSI_INTERMEDIATE, ParserAction.EXECUTE, ParserState.CSI_INTERMEDIATE); + table.add(0x7f, ParserState.CSI_INTERMEDIATE, ParserAction.IGNORE, ParserState.CSI_INTERMEDIATE); + table.addMany(EXECUTABLES, ParserState.ESCAPE_INTERMEDIATE, ParserAction.EXECUTE, ParserState.ESCAPE_INTERMEDIATE); + table.add(0x7f, ParserState.ESCAPE_INTERMEDIATE, ParserAction.IGNORE, ParserState.ESCAPE_INTERMEDIATE); + // osc + table.add(0x5d, ParserState.ESCAPE, ParserAction.OSC_START, ParserState.OSC_STRING); + table.addMany(PRINTABLES, ParserState.OSC_STRING, ParserAction.OSC_PUT, ParserState.OSC_STRING); + table.add(0x7f, ParserState.OSC_STRING, ParserAction.OSC_PUT, ParserState.OSC_STRING); + table.addMany([0x9c, 0x1b, 0x18, 0x1a, 0x07], ParserState.OSC_STRING, ParserAction.OSC_END, ParserState.GROUND); + table.addMany(r(0x1c, 0x20), ParserState.OSC_STRING, ParserAction.IGNORE, ParserState.OSC_STRING); + // sos/pm/apc does nothing + table.addMany([0x58, 0x5e, 0x5f], ParserState.ESCAPE, ParserAction.IGNORE, ParserState.SOS_PM_APC_STRING); + table.addMany(PRINTABLES, ParserState.SOS_PM_APC_STRING, ParserAction.IGNORE, ParserState.SOS_PM_APC_STRING); + table.addMany(EXECUTABLES, ParserState.SOS_PM_APC_STRING, ParserAction.IGNORE, ParserState.SOS_PM_APC_STRING); + table.add(0x9c, ParserState.SOS_PM_APC_STRING, ParserAction.IGNORE, ParserState.GROUND); + table.add(0x7f, ParserState.SOS_PM_APC_STRING, ParserAction.IGNORE, ParserState.SOS_PM_APC_STRING); + // csi entries + table.add(0x5b, ParserState.ESCAPE, ParserAction.CLEAR, ParserState.CSI_ENTRY); + table.addMany(r(0x40, 0x7f), ParserState.CSI_ENTRY, ParserAction.CSI_DISPATCH, ParserState.GROUND); + table.addMany(r(0x30, 0x3c), ParserState.CSI_ENTRY, ParserAction.PARAM, ParserState.CSI_PARAM); + table.addMany([0x3c, 0x3d, 0x3e, 0x3f], ParserState.CSI_ENTRY, ParserAction.COLLECT, ParserState.CSI_PARAM); + table.addMany(r(0x30, 0x3c), ParserState.CSI_PARAM, ParserAction.PARAM, ParserState.CSI_PARAM); + table.addMany(r(0x40, 0x7f), ParserState.CSI_PARAM, ParserAction.CSI_DISPATCH, ParserState.GROUND); + table.addMany([0x3c, 0x3d, 0x3e, 0x3f], ParserState.CSI_PARAM, ParserAction.IGNORE, ParserState.CSI_IGNORE); + table.addMany(r(0x20, 0x40), ParserState.CSI_IGNORE, ParserAction.IGNORE, ParserState.CSI_IGNORE); + table.add(0x7f, ParserState.CSI_IGNORE, ParserAction.IGNORE, ParserState.CSI_IGNORE); + table.addMany(r(0x40, 0x7f), ParserState.CSI_IGNORE, ParserAction.IGNORE, ParserState.GROUND); + table.addMany(r(0x20, 0x30), ParserState.CSI_ENTRY, ParserAction.COLLECT, ParserState.CSI_INTERMEDIATE); + table.addMany(r(0x20, 0x30), ParserState.CSI_INTERMEDIATE, ParserAction.COLLECT, ParserState.CSI_INTERMEDIATE); + table.addMany(r(0x30, 0x40), ParserState.CSI_INTERMEDIATE, ParserAction.IGNORE, ParserState.CSI_IGNORE); + table.addMany(r(0x40, 0x7f), ParserState.CSI_INTERMEDIATE, ParserAction.CSI_DISPATCH, ParserState.GROUND); + table.addMany(r(0x20, 0x30), ParserState.CSI_PARAM, ParserAction.COLLECT, ParserState.CSI_INTERMEDIATE); + // esc_intermediate + table.addMany(r(0x20, 0x30), ParserState.ESCAPE, ParserAction.COLLECT, ParserState.ESCAPE_INTERMEDIATE); + table.addMany(r(0x20, 0x30), ParserState.ESCAPE_INTERMEDIATE, ParserAction.COLLECT, ParserState.ESCAPE_INTERMEDIATE); + table.addMany(r(0x30, 0x7f), ParserState.ESCAPE_INTERMEDIATE, ParserAction.ESC_DISPATCH, ParserState.GROUND); + table.addMany(r(0x30, 0x50), ParserState.ESCAPE, ParserAction.ESC_DISPATCH, ParserState.GROUND); + table.addMany(r(0x51, 0x58), ParserState.ESCAPE, ParserAction.ESC_DISPATCH, ParserState.GROUND); + table.addMany([0x59, 0x5a, 0x5c], ParserState.ESCAPE, ParserAction.ESC_DISPATCH, ParserState.GROUND); + table.addMany(r(0x60, 0x7f), ParserState.ESCAPE, ParserAction.ESC_DISPATCH, ParserState.GROUND); + // dcs entry + table.add(0x50, ParserState.ESCAPE, ParserAction.CLEAR, ParserState.DCS_ENTRY); + table.addMany(EXECUTABLES, ParserState.DCS_ENTRY, ParserAction.IGNORE, ParserState.DCS_ENTRY); + table.add(0x7f, ParserState.DCS_ENTRY, ParserAction.IGNORE, ParserState.DCS_ENTRY); + table.addMany(r(0x1c, 0x20), ParserState.DCS_ENTRY, ParserAction.IGNORE, ParserState.DCS_ENTRY); + table.addMany(r(0x20, 0x30), ParserState.DCS_ENTRY, ParserAction.COLLECT, ParserState.DCS_INTERMEDIATE); + table.addMany(r(0x30, 0x3c), ParserState.DCS_ENTRY, ParserAction.PARAM, ParserState.DCS_PARAM); + table.addMany([0x3c, 0x3d, 0x3e, 0x3f], ParserState.DCS_ENTRY, ParserAction.COLLECT, ParserState.DCS_PARAM); + table.addMany(EXECUTABLES, ParserState.DCS_IGNORE, ParserAction.IGNORE, ParserState.DCS_IGNORE); + table.addMany(r(0x20, 0x80), ParserState.DCS_IGNORE, ParserAction.IGNORE, ParserState.DCS_IGNORE); + table.addMany(r(0x1c, 0x20), ParserState.DCS_IGNORE, ParserAction.IGNORE, ParserState.DCS_IGNORE); + table.addMany(EXECUTABLES, ParserState.DCS_PARAM, ParserAction.IGNORE, ParserState.DCS_PARAM); + table.add(0x7f, ParserState.DCS_PARAM, ParserAction.IGNORE, ParserState.DCS_PARAM); + table.addMany(r(0x1c, 0x20), ParserState.DCS_PARAM, ParserAction.IGNORE, ParserState.DCS_PARAM); + table.addMany(r(0x30, 0x3c), ParserState.DCS_PARAM, ParserAction.PARAM, ParserState.DCS_PARAM); + table.addMany([0x3c, 0x3d, 0x3e, 0x3f], ParserState.DCS_PARAM, ParserAction.IGNORE, ParserState.DCS_IGNORE); + table.addMany(r(0x20, 0x30), ParserState.DCS_PARAM, ParserAction.COLLECT, ParserState.DCS_INTERMEDIATE); + table.addMany(EXECUTABLES, ParserState.DCS_INTERMEDIATE, ParserAction.IGNORE, ParserState.DCS_INTERMEDIATE); + table.add(0x7f, ParserState.DCS_INTERMEDIATE, ParserAction.IGNORE, ParserState.DCS_INTERMEDIATE); + table.addMany(r(0x1c, 0x20), ParserState.DCS_INTERMEDIATE, ParserAction.IGNORE, ParserState.DCS_INTERMEDIATE); + table.addMany(r(0x20, 0x30), ParserState.DCS_INTERMEDIATE, ParserAction.COLLECT, ParserState.DCS_INTERMEDIATE); + table.addMany(r(0x30, 0x40), ParserState.DCS_INTERMEDIATE, ParserAction.IGNORE, ParserState.DCS_IGNORE); + table.addMany(r(0x40, 0x7f), ParserState.DCS_INTERMEDIATE, ParserAction.DCS_HOOK, ParserState.DCS_PASSTHROUGH); + table.addMany(r(0x40, 0x7f), ParserState.DCS_PARAM, ParserAction.DCS_HOOK, ParserState.DCS_PASSTHROUGH); + table.addMany(r(0x40, 0x7f), ParserState.DCS_ENTRY, ParserAction.DCS_HOOK, ParserState.DCS_PASSTHROUGH); + table.addMany(EXECUTABLES, ParserState.DCS_PASSTHROUGH, ParserAction.DCS_PUT, ParserState.DCS_PASSTHROUGH); + table.addMany(PRINTABLES, ParserState.DCS_PASSTHROUGH, ParserAction.DCS_PUT, ParserState.DCS_PASSTHROUGH); + table.add(0x7f, ParserState.DCS_PASSTHROUGH, ParserAction.IGNORE, ParserState.DCS_PASSTHROUGH); + table.addMany([0x1b, 0x9c, 0x18, 0x1a], ParserState.DCS_PASSTHROUGH, ParserAction.DCS_UNHOOK, ParserState.GROUND); + // special handling of unicode chars + table.add(NON_ASCII_PRINTABLE, ParserState.GROUND, ParserAction.PRINT, ParserState.GROUND); + table.add(NON_ASCII_PRINTABLE, ParserState.OSC_STRING, ParserAction.OSC_PUT, ParserState.OSC_STRING); + table.add(NON_ASCII_PRINTABLE, ParserState.CSI_IGNORE, ParserAction.IGNORE, ParserState.CSI_IGNORE); + table.add(NON_ASCII_PRINTABLE, ParserState.DCS_IGNORE, ParserAction.IGNORE, ParserState.DCS_IGNORE); + table.add(NON_ASCII_PRINTABLE, ParserState.DCS_PASSTHROUGH, ParserAction.DCS_PUT, ParserState.DCS_PASSTHROUGH); + return table; +})(); + + +/** + * EscapeSequenceParser. + * This class implements the ANSI/DEC compatible parser described by + * Paul Williams (https://vt100.net/emu/dec_ansi_parser). + * + * To implement custom ANSI compliant escape sequences it is not needed to + * alter this parser, instead consider registering a custom handler. + * For non ANSI compliant sequences change the transition table with + * the optional `transitions` constructor argument and + * reimplement the `parse` method. + * + * This parser is currently hardcoded to operate in ZDM (Zero Default Mode) + * as suggested by the original parser, thus empty parameters are set to 0. + * This this is not in line with the latest ECMA-48 specification + * (ZDM was part of the early specs and got completely removed later on). + * + * Other than the original parser from vt100.net this parser supports + * sub parameters in digital parameters separated by colons. Empty sub parameters + * are set to -1 (no ZDM for sub parameters). + * + * About prefix and intermediate bytes: + * This parser follows the assumptions of the vt100.net parser with these restrictions: + * - only one prefix byte is allowed as first parameter byte, byte range 0x3c .. 0x3f + * - max. two intermediates are respected, byte range 0x20 .. 0x2f + * Note that this is not in line with ECMA-48 which does not limit either of those. + * Furthermore ECMA-48 allows the prefix byte range at any param byte position. Currently + * there are no known sequences that follow the broader definition of the specification. + * + * TODO: implement error recovery hook via error handler return values + */ +export class EscapeSequenceParser extends Disposable implements IEscapeSequenceParser { + public initialState: number; + public currentState: number; + public precedingJoinState: number; // UnicodeJoinProperties + + // buffers over several parse calls + protected _params: Params; + protected _collect: number; + + // handler lookup containers + protected _printHandler: PrintHandlerType; + protected _executeHandlers: { [flag: number]: ExecuteHandlerType }; + protected _csiHandlers: IHandlerCollection; + protected _escHandlers: IHandlerCollection; + protected readonly _oscParser: IOscParser; + protected readonly _dcsParser: IDcsParser; + protected _errorHandler: (state: IParsingState) => IParsingState; + + // fallback handlers + protected _printHandlerFb: PrintFallbackHandlerType; + protected _executeHandlerFb: ExecuteFallbackHandlerType; + protected _csiHandlerFb: CsiFallbackHandlerType; + protected _escHandlerFb: EscFallbackHandlerType; + protected _errorHandlerFb: (state: IParsingState) => IParsingState; + + // parser stack save for async handler support + protected _parseStack: IParserStackState = { + state: ParserStackType.NONE, + handlers: [], + handlerPos: 0, + transition: 0, + chunkPos: 0 + }; + + constructor( + protected readonly _transitions: TransitionTable = VT500_TRANSITION_TABLE + ) { + super(); + + this.initialState = ParserState.GROUND; + this.currentState = this.initialState; + this._params = new Params(); // defaults to 32 storable params/subparams + this._params.addParam(0); // ZDM + this._collect = 0; + this.precedingJoinState = 0; + + // set default fallback handlers and handler lookup containers + this._printHandlerFb = (data, start, end): void => { }; + this._executeHandlerFb = (code: number): void => { }; + this._csiHandlerFb = (ident: number, params: IParams): void => { }; + this._escHandlerFb = (ident: number): void => { }; + this._errorHandlerFb = (state: IParsingState): IParsingState => state; + this._printHandler = this._printHandlerFb; + this._executeHandlers = Object.create(null); + this._csiHandlers = Object.create(null); + this._escHandlers = Object.create(null); + this._register(toDisposable(() => { + this._csiHandlers = Object.create(null); + this._executeHandlers = Object.create(null); + this._escHandlers = Object.create(null); + })); + this._oscParser = this._register(new OscParser()); + this._dcsParser = this._register(new DcsParser()); + this._errorHandler = this._errorHandlerFb; + + // swallow 7bit ST (ESC+\) + this.registerEscHandler({ final: '\\' }, () => true); + } + + protected _identifier(id: IFunctionIdentifier, finalRange: number[] = [0x40, 0x7e]): number { + let res = 0; + if (id.prefix) { + if (id.prefix.length > 1) { + throw new Error('only one byte as prefix supported'); + } + res = id.prefix.charCodeAt(0); + if (res && 0x3c > res || res > 0x3f) { + throw new Error('prefix must be in range 0x3c .. 0x3f'); + } + } + if (id.intermediates) { + if (id.intermediates.length > 2) { + throw new Error('only two bytes as intermediates are supported'); + } + for (let i = 0; i < id.intermediates.length; ++i) { + const intermediate = id.intermediates.charCodeAt(i); + if (0x20 > intermediate || intermediate > 0x2f) { + throw new Error('intermediate must be in range 0x20 .. 0x2f'); + } + res <<= 8; + res |= intermediate; + } + } + if (id.final.length !== 1) { + throw new Error('final must be a single byte'); + } + const finalCode = id.final.charCodeAt(0); + if (finalRange[0] > finalCode || finalCode > finalRange[1]) { + throw new Error(`final must be in range ${finalRange[0]} .. ${finalRange[1]}`); + } + res <<= 8; + res |= finalCode; + + return res; + } + + public identToString(ident: number): string { + const res: string[] = []; + while (ident) { + res.push(String.fromCharCode(ident & 0xFF)); + ident >>= 8; + } + return res.reverse().join(''); + } + + public setPrintHandler(handler: PrintHandlerType): void { + this._printHandler = handler; + } + public clearPrintHandler(): void { + this._printHandler = this._printHandlerFb; + } + + public registerEscHandler(id: IFunctionIdentifier, handler: EscHandlerType): IDisposable { + const ident = this._identifier(id, [0x30, 0x7e]); + if (this._escHandlers[ident] === undefined) { + this._escHandlers[ident] = []; + } + const handlerList = this._escHandlers[ident]; + handlerList.push(handler); + return { + dispose: () => { + const handlerIndex = handlerList.indexOf(handler); + if (handlerIndex !== -1) { + handlerList.splice(handlerIndex, 1); + } + } + }; + } + public clearEscHandler(id: IFunctionIdentifier): void { + if (this._escHandlers[this._identifier(id, [0x30, 0x7e])]) delete this._escHandlers[this._identifier(id, [0x30, 0x7e])]; + } + public setEscHandlerFallback(handler: EscFallbackHandlerType): void { + this._escHandlerFb = handler; + } + + public setExecuteHandler(flag: string, handler: ExecuteHandlerType): void { + this._executeHandlers[flag.charCodeAt(0)] = handler; + } + public clearExecuteHandler(flag: string): void { + if (this._executeHandlers[flag.charCodeAt(0)]) delete this._executeHandlers[flag.charCodeAt(0)]; + } + public setExecuteHandlerFallback(handler: ExecuteFallbackHandlerType): void { + this._executeHandlerFb = handler; + } + + public registerCsiHandler(id: IFunctionIdentifier, handler: CsiHandlerType): IDisposable { + const ident = this._identifier(id); + if (this._csiHandlers[ident] === undefined) { + this._csiHandlers[ident] = []; + } + const handlerList = this._csiHandlers[ident]; + handlerList.push(handler); + return { + dispose: () => { + const handlerIndex = handlerList.indexOf(handler); + if (handlerIndex !== -1) { + handlerList.splice(handlerIndex, 1); + } + } + }; + } + public clearCsiHandler(id: IFunctionIdentifier): void { + if (this._csiHandlers[this._identifier(id)]) delete this._csiHandlers[this._identifier(id)]; + } + public setCsiHandlerFallback(callback: (ident: number, params: IParams) => void): void { + this._csiHandlerFb = callback; + } + + public registerDcsHandler(id: IFunctionIdentifier, handler: IDcsHandler): IDisposable { + return this._dcsParser.registerHandler(this._identifier(id), handler); + } + public clearDcsHandler(id: IFunctionIdentifier): void { + this._dcsParser.clearHandler(this._identifier(id)); + } + public setDcsHandlerFallback(handler: DcsFallbackHandlerType): void { + this._dcsParser.setHandlerFallback(handler); + } + + public registerOscHandler(ident: number, handler: IOscHandler): IDisposable { + return this._oscParser.registerHandler(ident, handler); + } + public clearOscHandler(ident: number): void { + this._oscParser.clearHandler(ident); + } + public setOscHandlerFallback(handler: OscFallbackHandlerType): void { + this._oscParser.setHandlerFallback(handler); + } + + public setErrorHandler(callback: (state: IParsingState) => IParsingState): void { + this._errorHandler = callback; + } + public clearErrorHandler(): void { + this._errorHandler = this._errorHandlerFb; + } + + /** + * Reset parser to initial values. + * + * This can also be used to lift the improper continuation error condition + * when dealing with async handlers. Use this only as a last resort to silence + * that error when the terminal has no pending data to be processed. Note that + * the interrupted async handler might continue its work in the future messing + * up the terminal state even further. + */ + public reset(): void { + this.currentState = this.initialState; + this._oscParser.reset(); + this._dcsParser.reset(); + this._params.reset(); + this._params.addParam(0); // ZDM + this._collect = 0; + this.precedingJoinState = 0; + // abort pending continuation from async handler + // Here the RESET type indicates, that the next parse call will + // ignore any saved stack, instead continues sync with next codepoint from GROUND + if (this._parseStack.state !== ParserStackType.NONE) { + this._parseStack.state = ParserStackType.RESET; + this._parseStack.handlers = []; // also release handlers ref + } + } + + /** + * Async parse support. + */ + protected _preserveStack( + state: ParserStackType, + handlers: ResumableHandlersType, + handlerPos: number, + transition: number, + chunkPos: number + ): void { + this._parseStack.state = state; + this._parseStack.handlers = handlers; + this._parseStack.handlerPos = handlerPos; + this._parseStack.transition = transition; + this._parseStack.chunkPos = chunkPos; + } + + /** + * Parse UTF32 codepoints in `data` up to `length`. + * + * Note: For several actions with high data load the parsing is optimized + * by using local read ahead loops with hardcoded conditions to + * avoid costly table lookups. Make sure that any change of table values + * will be reflected in the loop conditions as well and vice versa. + * Affected states/actions: + * - GROUND:PRINT + * - CSI_PARAM:PARAM + * - DCS_PARAM:PARAM + * - OSC_STRING:OSC_PUT + * - DCS_PASSTHROUGH:DCS_PUT + * + * Note on asynchronous handler support: + * Any handler returning a promise will be treated as asynchronous. + * To keep the in-band blocking working for async handlers, `parse` pauses execution, + * creates a stack save and returns the promise to the caller. + * For proper continuation of the paused state it is important + * to await the promise resolving. On resolve the parse must be repeated + * with the same chunk of data and the resolved value in `promiseResult` + * until no promise is returned. + * + * Important: With only sync handlers defined, parsing is completely synchronous as well. + * As soon as an async handler is involved, synchronous parsing is not possible anymore. + * + * Boilerplate for proper parsing of multiple chunks with async handlers: + * + * ```typescript + * async function parseMultipleChunks(chunks: Uint32Array[]): Promise { + * for (const chunk of chunks) { + * let result: void | Promise; + * let prev: boolean | undefined; + * while (result = parser.parse(chunk, chunk.length, prev)) { + * prev = await result; + * } + * } + * // finished parsing all chunks... + * } + * ``` + */ + public parse(data: Uint32Array, length: number, promiseResult?: boolean): void | Promise { + let code = 0; + let transition = 0; + let start = 0; + let handlerResult: void | boolean | Promise; + + // resume from async handler + if (this._parseStack.state) { + // allow sync parser reset even in continuation mode + // Note: can be used to recover parser from improper continuation error below + if (this._parseStack.state === ParserStackType.RESET) { + this._parseStack.state = ParserStackType.NONE; + start = this._parseStack.chunkPos + 1; // continue with next codepoint in GROUND + } else { + if (promiseResult === undefined || this._parseStack.state === ParserStackType.FAIL) { + /** + * Reject further parsing on improper continuation after pausing. This is a really bad + * condition with screwed up execution order and prolly messed up terminal state, + * therefore we exit hard with an exception and reject any further parsing. + * + * Note: With `Terminal.write` usage this exception should never occur, as the top level + * calls are guaranteed to handle async conditions properly. If you ever encounter this + * exception in your terminal integration it indicates, that you injected data chunks to + * `InputHandler.parse` or `EscapeSequenceParser.parse` synchronously without waiting for + * continuation of a running async handler. + * + * It is possible to get rid of this error by calling `reset`. But dont rely on that, as + * the pending async handler still might mess up the terminal later. Instead fix the + * faulty async handling, so this error will not be thrown anymore. + */ + this._parseStack.state = ParserStackType.FAIL; + throw new Error('improper continuation due to previous async handler, giving up parsing'); + } + + // we have to resume the old handler loop if: + // - return value of the promise was `false` + // - handlers are not exhausted yet + const handlers = this._parseStack.handlers; + let handlerPos = this._parseStack.handlerPos - 1; + switch (this._parseStack.state) { + case ParserStackType.CSI: + if (promiseResult === false && handlerPos > -1) { + for (; handlerPos >= 0; handlerPos--) { + handlerResult = (handlers as CsiHandlerType[])[handlerPos](this._params); + if (handlerResult === true) { + break; + } else if (handlerResult instanceof Promise) { + this._parseStack.handlerPos = handlerPos; + return handlerResult; + } + } + } + this._parseStack.handlers = []; + break; + case ParserStackType.ESC: + if (promiseResult === false && handlerPos > -1) { + for (; handlerPos >= 0; handlerPos--) { + handlerResult = (handlers as EscHandlerType[])[handlerPos](); + if (handlerResult === true) { + break; + } else if (handlerResult instanceof Promise) { + this._parseStack.handlerPos = handlerPos; + return handlerResult; + } + } + } + this._parseStack.handlers = []; + break; + case ParserStackType.DCS: + code = data[this._parseStack.chunkPos]; + handlerResult = this._dcsParser.unhook(code !== 0x18 && code !== 0x1a, promiseResult); + if (handlerResult) { + return handlerResult; + } + if (code === 0x1b) this._parseStack.transition |= ParserState.ESCAPE; + this._params.reset(); + this._params.addParam(0); // ZDM + this._collect = 0; + break; + case ParserStackType.OSC: + code = data[this._parseStack.chunkPos]; + handlerResult = this._oscParser.end(code !== 0x18 && code !== 0x1a, promiseResult); + if (handlerResult) { + return handlerResult; + } + if (code === 0x1b) this._parseStack.transition |= ParserState.ESCAPE; + this._params.reset(); + this._params.addParam(0); // ZDM + this._collect = 0; + break; + } + // cleanup before continuing with the main sync loop + this._parseStack.state = ParserStackType.NONE; + start = this._parseStack.chunkPos + 1; + this.precedingJoinState = 0; + this.currentState = this._parseStack.transition & TableAccess.TRANSITION_STATE_MASK; + } + } + + // continue with main sync loop + + // process input string + for (let i = start; i < length; ++i) { + code = data[i]; + + // normal transition & action lookup + transition = this._transitions.table[this.currentState << TableAccess.INDEX_STATE_SHIFT | (code < 0xa0 ? code : NON_ASCII_PRINTABLE)]; + switch (transition >> TableAccess.TRANSITION_ACTION_SHIFT) { + case ParserAction.PRINT: + // read ahead with loop unrolling + // Note: 0x20 (SP) is included, 0x7F (DEL) is excluded + for (let j = i + 1; ; ++j) { + if (j >= length || (code = data[j]) < 0x20 || (code > 0x7e && code < NON_ASCII_PRINTABLE)) { + this._printHandler(data, i, j); + i = j - 1; + break; + } + if (++j >= length || (code = data[j]) < 0x20 || (code > 0x7e && code < NON_ASCII_PRINTABLE)) { + this._printHandler(data, i, j); + i = j - 1; + break; + } + if (++j >= length || (code = data[j]) < 0x20 || (code > 0x7e && code < NON_ASCII_PRINTABLE)) { + this._printHandler(data, i, j); + i = j - 1; + break; + } + if (++j >= length || (code = data[j]) < 0x20 || (code > 0x7e && code < NON_ASCII_PRINTABLE)) { + this._printHandler(data, i, j); + i = j - 1; + break; + } + } + break; + case ParserAction.EXECUTE: + if (this._executeHandlers[code]) this._executeHandlers[code](); + else this._executeHandlerFb(code); + this.precedingJoinState = 0; + break; + case ParserAction.IGNORE: + break; + case ParserAction.ERROR: + const inject: IParsingState = this._errorHandler( + { + position: i, + code, + currentState: this.currentState, + collect: this._collect, + params: this._params, + abort: false + }); + if (inject.abort) return; + // inject values: currently not implemented + break; + case ParserAction.CSI_DISPATCH: + // Trigger CSI Handler + const handlers = this._csiHandlers[this._collect << 8 | code]; + let j = handlers ? handlers.length - 1 : -1; + for (; j >= 0; j--) { + // true means success and to stop bubbling + // a promise indicates an async handler that needs to finish before progressing + handlerResult = handlers[j](this._params); + if (handlerResult === true) { + break; + } else if (handlerResult instanceof Promise) { + this._preserveStack(ParserStackType.CSI, handlers, j, transition, i); + return handlerResult; + } + } + if (j < 0) { + this._csiHandlerFb(this._collect << 8 | code, this._params); + } + this.precedingJoinState = 0; + break; + case ParserAction.PARAM: + // inner loop: digits (0x30 - 0x39) and ; (0x3b) and : (0x3a) + do { + switch (code) { + case 0x3b: + this._params.addParam(0); // ZDM + break; + case 0x3a: + this._params.addSubParam(-1); + break; + default: // 0x30 - 0x39 + this._params.addDigit(code - 48); + } + } while (++i < length && (code = data[i]) > 0x2f && code < 0x3c); + i--; + break; + case ParserAction.COLLECT: + this._collect <<= 8; + this._collect |= code; + break; + case ParserAction.ESC_DISPATCH: + const handlersEsc = this._escHandlers[this._collect << 8 | code]; + let jj = handlersEsc ? handlersEsc.length - 1 : -1; + for (; jj >= 0; jj--) { + // true means success and to stop bubbling + // a promise indicates an async handler that needs to finish before progressing + handlerResult = handlersEsc[jj](); + if (handlerResult === true) { + break; + } else if (handlerResult instanceof Promise) { + this._preserveStack(ParserStackType.ESC, handlersEsc, jj, transition, i); + return handlerResult; + } + } + if (jj < 0) { + this._escHandlerFb(this._collect << 8 | code); + } + this.precedingJoinState = 0; + break; + case ParserAction.CLEAR: + this._params.reset(); + this._params.addParam(0); // ZDM + this._collect = 0; + break; + case ParserAction.DCS_HOOK: + this._dcsParser.hook(this._collect << 8 | code, this._params); + break; + case ParserAction.DCS_PUT: + // inner loop - exit DCS_PUT: 0x18, 0x1a, 0x1b, 0x7f, 0x80 - 0x9f + // unhook triggered by: 0x1b, 0x9c (success) and 0x18, 0x1a (abort) + for (let j = i + 1; ; ++j) { + if (j >= length || (code = data[j]) === 0x18 || code === 0x1a || code === 0x1b || (code > 0x7f && code < NON_ASCII_PRINTABLE)) { + this._dcsParser.put(data, i, j); + i = j - 1; + break; + } + } + break; + case ParserAction.DCS_UNHOOK: + handlerResult = this._dcsParser.unhook(code !== 0x18 && code !== 0x1a); + if (handlerResult) { + this._preserveStack(ParserStackType.DCS, [], 0, transition, i); + return handlerResult; + } + if (code === 0x1b) transition |= ParserState.ESCAPE; + this._params.reset(); + this._params.addParam(0); // ZDM + this._collect = 0; + this.precedingJoinState = 0; + break; + case ParserAction.OSC_START: + this._oscParser.start(); + break; + case ParserAction.OSC_PUT: + // inner loop: 0x20 (SP) included, 0x7F (DEL) included + for (let j = i + 1; ; j++) { + if (j >= length || (code = data[j]) < 0x20 || (code > 0x7f && code < NON_ASCII_PRINTABLE)) { + this._oscParser.put(data, i, j); + i = j - 1; + break; + } + } + break; + case ParserAction.OSC_END: + handlerResult = this._oscParser.end(code !== 0x18 && code !== 0x1a); + if (handlerResult) { + this._preserveStack(ParserStackType.OSC, [], 0, transition, i); + return handlerResult; + } + if (code === 0x1b) transition |= ParserState.ESCAPE; + this._params.reset(); + this._params.addParam(0); // ZDM + this._collect = 0; + this.precedingJoinState = 0; + break; + } + this.currentState = transition & TableAccess.TRANSITION_STATE_MASK; + } + } +} diff --git a/node_modules/@xterm/xterm/src/common/parser/OscParser.ts b/node_modules/@xterm/xterm/src/common/parser/OscParser.ts new file mode 100644 index 0000000..32710ae --- /dev/null +++ b/node_modules/@xterm/xterm/src/common/parser/OscParser.ts @@ -0,0 +1,238 @@ +/** + * Copyright (c) 2019 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { IOscHandler, IHandlerCollection, OscFallbackHandlerType, IOscParser, ISubParserStackState } from 'common/parser/Types'; +import { OscState, PAYLOAD_LIMIT } from 'common/parser/Constants'; +import { utf32ToString } from 'common/input/TextDecoder'; +import { IDisposable } from 'common/Types'; + +const EMPTY_HANDLERS: IOscHandler[] = []; + +export class OscParser implements IOscParser { + private _state = OscState.START; + private _active = EMPTY_HANDLERS; + private _id = -1; + private _handlers: IHandlerCollection = Object.create(null); + private _handlerFb: OscFallbackHandlerType = () => { }; + private _stack: ISubParserStackState = { + paused: false, + loopPosition: 0, + fallThrough: false + }; + + public registerHandler(ident: number, handler: IOscHandler): IDisposable { + if (this._handlers[ident] === undefined) { + this._handlers[ident] = []; + } + const handlerList = this._handlers[ident]; + handlerList.push(handler); + return { + dispose: () => { + const handlerIndex = handlerList.indexOf(handler); + if (handlerIndex !== -1) { + handlerList.splice(handlerIndex, 1); + } + } + }; + } + public clearHandler(ident: number): void { + if (this._handlers[ident]) delete this._handlers[ident]; + } + public setHandlerFallback(handler: OscFallbackHandlerType): void { + this._handlerFb = handler; + } + + public dispose(): void { + this._handlers = Object.create(null); + this._handlerFb = () => { }; + this._active = EMPTY_HANDLERS; + } + + public reset(): void { + // force cleanup handlers if payload was already sent + if (this._state === OscState.PAYLOAD) { + for (let j = this._stack.paused ? this._stack.loopPosition - 1 : this._active.length - 1; j >= 0; --j) { + this._active[j].end(false); + } + } + this._stack.paused = false; + this._active = EMPTY_HANDLERS; + this._id = -1; + this._state = OscState.START; + } + + private _start(): void { + this._active = this._handlers[this._id] || EMPTY_HANDLERS; + if (!this._active.length) { + this._handlerFb(this._id, 'START'); + } else { + for (let j = this._active.length - 1; j >= 0; j--) { + this._active[j].start(); + } + } + } + + private _put(data: Uint32Array, start: number, end: number): void { + if (!this._active.length) { + this._handlerFb(this._id, 'PUT', utf32ToString(data, start, end)); + } else { + for (let j = this._active.length - 1; j >= 0; j--) { + this._active[j].put(data, start, end); + } + } + } + + public start(): void { + // always reset leftover handlers + this.reset(); + this._state = OscState.ID; + } + + /** + * Put data to current OSC command. + * Expects the identifier of the OSC command in the form + * OSC id ; payload ST/BEL + * Payload chunks are not further processed and get + * directly passed to the handlers. + */ + public put(data: Uint32Array, start: number, end: number): void { + if (this._state === OscState.ABORT) { + return; + } + if (this._state === OscState.ID) { + while (start < end) { + const code = data[start++]; + if (code === 0x3b) { + this._state = OscState.PAYLOAD; + this._start(); + break; + } + if (code < 0x30 || 0x39 < code) { + this._state = OscState.ABORT; + return; + } + if (this._id === -1) { + this._id = 0; + } + this._id = this._id * 10 + code - 48; + } + } + if (this._state === OscState.PAYLOAD && end - start > 0) { + this._put(data, start, end); + } + } + + /** + * Indicates end of an OSC command. + * Whether the OSC got aborted or finished normally + * is indicated by `success`. + */ + public end(success: boolean, promiseResult: boolean = true): void | Promise { + if (this._state === OscState.START) { + return; + } + // do nothing if command was faulty + if (this._state !== OscState.ABORT) { + // if we are still in ID state and get an early end + // means that the command has no payload thus we still have + // to announce START and send END right after + if (this._state === OscState.ID) { + this._start(); + } + + if (!this._active.length) { + this._handlerFb(this._id, 'END', success); + } else { + let handlerResult: boolean | Promise = false; + let j = this._active.length - 1; + let fallThrough = false; + if (this._stack.paused) { + j = this._stack.loopPosition - 1; + handlerResult = promiseResult; + fallThrough = this._stack.fallThrough; + this._stack.paused = false; + } + if (!fallThrough && handlerResult === false) { + for (; j >= 0; j--) { + handlerResult = this._active[j].end(success); + if (handlerResult === true) { + break; + } else if (handlerResult instanceof Promise) { + this._stack.paused = true; + this._stack.loopPosition = j; + this._stack.fallThrough = false; + return handlerResult; + } + } + j--; + } + // cleanup left over handlers + // we always have to call .end for proper cleanup, + // here we use `success` to indicate whether a handler should execute + for (; j >= 0; j--) { + handlerResult = this._active[j].end(false); + if (handlerResult instanceof Promise) { + this._stack.paused = true; + this._stack.loopPosition = j; + this._stack.fallThrough = true; + return handlerResult; + } + } + } + + } + this._active = EMPTY_HANDLERS; + this._id = -1; + this._state = OscState.START; + } +} + +/** + * Convenient class to allow attaching string based handler functions + * as OSC handlers. + */ +export class OscHandler implements IOscHandler { + private _data = ''; + private _hitLimit: boolean = false; + + constructor(private _handler: (data: string) => boolean | Promise) { } + + public start(): void { + this._data = ''; + this._hitLimit = false; + } + + public put(data: Uint32Array, start: number, end: number): void { + if (this._hitLimit) { + return; + } + this._data += utf32ToString(data, start, end); + if (this._data.length > PAYLOAD_LIMIT) { + this._data = ''; + this._hitLimit = true; + } + } + + public end(success: boolean): boolean | Promise { + let ret: boolean | Promise = false; + if (this._hitLimit) { + ret = false; + } else if (success) { + ret = this._handler(this._data); + if (ret instanceof Promise) { + // need to hold data until `ret` got resolved + // dont care for errors, data will be freed anyway on next start + return ret.then(res => { + this._data = ''; + this._hitLimit = false; + return res; + }); + } + } + this._data = ''; + this._hitLimit = false; + return ret; + } +} diff --git a/node_modules/@xterm/xterm/src/common/parser/Params.ts b/node_modules/@xterm/xterm/src/common/parser/Params.ts new file mode 100644 index 0000000..7071453 --- /dev/null +++ b/node_modules/@xterm/xterm/src/common/parser/Params.ts @@ -0,0 +1,229 @@ +/** + * Copyright (c) 2019 The xterm.js authors. All rights reserved. + * @license MIT + */ +import { IParams, ParamsArray } from 'common/parser/Types'; + +// max value supported for a single param/subparam (clamped to positive int32 range) +const MAX_VALUE = 0x7FFFFFFF; +// max allowed subparams for a single sequence (hardcoded limitation) +const MAX_SUBPARAMS = 256; + +/** + * Params storage class. + * This type is used by the parser to accumulate sequence parameters and sub parameters + * and transmit them to the input handler actions. + * + * NOTES: + * - params object for action handlers is borrowed, use `.toArray` or `.clone` to get a copy + * - never read beyond `params.length - 1` (likely to contain arbitrary data) + * - `.getSubParams` returns a borrowed typed array, use `.getSubParamsAll` for cloned sub params + * - hardcoded limitations: + * - max. value for a single (sub) param is 2^31 - 1 (greater values are clamped to that) + * - max. 256 sub params possible + * - negative values are not allowed beside -1 (placeholder for default value) + * + * About ZDM (Zero Default Mode): + * ZDM is not orchestrated by this class. If the parser is in ZDM, + * it should add 0 for empty params, otherwise -1. This does not apply + * to subparams, empty subparams should always be added with -1. + */ +export class Params implements IParams { + // params store and length + public params: Int32Array; + public length: number; + + // sub params store and length + protected _subParams: Int32Array; + protected _subParamsLength: number; + + // sub params offsets from param: param idx --> [start, end] offset + private _subParamsIdx: Uint16Array; + private _rejectDigits: boolean; + private _rejectSubDigits: boolean; + private _digitIsSub: boolean; + + /** + * Create a `Params` type from JS array representation. + */ + public static fromArray(values: ParamsArray): Params { + const params = new Params(); + if (!values.length) { + return params; + } + // skip leading sub params + for (let i = (Array.isArray(values[0])) ? 1 : 0; i < values.length; ++i) { + const value = values[i]; + if (Array.isArray(value)) { + for (let k = 0; k < value.length; ++k) { + params.addSubParam(value[k]); + } + } else { + params.addParam(value); + } + } + return params; + } + + /** + * @param maxLength max length of storable parameters + * @param maxSubParamsLength max length of storable sub parameters + */ + constructor(public maxLength: number = 32, public maxSubParamsLength: number = 32) { + if (maxSubParamsLength > MAX_SUBPARAMS) { + throw new Error('maxSubParamsLength must not be greater than 256'); + } + this.params = new Int32Array(maxLength); + this.length = 0; + this._subParams = new Int32Array(maxSubParamsLength); + this._subParamsLength = 0; + this._subParamsIdx = new Uint16Array(maxLength); + this._rejectDigits = false; + this._rejectSubDigits = false; + this._digitIsSub = false; + } + + /** + * Clone object. + */ + public clone(): Params { + const newParams = new Params(this.maxLength, this.maxSubParamsLength); + newParams.params.set(this.params); + newParams.length = this.length; + newParams._subParams.set(this._subParams); + newParams._subParamsLength = this._subParamsLength; + newParams._subParamsIdx.set(this._subParamsIdx); + newParams._rejectDigits = this._rejectDigits; + newParams._rejectSubDigits = this._rejectSubDigits; + newParams._digitIsSub = this._digitIsSub; + return newParams; + } + + /** + * Get a JS array representation of the current parameters and sub parameters. + * The array is structured as follows: + * sequence: "1;2:3:4;5::6" + * array : [1, 2, [3, 4], 5, [-1, 6]] + */ + public toArray(): ParamsArray { + const res: ParamsArray = []; + for (let i = 0; i < this.length; ++i) { + res.push(this.params[i]); + const start = this._subParamsIdx[i] >> 8; + const end = this._subParamsIdx[i] & 0xFF; + if (end - start > 0) { + res.push(Array.prototype.slice.call(this._subParams, start, end)); + } + } + return res; + } + + /** + * Reset to initial empty state. + */ + public reset(): void { + this.length = 0; + this._subParamsLength = 0; + this._rejectDigits = false; + this._rejectSubDigits = false; + this._digitIsSub = false; + } + + /** + * Add a parameter value. + * `Params` only stores up to `maxLength` parameters, any later + * parameter will be ignored. + * Note: VT devices only stored up to 16 values, xterm seems to + * store up to 30. + */ + public addParam(value: number): void { + this._digitIsSub = false; + if (this.length >= this.maxLength) { + this._rejectDigits = true; + return; + } + if (value < -1) { + throw new Error('values lesser than -1 are not allowed'); + } + this._subParamsIdx[this.length] = this._subParamsLength << 8 | this._subParamsLength; + this.params[this.length++] = value > MAX_VALUE ? MAX_VALUE : value; + } + + /** + * Add a sub parameter value. + * The sub parameter is automatically associated with the last parameter value. + * Thus it is not possible to add a subparameter without any parameter added yet. + * `Params` only stores up to `subParamsLength` sub parameters, any later + * sub parameter will be ignored. + */ + public addSubParam(value: number): void { + this._digitIsSub = true; + if (!this.length) { + return; + } + if (this._rejectDigits || this._subParamsLength >= this.maxSubParamsLength) { + this._rejectSubDigits = true; + return; + } + if (value < -1) { + throw new Error('values lesser than -1 are not allowed'); + } + this._subParams[this._subParamsLength++] = value > MAX_VALUE ? MAX_VALUE : value; + this._subParamsIdx[this.length - 1]++; + } + + /** + * Whether parameter at index `idx` has sub parameters. + */ + public hasSubParams(idx: number): boolean { + return ((this._subParamsIdx[idx] & 0xFF) - (this._subParamsIdx[idx] >> 8) > 0); + } + + /** + * Return sub parameters for parameter at index `idx`. + * Note: The values are borrowed, thus you need to copy + * the values if you need to hold them in nonlocal scope. + */ + public getSubParams(idx: number): Int32Array | null { + const start = this._subParamsIdx[idx] >> 8; + const end = this._subParamsIdx[idx] & 0xFF; + if (end - start > 0) { + return this._subParams.subarray(start, end); + } + return null; + } + + /** + * Return all sub parameters as {idx: subparams} mapping. + * Note: The values are not borrowed. + */ + public getSubParamsAll(): {[idx: number]: Int32Array} { + const result: {[idx: number]: Int32Array} = {}; + for (let i = 0; i < this.length; ++i) { + const start = this._subParamsIdx[i] >> 8; + const end = this._subParamsIdx[i] & 0xFF; + if (end - start > 0) { + result[i] = this._subParams.slice(start, end); + } + } + return result; + } + + /** + * Add a single digit value to current parameter. + * This is used by the parser to account digits on a char by char basis. + */ + public addDigit(value: number): void { + let length; + if (this._rejectDigits + || !(length = this._digitIsSub ? this._subParamsLength : this.length) + || (this._digitIsSub && this._rejectSubDigits) + ) { + return; + } + + const store = this._digitIsSub ? this._subParams : this.params; + const cur = store[length - 1]; + store[length - 1] = ~cur ? Math.min(cur * 10 + value, MAX_VALUE) : value; + } +} diff --git a/node_modules/@xterm/xterm/src/common/parser/Types.ts b/node_modules/@xterm/xterm/src/common/parser/Types.ts new file mode 100644 index 0000000..2ed4acd --- /dev/null +++ b/node_modules/@xterm/xterm/src/common/parser/Types.ts @@ -0,0 +1,275 @@ +/** + * Copyright (c) 2017 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { IDisposable } from 'common/Types'; +import { ParserState } from 'common/parser/Constants'; + + +/** sequence params serialized to js arrays */ +export type ParamsArray = (number | number[])[]; + +/** Params constructor type. */ +export interface IParamsConstructor { + new(maxLength: number, maxSubParamsLength: number): IParams; + + /** create params from ParamsArray */ + fromArray(values: ParamsArray): IParams; +} + +/** Interface of Params storage class. */ +export interface IParams { + /** from ctor */ + maxLength: number; + maxSubParamsLength: number; + + /** param values and its length */ + params: Int32Array; + length: number; + + /** methods */ + clone(): IParams; + toArray(): ParamsArray; + reset(): void; + addParam(value: number): void; + addSubParam(value: number): void; + hasSubParams(idx: number): boolean; + getSubParams(idx: number): Int32Array | null; + getSubParamsAll(): {[idx: number]: Int32Array}; +} + +/** + * Internal state of EscapeSequenceParser. + * Used as argument of the error handler to allow + * introspection at runtime on parse errors. + * Return it with altered values to recover from + * faulty states (not yet supported). + * Set `abort` to `true` to abort the current parsing. + */ +export interface IParsingState { + // position in parse string + position: number; + // actual character code + code: number; + // current parser state + currentState: ParserState; + // collect buffer with intermediate characters + collect: number; + // params buffer + params: IParams; + // should abort (default: false) + abort: boolean; +} + +/** + * Command handler interfaces. + */ + +/** + * CSI handler types. + * Note: `params` is borrowed. + */ +export type CsiHandlerType = (params: IParams) => boolean | Promise; +export type CsiFallbackHandlerType = (ident: number, params: IParams) => void; + +/** + * DCS handler types. + */ +export interface IDcsHandler { + /** + * Called when a DCS command starts. + * Prepare needed data structures here. + * Note: `params` is borrowed. + */ + hook(params: IParams): void; + /** + * Incoming payload chunk. + * Note: `params` is borrowed. + */ + put(data: Uint32Array, start: number, end: number): void; + /** + * End of DCS command. `success` indicates whether the + * command finished normally or got aborted, thus final + * execution of the command should depend on `success`. + * To save memory also cleanup data structures here. + */ + unhook(success: boolean): boolean | Promise; +} +export type DcsFallbackHandlerType = (ident: number, action: 'HOOK' | 'PUT' | 'UNHOOK', payload?: any) => void; + +/** + * ESC handler types. + */ +export type EscHandlerType = () => boolean | Promise; +export type EscFallbackHandlerType = (identifier: number) => void; + +/** + * EXECUTE handler types. + */ +export type ExecuteHandlerType = () => boolean; +export type ExecuteFallbackHandlerType = (ident: number) => void; + +/** + * OSC handler types. + */ +export interface IOscHandler { + /** + * Announces start of this OSC command. + * Prepare needed data structures here. + */ + start(): void; + /** + * Incoming data chunk. + * Note: Data is borrowed. + */ + put(data: Uint32Array, start: number, end: number): void; + /** + * End of OSC command. `success` indicates whether the + * command finished normally or got aborted, thus final + * execution of the command should depend on `success`. + * To save memory also cleanup data structures here. + */ + end(success: boolean): boolean | Promise; +} +export type OscFallbackHandlerType = (ident: number, action: 'START' | 'PUT' | 'END', payload?: any) => void; + +/** + * PRINT handler types. + */ +export type PrintHandlerType = (data: Uint32Array, start: number, end: number) => void; +export type PrintFallbackHandlerType = PrintHandlerType; + + +/** + * EscapeSequenceParser interface. + */ +export interface IEscapeSequenceParser extends IDisposable { + /** + * Preceding grapheme-join-state. + * Used for joining grapheme clusters across calls to `print`. + * Also used by REP to check if repeating a character is allowed. + * It gets reset by the parser for any valid sequence besides text. + */ + precedingJoinState: number; // More specifically: UnicodeJoinProperties + + /** + * Reset the parser to its initial state (handlers are kept). + */ + reset(): void; + + /** + * Parse UTF32 codepoints in `data` up to `length`. + * @param data The data to parse. + */ + parse(data: Uint32Array, length: number, promiseResult?: boolean): void | Promise; + + /** + * Get string from numercial function identifier `ident`. + * Useful in fallback handlers which expose the low level + * numcerical function identifier for debugging purposes. + * Note: A full back translation to `IFunctionIdentifier` + * is not implemented. + */ + identToString(ident: number): string; + + setPrintHandler(handler: PrintHandlerType): void; + clearPrintHandler(): void; + + registerEscHandler(id: IFunctionIdentifier, handler: EscHandlerType): IDisposable; + clearEscHandler(id: IFunctionIdentifier): void; + setEscHandlerFallback(handler: EscFallbackHandlerType): void; + + setExecuteHandler(flag: string, handler: ExecuteHandlerType): void; + clearExecuteHandler(flag: string): void; + setExecuteHandlerFallback(handler: ExecuteFallbackHandlerType): void; + + registerCsiHandler(id: IFunctionIdentifier, handler: CsiHandlerType): IDisposable; + clearCsiHandler(id: IFunctionIdentifier): void; + setCsiHandlerFallback(callback: CsiFallbackHandlerType): void; + + registerDcsHandler(id: IFunctionIdentifier, handler: IDcsHandler): IDisposable; + clearDcsHandler(id: IFunctionIdentifier): void; + setDcsHandlerFallback(handler: DcsFallbackHandlerType): void; + + registerOscHandler(ident: number, handler: IOscHandler): IDisposable; + clearOscHandler(ident: number): void; + setOscHandlerFallback(handler: OscFallbackHandlerType): void; + + setErrorHandler(handler: (state: IParsingState) => IParsingState): void; + clearErrorHandler(): void; +} + +/** + * Subparser interfaces. + * The subparsers are instantiated in `EscapeSequenceParser` and + * called during `EscapeSequenceParser.parse`. + */ +export interface ISubParser extends IDisposable { + reset(): void; + registerHandler(ident: number, handler: T): IDisposable; + clearHandler(ident: number): void; + setHandlerFallback(handler: U): void; + put(data: Uint32Array, start: number, end: number): void; +} + +export interface IOscParser extends ISubParser { + start(): void; + end(success: boolean, promiseResult?: boolean): void | Promise; +} + +export interface IDcsParser extends ISubParser { + hook(ident: number, params: IParams): void; + unhook(success: boolean, promiseResult?: boolean): void | Promise; +} + +/** + * Interface to denote a specific ESC, CSI or DCS handler slot. + * The values are used to create an integer respresentation during handler + * regristation before passed to the subparsers as `ident`. + * The integer translation is made to allow a faster handler access + * in `EscapeSequenceParser.parse`. + */ +export interface IFunctionIdentifier { + prefix?: string; + intermediates?: string; + final: string; +} + +export interface IHandlerCollection { + [key: string]: T[]; +} + +/** + * Types for async parser support. + */ + +// type of saved stack state in parser +export const enum ParserStackType { + NONE = 0, + FAIL, + RESET, + CSI, + ESC, + OSC, + DCS +} + +// aggregate of resumable handler lists +export type ResumableHandlersType = CsiHandlerType[] | EscHandlerType[]; + +// saved stack state of the parser +export interface IParserStackState { + state: ParserStackType; + handlers: ResumableHandlersType; + handlerPos: number; + transition: number; + chunkPos: number; +} + +// saved stack state of subparser (OSC and DCS) +export interface ISubParserStackState { + paused: boolean; + loopPosition: number; + fallThrough: boolean; +} diff --git a/node_modules/@xterm/xterm/src/common/public/AddonManager.ts b/node_modules/@xterm/xterm/src/common/public/AddonManager.ts new file mode 100644 index 0000000..9a36e2a --- /dev/null +++ b/node_modules/@xterm/xterm/src/common/public/AddonManager.ts @@ -0,0 +1,53 @@ +/** + * Copyright (c) 2019 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { ITerminalAddon, IDisposable, Terminal } from '@xterm/xterm'; + +export interface ILoadedAddon { + instance: ITerminalAddon; + dispose: () => void; + isDisposed: boolean; +} + +export class AddonManager implements IDisposable { + protected _addons: ILoadedAddon[] = []; + + public dispose(): void { + for (let i = this._addons.length - 1; i >= 0; i--) { + this._addons[i].instance.dispose(); + } + } + + public loadAddon(terminal: Terminal, instance: ITerminalAddon): void { + const loadedAddon: ILoadedAddon = { + instance, + dispose: instance.dispose, + isDisposed: false + }; + this._addons.push(loadedAddon); + instance.dispose = () => this._wrappedAddonDispose(loadedAddon); + instance.activate(terminal as any); + } + + private _wrappedAddonDispose(loadedAddon: ILoadedAddon): void { + if (loadedAddon.isDisposed) { + // Do nothing if already disposed + return; + } + let index = -1; + for (let i = 0; i < this._addons.length; i++) { + if (this._addons[i] === loadedAddon) { + index = i; + break; + } + } + if (index === -1) { + throw new Error('Could not dispose an addon that has not been loaded'); + } + loadedAddon.isDisposed = true; + loadedAddon.dispose.apply(loadedAddon.instance); + this._addons.splice(index, 1); + } +} diff --git a/node_modules/@xterm/xterm/src/common/public/BufferApiView.ts b/node_modules/@xterm/xterm/src/common/public/BufferApiView.ts new file mode 100644 index 0000000..834cedb --- /dev/null +++ b/node_modules/@xterm/xterm/src/common/public/BufferApiView.ts @@ -0,0 +1,35 @@ +/** + * Copyright (c) 2021 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { IBuffer as IBufferApi, IBufferLine as IBufferLineApi, IBufferCell as IBufferCellApi } from '@xterm/xterm'; +import { IBuffer } from 'common/buffer/Types'; +import { BufferLineApiView } from 'common/public/BufferLineApiView'; +import { CellData } from 'common/buffer/CellData'; + +export class BufferApiView implements IBufferApi { + constructor( + private _buffer: IBuffer, + public readonly type: 'normal' | 'alternate' + ) { } + + public init(buffer: IBuffer): BufferApiView { + this._buffer = buffer; + return this; + } + + public get cursorY(): number { return this._buffer.y; } + public get cursorX(): number { return this._buffer.x; } + public get viewportY(): number { return this._buffer.ydisp; } + public get baseY(): number { return this._buffer.ybase; } + public get length(): number { return this._buffer.lines.length; } + public getLine(y: number): IBufferLineApi | undefined { + const line = this._buffer.lines.get(y); + if (!line) { + return undefined; + } + return new BufferLineApiView(line); + } + public getNullCell(): IBufferCellApi { return new CellData(); } +} diff --git a/node_modules/@xterm/xterm/src/common/public/BufferLineApiView.ts b/node_modules/@xterm/xterm/src/common/public/BufferLineApiView.ts new file mode 100644 index 0000000..560dd0b --- /dev/null +++ b/node_modules/@xterm/xterm/src/common/public/BufferLineApiView.ts @@ -0,0 +1,29 @@ +/** + * Copyright (c) 2021 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { CellData } from 'common/buffer/CellData'; +import { IBufferLine, ICellData } from 'common/Types'; +import { IBufferCell as IBufferCellApi, IBufferLine as IBufferLineApi } from '@xterm/xterm'; + +export class BufferLineApiView implements IBufferLineApi { + constructor(private _line: IBufferLine) { } + + public get isWrapped(): boolean { return this._line.isWrapped; } + public get length(): number { return this._line.length; } + public getCell(x: number, cell?: IBufferCellApi): IBufferCellApi | undefined { + if (x < 0 || x >= this._line.length) { + return undefined; + } + + if (cell) { + this._line.loadCell(x, cell as ICellData); + return cell; + } + return this._line.loadCell(x, new CellData()); + } + public translateToString(trimRight?: boolean, startColumn?: number, endColumn?: number): string { + return this._line.translateToString(trimRight, startColumn, endColumn); + } +} diff --git a/node_modules/@xterm/xterm/src/common/public/BufferNamespaceApi.ts b/node_modules/@xterm/xterm/src/common/public/BufferNamespaceApi.ts new file mode 100644 index 0000000..e850860 --- /dev/null +++ b/node_modules/@xterm/xterm/src/common/public/BufferNamespaceApi.ts @@ -0,0 +1,36 @@ +/** + * Copyright (c) 2021 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { IBuffer as IBufferApi, IBufferNamespace as IBufferNamespaceApi } from '@xterm/xterm'; +import { BufferApiView } from 'common/public/BufferApiView'; +import { ICoreTerminal } from 'common/Types'; +import { Disposable } from 'vs/base/common/lifecycle'; +import { Emitter } from 'vs/base/common/event'; + +export class BufferNamespaceApi extends Disposable implements IBufferNamespaceApi { + private _normal: BufferApiView; + private _alternate: BufferApiView; + + private readonly _onBufferChange = this._register(new Emitter()); + public readonly onBufferChange = this._onBufferChange.event; + + constructor(private _core: ICoreTerminal) { + super(); + this._normal = new BufferApiView(this._core.buffers.normal, 'normal'); + this._alternate = new BufferApiView(this._core.buffers.alt, 'alternate'); + this._core.buffers.onBufferActivate(() => this._onBufferChange.fire(this.active)); + } + public get active(): IBufferApi { + if (this._core.buffers.active === this._core.buffers.normal) { return this.normal; } + if (this._core.buffers.active === this._core.buffers.alt) { return this.alternate; } + throw new Error('Active buffer is neither normal nor alternate'); + } + public get normal(): IBufferApi { + return this._normal.init(this._core.buffers.normal); + } + public get alternate(): IBufferApi { + return this._alternate.init(this._core.buffers.alt); + } +} diff --git a/node_modules/@xterm/xterm/src/common/public/ParserApi.ts b/node_modules/@xterm/xterm/src/common/public/ParserApi.ts new file mode 100644 index 0000000..afcc01b --- /dev/null +++ b/node_modules/@xterm/xterm/src/common/public/ParserApi.ts @@ -0,0 +1,37 @@ +/** + * Copyright (c) 2021 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { IParams } from 'common/parser/Types'; +import { IDisposable, IFunctionIdentifier, IParser } from '@xterm/xterm'; +import { ICoreTerminal } from 'common/Types'; + +export class ParserApi implements IParser { + constructor(private _core: ICoreTerminal) { } + + public registerCsiHandler(id: IFunctionIdentifier, callback: (params: (number | number[])[]) => boolean | Promise): IDisposable { + return this._core.registerCsiHandler(id, (params: IParams) => callback(params.toArray())); + } + public addCsiHandler(id: IFunctionIdentifier, callback: (params: (number | number[])[]) => boolean | Promise): IDisposable { + return this.registerCsiHandler(id, callback); + } + public registerDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: (number | number[])[]) => boolean | Promise): IDisposable { + return this._core.registerDcsHandler(id, (data: string, params: IParams) => callback(data, params.toArray())); + } + public addDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: (number | number[])[]) => boolean | Promise): IDisposable { + return this.registerDcsHandler(id, callback); + } + public registerEscHandler(id: IFunctionIdentifier, handler: () => boolean | Promise): IDisposable { + return this._core.registerEscHandler(id, handler); + } + public addEscHandler(id: IFunctionIdentifier, handler: () => boolean | Promise): IDisposable { + return this.registerEscHandler(id, handler); + } + public registerOscHandler(ident: number, callback: (data: string) => boolean | Promise): IDisposable { + return this._core.registerOscHandler(ident, callback); + } + public addOscHandler(ident: number, callback: (data: string) => boolean | Promise): IDisposable { + return this.registerOscHandler(ident, callback); + } +} diff --git a/node_modules/@xterm/xterm/src/common/public/UnicodeApi.ts b/node_modules/@xterm/xterm/src/common/public/UnicodeApi.ts new file mode 100644 index 0000000..ec9bd1f --- /dev/null +++ b/node_modules/@xterm/xterm/src/common/public/UnicodeApi.ts @@ -0,0 +1,27 @@ +/** + * Copyright (c) 2021 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { ICoreTerminal } from 'common/Types'; +import { IUnicodeHandling, IUnicodeVersionProvider } from '@xterm/xterm'; + +export class UnicodeApi implements IUnicodeHandling { + constructor(private _core: ICoreTerminal) { } + + public register(provider: IUnicodeVersionProvider): void { + this._core.unicodeService.register(provider); + } + + public get versions(): string[] { + return this._core.unicodeService.versions; + } + + public get activeVersion(): string { + return this._core.unicodeService.activeVersion; + } + + public set activeVersion(version: string) { + this._core.unicodeService.activeVersion = version; + } +} diff --git a/node_modules/@xterm/xterm/src/common/services/BufferService.ts b/node_modules/@xterm/xterm/src/common/services/BufferService.ts new file mode 100644 index 0000000..4cba3c1 --- /dev/null +++ b/node_modules/@xterm/xterm/src/common/services/BufferService.ts @@ -0,0 +1,154 @@ +/** + * Copyright (c) 2019 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { Disposable } from 'vs/base/common/lifecycle'; +import { IAttributeData, IBufferLine } from 'common/Types'; +import { BufferSet } from 'common/buffer/BufferSet'; +import { IBuffer, IBufferSet } from 'common/buffer/Types'; +import { IBufferService, IOptionsService, type IBufferResizeEvent } from 'common/services/Services'; +import { Emitter } from 'vs/base/common/event'; + +export const MINIMUM_COLS = 2; // Less than 2 can mess with wide chars +export const MINIMUM_ROWS = 1; + +export class BufferService extends Disposable implements IBufferService { + public serviceBrand: any; + + public cols: number; + public rows: number; + public buffers: IBufferSet; + /** Whether the user is scrolling (locks the scroll position) */ + public isUserScrolling: boolean = false; + + private readonly _onResize = this._register(new Emitter()); + public readonly onResize = this._onResize.event; + private readonly _onScroll = this._register(new Emitter()); + public readonly onScroll = this._onScroll.event; + + public get buffer(): IBuffer { return this.buffers.active; } + + /** An IBufferline to clone/copy from for new blank lines */ + private _cachedBlankLine: IBufferLine | undefined; + + constructor(@IOptionsService optionsService: IOptionsService) { + super(); + this.cols = Math.max(optionsService.rawOptions.cols || 0, MINIMUM_COLS); + this.rows = Math.max(optionsService.rawOptions.rows || 0, MINIMUM_ROWS); + this.buffers = this._register(new BufferSet(optionsService, this)); + this._register(this.buffers.onBufferActivate(e => { + this._onScroll.fire(e.activeBuffer.ydisp); + })); + } + + public resize(cols: number, rows: number): void { + const colsChanged = this.cols !== cols; + const rowsChanged = this.rows !== rows; + this.cols = cols; + this.rows = rows; + this.buffers.resize(cols, rows); + this._onResize.fire({ cols, rows, colsChanged, rowsChanged }); + } + + public reset(): void { + this.buffers.reset(); + this.isUserScrolling = false; + } + + /** + * Scroll the terminal down 1 row, creating a blank line. + * @param eraseAttr The attribute data to use the for blank line. + * @param isWrapped Whether the new line is wrapped from the previous line. + */ + public scroll(eraseAttr: IAttributeData, isWrapped: boolean = false): void { + const buffer = this.buffer; + + let newLine: IBufferLine | undefined; + newLine = this._cachedBlankLine; + if (!newLine || newLine.length !== this.cols || newLine.getFg(0) !== eraseAttr.fg || newLine.getBg(0) !== eraseAttr.bg) { + newLine = buffer.getBlankLine(eraseAttr, isWrapped); + this._cachedBlankLine = newLine; + } + newLine.isWrapped = isWrapped; + + const topRow = buffer.ybase + buffer.scrollTop; + const bottomRow = buffer.ybase + buffer.scrollBottom; + + if (buffer.scrollTop === 0) { + // Determine whether the buffer is going to be trimmed after insertion. + const willBufferBeTrimmed = buffer.lines.isFull; + + // Insert the line using the fastest method + if (bottomRow === buffer.lines.length - 1) { + if (willBufferBeTrimmed) { + buffer.lines.recycle().copyFrom(newLine); + } else { + buffer.lines.push(newLine.clone()); + } + } else { + buffer.lines.splice(bottomRow + 1, 0, newLine.clone()); + } + + // Only adjust ybase and ydisp when the buffer is not trimmed + if (!willBufferBeTrimmed) { + buffer.ybase++; + // Only scroll the ydisp with ybase if the user has not scrolled up + if (!this.isUserScrolling) { + buffer.ydisp++; + } + } else { + // When the buffer is full and the user has scrolled up, keep the text + // stable unless ydisp is right at the top + if (this.isUserScrolling) { + buffer.ydisp = Math.max(buffer.ydisp - 1, 0); + } + } + } else { + // scrollTop is non-zero which means no line will be going to the + // scrollback, instead we can just shift them in-place. + const scrollRegionHeight = bottomRow - topRow + 1 /* as it's zero-based */; + buffer.lines.shiftElements(topRow + 1, scrollRegionHeight - 1, -1); + buffer.lines.set(bottomRow, newLine.clone()); + } + + // Move the viewport to the bottom of the buffer unless the user is + // scrolling. + if (!this.isUserScrolling) { + buffer.ydisp = buffer.ybase; + } + + this._onScroll.fire(buffer.ydisp); + } + + /** + * Scroll the display of the terminal + * @param disp The number of lines to scroll down (negative scroll up). + * @param suppressScrollEvent Don't emit the scroll event as scrollLines. This is used + * to avoid unwanted events being handled by the viewport when the event was triggered from the + * viewport originally. + */ + public scrollLines(disp: number, suppressScrollEvent?: boolean): void { + const buffer = this.buffer; + if (disp < 0) { + if (buffer.ydisp === 0) { + return; + } + this.isUserScrolling = true; + } else if (disp + buffer.ydisp >= buffer.ybase) { + this.isUserScrolling = false; + } + + const oldYdisp = buffer.ydisp; + buffer.ydisp = Math.max(Math.min(buffer.ydisp + disp, buffer.ybase), 0); + + // No change occurred, don't trigger scroll/refresh + if (oldYdisp === buffer.ydisp) { + return; + } + + if (!suppressScrollEvent) { + this._onScroll.fire(buffer.ydisp); + } + } +} diff --git a/node_modules/@xterm/xterm/src/common/services/CharsetService.ts b/node_modules/@xterm/xterm/src/common/services/CharsetService.ts new file mode 100644 index 0000000..c538106 --- /dev/null +++ b/node_modules/@xterm/xterm/src/common/services/CharsetService.ts @@ -0,0 +1,34 @@ +/** + * Copyright (c) 2019 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { ICharsetService } from 'common/services/Services'; +import { ICharset } from 'common/Types'; + +export class CharsetService implements ICharsetService { + public serviceBrand: any; + + public charset: ICharset | undefined; + public glevel: number = 0; + + private _charsets: (ICharset | undefined)[] = []; + + public reset(): void { + this.charset = undefined; + this._charsets = []; + this.glevel = 0; + } + + public setgLevel(g: number): void { + this.glevel = g; + this.charset = this._charsets[g]; + } + + public setgCharset(g: number, charset: ICharset | undefined): void { + this._charsets[g] = charset; + if (this.glevel === g) { + this.charset = charset; + } + } +} diff --git a/node_modules/@xterm/xterm/src/common/services/CoreMouseService.ts b/node_modules/@xterm/xterm/src/common/services/CoreMouseService.ts new file mode 100644 index 0000000..a10ddaf --- /dev/null +++ b/node_modules/@xterm/xterm/src/common/services/CoreMouseService.ts @@ -0,0 +1,365 @@ +/** + * Copyright (c) 2019 The xterm.js authors. All rights reserved. + * @license MIT + */ +import { IBufferService, ICoreService, ICoreMouseService, IOptionsService } from 'common/services/Services'; +import { ICoreMouseProtocol, ICoreMouseEvent, CoreMouseEncoding, CoreMouseEventType, CoreMouseButton, CoreMouseAction } from 'common/Types'; +import { Disposable } from 'vs/base/common/lifecycle'; +import { Emitter } from 'vs/base/common/event'; + +/** + * Supported default protocols. + */ +const DEFAULT_PROTOCOLS: { [key: string]: ICoreMouseProtocol } = { + /** + * NONE + * Events: none + * Modifiers: none + */ + NONE: { + events: CoreMouseEventType.NONE, + restrict: () => false + }, + /** + * X10 + * Events: mousedown + * Modifiers: none + */ + X10: { + events: CoreMouseEventType.DOWN, + restrict: (e: ICoreMouseEvent) => { + // no wheel, no move, no up + if (e.button === CoreMouseButton.WHEEL || e.action !== CoreMouseAction.DOWN) { + return false; + } + // no modifiers + e.ctrl = false; + e.alt = false; + e.shift = false; + return true; + } + }, + /** + * VT200 + * Events: mousedown / mouseup / wheel + * Modifiers: all + */ + VT200: { + events: CoreMouseEventType.DOWN | CoreMouseEventType.UP | CoreMouseEventType.WHEEL, + restrict: (e: ICoreMouseEvent) => { + // no move + if (e.action === CoreMouseAction.MOVE) { + return false; + } + return true; + } + }, + /** + * DRAG + * Events: mousedown / mouseup / wheel / mousedrag + * Modifiers: all + */ + DRAG: { + events: CoreMouseEventType.DOWN | CoreMouseEventType.UP | CoreMouseEventType.WHEEL | CoreMouseEventType.DRAG, + restrict: (e: ICoreMouseEvent) => { + // no move without button + if (e.action === CoreMouseAction.MOVE && e.button === CoreMouseButton.NONE) { + return false; + } + return true; + } + }, + /** + * ANY + * Events: all mouse related events + * Modifiers: all + */ + ANY: { + events: + CoreMouseEventType.DOWN | CoreMouseEventType.UP | CoreMouseEventType.WHEEL + | CoreMouseEventType.DRAG | CoreMouseEventType.MOVE, + restrict: (e: ICoreMouseEvent) => true + } +}; + +const enum Modifiers { + SHIFT = 4, + ALT = 8, + CTRL = 16 +} + +// helper for default encoders to generate the event code. +function eventCode(e: ICoreMouseEvent, isSGR: boolean): number { + let code = (e.ctrl ? Modifiers.CTRL : 0) | (e.shift ? Modifiers.SHIFT : 0) | (e.alt ? Modifiers.ALT : 0); + if (e.button === CoreMouseButton.WHEEL) { + code |= 64; + code |= e.action; + } else { + code |= e.button & 3; + if (e.button & 4) { + code |= 64; + } + if (e.button & 8) { + code |= 128; + } + if (e.action === CoreMouseAction.MOVE) { + code |= CoreMouseAction.MOVE; + } else if (e.action === CoreMouseAction.UP && !isSGR) { + // special case - only SGR can report button on release + // all others have to go with NONE + code |= CoreMouseButton.NONE; + } + } + return code; +} + +const S = String.fromCharCode; + +/** + * Supported default encodings. + */ +const DEFAULT_ENCODINGS: { [key: string]: CoreMouseEncoding } = { + /** + * DEFAULT - CSI M Pb Px Py + * Single byte encoding for coords and event code. + * Can encode values up to 223 (1-based). + */ + DEFAULT: (e: ICoreMouseEvent) => { + const params = [eventCode(e, false) + 32, e.col + 32, e.row + 32]; + // supress mouse report if we exceed addressible range + // Note this is handled differently by emulators + // - xterm: sends 0;0 coords instead + // - vte, konsole: no report + if (params[0] > 255 || params[1] > 255 || params[2] > 255) { + return ''; + } + return `\x1b[M${S(params[0])}${S(params[1])}${S(params[2])}`; + }, + /** + * SGR - CSI < Pb ; Px ; Py M|m + * No encoding limitation. + * Can report button on release and works with a well formed sequence. + */ + SGR: (e: ICoreMouseEvent) => { + const final = (e.action === CoreMouseAction.UP && e.button !== CoreMouseButton.WHEEL) ? 'm' : 'M'; + return `\x1b[<${eventCode(e, true)};${e.col};${e.row}${final}`; + }, + SGR_PIXELS: (e: ICoreMouseEvent) => { + const final = (e.action === CoreMouseAction.UP && e.button !== CoreMouseButton.WHEEL) ? 'm' : 'M'; + return `\x1b[<${eventCode(e, true)};${e.x};${e.y}${final}`; + } +}; + +/** + * CoreMouseService + * + * Provides mouse tracking reports with different protocols and encodings. + * - protocols: NONE (default), X10, VT200, DRAG, ANY + * - encodings: DEFAULT, SGR (UTF8, URXVT removed in #2507) + * + * Custom protocols/encodings can be added by `addProtocol` / `addEncoding`. + * To activate a protocol/encoding, set `activeProtocol` / `activeEncoding`. + * Switching a protocol will send a notification event `onProtocolChange` + * with a list of needed events to track. + * + * The service handles the mouse tracking state and decides whether to send + * a tracking report to the backend based on protocol and encoding limitations. + * To send a mouse event call `triggerMouseEvent`. + */ +export class CoreMouseService extends Disposable implements ICoreMouseService { + public serviceBrand: any; + + private _protocols: { [name: string]: ICoreMouseProtocol } = {}; + private _encodings: { [name: string]: CoreMouseEncoding } = {}; + private _activeProtocol: string = ''; + private _activeEncoding: string = ''; + private _lastEvent: ICoreMouseEvent | null = null; + private _wheelPartialScroll: number = 0; + + private readonly _onProtocolChange = this._register(new Emitter()); + public readonly onProtocolChange = this._onProtocolChange.event; + + constructor( + @IBufferService private readonly _bufferService: IBufferService, + @ICoreService private readonly _coreService: ICoreService, + @IOptionsService private readonly _optionsService: IOptionsService + ) { + super(); + // register default protocols and encodings + for (const name of Object.keys(DEFAULT_PROTOCOLS)) this.addProtocol(name, DEFAULT_PROTOCOLS[name]); + for (const name of Object.keys(DEFAULT_ENCODINGS)) this.addEncoding(name, DEFAULT_ENCODINGS[name]); + // call reset to set defaults + this.reset(); + } + + public addProtocol(name: string, protocol: ICoreMouseProtocol): void { + this._protocols[name] = protocol; + } + + public addEncoding(name: string, encoding: CoreMouseEncoding): void { + this._encodings[name] = encoding; + } + + public get activeProtocol(): string { + return this._activeProtocol; + } + + public get areMouseEventsActive(): boolean { + return this._protocols[this._activeProtocol].events !== 0; + } + + public set activeProtocol(name: string) { + if (!this._protocols[name]) { + throw new Error(`unknown protocol "${name}"`); + } + this._activeProtocol = name; + this._onProtocolChange.fire(this._protocols[name].events); + } + + public get activeEncoding(): string { + return this._activeEncoding; + } + + public set activeEncoding(name: string) { + if (!this._encodings[name]) { + throw new Error(`unknown encoding "${name}"`); + } + this._activeEncoding = name; + } + + public reset(): void { + this.activeProtocol = 'NONE'; + this.activeEncoding = 'DEFAULT'; + this._lastEvent = null; + this._wheelPartialScroll = 0; + } + + /** + * Processes a wheel event, accounting for partial scrolls for trackpad, mouse scrolls. + * This prevents hyper-sensitive scrolling in alt buffer. + */ + public consumeWheelEvent(ev: WheelEvent, cellHeight?: number, dpr?: number): number { + // Do nothing if it's not a vertical scroll event + if (ev.deltaY === 0 || ev.shiftKey) { + return 0; + } + + if (cellHeight === undefined || dpr === undefined) { + return 0; + } + + const targetWheelEventPixels = cellHeight / dpr; + let amount = this._applyScrollModifier(ev.deltaY, ev); + + if (ev.deltaMode === WheelEvent.DOM_DELTA_PIXEL) { + amount /= (targetWheelEventPixels + 0.0); // Prevent integer division + + const isLikelyTrackpad = Math.abs(ev.deltaY) < 50; + if (isLikelyTrackpad) { + amount *= 0.3; + } + + this._wheelPartialScroll += amount; + amount = Math.floor(Math.abs(this._wheelPartialScroll)) * (this._wheelPartialScroll > 0 ? 1 : -1); + this._wheelPartialScroll %= 1; + } else if (ev.deltaMode === WheelEvent.DOM_DELTA_PAGE) { + amount *= this._bufferService.rows; + } + return amount; + } + + private _applyScrollModifier(amount: number, ev: WheelEvent): number { + // Multiply the scroll speed when the modifier key is pressed + if (ev.altKey || ev.ctrlKey || ev.shiftKey) { + return amount * this._optionsService.rawOptions.fastScrollSensitivity * this._optionsService.rawOptions.scrollSensitivity; + } + return amount * this._optionsService.rawOptions.scrollSensitivity; + } + + /** + * Triggers a mouse event to be sent. + * + * Returns true if the event passed all protocol restrictions and a report + * was sent, otherwise false. The return value may be used to decide whether + * the default event action in the bowser component should be omitted. + * + * Note: The method will change values of the given event object + * to fullfill protocol and encoding restrictions. + */ + public triggerMouseEvent(e: ICoreMouseEvent): boolean { + // range check for col/row + if (e.col < 0 || e.col >= this._bufferService.cols + || e.row < 0 || e.row >= this._bufferService.rows) { + return false; + } + + // filter nonsense combinations of button + action + if (e.button === CoreMouseButton.WHEEL && e.action === CoreMouseAction.MOVE) { + return false; + } + if (e.button === CoreMouseButton.NONE && e.action !== CoreMouseAction.MOVE) { + return false; + } + if (e.button !== CoreMouseButton.WHEEL && (e.action === CoreMouseAction.LEFT || e.action === CoreMouseAction.RIGHT)) { + return false; + } + + // report 1-based coords + e.col++; + e.row++; + + // debounce move events at grid or pixel level + if (e.action === CoreMouseAction.MOVE + && this._lastEvent + && this._equalEvents(this._lastEvent, e, this._activeEncoding === 'SGR_PIXELS') + ) { + return false; + } + + // apply protocol restrictions + if (!this._protocols[this._activeProtocol].restrict(e)) { + return false; + } + + // encode report and send + const report = this._encodings[this._activeEncoding](e); + if (report) { + // always send DEFAULT as binary data + if (this._activeEncoding === 'DEFAULT') { + this._coreService.triggerBinaryEvent(report); + } else { + this._coreService.triggerDataEvent(report, true); + } + } + + this._lastEvent = e; + + return true; + } + + public explainEvents(events: CoreMouseEventType): { [event: string]: boolean } { + return { + down: !!(events & CoreMouseEventType.DOWN), + up: !!(events & CoreMouseEventType.UP), + drag: !!(events & CoreMouseEventType.DRAG), + move: !!(events & CoreMouseEventType.MOVE), + wheel: !!(events & CoreMouseEventType.WHEEL) + }; + } + + private _equalEvents(e1: ICoreMouseEvent, e2: ICoreMouseEvent, pixels: boolean): boolean { + if (pixels) { + if (e1.x !== e2.x) return false; + if (e1.y !== e2.y) return false; + } else { + if (e1.col !== e2.col) return false; + if (e1.row !== e2.row) return false; + } + if (e1.button !== e2.button) return false; + if (e1.action !== e2.action) return false; + if (e1.ctrl !== e2.ctrl) return false; + if (e1.alt !== e2.alt) return false; + if (e1.shift !== e2.shift) return false; + return true; + } +} diff --git a/node_modules/@xterm/xterm/src/common/services/CoreService.ts b/node_modules/@xterm/xterm/src/common/services/CoreService.ts new file mode 100644 index 0000000..7b5f532 --- /dev/null +++ b/node_modules/@xterm/xterm/src/common/services/CoreService.ts @@ -0,0 +1,92 @@ +/** + * Copyright (c) 2019 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { clone } from 'common/Clone'; +import { Disposable } from 'vs/base/common/lifecycle'; +import { IDecPrivateModes, IModes } from 'common/Types'; +import { IBufferService, ICoreService, ILogService, IOptionsService } from 'common/services/Services'; +import { Emitter } from 'vs/base/common/event'; + +const DEFAULT_MODES: IModes = Object.freeze({ + insertMode: false +}); + +const DEFAULT_DEC_PRIVATE_MODES: IDecPrivateModes = Object.freeze({ + applicationCursorKeys: false, + applicationKeypad: false, + bracketedPasteMode: false, + cursorBlink: undefined, + cursorStyle: undefined, + origin: false, + reverseWraparound: false, + sendFocus: false, + synchronizedOutput: false, + wraparound: true // defaults: xterm - true, vt100 - false +}); + +export class CoreService extends Disposable implements ICoreService { + public serviceBrand: any; + + public isCursorInitialized: boolean = false; + public isCursorHidden: boolean = false; + public modes: IModes; + public decPrivateModes: IDecPrivateModes; + + private readonly _onData = this._register(new Emitter()); + public readonly onData = this._onData.event; + private readonly _onUserInput = this._register(new Emitter()); + public readonly onUserInput = this._onUserInput.event; + private readonly _onBinary = this._register(new Emitter()); + public readonly onBinary = this._onBinary.event; + private readonly _onRequestScrollToBottom = this._register(new Emitter()); + public readonly onRequestScrollToBottom = this._onRequestScrollToBottom.event; + + constructor( + @IBufferService private readonly _bufferService: IBufferService, + @ILogService private readonly _logService: ILogService, + @IOptionsService private readonly _optionsService: IOptionsService + ) { + super(); + this.modes = clone(DEFAULT_MODES); + this.decPrivateModes = clone(DEFAULT_DEC_PRIVATE_MODES); + } + + public reset(): void { + this.modes = clone(DEFAULT_MODES); + this.decPrivateModes = clone(DEFAULT_DEC_PRIVATE_MODES); + } + + public triggerDataEvent(data: string, wasUserInput: boolean = false): void { + // Prevents all events to pty process if stdin is disabled + if (this._optionsService.rawOptions.disableStdin) { + return; + } + + // Input is being sent to the terminal, the terminal should focus the prompt. + const buffer = this._bufferService.buffer; + if (wasUserInput && this._optionsService.rawOptions.scrollOnUserInput && buffer.ybase !== buffer.ydisp) { + this._onRequestScrollToBottom.fire(); + } + + // Fire onUserInput so listeners can react as well (eg. clear selection) + if (wasUserInput) { + this._onUserInput.fire(); + } + + // Fire onData API + this._logService.debug(`sending data "${data}"`); + this._logService.trace(`sending data (codes)`, () => data.split('').map(e => e.charCodeAt(0))); + this._onData.fire(data); + } + + public triggerBinaryEvent(data: string): void { + if (this._optionsService.rawOptions.disableStdin) { + return; + } + this._logService.debug(`sending binary "${data}"`); + this._logService.trace(`sending binary (codes)`, () => data.split('').map(e => e.charCodeAt(0))); + this._onBinary.fire(data); + } +} diff --git a/node_modules/@xterm/xterm/src/common/services/DecorationService.ts b/node_modules/@xterm/xterm/src/common/services/DecorationService.ts new file mode 100644 index 0000000..608106c --- /dev/null +++ b/node_modules/@xterm/xterm/src/common/services/DecorationService.ts @@ -0,0 +1,140 @@ +/** + * Copyright (c) 2022 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { css } from 'common/Color'; +import { Disposable, DisposableStore, toDisposable } from 'vs/base/common/lifecycle'; +import { IDecorationService, IInternalDecoration } from 'common/services/Services'; +import { SortedList } from 'common/SortedList'; +import { IColor } from 'common/Types'; +import { IDecoration, IDecorationOptions, IMarker } from '@xterm/xterm'; +import { Emitter } from 'vs/base/common/event'; + +// Work variables to avoid garbage collection +let $xmin = 0; +let $xmax = 0; + +export class DecorationService extends Disposable implements IDecorationService { + public serviceBrand: any; + + /** + * A list of all decorations, sorted by the marker's line value. This relies on the fact that + * while marker line values do change, they should all change by the same amount so this should + * never become out of order. + */ + private readonly _decorations: SortedList = new SortedList(e => e?.marker.line); + + private readonly _onDecorationRegistered = this._register(new Emitter()); + public readonly onDecorationRegistered = this._onDecorationRegistered.event; + private readonly _onDecorationRemoved = this._register(new Emitter()); + public readonly onDecorationRemoved = this._onDecorationRemoved.event; + + public get decorations(): IterableIterator { return this._decorations.values(); } + + constructor() { + super(); + + this._register(toDisposable(() => this.reset())); + } + + public registerDecoration(options: IDecorationOptions): IDecoration | undefined { + if (options.marker.isDisposed) { + return undefined; + } + const decoration = new Decoration(options); + if (decoration) { + const markerDispose = decoration.marker.onDispose(() => decoration.dispose()); + const listener = decoration.onDispose(() => { + listener.dispose(); + if (decoration) { + if (this._decorations.delete(decoration)) { + this._onDecorationRemoved.fire(decoration); + } + markerDispose.dispose(); + } + }); + this._decorations.insert(decoration); + this._onDecorationRegistered.fire(decoration); + } + return decoration; + } + + public reset(): void { + for (const d of this._decorations.values()) { + d.dispose(); + } + this._decorations.clear(); + } + + public *getDecorationsAtCell(x: number, line: number, layer?: 'bottom' | 'top'): IterableIterator { + let xmin = 0; + let xmax = 0; + for (const d of this._decorations.getKeyIterator(line)) { + xmin = d.options.x ?? 0; + xmax = xmin + (d.options.width ?? 1); + if (x >= xmin && x < xmax && (!layer || (d.options.layer ?? 'bottom') === layer)) { + yield d; + } + } + } + + public forEachDecorationAtCell(x: number, line: number, layer: 'bottom' | 'top' | undefined, callback: (decoration: IInternalDecoration) => void): void { + this._decorations.forEachByKey(line, d => { + $xmin = d.options.x ?? 0; + $xmax = $xmin + (d.options.width ?? 1); + if (x >= $xmin && x < $xmax && (!layer || (d.options.layer ?? 'bottom') === layer)) { + callback(d); + } + }); + } +} + +class Decoration extends DisposableStore implements IInternalDecoration { + public readonly marker: IMarker; + public element: HTMLElement | undefined; + + public readonly onRenderEmitter = this.add(new Emitter()); + public readonly onRender = this.onRenderEmitter.event; + private readonly _onDispose = this.add(new Emitter()); + public readonly onDispose = this._onDispose.event; + + private _cachedBg: IColor | undefined | null = null; + public get backgroundColorRGB(): IColor | undefined { + if (this._cachedBg === null) { + if (this.options.backgroundColor) { + this._cachedBg = css.toColor(this.options.backgroundColor); + } else { + this._cachedBg = undefined; + } + } + return this._cachedBg; + } + + private _cachedFg: IColor | undefined | null = null; + public get foregroundColorRGB(): IColor | undefined { + if (this._cachedFg === null) { + if (this.options.foregroundColor) { + this._cachedFg = css.toColor(this.options.foregroundColor); + } else { + this._cachedFg = undefined; + } + } + return this._cachedFg; + } + + constructor( + public readonly options: IDecorationOptions + ) { + super(); + this.marker = options.marker; + if (this.options.overviewRulerOptions && !this.options.overviewRulerOptions.position) { + this.options.overviewRulerOptions.position = 'full'; + } + } + + public override dispose(): void { + this._onDispose.fire(); + super.dispose(); + } +} diff --git a/node_modules/@xterm/xterm/src/common/services/InstantiationService.ts b/node_modules/@xterm/xterm/src/common/services/InstantiationService.ts new file mode 100644 index 0000000..7e76954 --- /dev/null +++ b/node_modules/@xterm/xterm/src/common/services/InstantiationService.ts @@ -0,0 +1,85 @@ +/** + * Copyright (c) 2019 The xterm.js authors. All rights reserved. + * @license MIT + * + * This was heavily inspired from microsoft/vscode's dependency injection system (MIT). + */ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { IInstantiationService, IServiceIdentifier } from 'common/services/Services'; +import { getServiceDependencies } from 'common/services/ServiceRegistry'; + +export class ServiceCollection { + + private _entries = new Map, any>(); + + constructor(...entries: [IServiceIdentifier, any][]) { + for (const [id, service] of entries) { + this.set(id, service); + } + } + + public set(id: IServiceIdentifier, instance: T): T { + const result = this._entries.get(id); + this._entries.set(id, instance); + return result; + } + + public forEach(callback: (id: IServiceIdentifier, instance: any) => any): void { + for (const [key, value] of this._entries.entries()) { + callback(key, value); + } + } + + public has(id: IServiceIdentifier): boolean { + return this._entries.has(id); + } + + public get(id: IServiceIdentifier): T | undefined { + return this._entries.get(id); + } +} + +export class InstantiationService implements IInstantiationService { + public serviceBrand: undefined; + + private readonly _services: ServiceCollection = new ServiceCollection(); + + constructor() { + this._services.set(IInstantiationService, this); + } + + public setService(id: IServiceIdentifier, instance: T): void { + this._services.set(id, instance); + } + + public getService(id: IServiceIdentifier): T | undefined { + return this._services.get(id); + } + + public createInstance(ctor: any, ...args: any[]): T { + const serviceDependencies = getServiceDependencies(ctor).sort((a, b) => a.index - b.index); + + const serviceArgs: any[] = []; + for (const dependency of serviceDependencies) { + const service = this._services.get(dependency.id); + if (!service) { + throw new Error(`[createInstance] ${ctor.name} depends on UNKNOWN service ${dependency.id._id}.`); + } + serviceArgs.push(service); + } + + const firstServiceArgPos = serviceDependencies.length > 0 ? serviceDependencies[0].index : args.length; + + // check for argument mismatches, adjust static args if needed + if (args.length !== firstServiceArgPos) { + throw new Error(`[createInstance] First service dependency of ${ctor.name} at position ${firstServiceArgPos + 1} conflicts with ${args.length} static arguments`); + } + + // now create the instance + return new ctor(...[...args, ...serviceArgs]); + } +} diff --git a/node_modules/@xterm/xterm/src/common/services/LogService.ts b/node_modules/@xterm/xterm/src/common/services/LogService.ts new file mode 100644 index 0000000..986ff62 --- /dev/null +++ b/node_modules/@xterm/xterm/src/common/services/LogService.ts @@ -0,0 +1,124 @@ +/** + * Copyright (c) 2019 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { Disposable } from 'vs/base/common/lifecycle'; +import { ILogService, IOptionsService, LogLevelEnum } from 'common/services/Services'; + +type LogType = (message?: any, ...optionalParams: any[]) => void; + +interface IConsole { + log: LogType; + error: LogType; + info: LogType; + trace: LogType; + warn: LogType; +} + +// console is available on both node.js and browser contexts but the common +// module doesn't depend on them so we need to explicitly declare it. +declare const console: IConsole; + +const optionsKeyToLogLevel: { [key: string]: LogLevelEnum } = { + trace: LogLevelEnum.TRACE, + debug: LogLevelEnum.DEBUG, + info: LogLevelEnum.INFO, + warn: LogLevelEnum.WARN, + error: LogLevelEnum.ERROR, + off: LogLevelEnum.OFF +}; + +const LOG_PREFIX = 'xterm.js: '; + +export class LogService extends Disposable implements ILogService { + public serviceBrand: any; + + private _logLevel: LogLevelEnum = LogLevelEnum.OFF; + public get logLevel(): LogLevelEnum { return this._logLevel; } + + constructor( + @IOptionsService private readonly _optionsService: IOptionsService + ) { + super(); + this._updateLogLevel(); + this._register(this._optionsService.onSpecificOptionChange('logLevel', () => this._updateLogLevel())); + + // For trace logging, assume the latest created log service is valid + traceLogger = this; + } + + private _updateLogLevel(): void { + this._logLevel = optionsKeyToLogLevel[this._optionsService.rawOptions.logLevel]; + } + + private _evalLazyOptionalParams(optionalParams: any[]): void { + for (let i = 0; i < optionalParams.length; i++) { + if (typeof optionalParams[i] === 'function') { + optionalParams[i] = optionalParams[i](); + } + } + } + + private _log(type: LogType, message: string, optionalParams: any[]): void { + this._evalLazyOptionalParams(optionalParams); + type.call(console, (this._optionsService.options.logger ? '' : LOG_PREFIX) + message, ...optionalParams); + } + + public trace(message: string, ...optionalParams: any[]): void { + if (this._logLevel <= LogLevelEnum.TRACE) { + this._log(this._optionsService.options.logger?.trace.bind(this._optionsService.options.logger) ?? console.log, message, optionalParams); + } + } + + public debug(message: string, ...optionalParams: any[]): void { + if (this._logLevel <= LogLevelEnum.DEBUG) { + this._log(this._optionsService.options.logger?.debug.bind(this._optionsService.options.logger) ?? console.log, message, optionalParams); + } + } + + public info(message: string, ...optionalParams: any[]): void { + if (this._logLevel <= LogLevelEnum.INFO) { + this._log(this._optionsService.options.logger?.info.bind(this._optionsService.options.logger) ?? console.info, message, optionalParams); + } + } + + public warn(message: string, ...optionalParams: any[]): void { + if (this._logLevel <= LogLevelEnum.WARN) { + this._log(this._optionsService.options.logger?.warn.bind(this._optionsService.options.logger) ?? console.warn, message, optionalParams); + } + } + + public error(message: string, ...optionalParams: any[]): void { + if (this._logLevel <= LogLevelEnum.ERROR) { + this._log(this._optionsService.options.logger?.error.bind(this._optionsService.options.logger) ?? console.error, message, optionalParams); + } + } +} + +let traceLogger: ILogService; +export function setTraceLogger(logger: ILogService): void { + traceLogger = logger; +} + +/** + * A decorator that can be used to automatically log trace calls to the decorated function. + */ +export function traceCall(_target: any, key: string, descriptor: any): any { + if (typeof descriptor.value !== 'function') { + throw new Error('not supported'); + } + const fnKey = 'value'; + const fn = descriptor.value; + descriptor[fnKey] = function (...args: any[]) { + // Early exit + if (traceLogger.logLevel !== LogLevelEnum.TRACE) { + return fn.apply(this, args); + } + + traceLogger.trace(`GlyphRenderer#${fn.name}(${args.map(e => JSON.stringify(e)).join(', ')})`); + const result = fn.apply(this, args); + traceLogger.trace(`GlyphRenderer#${fn.name} return`, result); + return result; + }; +} diff --git a/node_modules/@xterm/xterm/src/common/services/OptionsService.ts b/node_modules/@xterm/xterm/src/common/services/OptionsService.ts new file mode 100644 index 0000000..6ad48b9 --- /dev/null +++ b/node_modules/@xterm/xterm/src/common/services/OptionsService.ts @@ -0,0 +1,212 @@ +/** + * Copyright (c) 2019 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { Disposable, toDisposable } from 'vs/base/common/lifecycle'; +import { isMac } from 'common/Platform'; +import { CursorStyle, IDisposable } from 'common/Types'; +import { FontWeight, IOptionsService, ITerminalOptions } from 'common/services/Services'; +import { Emitter } from 'vs/base/common/event'; + +export const DEFAULT_OPTIONS: Readonly> = { + cols: 80, + rows: 24, + cursorBlink: false, + cursorStyle: 'block', + cursorWidth: 1, + cursorInactiveStyle: 'outline', + customGlyphs: true, + drawBoldTextInBrightColors: true, + documentOverride: null, + fastScrollModifier: 'alt', + fastScrollSensitivity: 5, + fontFamily: 'monospace', + fontSize: 15, + fontWeight: 'normal', + fontWeightBold: 'bold', + ignoreBracketedPasteMode: false, + lineHeight: 1.0, + letterSpacing: 0, + linkHandler: null, + logLevel: 'info', + logger: null, + scrollback: 1000, + scrollOnEraseInDisplay: false, + scrollOnUserInput: true, + scrollSensitivity: 1, + screenReaderMode: false, + smoothScrollDuration: 0, + macOptionIsMeta: false, + macOptionClickForcesSelection: false, + minimumContrastRatio: 1, + disableStdin: false, + allowProposedApi: false, + allowTransparency: false, + tabStopWidth: 8, + theme: {}, + reflowCursorLine: false, + rescaleOverlappingGlyphs: false, + rightClickSelectsWord: isMac, + windowOptions: {}, + windowsMode: false, + windowsPty: {}, + wordSeparator: ' ()[]{}\',"`', + altClickMovesCursor: true, + convertEol: false, + termName: 'xterm', + cancelEvents: false, + overviewRuler: {} +}; + +const FONT_WEIGHT_OPTIONS: Extract[] = ['normal', 'bold', '100', '200', '300', '400', '500', '600', '700', '800', '900']; + +export class OptionsService extends Disposable implements IOptionsService { + public serviceBrand: any; + + public readonly rawOptions: Required; + public options: Required; + + private readonly _onOptionChange = this._register(new Emitter()); + public readonly onOptionChange = this._onOptionChange.event; + + constructor(options: Partial) { + super(); + // set the default value of each option + const defaultOptions = { ...DEFAULT_OPTIONS }; + for (const key in options) { + if (key in defaultOptions) { + try { + const newValue = options[key]; + defaultOptions[key] = this._sanitizeAndValidateOption(key, newValue); + } catch (e) { + console.error(e); + } + } + } + + // set up getters and setters for each option + this.rawOptions = defaultOptions; + this.options = { ... defaultOptions }; + this._setupOptions(); + + // Clear out options that could link outside xterm.js as they could easily cause an embedder + // memory leak + this._register(toDisposable(() => { + this.rawOptions.linkHandler = null; + this.rawOptions.documentOverride = null; + })); + } + + // eslint-disable-next-line @typescript-eslint/naming-convention + public onSpecificOptionChange(key: T, listener: (value: ITerminalOptions[T]) => any): IDisposable { + return this.onOptionChange(eventKey => { + if (eventKey === key) { + listener(this.rawOptions[key]); + } + }); + } + + // eslint-disable-next-line @typescript-eslint/naming-convention + public onMultipleOptionChange(keys: (keyof ITerminalOptions)[], listener: () => any): IDisposable { + return this.onOptionChange(eventKey => { + if (keys.indexOf(eventKey) !== -1) { + listener(); + } + }); + } + + private _setupOptions(): void { + const getter = (propName: string): any => { + if (!(propName in DEFAULT_OPTIONS)) { + throw new Error(`No option with key "${propName}"`); + } + return this.rawOptions[propName]; + }; + + const setter = (propName: string, value: any): void => { + if (!(propName in DEFAULT_OPTIONS)) { + throw new Error(`No option with key "${propName}"`); + } + + value = this._sanitizeAndValidateOption(propName, value); + // Don't fire an option change event if they didn't change + if (this.rawOptions[propName] !== value) { + this.rawOptions[propName] = value; + this._onOptionChange.fire(propName); + } + }; + + for (const propName in this.rawOptions) { + const desc = { + get: getter.bind(this, propName), + set: setter.bind(this, propName) + }; + Object.defineProperty(this.options, propName, desc); + } + } + + private _sanitizeAndValidateOption(key: string, value: any): any { + switch (key) { + case 'cursorStyle': + if (!value) { + value = DEFAULT_OPTIONS[key]; + } + if (!isCursorStyle(value)) { + throw new Error(`"${value}" is not a valid value for ${key}`); + } + break; + case 'wordSeparator': + if (!value) { + value = DEFAULT_OPTIONS[key]; + } + break; + case 'fontWeight': + case 'fontWeightBold': + if (typeof value === 'number' && 1 <= value && value <= 1000) { + // already valid numeric value + break; + } + value = FONT_WEIGHT_OPTIONS.includes(value) ? value : DEFAULT_OPTIONS[key]; + break; + case 'cursorWidth': + value = Math.floor(value); + // Fall through for bounds check + case 'lineHeight': + case 'tabStopWidth': + if (value < 1) { + throw new Error(`${key} cannot be less than 1, value: ${value}`); + } + break; + case 'minimumContrastRatio': + value = Math.max(1, Math.min(21, Math.round(value * 10) / 10)); + break; + case 'scrollback': + value = Math.min(value, 4294967295); + if (value < 0) { + throw new Error(`${key} cannot be less than 0, value: ${value}`); + } + break; + case 'fastScrollSensitivity': + case 'scrollSensitivity': + if (value <= 0) { + throw new Error(`${key} cannot be less than or equal to 0, value: ${value}`); + } + break; + case 'rows': + case 'cols': + if (!value && value !== 0) { + throw new Error(`${key} must be numeric, value: ${value}`); + } + break; + case 'windowsPty': + value = value ?? {}; + break; + } + return value; + } +} + +function isCursorStyle(value: unknown): value is CursorStyle { + return value === 'block' || value === 'underline' || value === 'bar'; +} diff --git a/node_modules/@xterm/xterm/src/common/services/OscLinkService.ts b/node_modules/@xterm/xterm/src/common/services/OscLinkService.ts new file mode 100644 index 0000000..13bd8aa --- /dev/null +++ b/node_modules/@xterm/xterm/src/common/services/OscLinkService.ts @@ -0,0 +1,115 @@ +/** + * Copyright (c) 2022 The xterm.js authors. All rights reserved. + * @license MIT + */ +import { IBufferService, IOscLinkService } from 'common/services/Services'; +import { IMarker, IOscLinkData } from 'common/Types'; + +export class OscLinkService implements IOscLinkService { + public serviceBrand: any; + + private _nextId = 1; + + /** + * A map of the link key to link entry. This is used to add additional lines to links with ids. + */ + private _entriesWithId: Map = new Map(); + + /** + * A map of the link id to the link entry. The "link id" (number) which is the numberic + * representation of a unique link should not be confused with "id" (string) which comes in with + * `id=` in the OSC link's properties. + */ + private _dataByLinkId: Map = new Map(); + + constructor( + @IBufferService private readonly _bufferService: IBufferService + ) { + } + + public registerLink(data: IOscLinkData): number { + const buffer = this._bufferService.buffer; + + // Links with no id will only ever be registered a single time + if (data.id === undefined) { + const marker = buffer.addMarker(buffer.ybase + buffer.y); + const entry: IOscLinkEntryNoId = { + data, + id: this._nextId++, + lines: [marker] + }; + marker.onDispose(() => this._removeMarkerFromLink(entry, marker)); + this._dataByLinkId.set(entry.id, entry); + return entry.id; + } + + // Add the line to the link if it already exists + const castData = data as Required; + const key = this._getEntryIdKey(castData); + const match = this._entriesWithId.get(key); + if (match) { + this.addLineToLink(match.id, buffer.ybase + buffer.y); + return match.id; + } + + // Create the link + const marker = buffer.addMarker(buffer.ybase + buffer.y); + const entry: IOscLinkEntryWithId = { + id: this._nextId++, + key: this._getEntryIdKey(castData), + data: castData, + lines: [marker] + }; + marker.onDispose(() => this._removeMarkerFromLink(entry, marker)); + this._entriesWithId.set(entry.key, entry); + this._dataByLinkId.set(entry.id, entry); + return entry.id; + } + + public addLineToLink(linkId: number, y: number): void { + const entry = this._dataByLinkId.get(linkId); + if (!entry) { + return; + } + if (entry.lines.every(e => e.line !== y)) { + const marker = this._bufferService.buffer.addMarker(y); + entry.lines.push(marker); + marker.onDispose(() => this._removeMarkerFromLink(entry, marker)); + } + } + + public getLinkData(linkId: number): IOscLinkData | undefined { + return this._dataByLinkId.get(linkId)?.data; + } + + private _getEntryIdKey(linkData: Required): string { + return `${linkData.id};;${linkData.uri}`; + } + + private _removeMarkerFromLink(entry: IOscLinkEntryNoId | IOscLinkEntryWithId, marker: IMarker): void { + const index = entry.lines.indexOf(marker); + if (index === -1) { + return; + } + entry.lines.splice(index, 1); + if (entry.lines.length === 0) { + if (entry.data.id !== undefined) { + this._entriesWithId.delete((entry as IOscLinkEntryWithId).key); + } + this._dataByLinkId.delete(entry.id); + } + } +} + +interface IOscLinkEntry { + data: T; + id: number; + lines: IMarker[]; +} + +interface IOscLinkEntryNoId extends IOscLinkEntry { +} + +interface IOscLinkEntryWithId extends IOscLinkEntry> { + key: string; +} diff --git a/node_modules/@xterm/xterm/src/common/services/ServiceRegistry.ts b/node_modules/@xterm/xterm/src/common/services/ServiceRegistry.ts new file mode 100644 index 0000000..7d887bc --- /dev/null +++ b/node_modules/@xterm/xterm/src/common/services/ServiceRegistry.ts @@ -0,0 +1,49 @@ +/** + * Copyright (c) 2019 The xterm.js authors. All rights reserved. + * @license MIT + * + * This was heavily inspired from microsoft/vscode's dependency injection system (MIT). + */ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { IServiceIdentifier } from 'common/services/Services'; + +const DI_TARGET = 'di$target'; +const DI_DEPENDENCIES = 'di$dependencies'; + +export const serviceRegistry: Map> = new Map(); + +export function getServiceDependencies(ctor: any): { id: IServiceIdentifier, index: number, optional: boolean }[] { + return ctor[DI_DEPENDENCIES] || []; +} + +export function createDecorator(id: string): IServiceIdentifier { + if (serviceRegistry.has(id)) { + return serviceRegistry.get(id)!; + } + + const decorator: any = function (target: Function, key: string, index: number): any { + if (arguments.length !== 3) { + throw new Error('@IServiceName-decorator can only be used to decorate a parameter'); + } + + storeServiceDependency(decorator, target, index); + }; + + decorator._id = id; + + serviceRegistry.set(id, decorator); + return decorator; +} + +function storeServiceDependency(id: Function, target: Function, index: number): void { + if ((target as any)[DI_TARGET] === target) { + (target as any)[DI_DEPENDENCIES].push({ id, index }); + } else { + (target as any)[DI_DEPENDENCIES] = [{ id, index }]; + (target as any)[DI_TARGET] = target; + } +} diff --git a/node_modules/@xterm/xterm/src/common/services/Services.ts b/node_modules/@xterm/xterm/src/common/services/Services.ts new file mode 100644 index 0000000..a2847f1 --- /dev/null +++ b/node_modules/@xterm/xterm/src/common/services/Services.ts @@ -0,0 +1,396 @@ +/** + * Copyright (c) 2019 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { IDecoration, IDecorationOptions, ILinkHandler, ILogger, IWindowsPty, type IOverviewRulerOptions } from '@xterm/xterm'; +import { CoreMouseEncoding, CoreMouseEventType, CursorInactiveStyle, CursorStyle, IAttributeData, ICharset, IColor, ICoreMouseEvent, ICoreMouseProtocol, IDecPrivateModes, IDisposable, IModes, IOscLinkData, IWindowOptions } from 'common/Types'; +import { IBuffer, IBufferSet } from 'common/buffer/Types'; +import { createDecorator } from 'common/services/ServiceRegistry'; +import type { Emitter, Event } from 'vs/base/common/event'; + +export const IBufferService = createDecorator('BufferService'); +export interface IBufferService { + serviceBrand: undefined; + + readonly cols: number; + readonly rows: number; + readonly buffer: IBuffer; + readonly buffers: IBufferSet; + isUserScrolling: boolean; + onResize: Event; + onScroll: Event; + scroll(eraseAttr: IAttributeData, isWrapped?: boolean): void; + scrollLines(disp: number, suppressScrollEvent?: boolean): void; + resize(cols: number, rows: number): void; + reset(): void; +} + +export interface IBufferResizeEvent { + cols: number; + rows: number; + colsChanged: boolean; + rowsChanged: boolean; +} + +export const ICoreMouseService = createDecorator('CoreMouseService'); +export interface ICoreMouseService { + serviceBrand: undefined; + + activeProtocol: string; + activeEncoding: string; + areMouseEventsActive: boolean; + addProtocol(name: string, protocol: ICoreMouseProtocol): void; + addEncoding(name: string, encoding: CoreMouseEncoding): void; + reset(): void; + + /** + * Triggers a mouse event to be sent. + * + * Returns true if the event passed all protocol restrictions and a report + * was sent, otherwise false. The return value may be used to decide whether + * the default event action in the bowser component should be omitted. + * + * Note: The method will change values of the given event object + * to fullfill protocol and encoding restrictions. + */ + triggerMouseEvent(event: ICoreMouseEvent): boolean; + + /** + * Event to announce changes in mouse tracking. + */ + onProtocolChange: Event; + + /** + * Human readable version of mouse events. + */ + explainEvents(events: CoreMouseEventType): { [event: string]: boolean }; + + /** + * Process wheel event taking partial scroll into account. + */ + consumeWheelEvent(ev: WheelEvent, cellHeight?: number, dpr?: number): number; +} + +export const ICoreService = createDecorator('CoreService'); +export interface ICoreService { + serviceBrand: undefined; + + /** + * Initially the cursor will not be visible until the first time the terminal + * is focused. + */ + isCursorInitialized: boolean; + isCursorHidden: boolean; + + readonly modes: IModes; + readonly decPrivateModes: IDecPrivateModes; + + readonly onData: Event; + readonly onUserInput: Event; + readonly onBinary: Event; + readonly onRequestScrollToBottom: Event; + + reset(): void; + + /** + * Triggers the onData event in the public API. + * @param data The data that is being emitted. + * @param wasUserInput Whether the data originated from the user (as opposed to + * resulting from parsing incoming data). When true this will also: + * - Scroll to the bottom of the buffer if option scrollOnUserInput is true. + * - Fire the `onUserInput` event (so selection can be cleared). + */ + triggerDataEvent(data: string, wasUserInput?: boolean): void; + + /** + * Triggers the onBinary event in the public API. + * @param data The data that is being emitted. + */ + triggerBinaryEvent(data: string): void; +} + +export const ICharsetService = createDecorator('CharsetService'); +export interface ICharsetService { + serviceBrand: undefined; + + charset: ICharset | undefined; + readonly glevel: number; + + reset(): void; + + /** + * Set the G level of the terminal. + * @param g + */ + setgLevel(g: number): void; + + /** + * Set the charset for the given G level of the terminal. + * @param g + * @param charset + */ + setgCharset(g: number, charset: ICharset | undefined): void; +} + +export interface IServiceIdentifier { + (...args: any[]): void; + type: T; + _id: string; +} + +export interface IBrandedService { + serviceBrand: undefined; +} + +type GetLeadingNonServiceArgs = TArgs extends [] ? [] + : TArgs extends [...infer TFirst, infer TLast] ? TLast extends IBrandedService ? GetLeadingNonServiceArgs : TArgs + : never; + +export const IInstantiationService = createDecorator('InstantiationService'); +export interface IInstantiationService { + serviceBrand: undefined; + + setService(id: IServiceIdentifier, instance: T): void; + getService(id: IServiceIdentifier): T | undefined; + createInstance any, R extends InstanceType>(t: Ctor, ...args: GetLeadingNonServiceArgs>): R; +} + +export enum LogLevelEnum { + TRACE = 0, + DEBUG = 1, + INFO = 2, + WARN = 3, + ERROR = 4, + OFF = 5 +} + +export const ILogService = createDecorator('LogService'); +export interface ILogService { + serviceBrand: undefined; + + readonly logLevel: LogLevelEnum; + + trace(message: any, ...optionalParams: any[]): void; + debug(message: any, ...optionalParams: any[]): void; + info(message: any, ...optionalParams: any[]): void; + warn(message: any, ...optionalParams: any[]): void; + error(message: any, ...optionalParams: any[]): void; +} + +export const IOptionsService = createDecorator('OptionsService'); +export interface IOptionsService { + serviceBrand: undefined; + + /** + * Read only access to the raw options object, this is an internal-only fast path for accessing + * single options without any validation as we trust TypeScript to enforce correct usage + * internally. + */ + readonly rawOptions: Required; + + /** + * Options as exposed through the public API, this property uses getters and setters with + * validation which makes it safer but slower. {@link rawOptions} should be used for pretty much + * all internal usage for performance reasons. + */ + readonly options: Required; + + /** + * Adds an event listener for when any option changes. + */ + readonly onOptionChange: Event; + + /** + * Adds an event listener for when a specific option changes, this is a convenience method that is + * preferred over {@link onOptionChange} when only a single option is being listened to. + */ + // eslint-disable-next-line @typescript-eslint/naming-convention + onSpecificOptionChange(key: T, listener: (arg1: Required[T]) => any): IDisposable; + + /** + * Adds an event listener for when a set of specific options change, this is a convenience method + * that is preferred over {@link onOptionChange} when multiple options are being listened to and + * handled the same way. + */ + // eslint-disable-next-line @typescript-eslint/naming-convention + onMultipleOptionChange(keys: (keyof ITerminalOptions)[], listener: () => any): IDisposable; +} + +export type FontWeight = 'normal' | 'bold' | '100' | '200' | '300' | '400' | '500' | '600' | '700' | '800' | '900' | number; +export type LogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'off'; + +export interface ITerminalOptions { + allowProposedApi?: boolean; + allowTransparency?: boolean; + altClickMovesCursor?: boolean; + cols?: number; + convertEol?: boolean; + cursorBlink?: boolean; + cursorStyle?: CursorStyle; + cursorWidth?: number; + cursorInactiveStyle?: CursorInactiveStyle; + customGlyphs?: boolean; + disableStdin?: boolean; + documentOverride?: any | null; + drawBoldTextInBrightColors?: boolean; + /** @deprecated No longer supported */ + fastScrollModifier?: 'none' | 'alt' | 'ctrl' | 'shift'; + fastScrollSensitivity?: number; + fontSize?: number; + fontFamily?: string; + fontWeight?: FontWeight; + fontWeightBold?: FontWeight; + ignoreBracketedPasteMode?: boolean; + letterSpacing?: number; + lineHeight?: number; + linkHandler?: ILinkHandler | null; + logLevel?: LogLevel; + logger?: ILogger | null; + macOptionIsMeta?: boolean; + macOptionClickForcesSelection?: boolean; + minimumContrastRatio?: number; + reflowCursorLine?: boolean; + rescaleOverlappingGlyphs?: boolean; + rightClickSelectsWord?: boolean; + rows?: number; + screenReaderMode?: boolean; + scrollback?: number; + scrollOnUserInput?: boolean; + scrollSensitivity?: number; + smoothScrollDuration?: number; + tabStopWidth?: number; + theme?: ITheme; + windowsMode?: boolean; + windowsPty?: IWindowsPty; + windowOptions?: IWindowOptions; + wordSeparator?: string; + overviewRuler?: IOverviewRulerOptions; + scrollOnEraseInDisplay?: boolean; + + [key: string]: any; + cancelEvents: boolean; + termName: string; +} + +export interface ITheme { + foreground?: string; + background?: string; + cursor?: string; + cursorAccent?: string; + selectionForeground?: string; + selectionBackground?: string; + selectionInactiveBackground?: string; + scrollbarSliderBackground?: string; + scrollbarSliderHoverBackground?: string; + scrollbarSliderActiveBackground?: string; + overviewRulerBorder?: string; + black?: string; + red?: string; + green?: string; + yellow?: string; + blue?: string; + magenta?: string; + cyan?: string; + white?: string; + brightBlack?: string; + brightRed?: string; + brightGreen?: string; + brightYellow?: string; + brightBlue?: string; + brightMagenta?: string; + brightCyan?: string; + brightWhite?: string; + extendedAnsi?: string[]; +} + +export const IOscLinkService = createDecorator('OscLinkService'); +export interface IOscLinkService { + serviceBrand: undefined; + /** + * Registers a link to the service, returning the link ID. The link data is managed by this + * service and will be freed when this current cursor position is trimmed off the buffer. + */ + registerLink(linkData: IOscLinkData): number; + /** + * Adds a line to a link if needed. + */ + addLineToLink(linkId: number, y: number): void; + /** Get the link data associated with a link ID. */ + getLinkData(linkId: number): IOscLinkData | undefined; +} + +/* + * Width and Grapheme_Cluster_Break properties of a character as a bit mask. + * + * bit 0: shouldJoin - should combine with preceding character. + * bit 1..2: wcwidth - see UnicodeCharWidth. + * bit 3..31: class of character (currently only 4 bits are used). + * This is used to determined grapheme clustering - i.e. which codepoints + * are to be combined into a single compound character. + * + * Use the UnicodeService static function createPropertyValue to create a + * UnicodeCharProperties; use extractShouldJoin, extractWidth, and + * extractCharKind to extract the components. + */ +export type UnicodeCharProperties = number; + +/** + * Width in columns of a character. + * In a CJK context, "half-width" characters (such as Latin) are width 1, + * while "full-width" characters (such as Kanji) are 2 columns wide. + * Combining characters (such as accents) are width 0. + */ +export type UnicodeCharWidth = 0 | 1 | 2; + +export const IUnicodeService = createDecorator('UnicodeService'); +export interface IUnicodeService { + serviceBrand: undefined; + /** Register an Unicode version provider. */ + register(provider: IUnicodeVersionProvider): void; + /** Registered Unicode versions. */ + readonly versions: string[]; + /** Currently active version. */ + activeVersion: string; + /** Event triggered, when activate version changed. */ + readonly onChange: Event; + + /** + * Unicode version dependent + */ + wcwidth(codepoint: number): UnicodeCharWidth; + getStringCellWidth(s: string): number; + /** + * Return character width and type for grapheme clustering. + * If preceding != 0, it is the return code from the previous character; + * in that case the result specifies if the characters should be joined. + */ + charProperties(codepoint: number, preceding: UnicodeCharProperties): UnicodeCharProperties; +} + +export interface IUnicodeVersionProvider { + readonly version: string; + wcwidth(ucs: number): UnicodeCharWidth; + charProperties(codepoint: number, preceding: UnicodeCharProperties): UnicodeCharProperties; +} + +export const IDecorationService = createDecorator('DecorationService'); +export interface IDecorationService extends IDisposable { + serviceBrand: undefined; + readonly decorations: IterableIterator; + readonly onDecorationRegistered: Event; + readonly onDecorationRemoved: Event; + registerDecoration(decorationOptions: IDecorationOptions): IDecoration | undefined; + reset(): void; + /** + * Trigger a callback over the decoration at a cell (in no particular order). This uses a callback + * instead of an iterator as it's typically used in hot code paths. + */ + forEachDecorationAtCell(x: number, line: number, layer: 'bottom' | 'top' | undefined, callback: (decoration: IInternalDecoration) => void): void; +} +export interface IInternalDecoration extends IDecoration { + readonly options: IDecorationOptions; + readonly backgroundColorRGB: IColor | undefined; + readonly foregroundColorRGB: IColor | undefined; + readonly onRenderEmitter: Emitter; +} diff --git a/node_modules/@xterm/xterm/src/common/services/UnicodeService.ts b/node_modules/@xterm/xterm/src/common/services/UnicodeService.ts new file mode 100644 index 0000000..12e4ec4 --- /dev/null +++ b/node_modules/@xterm/xterm/src/common/services/UnicodeService.ts @@ -0,0 +1,111 @@ +/** + * Copyright (c) 2019 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { UnicodeV6 } from 'common/input/UnicodeV6'; +import { IUnicodeService, IUnicodeVersionProvider, UnicodeCharProperties, UnicodeCharWidth } from 'common/services/Services'; +import { Emitter } from 'vs/base/common/event'; + +export class UnicodeService implements IUnicodeService { + public serviceBrand: any; + + private _providers: {[key: string]: IUnicodeVersionProvider} = Object.create(null); + private _active: string = ''; + private _activeProvider: IUnicodeVersionProvider; + + private readonly _onChange = new Emitter(); + public readonly onChange = this._onChange.event; + + public static extractShouldJoin(value: UnicodeCharProperties): boolean { + return (value & 1) !== 0; + } + public static extractWidth(value: UnicodeCharProperties): UnicodeCharWidth { + return ((value >> 1) & 0x3) as UnicodeCharWidth; + } + public static extractCharKind(value: UnicodeCharProperties): number { + return value >> 3; + } + public static createPropertyValue(state: number, width: number, shouldJoin: boolean = false): UnicodeCharProperties { + return ((state & 0xffffff) << 3) | ((width & 3) << 1) | (shouldJoin?1:0); + } + + constructor() { + const defaultProvider = new UnicodeV6(); + this.register(defaultProvider); + this._active = defaultProvider.version; + this._activeProvider = defaultProvider; + } + + public dispose(): void { + this._onChange.dispose(); + } + + public get versions(): string[] { + return Object.keys(this._providers); + } + + public get activeVersion(): string { + return this._active; + } + + public set activeVersion(version: string) { + if (!this._providers[version]) { + throw new Error(`unknown Unicode version "${version}"`); + } + this._active = version; + this._activeProvider = this._providers[version]; + this._onChange.fire(version); + } + + public register(provider: IUnicodeVersionProvider): void { + this._providers[provider.version] = provider; + } + + /** + * Unicode version dependent interface. + */ + public wcwidth(num: number): UnicodeCharWidth { + return this._activeProvider.wcwidth(num); + } + + public getStringCellWidth(s: string): number { + let result = 0; + let precedingInfo = 0; + const length = s.length; + for (let i = 0; i < length; ++i) { + let code = s.charCodeAt(i); + // surrogate pair first + if (0xD800 <= code && code <= 0xDBFF) { + if (++i >= length) { + // this should not happen with strings retrieved from + // Buffer.translateToString as it converts from UTF-32 + // and therefore always should contain the second part + // for any other string we still have to handle it somehow: + // simply treat the lonely surrogate first as a single char (UCS-2 behavior) + return result + this.wcwidth(code); + } + const second = s.charCodeAt(i); + // convert surrogate pair to high codepoint only for valid second part (UTF-16) + // otherwise treat them independently (UCS-2 behavior) + if (0xDC00 <= second && second <= 0xDFFF) { + code = (code - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; + } else { + result += this.wcwidth(second); + } + } + const currentInfo = this.charProperties(code, precedingInfo); + let chWidth = UnicodeService.extractWidth(currentInfo); + if (UnicodeService.extractShouldJoin(currentInfo)) { + chWidth -= UnicodeService.extractWidth(precedingInfo); + } + result += chWidth; + precedingInfo = currentInfo; + } + return result; + } + + public charProperties(codepoint: number, preceding: UnicodeCharProperties): UnicodeCharProperties { + return this._activeProvider.charProperties(codepoint, preceding); + } +} diff --git a/node_modules/@xterm/xterm/src/vs/base/browser/browser.ts b/node_modules/@xterm/xterm/src/vs/base/browser/browser.ts new file mode 100644 index 0000000..a34f479 --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/browser/browser.ts @@ -0,0 +1,141 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { CodeWindow, mainWindow } from 'vs/base/browser/window'; +import { Emitter } from 'vs/base/common/event'; + +class WindowManager { + + static readonly INSTANCE = new WindowManager(); + + // --- Zoom Level + + private readonly mapWindowIdToZoomLevel = new Map(); + + private readonly _onDidChangeZoomLevel = new Emitter(); + readonly onDidChangeZoomLevel = this._onDidChangeZoomLevel.event; + + getZoomLevel(targetWindow: Window): number { + return this.mapWindowIdToZoomLevel.get(this.getWindowId(targetWindow)) ?? 0; + } + setZoomLevel(zoomLevel: number, targetWindow: Window): void { + if (this.getZoomLevel(targetWindow) === zoomLevel) { + return; + } + + const targetWindowId = this.getWindowId(targetWindow); + this.mapWindowIdToZoomLevel.set(targetWindowId, zoomLevel); + this._onDidChangeZoomLevel.fire(targetWindowId); + } + + // --- Zoom Factor + + private readonly mapWindowIdToZoomFactor = new Map(); + + getZoomFactor(targetWindow: Window): number { + return this.mapWindowIdToZoomFactor.get(this.getWindowId(targetWindow)) ?? 1; + } + setZoomFactor(zoomFactor: number, targetWindow: Window): void { + this.mapWindowIdToZoomFactor.set(this.getWindowId(targetWindow), zoomFactor); + } + + // --- Fullscreen + + private readonly _onDidChangeFullscreen = new Emitter(); + readonly onDidChangeFullscreen = this._onDidChangeFullscreen.event; + + private readonly mapWindowIdToFullScreen = new Map(); + + setFullscreen(fullscreen: boolean, targetWindow: Window): void { + if (this.isFullscreen(targetWindow) === fullscreen) { + return; + } + + const windowId = this.getWindowId(targetWindow); + this.mapWindowIdToFullScreen.set(windowId, fullscreen); + this._onDidChangeFullscreen.fire(windowId); + } + isFullscreen(targetWindow: Window): boolean { + return !!this.mapWindowIdToFullScreen.get(this.getWindowId(targetWindow)); + } + + private getWindowId(targetWindow: Window): number { + return (targetWindow as CodeWindow).vscodeWindowId; + } +} + +export function addMatchMediaChangeListener(targetWindow: Window, query: string | MediaQueryList, callback: (this: MediaQueryList, ev: MediaQueryListEvent) => any): void { + if (typeof query === 'string') { + query = targetWindow.matchMedia(query); + } + query.addEventListener('change', callback); +} + +/** A zoom index, e.g. 1, 2, 3 */ +export function setZoomLevel(zoomLevel: number, targetWindow: Window): void { + WindowManager.INSTANCE.setZoomLevel(zoomLevel, targetWindow); +} +export function getZoomLevel(targetWindow: Window): number { + return WindowManager.INSTANCE.getZoomLevel(targetWindow); +} +export const onDidChangeZoomLevel = WindowManager.INSTANCE.onDidChangeZoomLevel; + +/** The zoom scale for an index, e.g. 1, 1.2, 1.4 */ +export function getZoomFactor(targetWindow: Window): number { + return WindowManager.INSTANCE.getZoomFactor(targetWindow); +} +export function setZoomFactor(zoomFactor: number, targetWindow: Window): void { + WindowManager.INSTANCE.setZoomFactor(zoomFactor, targetWindow); +} + +export function setFullscreen(fullscreen: boolean, targetWindow: Window): void { + WindowManager.INSTANCE.setFullscreen(fullscreen, targetWindow); +} +export function isFullscreen(targetWindow: Window): boolean { + return WindowManager.INSTANCE.isFullscreen(targetWindow); +} +export const onDidChangeFullscreen = WindowManager.INSTANCE.onDidChangeFullscreen; + +const userAgent = typeof navigator === 'object' ? navigator.userAgent : ''; + +export const isFirefox = (userAgent.indexOf('Firefox') >= 0); +export const isWebKit = (userAgent.indexOf('AppleWebKit') >= 0); +export const isChrome = (userAgent.indexOf('Chrome') >= 0); +export const isSafari = (!isChrome && (userAgent.indexOf('Safari') >= 0)); +export const isWebkitWebView = (!isChrome && !isSafari && isWebKit); +export const isElectron = (userAgent.indexOf('Electron/') >= 0); +export const isAndroid = (userAgent.indexOf('Android') >= 0); + +let standalone = false; +if (typeof mainWindow.matchMedia === 'function') { + const standaloneMatchMedia = mainWindow.matchMedia('(display-mode: standalone) or (display-mode: window-controls-overlay)'); + const fullScreenMatchMedia = mainWindow.matchMedia('(display-mode: fullscreen)'); + standalone = standaloneMatchMedia.matches; + addMatchMediaChangeListener(mainWindow, standaloneMatchMedia, ({ matches }) => { + // entering fullscreen would change standaloneMatchMedia.matches to false + // if standalone is true (running as PWA) and entering fullscreen, skip this change + if (standalone && fullScreenMatchMedia.matches) { + return; + } + // otherwise update standalone (browser to PWA or PWA to browser) + standalone = matches; + }); +} +export function isStandalone(): boolean { + return standalone; +} + +// Visible means that the feature is enabled, not necessarily being rendered +// e.g. visible is true even in fullscreen mode where the controls are hidden +// See docs at https://developer.mozilla.org/en-US/docs/Web/API/WindowControlsOverlay/visible +export function isWCOEnabled(): boolean { + return (navigator as any)?.windowControlsOverlay?.visible; +} + +// Returns the bounding rect of the titlebar area if it is supported and defined +// See docs at https://developer.mozilla.org/en-US/docs/Web/API/WindowControlsOverlay/getTitlebarAreaRect +export function getWCOBoundingRect(): DOMRect | undefined { + return (navigator as any)?.windowControlsOverlay?.getTitlebarAreaRect(); +} diff --git a/node_modules/@xterm/xterm/src/vs/base/browser/canIUse.ts b/node_modules/@xterm/xterm/src/vs/base/browser/canIUse.ts new file mode 100644 index 0000000..b5b648f --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/browser/canIUse.ts @@ -0,0 +1,49 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import * as browser from 'vs/base/browser/browser'; +import { mainWindow } from 'vs/base/browser/window'; +import * as platform from 'vs/base/common/platform'; + +export const enum KeyboardSupport { + Always, + FullScreen, + None +} + +const safeNavigator = typeof navigator === 'object' ? navigator : {} as { [key: string]: any }; + +/** + * Browser feature we can support in current platform, browser and environment. + */ +export const BrowserFeatures = { + clipboard: { + writeText: ( + platform.isNative + || (document.queryCommandSupported && document.queryCommandSupported('copy')) + || !!(safeNavigator && safeNavigator.clipboard && safeNavigator.clipboard.writeText) + ), + readText: ( + platform.isNative + || !!(safeNavigator && safeNavigator.clipboard && safeNavigator.clipboard.readText) + ) + }, + keyboard: (() => { + if (platform.isNative || browser.isStandalone()) { + return KeyboardSupport.Always; + } + + if ((safeNavigator).keyboard || browser.isSafari) { + return KeyboardSupport.FullScreen; + } + + return KeyboardSupport.None; + })(), + + // 'ontouchstart' in window always evaluates to true with typescript's modern typings. This causes `window` to be + // `never` later in `window.navigator`. That's why we need the explicit `window as Window` cast + touch: 'ontouchstart' in mainWindow || safeNavigator.maxTouchPoints > 0, + pointerEvents: mainWindow.PointerEvent && ('ontouchstart' in mainWindow || navigator.maxTouchPoints > 0) +}; diff --git a/node_modules/@xterm/xterm/src/vs/base/browser/dom.ts b/node_modules/@xterm/xterm/src/vs/base/browser/dom.ts new file mode 100644 index 0000000..eb6d73c --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/browser/dom.ts @@ -0,0 +1,2369 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import * as browser from 'vs/base/browser/browser'; +import { BrowserFeatures } from 'vs/base/browser/canIUse'; +import { IKeyboardEvent, StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; +import { IMouseEvent, StandardMouseEvent } from 'vs/base/browser/mouseEvent'; +import { AbstractIdleValue, IntervalTimer, TimeoutTimer, _runWhenIdle, IdleDeadline } from 'vs/base/common/async'; +import { onUnexpectedError } from 'vs/base/common/errors'; +import * as event from 'vs/base/common/event'; +import { KeyCode } from 'vs/base/common/keyCodes'; +import { Disposable, DisposableStore, IDisposable, toDisposable } from 'vs/base/common/lifecycle'; +import * as platform from 'vs/base/common/platform'; +import { hash } from 'vs/base/common/hash'; +import { CodeWindow, ensureCodeWindow, mainWindow } from 'vs/base/browser/window'; +import { isPointWithinTriangle } from 'vs/base/common/numbers'; + +export interface IRegisteredCodeWindow { + readonly window: CodeWindow; + readonly disposables: DisposableStore; +} + +//# region Multi-Window Support Utilities + +export const { + registerWindow, + getWindow, + getDocument, + getWindows, + getWindowsCount, + getWindowId, + getWindowById, + hasWindow, + onDidRegisterWindow, + onWillUnregisterWindow, + onDidUnregisterWindow +} = (function () { + const windows = new Map(); + + ensureCodeWindow(mainWindow, 1); + const mainWindowRegistration = { window: mainWindow, disposables: new DisposableStore() }; + windows.set(mainWindow.vscodeWindowId, mainWindowRegistration); + + const onDidRegisterWindow = new event.Emitter(); + const onDidUnregisterWindow = new event.Emitter(); + const onWillUnregisterWindow = new event.Emitter(); + + function getWindowById(windowId: number): IRegisteredCodeWindow | undefined; + function getWindowById(windowId: number | undefined, fallbackToMain: true): IRegisteredCodeWindow; + function getWindowById(windowId: number | undefined, fallbackToMain?: boolean): IRegisteredCodeWindow | undefined { + const window = typeof windowId === 'number' ? windows.get(windowId) : undefined; + + return window ?? (fallbackToMain ? mainWindowRegistration : undefined); + } + + return { + onDidRegisterWindow: onDidRegisterWindow.event, + onWillUnregisterWindow: onWillUnregisterWindow.event, + onDidUnregisterWindow: onDidUnregisterWindow.event, + registerWindow(window: CodeWindow): IDisposable { + if (windows.has(window.vscodeWindowId)) { + return Disposable.None; + } + + const disposables = new DisposableStore(); + + const registeredWindow = { + window, + disposables: disposables.add(new DisposableStore()) + }; + windows.set(window.vscodeWindowId, registeredWindow); + + disposables.add(toDisposable(() => { + windows.delete(window.vscodeWindowId); + onDidUnregisterWindow.fire(window); + })); + + disposables.add(addDisposableListener(window, EventType.BEFORE_UNLOAD, () => { + onWillUnregisterWindow.fire(window); + })); + + onDidRegisterWindow.fire(registeredWindow); + + return disposables; + }, + getWindows(): Iterable { + return windows.values(); + }, + getWindowsCount(): number { + return windows.size; + }, + getWindowId(targetWindow: Window): number { + return (targetWindow as CodeWindow).vscodeWindowId; + }, + hasWindow(windowId: number): boolean { + return windows.has(windowId); + }, + getWindowById, + getWindow(e: Node | UIEvent | undefined | null): CodeWindow { + const candidateNode = e as Node | undefined | null; + if (candidateNode?.ownerDocument?.defaultView) { + return candidateNode.ownerDocument.defaultView.window as CodeWindow; + } + + const candidateEvent = e as UIEvent | undefined | null; + if (candidateEvent?.view) { + return candidateEvent.view.window as CodeWindow; + } + + return mainWindow; + }, + getDocument(e: Node | UIEvent | undefined | null): Document { + const candidateNode = e as Node | undefined | null; + return getWindow(candidateNode).document; + } + }; +})(); + +//#endregion + +export function clearNode(node: HTMLElement): void { + while (node.firstChild) { + node.firstChild.remove(); + } +} + + +export function clearNodeRecursively(domNode: ChildNode) { + while (domNode.firstChild) { + const element = domNode.firstChild; + element.remove(); + clearNodeRecursively(element); + } +} + + +class DomListener implements IDisposable { + + private _handler: (e: any) => void; + private _node: EventTarget; + private readonly _type: string; + private readonly _options: boolean | AddEventListenerOptions; + + constructor(node: EventTarget, type: string, handler: (e: any) => void, options?: boolean | AddEventListenerOptions) { + this._node = node; + this._type = type; + this._handler = handler; + this._options = (options || false); + this._node.addEventListener(this._type, this._handler, this._options); + } + + dispose(): void { + if (!this._handler) { + // Already disposed + return; + } + + this._node.removeEventListener(this._type, this._handler, this._options); + + // Prevent leakers from holding on to the dom or handler func + this._node = null!; + this._handler = null!; + } +} + +export function addDisposableListener(node: EventTarget, type: K, handler: (event: GlobalEventHandlersEventMap[K]) => void, useCapture?: boolean): IDisposable; +export function addDisposableListener(node: EventTarget, type: string, handler: (event: any) => void, useCapture?: boolean): IDisposable; +export function addDisposableListener(node: EventTarget, type: string, handler: (event: any) => void, options: AddEventListenerOptions): IDisposable; +export function addDisposableListener(node: EventTarget, type: string, handler: (event: any) => void, useCaptureOrOptions?: boolean | AddEventListenerOptions): IDisposable { + return new DomListener(node, type, handler, useCaptureOrOptions); +} + +export interface IAddStandardDisposableListenerSignature { + (node: HTMLElement, type: 'click', handler: (event: IMouseEvent) => void, useCapture?: boolean): IDisposable; + (node: HTMLElement, type: 'mousedown', handler: (event: IMouseEvent) => void, useCapture?: boolean): IDisposable; + (node: HTMLElement, type: 'keydown', handler: (event: IKeyboardEvent) => void, useCapture?: boolean): IDisposable; + (node: HTMLElement, type: 'keypress', handler: (event: IKeyboardEvent) => void, useCapture?: boolean): IDisposable; + (node: HTMLElement, type: 'keyup', handler: (event: IKeyboardEvent) => void, useCapture?: boolean): IDisposable; + (node: HTMLElement, type: 'pointerdown', handler: (event: PointerEvent) => void, useCapture?: boolean): IDisposable; + (node: HTMLElement, type: 'pointermove', handler: (event: PointerEvent) => void, useCapture?: boolean): IDisposable; + (node: HTMLElement, type: 'pointerup', handler: (event: PointerEvent) => void, useCapture?: boolean): IDisposable; + (node: HTMLElement, type: string, handler: (event: any) => void, useCapture?: boolean): IDisposable; +} +function _wrapAsStandardMouseEvent(targetWindow: Window, handler: (e: IMouseEvent) => void): (e: MouseEvent) => void { + return function (e: MouseEvent) { + return handler(new StandardMouseEvent(targetWindow, e)); + }; +} +function _wrapAsStandardKeyboardEvent(handler: (e: IKeyboardEvent) => void): (e: KeyboardEvent) => void { + return function (e: KeyboardEvent) { + return handler(new StandardKeyboardEvent(e)); + }; +} +export const addStandardDisposableListener: IAddStandardDisposableListenerSignature = function addStandardDisposableListener(node: HTMLElement, type: string, handler: (event: any) => void, useCapture?: boolean): IDisposable { + let wrapHandler = handler; + + if (type === 'click' || type === 'mousedown' || type === 'contextmenu') { + wrapHandler = _wrapAsStandardMouseEvent(getWindow(node), handler); + } else if (type === 'keydown' || type === 'keypress' || type === 'keyup') { + wrapHandler = _wrapAsStandardKeyboardEvent(handler); + } + + return addDisposableListener(node, type, wrapHandler, useCapture); +}; + +export const addStandardDisposableGenericMouseDownListener = function addStandardDisposableListener(node: HTMLElement, handler: (event: any) => void, useCapture?: boolean): IDisposable { + const wrapHandler = _wrapAsStandardMouseEvent(getWindow(node), handler); + + return addDisposableGenericMouseDownListener(node, wrapHandler, useCapture); +}; + +export const addStandardDisposableGenericMouseUpListener = function addStandardDisposableListener(node: HTMLElement, handler: (event: any) => void, useCapture?: boolean): IDisposable { + const wrapHandler = _wrapAsStandardMouseEvent(getWindow(node), handler); + + return addDisposableGenericMouseUpListener(node, wrapHandler, useCapture); +}; +export function addDisposableGenericMouseDownListener(node: EventTarget, handler: (event: any) => void, useCapture?: boolean): IDisposable { + return addDisposableListener(node, platform.isIOS && BrowserFeatures.pointerEvents ? EventType.POINTER_DOWN : EventType.MOUSE_DOWN, handler, useCapture); +} + +export function addDisposableGenericMouseMoveListener(node: EventTarget, handler: (event: any) => void, useCapture?: boolean): IDisposable { + return addDisposableListener(node, platform.isIOS && BrowserFeatures.pointerEvents ? EventType.POINTER_MOVE : EventType.MOUSE_MOVE, handler, useCapture); +} + +export function addDisposableGenericMouseUpListener(node: EventTarget, handler: (event: any) => void, useCapture?: boolean): IDisposable { + return addDisposableListener(node, platform.isIOS && BrowserFeatures.pointerEvents ? EventType.POINTER_UP : EventType.MOUSE_UP, handler, useCapture); +} + +/** + * Execute the callback the next time the browser is idle, returning an + * {@link IDisposable} that will cancel the callback when disposed. This wraps + * [requestIdleCallback] so it will fallback to [setTimeout] if the environment + * doesn't support it. + * + * @param targetWindow The window for which to run the idle callback + * @param callback The callback to run when idle, this includes an + * [IdleDeadline] that provides the time alloted for the idle callback by the + * browser. Not respecting this deadline will result in a degraded user + * experience. + * @param timeout A timeout at which point to queue no longer wait for an idle + * callback but queue it on the regular event loop (like setTimeout). Typically + * this should not be used. + * + * [IdleDeadline]: https://developer.mozilla.org/en-US/docs/Web/API/IdleDeadline + * [requestIdleCallback]: https://developer.mozilla.org/en-US/docs/Web/API/Window/requestIdleCallback + * [setTimeout]: https://developer.mozilla.org/en-US/docs/Web/API/Window/setTimeout + */ +export function runWhenWindowIdle(targetWindow: Window | typeof globalThis, callback: (idle: IdleDeadline) => void, timeout?: number): IDisposable { + return _runWhenIdle(targetWindow, callback, timeout); +} + +/** + * An implementation of the "idle-until-urgent"-strategy as introduced + * here: https://philipwalton.com/articles/idle-until-urgent/ + */ +export class WindowIdleValue extends AbstractIdleValue { + constructor(targetWindow: Window | typeof globalThis, executor: () => T) { + super(targetWindow, executor); + } +} + +/** + * Schedule a callback to be run at the next animation frame. + * This allows multiple parties to register callbacks that should run at the next animation frame. + * If currently in an animation frame, `runner` will be executed immediately. + * @return token that can be used to cancel the scheduled runner (only if `runner` was not executed immediately). + */ +export let runAtThisOrScheduleAtNextAnimationFrame: (targetWindow: Window, runner: () => void, priority?: number) => IDisposable; +/** + * Schedule a callback to be run at the next animation frame. + * This allows multiple parties to register callbacks that should run at the next animation frame. + * If currently in an animation frame, `runner` will be executed at the next animation frame. + * @return token that can be used to cancel the scheduled runner. + */ +export let scheduleAtNextAnimationFrame: (targetWindow: Window, runner: () => void, priority?: number) => IDisposable; + +export function disposableWindowInterval(targetWindow: Window, handler: () => void | boolean /* stop interval */ | Promise, interval: number, iterations?: number): IDisposable { + let iteration = 0; + const timer = targetWindow.setInterval(() => { + iteration++; + if ((typeof iterations === 'number' && iteration >= iterations) || handler() === true) { + disposable.dispose(); + } + }, interval); + const disposable = toDisposable(() => { + targetWindow.clearInterval(timer); + }); + return disposable; +} + +export class WindowIntervalTimer extends IntervalTimer { + + private readonly defaultTarget?: Window & typeof globalThis; + + /** + * + * @param node The optional node from which the target window is determined + */ + constructor(node?: Node) { + super(); + this.defaultTarget = node && getWindow(node); + } + + override cancelAndSet(runner: () => void, interval: number, targetWindow?: Window & typeof globalThis): void { + return super.cancelAndSet(runner, interval, targetWindow ?? this.defaultTarget); + } +} + +class AnimationFrameQueueItem implements IDisposable { + + private _runner: () => void; + public priority: number; + private _canceled: boolean; + + constructor(runner: () => void, priority: number = 0) { + this._runner = runner; + this.priority = priority; + this._canceled = false; + } + + dispose(): void { + this._canceled = true; + } + + execute(): void { + if (this._canceled) { + return; + } + + try { + this._runner(); + } catch (e) { + onUnexpectedError(e); + } + } + + // Sort by priority (largest to lowest) + static sort(a: AnimationFrameQueueItem, b: AnimationFrameQueueItem): number { + return b.priority - a.priority; + } +} + +(function () { + /** + * The runners scheduled at the next animation frame + */ + const NEXT_QUEUE = new Map(); + /** + * The runners scheduled at the current animation frame + */ + const CURRENT_QUEUE = new Map(); + /** + * A flag to keep track if the native requestAnimationFrame was already called + */ + const animFrameRequested = new Map(); + /** + * A flag to indicate if currently handling a native requestAnimationFrame callback + */ + const inAnimationFrameRunner = new Map(); + + const animationFrameRunner = (targetWindowId: number) => { + animFrameRequested.set(targetWindowId, false); + + const currentQueue = NEXT_QUEUE.get(targetWindowId) ?? []; + CURRENT_QUEUE.set(targetWindowId, currentQueue); + NEXT_QUEUE.set(targetWindowId, []); + + inAnimationFrameRunner.set(targetWindowId, true); + while (currentQueue.length > 0) { + currentQueue.sort(AnimationFrameQueueItem.sort); + const top = currentQueue.shift()!; + top.execute(); + } + inAnimationFrameRunner.set(targetWindowId, false); + }; + + scheduleAtNextAnimationFrame = (targetWindow: Window, runner: () => void, priority: number = 0) => { + const targetWindowId = getWindowId(targetWindow); + const item = new AnimationFrameQueueItem(runner, priority); + + let nextQueue = NEXT_QUEUE.get(targetWindowId); + if (!nextQueue) { + nextQueue = []; + NEXT_QUEUE.set(targetWindowId, nextQueue); + } + nextQueue.push(item); + + if (!animFrameRequested.get(targetWindowId)) { + animFrameRequested.set(targetWindowId, true); + targetWindow.requestAnimationFrame(() => animationFrameRunner(targetWindowId)); + } + + return item; + }; + + runAtThisOrScheduleAtNextAnimationFrame = (targetWindow: Window, runner: () => void, priority?: number) => { + const targetWindowId = getWindowId(targetWindow); + if (inAnimationFrameRunner.get(targetWindowId)) { + const item = new AnimationFrameQueueItem(runner, priority); + let currentQueue = CURRENT_QUEUE.get(targetWindowId); + if (!currentQueue) { + currentQueue = []; + CURRENT_QUEUE.set(targetWindowId, currentQueue); + } + currentQueue.push(item); + return item; + } else { + return scheduleAtNextAnimationFrame(targetWindow, runner, priority); + } + }; +})(); + +export function measure(targetWindow: Window, callback: () => void): IDisposable { + return scheduleAtNextAnimationFrame(targetWindow, callback, 10000 /* must be early */); +} + +export function modify(targetWindow: Window, callback: () => void): IDisposable { + return scheduleAtNextAnimationFrame(targetWindow, callback, -10000 /* must be late */); +} + +/** + * Add a throttled listener. `handler` is fired at most every 8.33333ms or with the next animation frame (if browser supports it). + */ +export interface IEventMerger { + (lastEvent: R | null, currentEvent: E): R; +} + +const MINIMUM_TIME_MS = 8; +const DEFAULT_EVENT_MERGER: IEventMerger = function (lastEvent: Event | null, currentEvent: Event) { + return currentEvent; +}; + +class TimeoutThrottledDomListener extends Disposable { + + constructor(node: any, type: string, handler: (event: R) => void, eventMerger: IEventMerger = DEFAULT_EVENT_MERGER, minimumTimeMs: number = MINIMUM_TIME_MS) { + super(); + + let lastEvent: R | null = null; + let lastHandlerTime = 0; + const timeout = this._register(new TimeoutTimer()); + + const invokeHandler = () => { + lastHandlerTime = (new Date()).getTime(); + handler(lastEvent); + lastEvent = null; + }; + + this._register(addDisposableListener(node, type, (e) => { + + lastEvent = eventMerger(lastEvent, e); + const elapsedTime = (new Date()).getTime() - lastHandlerTime; + + if (elapsedTime >= minimumTimeMs) { + timeout.cancel(); + invokeHandler(); + } else { + timeout.setIfNotSet(invokeHandler, minimumTimeMs - elapsedTime); + } + })); + } +} + +export function addDisposableThrottledListener(node: any, type: string, handler: (event: R) => void, eventMerger?: IEventMerger, minimumTimeMs?: number): IDisposable { + return new TimeoutThrottledDomListener(node, type, handler, eventMerger, minimumTimeMs); +} + +export function getComputedStyle(el: HTMLElement): CSSStyleDeclaration { + return getWindow(el).getComputedStyle(el, null); +} + +export function getClientArea(element: HTMLElement, fallback?: HTMLElement): Dimension { + const elWindow = getWindow(element); + const elDocument = elWindow.document; + + // Try with DOM clientWidth / clientHeight + if (element !== elDocument.body) { + return new Dimension(element.clientWidth, element.clientHeight); + } + + // If visual view port exits and it's on mobile, it should be used instead of window innerWidth / innerHeight, or document.body.clientWidth / document.body.clientHeight + if (platform.isIOS && elWindow?.visualViewport) { + return new Dimension(elWindow.visualViewport.width, elWindow.visualViewport.height); + } + + // Try innerWidth / innerHeight + if (elWindow?.innerWidth && elWindow.innerHeight) { + return new Dimension(elWindow.innerWidth, elWindow.innerHeight); + } + + // Try with document.body.clientWidth / document.body.clientHeight + if (elDocument.body && elDocument.body.clientWidth && elDocument.body.clientHeight) { + return new Dimension(elDocument.body.clientWidth, elDocument.body.clientHeight); + } + + // Try with document.documentElement.clientWidth / document.documentElement.clientHeight + if (elDocument.documentElement && elDocument.documentElement.clientWidth && elDocument.documentElement.clientHeight) { + return new Dimension(elDocument.documentElement.clientWidth, elDocument.documentElement.clientHeight); + } + + if (fallback) { + return getClientArea(fallback); + } + + throw new Error('Unable to figure out browser width and height'); +} + +class SizeUtils { + // Adapted from WinJS + // Converts a CSS positioning string for the specified element to pixels. + private static convertToPixels(element: HTMLElement, value: string): number { + return parseFloat(value) || 0; + } + + private static getDimension(element: HTMLElement, cssPropertyName: string, jsPropertyName: string): number { + const computedStyle = getComputedStyle(element); + const value = computedStyle ? computedStyle.getPropertyValue(cssPropertyName) : '0'; + return SizeUtils.convertToPixels(element, value); + } + + static getBorderLeftWidth(element: HTMLElement): number { + return SizeUtils.getDimension(element, 'border-left-width', 'borderLeftWidth'); + } + static getBorderRightWidth(element: HTMLElement): number { + return SizeUtils.getDimension(element, 'border-right-width', 'borderRightWidth'); + } + static getBorderTopWidth(element: HTMLElement): number { + return SizeUtils.getDimension(element, 'border-top-width', 'borderTopWidth'); + } + static getBorderBottomWidth(element: HTMLElement): number { + return SizeUtils.getDimension(element, 'border-bottom-width', 'borderBottomWidth'); + } + + static getPaddingLeft(element: HTMLElement): number { + return SizeUtils.getDimension(element, 'padding-left', 'paddingLeft'); + } + static getPaddingRight(element: HTMLElement): number { + return SizeUtils.getDimension(element, 'padding-right', 'paddingRight'); + } + static getPaddingTop(element: HTMLElement): number { + return SizeUtils.getDimension(element, 'padding-top', 'paddingTop'); + } + static getPaddingBottom(element: HTMLElement): number { + return SizeUtils.getDimension(element, 'padding-bottom', 'paddingBottom'); + } + + static getMarginLeft(element: HTMLElement): number { + return SizeUtils.getDimension(element, 'margin-left', 'marginLeft'); + } + static getMarginTop(element: HTMLElement): number { + return SizeUtils.getDimension(element, 'margin-top', 'marginTop'); + } + static getMarginRight(element: HTMLElement): number { + return SizeUtils.getDimension(element, 'margin-right', 'marginRight'); + } + static getMarginBottom(element: HTMLElement): number { + return SizeUtils.getDimension(element, 'margin-bottom', 'marginBottom'); + } +} + +// ---------------------------------------------------------------------------------------- +// Position & Dimension + +export interface IDimension { + readonly width: number; + readonly height: number; +} + +export class Dimension implements IDimension { + + static readonly None = new Dimension(0, 0); + + constructor( + readonly width: number, + readonly height: number, + ) { } + + with(width: number = this.width, height: number = this.height): Dimension { + if (width !== this.width || height !== this.height) { + return new Dimension(width, height); + } else { + return this; + } + } + + static is(obj: unknown): obj is IDimension { + return typeof obj === 'object' && typeof (obj).height === 'number' && typeof (obj).width === 'number'; + } + + static lift(obj: IDimension): Dimension { + if (obj instanceof Dimension) { + return obj; + } else { + return new Dimension(obj.width, obj.height); + } + } + + static equals(a: Dimension | undefined, b: Dimension | undefined): boolean { + if (a === b) { + return true; + } + if (!a || !b) { + return false; + } + return a.width === b.width && a.height === b.height; + } +} + +export interface IDomPosition { + readonly left: number; + readonly top: number; +} + +export function getTopLeftOffset(element: HTMLElement): IDomPosition { + // Adapted from WinJS.Utilities.getPosition + // and added borders to the mix + + let offsetParent = element.offsetParent; + let top = element.offsetTop; + let left = element.offsetLeft; + + while ( + (element = element.parentNode) !== null + && element !== element.ownerDocument.body + && element !== element.ownerDocument.documentElement + ) { + top -= element.scrollTop; + const c = isShadowRoot(element) ? null : getComputedStyle(element); + if (c) { + left -= c.direction !== 'rtl' ? element.scrollLeft : -element.scrollLeft; + } + + if (element === offsetParent) { + left += SizeUtils.getBorderLeftWidth(element); + top += SizeUtils.getBorderTopWidth(element); + top += element.offsetTop; + left += element.offsetLeft; + offsetParent = element.offsetParent; + } + } + + return { + left: left, + top: top + }; +} + +export interface IDomNodePagePosition { + left: number; + top: number; + width: number; + height: number; +} + +export function size(element: HTMLElement, width: number | null, height: number | null): void { + if (typeof width === 'number') { + element.style.width = `${width}px`; + } + + if (typeof height === 'number') { + element.style.height = `${height}px`; + } +} + +export function position(element: HTMLElement, top: number, right?: number, bottom?: number, left?: number, position: string = 'absolute'): void { + if (typeof top === 'number') { + element.style.top = `${top}px`; + } + + if (typeof right === 'number') { + element.style.right = `${right}px`; + } + + if (typeof bottom === 'number') { + element.style.bottom = `${bottom}px`; + } + + if (typeof left === 'number') { + element.style.left = `${left}px`; + } + + element.style.position = position; +} + +/** + * Returns the position of a dom node relative to the entire page. + */ +export function getDomNodePagePosition(domNode: HTMLElement): IDomNodePagePosition { + const bb = domNode.getBoundingClientRect(); + const window = getWindow(domNode); + return { + left: bb.left + window.scrollX, + top: bb.top + window.scrollY, + width: bb.width, + height: bb.height + }; +} + +/** + * Returns the effective zoom on a given element before window zoom level is applied + */ +export function getDomNodeZoomLevel(domNode: HTMLElement): number { + let testElement: HTMLElement | null = domNode; + let zoom = 1.0; + do { + const elementZoomLevel = (getComputedStyle(testElement) as any).zoom; + if (elementZoomLevel !== null && elementZoomLevel !== undefined && elementZoomLevel !== '1') { + zoom *= elementZoomLevel; + } + + testElement = testElement.parentElement; + } while (testElement !== null && testElement !== testElement.ownerDocument.documentElement); + + return zoom; +} + + +// Adapted from WinJS +// Gets the width of the element, including margins. +export function getTotalWidth(element: HTMLElement): number { + const margin = SizeUtils.getMarginLeft(element) + SizeUtils.getMarginRight(element); + return element.offsetWidth + margin; +} + +export function getContentWidth(element: HTMLElement): number { + const border = SizeUtils.getBorderLeftWidth(element) + SizeUtils.getBorderRightWidth(element); + const padding = SizeUtils.getPaddingLeft(element) + SizeUtils.getPaddingRight(element); + return element.offsetWidth - border - padding; +} + +export function getTotalScrollWidth(element: HTMLElement): number { + const margin = SizeUtils.getMarginLeft(element) + SizeUtils.getMarginRight(element); + return element.scrollWidth + margin; +} + +// Adapted from WinJS +// Gets the height of the content of the specified element. The content height does not include borders or padding. +export function getContentHeight(element: HTMLElement): number { + const border = SizeUtils.getBorderTopWidth(element) + SizeUtils.getBorderBottomWidth(element); + const padding = SizeUtils.getPaddingTop(element) + SizeUtils.getPaddingBottom(element); + return element.offsetHeight - border - padding; +} + +// Adapted from WinJS +// Gets the height of the element, including its margins. +export function getTotalHeight(element: HTMLElement): number { + const margin = SizeUtils.getMarginTop(element) + SizeUtils.getMarginBottom(element); + return element.offsetHeight + margin; +} + +// Gets the left coordinate of the specified element relative to the specified parent. +function getRelativeLeft(element: HTMLElement, parent: HTMLElement): number { + if (element === null) { + return 0; + } + + const elementPosition = getTopLeftOffset(element); + const parentPosition = getTopLeftOffset(parent); + return elementPosition.left - parentPosition.left; +} + +export function getLargestChildWidth(parent: HTMLElement, children: HTMLElement[]): number { + const childWidths = children.map((child) => { + return Math.max(getTotalScrollWidth(child), getTotalWidth(child)) + getRelativeLeft(child, parent) || 0; + }); + const maxWidth = Math.max(...childWidths); + return maxWidth; +} + +// ---------------------------------------------------------------------------------------- + +export function isAncestor(testChild: Node | null, testAncestor: Node | null): boolean { + return Boolean(testAncestor?.contains(testChild)); +} + +const parentFlowToDataKey = 'parentFlowToElementId'; + +/** + * Set an explicit parent to use for nodes that are not part of the + * regular dom structure. + */ +export function setParentFlowTo(fromChildElement: HTMLElement, toParentElement: Element): void { + fromChildElement.dataset[parentFlowToDataKey] = toParentElement.id; +} + +function getParentFlowToElement(node: HTMLElement): HTMLElement | null { + const flowToParentId = node.dataset[parentFlowToDataKey]; + if (typeof flowToParentId === 'string') { + return node.ownerDocument.getElementById(flowToParentId); + } + return null; +} + +/** + * Check if `testAncestor` is an ancestor of `testChild`, observing the explicit + * parents set by `setParentFlowTo`. + */ +export function isAncestorUsingFlowTo(testChild: Node, testAncestor: Node): boolean { + let node: Node | null = testChild; + while (node) { + if (node === testAncestor) { + return true; + } + + if (isHTMLElement(node)) { + const flowToParentElement = getParentFlowToElement(node); + if (flowToParentElement) { + node = flowToParentElement; + continue; + } + } + node = node.parentNode; + } + + return false; +} + +export function findParentWithClass(node: HTMLElement, clazz: string, stopAtClazzOrNode?: string | HTMLElement): HTMLElement | null { + while (node && node.nodeType === node.ELEMENT_NODE) { + if (node.classList.contains(clazz)) { + return node; + } + + if (stopAtClazzOrNode) { + if (typeof stopAtClazzOrNode === 'string') { + if (node.classList.contains(stopAtClazzOrNode)) { + return null; + } + } else { + if (node === stopAtClazzOrNode) { + return null; + } + } + } + + node = node.parentNode; + } + + return null; +} + +export function hasParentWithClass(node: HTMLElement, clazz: string, stopAtClazzOrNode?: string | HTMLElement): boolean { + return !!findParentWithClass(node, clazz, stopAtClazzOrNode); +} + +export function isShadowRoot(node: Node): node is ShadowRoot { + return ( + node && !!(node).host && !!(node).mode + ); +} + +export function isInShadowDOM(domNode: Node): boolean { + return !!getShadowRoot(domNode); +} + +export function getShadowRoot(domNode: Node): ShadowRoot | null { + while (domNode.parentNode) { + if (domNode === domNode.ownerDocument?.body) { + // reached the body + return null; + } + domNode = domNode.parentNode; + } + return isShadowRoot(domNode) ? domNode : null; +} + +/** + * Returns the active element across all child windows + * based on document focus. Falls back to the main + * window if no window has focus. + */ +export function getActiveElement(): Element | null { + let result = getActiveDocument().activeElement; + + while (result?.shadowRoot) { + result = result.shadowRoot.activeElement; + } + + return result; +} + +/** + * Returns true if the focused window active element matches + * the provided element. Falls back to the main window if no + * window has focus. + */ +export function isActiveElement(element: Element): boolean { + return getActiveElement() === element; +} + +/** + * Returns true if the focused window active element is contained in + * `ancestor`. Falls back to the main window if no window has focus. + */ +export function isAncestorOfActiveElement(ancestor: Element): boolean { + return isAncestor(getActiveElement(), ancestor); +} + +/** + * Returns whether the element is in the active `document`. The active + * document has focus or will be the main windows document. + */ +export function isActiveDocument(element: Element): boolean { + return element.ownerDocument === getActiveDocument(); +} + +/** + * Returns the active document across main and child windows. + * Prefers the window with focus, otherwise falls back to + * the main windows document. + */ +export function getActiveDocument(): Document { + if (getWindowsCount() <= 1) { + return mainWindow.document; + } + + const documents = Array.from(getWindows()).map(({ window }) => window.document); + return documents.find(doc => doc.hasFocus()) ?? mainWindow.document; +} + +/** + * Returns the active window across main and child windows. + * Prefers the window with focus, otherwise falls back to + * the main window. + */ +export function getActiveWindow(): CodeWindow { + const document = getActiveDocument(); + return (document.defaultView?.window ?? mainWindow) as CodeWindow; +} + +const globalStylesheets = new Map>(); + +export function isGlobalStylesheet(node: Node): boolean { + return globalStylesheets.has(node as HTMLStyleElement); +} + +/** + * A version of createStyleSheet which has a unified API to initialize/set the style content. + */ +export function createStyleSheet2(): WrappedStyleElement { + return new WrappedStyleElement(); +} + +class WrappedStyleElement { + private _currentCssStyle = ''; + private _styleSheet: HTMLStyleElement | undefined = undefined; + + public setStyle(cssStyle: string): void { + if (cssStyle === this._currentCssStyle) { + return; + } + this._currentCssStyle = cssStyle; + + if (!this._styleSheet) { + this._styleSheet = createStyleSheet(mainWindow.document.head, (s) => s.innerText = cssStyle); + } else { + this._styleSheet.innerText = cssStyle; + } + } + + public dispose(): void { + if (this._styleSheet) { + this._styleSheet.remove(); + this._styleSheet = undefined; + } + } +} + +export function createStyleSheet(container: HTMLElement = mainWindow.document.head, beforeAppend?: (style: HTMLStyleElement) => void, disposableStore?: DisposableStore): HTMLStyleElement { + const style = document.createElement('style'); + style.type = 'text/css'; + style.media = 'screen'; + beforeAppend?.(style); + container.appendChild(style); + + if (disposableStore) { + disposableStore.add(toDisposable(() => style.remove())); + } + + // With as container, the stylesheet becomes global and is tracked + // to support auxiliary windows to clone the stylesheet. + if (container === mainWindow.document.head) { + const globalStylesheetClones = new Set(); + globalStylesheets.set(style, globalStylesheetClones); + + for (const { window: targetWindow, disposables } of getWindows()) { + if (targetWindow === mainWindow) { + continue; // main window is already tracked + } + + const cloneDisposable = disposables.add(cloneGlobalStyleSheet(style, globalStylesheetClones, targetWindow)); + disposableStore?.add(cloneDisposable); + } + } + + return style; +} + +export function cloneGlobalStylesheets(targetWindow: Window): IDisposable { + const disposables = new DisposableStore(); + + for (const [globalStylesheet, clonedGlobalStylesheets] of globalStylesheets) { + disposables.add(cloneGlobalStyleSheet(globalStylesheet, clonedGlobalStylesheets, targetWindow)); + } + + return disposables; +} + +function cloneGlobalStyleSheet(globalStylesheet: HTMLStyleElement, globalStylesheetClones: Set, targetWindow: Window): IDisposable { + const disposables = new DisposableStore(); + + const clone = globalStylesheet.cloneNode(true) as HTMLStyleElement; + targetWindow.document.head.appendChild(clone); + disposables.add(toDisposable(() => clone.remove())); + + for (const rule of getDynamicStyleSheetRules(globalStylesheet)) { + clone.sheet?.insertRule(rule.cssText, clone.sheet?.cssRules.length); + } + + disposables.add(sharedMutationObserver.observe(globalStylesheet, disposables, { childList: true })(() => { + clone.textContent = globalStylesheet.textContent; + })); + + globalStylesheetClones.add(clone); + disposables.add(toDisposable(() => globalStylesheetClones.delete(clone))); + + return disposables; +} + +interface IMutationObserver { + users: number; + readonly observer: MutationObserver; + readonly onDidMutate: event.Event; +} + +export const sharedMutationObserver = new class { + + readonly mutationObservers = new Map>(); + + observe(target: Node, disposables: DisposableStore, options?: MutationObserverInit): event.Event { + let mutationObserversPerTarget = this.mutationObservers.get(target); + if (!mutationObserversPerTarget) { + mutationObserversPerTarget = new Map(); + this.mutationObservers.set(target, mutationObserversPerTarget); + } + + const optionsHash = hash(options); + let mutationObserverPerOptions = mutationObserversPerTarget.get(optionsHash); + if (!mutationObserverPerOptions) { + const onDidMutate = new event.Emitter(); + const observer = new MutationObserver(mutations => onDidMutate.fire(mutations)); + observer.observe(target, options); + + const resolvedMutationObserverPerOptions = mutationObserverPerOptions = { + users: 1, + observer, + onDidMutate: onDidMutate.event + }; + + disposables.add(toDisposable(() => { + resolvedMutationObserverPerOptions.users -= 1; + + if (resolvedMutationObserverPerOptions.users === 0) { + onDidMutate.dispose(); + observer.disconnect(); + + mutationObserversPerTarget?.delete(optionsHash); + if (mutationObserversPerTarget?.size === 0) { + this.mutationObservers.delete(target); + } + } + })); + + mutationObserversPerTarget.set(optionsHash, mutationObserverPerOptions); + } else { + mutationObserverPerOptions.users += 1; + } + + return mutationObserverPerOptions.onDidMutate; + } +}; + +export function createMetaElement(container: HTMLElement = mainWindow.document.head): HTMLMetaElement { + return createHeadElement('meta', container) as HTMLMetaElement; +} + +export function createLinkElement(container: HTMLElement = mainWindow.document.head): HTMLLinkElement { + return createHeadElement('link', container) as HTMLLinkElement; +} + +function createHeadElement(tagName: string, container: HTMLElement = mainWindow.document.head): HTMLElement { + const element = document.createElement(tagName); + container.appendChild(element); + return element; +} + +let _sharedStyleSheet: HTMLStyleElement | null = null; +function getSharedStyleSheet(): HTMLStyleElement { + if (!_sharedStyleSheet) { + _sharedStyleSheet = createStyleSheet(); + } + return _sharedStyleSheet; +} + +function getDynamicStyleSheetRules(style: HTMLStyleElement) { + if (style?.sheet?.rules) { + // Chrome, IE + return style.sheet.rules; + } + if (style?.sheet?.cssRules) { + // FF + return style.sheet.cssRules; + } + return []; +} + +export function createCSSRule(selector: string, cssText: string, style = getSharedStyleSheet()): void { + if (!style || !cssText) { + return; + } + + style.sheet?.insertRule(`${selector} {${cssText}}`, 0); + + // Apply rule also to all cloned global stylesheets + for (const clonedGlobalStylesheet of globalStylesheets.get(style) ?? []) { + createCSSRule(selector, cssText, clonedGlobalStylesheet); + } +} + +export function removeCSSRulesContainingSelector(ruleName: string, style = getSharedStyleSheet()): void { + if (!style) { + return; + } + + const rules = getDynamicStyleSheetRules(style); + const toDelete: number[] = []; + for (let i = 0; i < rules.length; i++) { + const rule = rules[i]; + if (isCSSStyleRule(rule) && rule.selectorText.indexOf(ruleName) !== -1) { + toDelete.push(i); + } + } + + for (let i = toDelete.length - 1; i >= 0; i--) { + style.sheet?.deleteRule(toDelete[i]); + } + + // Remove rules also from all cloned global stylesheets + for (const clonedGlobalStylesheet of globalStylesheets.get(style) ?? []) { + removeCSSRulesContainingSelector(ruleName, clonedGlobalStylesheet); + } +} + +function isCSSStyleRule(rule: CSSRule): rule is CSSStyleRule { + return typeof (rule as CSSStyleRule).selectorText === 'string'; +} + +export function isHTMLElement(e: unknown): e is HTMLElement { + // eslint-disable-next-line no-restricted-syntax + return e instanceof HTMLElement || e instanceof getWindow(e as Node).HTMLElement; +} + +export function isHTMLAnchorElement(e: unknown): e is HTMLAnchorElement { + // eslint-disable-next-line no-restricted-syntax + return e instanceof HTMLAnchorElement || e instanceof getWindow(e as Node).HTMLAnchorElement; +} + +export function isHTMLSpanElement(e: unknown): e is HTMLSpanElement { + // eslint-disable-next-line no-restricted-syntax + return e instanceof HTMLSpanElement || e instanceof getWindow(e as Node).HTMLSpanElement; +} + +export function isHTMLTextAreaElement(e: unknown): e is HTMLTextAreaElement { + // eslint-disable-next-line no-restricted-syntax + return e instanceof HTMLTextAreaElement || e instanceof getWindow(e as Node).HTMLTextAreaElement; +} + +export function isHTMLInputElement(e: unknown): e is HTMLInputElement { + // eslint-disable-next-line no-restricted-syntax + return e instanceof HTMLInputElement || e instanceof getWindow(e as Node).HTMLInputElement; +} + +export function isHTMLButtonElement(e: unknown): e is HTMLButtonElement { + // eslint-disable-next-line no-restricted-syntax + return e instanceof HTMLButtonElement || e instanceof getWindow(e as Node).HTMLButtonElement; +} + +export function isHTMLDivElement(e: unknown): e is HTMLDivElement { + // eslint-disable-next-line no-restricted-syntax + return e instanceof HTMLDivElement || e instanceof getWindow(e as Node).HTMLDivElement; +} + +export function isSVGElement(e: unknown): e is SVGElement { + // eslint-disable-next-line no-restricted-syntax + return e instanceof SVGElement || e instanceof getWindow(e as Node).SVGElement; +} + +export function isMouseEvent(e: unknown): e is MouseEvent { + // eslint-disable-next-line no-restricted-syntax + return e instanceof MouseEvent || e instanceof getWindow(e as UIEvent).MouseEvent; +} + +export function isKeyboardEvent(e: unknown): e is KeyboardEvent { + // eslint-disable-next-line no-restricted-syntax + return e instanceof KeyboardEvent || e instanceof getWindow(e as UIEvent).KeyboardEvent; +} + +export function isPointerEvent(e: unknown): e is PointerEvent { + // eslint-disable-next-line no-restricted-syntax + return e instanceof PointerEvent || e instanceof getWindow(e as UIEvent).PointerEvent; +} + +export function isDragEvent(e: unknown): e is DragEvent { + // eslint-disable-next-line no-restricted-syntax + return e instanceof DragEvent || e instanceof getWindow(e as UIEvent).DragEvent; +} + +export const EventType = { + // Mouse + CLICK: 'click', + AUXCLICK: 'auxclick', + DBLCLICK: 'dblclick', + MOUSE_UP: 'mouseup', + MOUSE_DOWN: 'mousedown', + MOUSE_OVER: 'mouseover', + MOUSE_MOVE: 'mousemove', + MOUSE_OUT: 'mouseout', + MOUSE_ENTER: 'mouseenter', + MOUSE_LEAVE: 'mouseleave', + MOUSE_WHEEL: 'wheel', + POINTER_UP: 'pointerup', + POINTER_DOWN: 'pointerdown', + POINTER_MOVE: 'pointermove', + POINTER_LEAVE: 'pointerleave', + CONTEXT_MENU: 'contextmenu', + WHEEL: 'wheel', + // Keyboard + KEY_DOWN: 'keydown', + KEY_PRESS: 'keypress', + KEY_UP: 'keyup', + // HTML Document + LOAD: 'load', + BEFORE_UNLOAD: 'beforeunload', + UNLOAD: 'unload', + PAGE_SHOW: 'pageshow', + PAGE_HIDE: 'pagehide', + PASTE: 'paste', + ABORT: 'abort', + ERROR: 'error', + RESIZE: 'resize', + SCROLL: 'scroll', + FULLSCREEN_CHANGE: 'fullscreenchange', + WK_FULLSCREEN_CHANGE: 'webkitfullscreenchange', + // Form + SELECT: 'select', + CHANGE: 'change', + SUBMIT: 'submit', + RESET: 'reset', + FOCUS: 'focus', + FOCUS_IN: 'focusin', + FOCUS_OUT: 'focusout', + BLUR: 'blur', + INPUT: 'input', + // Local Storage + STORAGE: 'storage', + // Drag + DRAG_START: 'dragstart', + DRAG: 'drag', + DRAG_ENTER: 'dragenter', + DRAG_LEAVE: 'dragleave', + DRAG_OVER: 'dragover', + DROP: 'drop', + DRAG_END: 'dragend', + // Animation + ANIMATION_START: browser.isWebKit ? 'webkitAnimationStart' : 'animationstart', + ANIMATION_END: browser.isWebKit ? 'webkitAnimationEnd' : 'animationend', + ANIMATION_ITERATION: browser.isWebKit ? 'webkitAnimationIteration' : 'animationiteration' +} as const; + +export interface EventLike { + preventDefault(): void; + stopPropagation(): void; +} + +export function isEventLike(obj: unknown): obj is EventLike { + const candidate = obj as EventLike | undefined; + + return !!(candidate && typeof candidate.preventDefault === 'function' && typeof candidate.stopPropagation === 'function'); +} + +export const EventHelper = { + stop: (e: T, cancelBubble?: boolean): T => { + e.preventDefault(); + if (cancelBubble) { + e.stopPropagation(); + } + return e; + } +}; + +export interface IFocusTracker extends Disposable { + readonly onDidFocus: event.Event; + readonly onDidBlur: event.Event; + refreshState(): void; +} + +export function saveParentsScrollTop(node: Element): number[] { + const r: number[] = []; + for (let i = 0; node && node.nodeType === node.ELEMENT_NODE; i++) { + r[i] = node.scrollTop; + node = node.parentNode; + } + return r; +} + +export function restoreParentsScrollTop(node: Element, state: number[]): void { + for (let i = 0; node && node.nodeType === node.ELEMENT_NODE; i++) { + if (node.scrollTop !== state[i]) { + node.scrollTop = state[i]; + } + node = node.parentNode; + } +} + +class FocusTracker extends Disposable implements IFocusTracker { + + private readonly _onDidFocus = this._register(new event.Emitter()); + readonly onDidFocus = this._onDidFocus.event; + + private readonly _onDidBlur = this._register(new event.Emitter()); + readonly onDidBlur = this._onDidBlur.event; + + private _refreshStateHandler: () => void; + + private static hasFocusWithin(element: HTMLElement | Window): boolean { + if (isHTMLElement(element)) { + const shadowRoot = getShadowRoot(element); + const activeElement = (shadowRoot ? shadowRoot.activeElement : element.ownerDocument.activeElement); + return isAncestor(activeElement, element); + } else { + const window = element; + return isAncestor(window.document.activeElement, window.document); + } + } + + constructor(element: HTMLElement | Window) { + super(); + let hasFocus = FocusTracker.hasFocusWithin(element); + let loosingFocus = false; + + const onFocus = () => { + loosingFocus = false; + if (!hasFocus) { + hasFocus = true; + this._onDidFocus.fire(); + } + }; + + const onBlur = () => { + if (hasFocus) { + loosingFocus = true; + (isHTMLElement(element) ? getWindow(element) : element).setTimeout(() => { + if (loosingFocus) { + loosingFocus = false; + hasFocus = false; + this._onDidBlur.fire(); + } + }, 0); + } + }; + + this._refreshStateHandler = () => { + const currentNodeHasFocus = FocusTracker.hasFocusWithin(element); + if (currentNodeHasFocus !== hasFocus) { + if (hasFocus) { + onBlur(); + } else { + onFocus(); + } + } + }; + + this._register(addDisposableListener(element, EventType.FOCUS, onFocus, true)); + this._register(addDisposableListener(element, EventType.BLUR, onBlur, true)); + if (isHTMLElement(element)) { + this._register(addDisposableListener(element, EventType.FOCUS_IN, () => this._refreshStateHandler())); + this._register(addDisposableListener(element, EventType.FOCUS_OUT, () => this._refreshStateHandler())); + } + + } + + refreshState() { + this._refreshStateHandler(); + } +} + +/** + * Creates a new `IFocusTracker` instance that tracks focus changes on the given `element` and its descendants. + * + * @param element The `HTMLElement` or `Window` to track focus changes on. + * @returns An `IFocusTracker` instance. + */ +export function trackFocus(element: HTMLElement | Window): IFocusTracker { + return new FocusTracker(element); +} + +export function after(sibling: HTMLElement, child: T): T { + sibling.after(child); + return child; +} + +export function append(parent: HTMLElement, child: T): T; +export function append(parent: HTMLElement, ...children: (T | string)[]): void; +export function append(parent: HTMLElement, ...children: (T | string)[]): T | void { + parent.append(...children); + if (children.length === 1 && typeof children[0] !== 'string') { + return children[0]; + } +} + +export function prepend(parent: HTMLElement, child: T): T { + parent.insertBefore(child, parent.firstChild); + return child; +} + +/** + * Removes all children from `parent` and appends `children` + */ +export function reset(parent: HTMLElement, ...children: Array): void { + parent.innerText = ''; + append(parent, ...children); +} + +const SELECTOR_REGEX = /([\w\-]+)?(#([\w\-]+))?((\.([\w\-]+))*)/; + +export enum Namespace { + HTML = 'http://www.w3.org/1999/xhtml', + SVG = 'http://www.w3.org/2000/svg' +} + +function _$(namespace: Namespace, description: string, attrs?: { [key: string]: any }, ...children: Array): T { + const match = SELECTOR_REGEX.exec(description); + + if (!match) { + throw new Error('Bad use of emmet'); + } + + const tagName = match[1] || 'div'; + let result: T; + + if (namespace !== Namespace.HTML) { + result = document.createElementNS(namespace as string, tagName) as T; + } else { + result = document.createElement(tagName) as unknown as T; + } + + if (match[3]) { + result.id = match[3]; + } + if (match[4]) { + result.className = match[4].replace(/\./g, ' ').trim(); + } + + if (attrs) { + Object.entries(attrs).forEach(([name, value]) => { + if (typeof value === 'undefined') { + return; + } + + if (/^on\w+$/.test(name)) { + (result)[name] = value; + } else if (name === 'selected') { + if (value) { + result.setAttribute(name, 'true'); + } + + } else { + result.setAttribute(name, value); + } + }); + } + + result.append(...children); + + return result as T; +} + +export function $(description: string, attrs?: { [key: string]: any }, ...children: Array): T { + return _$(Namespace.HTML, description, attrs, ...children); +} + +$.SVG = function (description: string, attrs?: { [key: string]: any }, ...children: Array): T { + return _$(Namespace.SVG, description, attrs, ...children); +}; + +export function join(nodes: Node[], separator: Node | string): Node[] { + const result: Node[] = []; + + nodes.forEach((node, index) => { + if (index > 0) { + if (separator instanceof Node) { + result.push(separator.cloneNode()); + } else { + result.push(document.createTextNode(separator)); + } + } + + result.push(node); + }); + + return result; +} + +export function setVisibility(visible: boolean, ...elements: HTMLElement[]): void { + if (visible) { + show(...elements); + } else { + hide(...elements); + } +} + +export function show(...elements: HTMLElement[]): void { + for (const element of elements) { + element.style.display = ''; + element.removeAttribute('aria-hidden'); + } +} + +export function hide(...elements: HTMLElement[]): void { + for (const element of elements) { + element.style.display = 'none'; + element.setAttribute('aria-hidden', 'true'); + } +} + +function findParentWithAttribute(node: Node | null, attribute: string): HTMLElement | null { + while (node && node.nodeType === node.ELEMENT_NODE) { + if (isHTMLElement(node) && node.hasAttribute(attribute)) { + return node; + } + + node = node.parentNode; + } + + return null; +} + +export function removeTabIndexAndUpdateFocus(node: HTMLElement): void { + if (!node || !node.hasAttribute('tabIndex')) { + return; + } + + // If we are the currently focused element and tabIndex is removed, + // standard DOM behavior is to move focus to the element. We + // typically never want that, rather put focus to the closest element + // in the hierarchy of the parent DOM nodes. + if (node.ownerDocument.activeElement === node) { + const parentFocusable = findParentWithAttribute(node.parentElement, 'tabIndex'); + parentFocusable?.focus(); + } + + node.removeAttribute('tabindex'); +} + +export function finalHandler(fn: (event: T) => any): (event: T) => any { + return e => { + e.preventDefault(); + e.stopPropagation(); + fn(e); + }; +} + +export function domContentLoaded(targetWindow: Window): Promise { + return new Promise(resolve => { + const readyState = targetWindow.document.readyState; + if (readyState === 'complete' || (targetWindow.document && targetWindow.document.body !== null)) { + resolve(undefined); + } else { + const listener = () => { + targetWindow.window.removeEventListener('DOMContentLoaded', listener, false); + resolve(); + }; + + targetWindow.window.addEventListener('DOMContentLoaded', listener, false); + } + }); +} + +/** + * Find a value usable for a dom node size such that the likelihood that it would be + * displayed with constant screen pixels size is as high as possible. + * + * e.g. We would desire for the cursors to be 2px (CSS px) wide. Under a devicePixelRatio + * of 1.25, the cursor will be 2.5 screen pixels wide. Depending on how the dom node aligns/"snaps" + * with the screen pixels, it will sometimes be rendered with 2 screen pixels, and sometimes with 3 screen pixels. + */ +export function computeScreenAwareSize(window: Window, cssPx: number): number { + const screenPx = window.devicePixelRatio * cssPx; + return Math.max(1, Math.floor(screenPx)) / window.devicePixelRatio; +} + +/** + * Open safely a new window. This is the best way to do so, but you cannot tell + * if the window was opened or if it was blocked by the browser's popup blocker. + * If you want to tell if the browser blocked the new window, use {@link windowOpenWithSuccess}. + * + * See https://github.com/microsoft/monaco-editor/issues/601 + * To protect against malicious code in the linked site, particularly phishing attempts, + * the window.opener should be set to null to prevent the linked site from having access + * to change the location of the current page. + * See https://mathiasbynens.github.io/rel-noopener/ + */ +export function windowOpenNoOpener(url: string): void { + // By using 'noopener' in the `windowFeatures` argument, the newly created window will + // not be able to use `window.opener` to reach back to the current page. + // See https://stackoverflow.com/a/46958731 + // See https://developer.mozilla.org/en-US/docs/Web/API/Window/open#noopener + // However, this also doesn't allow us to realize if the browser blocked + // the creation of the window. + mainWindow.open(url, '_blank', 'noopener'); +} + +/** + * Open a new window in a popup. This is the best way to do so, but you cannot tell + * if the window was opened or if it was blocked by the browser's popup blocker. + * If you want to tell if the browser blocked the new window, use {@link windowOpenWithSuccess}. + * + * Note: this does not set {@link window.opener} to null. This is to allow the opened popup to + * be able to use {@link window.close} to close itself. Because of this, you should only use + * this function on urls that you trust. + * + * In otherwords, you should almost always use {@link windowOpenNoOpener} instead of this function. + */ +const popupWidth = 780, popupHeight = 640; +export function windowOpenPopup(url: string): void { + const left = Math.floor(mainWindow.screenLeft + mainWindow.innerWidth / 2 - popupWidth / 2); + const top = Math.floor(mainWindow.screenTop + mainWindow.innerHeight / 2 - popupHeight / 2); + mainWindow.open( + url, + '_blank', + `width=${popupWidth},height=${popupHeight},top=${top},left=${left}` + ); +} + +/** + * Attempts to open a window and returns whether it succeeded. This technique is + * not appropriate in certain contexts, like for example when the JS context is + * executing inside a sandboxed iframe. If it is not necessary to know if the + * browser blocked the new window, use {@link windowOpenNoOpener}. + * + * See https://github.com/microsoft/monaco-editor/issues/601 + * See https://github.com/microsoft/monaco-editor/issues/2474 + * See https://mathiasbynens.github.io/rel-noopener/ + * + * @param url the url to open + * @param noOpener whether or not to set the {@link window.opener} to null. You should leave the default + * (true) unless you trust the url that is being opened. + * @returns boolean indicating if the {@link window.open} call succeeded + */ +export function windowOpenWithSuccess(url: string, noOpener = true): boolean { + const newTab = mainWindow.open(); + if (newTab) { + if (noOpener) { + // see `windowOpenNoOpener` for details on why this is important + (newTab as any).opener = null; + } + newTab.location.href = url; + return true; + } + return false; +} + +export function animate(targetWindow: Window, fn: () => void): IDisposable { + const step = () => { + fn(); + stepDisposable = scheduleAtNextAnimationFrame(targetWindow, step); + }; + + let stepDisposable = scheduleAtNextAnimationFrame(targetWindow, step); + return toDisposable(() => stepDisposable.dispose()); +} + +export function asCSSPropertyValue(value: string) { + return `'${value.replace(/'/g, '%27')}'`; +} + +export function asCssValueWithDefault(cssPropertyValue: string | undefined, dflt: string): string { + if (cssPropertyValue !== undefined) { + const variableMatch = cssPropertyValue.match(/^\s*var\((.+)\)$/); + if (variableMatch) { + const varArguments = variableMatch[1].split(',', 2); + if (varArguments.length === 2) { + dflt = asCssValueWithDefault(varArguments[1].trim(), dflt); + } + return `var(${varArguments[0]}, ${dflt})`; + } + return cssPropertyValue; + } + return dflt; +} + +export enum DetectedFullscreenMode { + + /** + * The document is fullscreen, e.g. because an element + * in the document requested to be fullscreen. + */ + DOCUMENT = 1, + + /** + * The browser is fullscreen, e.g. because the user enabled + * native window fullscreen for it. + */ + BROWSER +} + +export interface IDetectedFullscreen { + + /** + * Figure out if the document is fullscreen or the browser. + */ + mode: DetectedFullscreenMode; + + /** + * Whether we know for sure that we are in fullscreen mode or + * it is a guess. + */ + guess: boolean; +} + +export function detectFullscreen(targetWindow: Window): IDetectedFullscreen | null { + + // Browser fullscreen: use DOM APIs to detect + if (targetWindow.document.fullscreenElement || (targetWindow.document).webkitFullscreenElement || (targetWindow.document).webkitIsFullScreen) { + return { mode: DetectedFullscreenMode.DOCUMENT, guess: false }; + } + + // There is no standard way to figure out if the browser + // is using native fullscreen. Via checking on screen + // height and comparing that to window height, we can guess + // it though. + + if (targetWindow.innerHeight === targetWindow.screen.height) { + // if the height of the window matches the screen height, we can + // safely assume that the browser is fullscreen because no browser + // chrome is taking height away (e.g. like toolbars). + return { mode: DetectedFullscreenMode.BROWSER, guess: false }; + } + + if (platform.isMacintosh || platform.isLinux) { + // macOS and Linux do not properly report `innerHeight`, only Windows does + if (targetWindow.outerHeight === targetWindow.screen.height && targetWindow.outerWidth === targetWindow.screen.width) { + // if the height of the browser matches the screen height, we can + // only guess that we are in fullscreen. It is also possible that + // the user has turned off taskbars in the OS and the browser is + // simply able to span the entire size of the screen. + return { mode: DetectedFullscreenMode.BROWSER, guess: true }; + } + } + + // Not in fullscreen + return null; +} + +/** + * Convert a Unicode string to a string in which each 16-bit unit occupies only one byte + * + * From https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/btoa + */ +function toBinary(str: string): string { + const codeUnits = new Uint16Array(str.length); + for (let i = 0; i < codeUnits.length; i++) { + codeUnits[i] = str.charCodeAt(i); + } + let binary = ''; + const uint8array = new Uint8Array(codeUnits.buffer); + for (let i = 0; i < uint8array.length; i++) { + binary += String.fromCharCode(uint8array[i]); + } + return binary; +} + +/** + * Version of the global `btoa` function that handles multi-byte characters instead + * of throwing an exception. + */ +export function multibyteAwareBtoa(str: string): string { + return btoa(toBinary(str)); +} + +type ModifierKey = 'alt' | 'ctrl' | 'shift' | 'meta'; + +export interface IModifierKeyStatus { + altKey: boolean; + shiftKey: boolean; + ctrlKey: boolean; + metaKey: boolean; + lastKeyPressed?: ModifierKey; + lastKeyReleased?: ModifierKey; + event?: KeyboardEvent; +} + +export class ModifierKeyEmitter extends event.Emitter { + + private readonly _subscriptions = new DisposableStore(); + private _keyStatus: IModifierKeyStatus; + private static instance: ModifierKeyEmitter; + + private constructor() { + super(); + + this._keyStatus = { + altKey: false, + shiftKey: false, + ctrlKey: false, + metaKey: false + }; + + this._subscriptions.add(event.Event.runAndSubscribe(onDidRegisterWindow, ({ window, disposables }) => this.registerListeners(window, disposables), { window: mainWindow, disposables: this._subscriptions })); + } + + private registerListeners(window: Window, disposables: DisposableStore): void { + disposables.add(addDisposableListener(window, 'keydown', e => { + if (e.defaultPrevented) { + return; + } + + const event = new StandardKeyboardEvent(e); + // If Alt-key keydown event is repeated, ignore it #112347 + // Only known to be necessary for Alt-Key at the moment #115810 + if (event.keyCode === KeyCode.Alt && e.repeat) { + return; + } + + if (e.altKey && !this._keyStatus.altKey) { + this._keyStatus.lastKeyPressed = 'alt'; + } else if (e.ctrlKey && !this._keyStatus.ctrlKey) { + this._keyStatus.lastKeyPressed = 'ctrl'; + } else if (e.metaKey && !this._keyStatus.metaKey) { + this._keyStatus.lastKeyPressed = 'meta'; + } else if (e.shiftKey && !this._keyStatus.shiftKey) { + this._keyStatus.lastKeyPressed = 'shift'; + } else if (event.keyCode !== KeyCode.Alt) { + this._keyStatus.lastKeyPressed = undefined; + } else { + return; + } + + this._keyStatus.altKey = e.altKey; + this._keyStatus.ctrlKey = e.ctrlKey; + this._keyStatus.metaKey = e.metaKey; + this._keyStatus.shiftKey = e.shiftKey; + + if (this._keyStatus.lastKeyPressed) { + this._keyStatus.event = e; + this.fire(this._keyStatus); + } + }, true)); + + disposables.add(addDisposableListener(window, 'keyup', e => { + if (e.defaultPrevented) { + return; + } + + if (!e.altKey && this._keyStatus.altKey) { + this._keyStatus.lastKeyReleased = 'alt'; + } else if (!e.ctrlKey && this._keyStatus.ctrlKey) { + this._keyStatus.lastKeyReleased = 'ctrl'; + } else if (!e.metaKey && this._keyStatus.metaKey) { + this._keyStatus.lastKeyReleased = 'meta'; + } else if (!e.shiftKey && this._keyStatus.shiftKey) { + this._keyStatus.lastKeyReleased = 'shift'; + } else { + this._keyStatus.lastKeyReleased = undefined; + } + + if (this._keyStatus.lastKeyPressed !== this._keyStatus.lastKeyReleased) { + this._keyStatus.lastKeyPressed = undefined; + } + + this._keyStatus.altKey = e.altKey; + this._keyStatus.ctrlKey = e.ctrlKey; + this._keyStatus.metaKey = e.metaKey; + this._keyStatus.shiftKey = e.shiftKey; + + if (this._keyStatus.lastKeyReleased) { + this._keyStatus.event = e; + this.fire(this._keyStatus); + } + }, true)); + + disposables.add(addDisposableListener(window.document.body, 'mousedown', () => { + this._keyStatus.lastKeyPressed = undefined; + }, true)); + + disposables.add(addDisposableListener(window.document.body, 'mouseup', () => { + this._keyStatus.lastKeyPressed = undefined; + }, true)); + + disposables.add(addDisposableListener(window.document.body, 'mousemove', e => { + if (e.buttons) { + this._keyStatus.lastKeyPressed = undefined; + } + }, true)); + + disposables.add(addDisposableListener(window, 'blur', () => { + this.resetKeyStatus(); + })); + } + + get keyStatus(): IModifierKeyStatus { + return this._keyStatus; + } + + get isModifierPressed(): boolean { + return this._keyStatus.altKey || this._keyStatus.ctrlKey || this._keyStatus.metaKey || this._keyStatus.shiftKey; + } + + /** + * Allows to explicitly reset the key status based on more knowledge (#109062) + */ + resetKeyStatus(): void { + this.doResetKeyStatus(); + this.fire(this._keyStatus); + } + + private doResetKeyStatus(): void { + this._keyStatus = { + altKey: false, + shiftKey: false, + ctrlKey: false, + metaKey: false + }; + } + + static getInstance() { + if (!ModifierKeyEmitter.instance) { + ModifierKeyEmitter.instance = new ModifierKeyEmitter(); + } + + return ModifierKeyEmitter.instance; + } + + override dispose() { + super.dispose(); + this._subscriptions.dispose(); + } +} + +export function getCookieValue(name: string): string | undefined { + const match = document.cookie.match('(^|[^;]+)\\s*' + name + '\\s*=\\s*([^;]+)'); // See https://stackoverflow.com/a/25490531 + + return match ? match.pop() : undefined; +} + +export interface IDragAndDropObserverCallbacks { + readonly onDragEnter?: (e: DragEvent) => void; + readonly onDragLeave?: (e: DragEvent) => void; + readonly onDrop?: (e: DragEvent) => void; + readonly onDragEnd?: (e: DragEvent) => void; + readonly onDragStart?: (e: DragEvent) => void; + readonly onDrag?: (e: DragEvent) => void; + readonly onDragOver?: (e: DragEvent, dragDuration: number) => void; +} + +export class DragAndDropObserver extends Disposable { + + // A helper to fix issues with repeated DRAG_ENTER / DRAG_LEAVE + // calls see https://github.com/microsoft/vscode/issues/14470 + // when the element has child elements where the events are fired + // repeadedly. + private counter: number = 0; + + // Allows to measure the duration of the drag operation. + private dragStartTime = 0; + + constructor(private readonly element: HTMLElement, private readonly callbacks: IDragAndDropObserverCallbacks) { + super(); + + this.registerListeners(); + } + + private registerListeners(): void { + if (this.callbacks.onDragStart) { + this._register(addDisposableListener(this.element, EventType.DRAG_START, (e: DragEvent) => { + this.callbacks.onDragStart?.(e); + })); + } + + if (this.callbacks.onDrag) { + this._register(addDisposableListener(this.element, EventType.DRAG, (e: DragEvent) => { + this.callbacks.onDrag?.(e); + })); + } + + this._register(addDisposableListener(this.element, EventType.DRAG_ENTER, (e: DragEvent) => { + this.counter++; + this.dragStartTime = e.timeStamp; + + this.callbacks.onDragEnter?.(e); + })); + + this._register(addDisposableListener(this.element, EventType.DRAG_OVER, (e: DragEvent) => { + e.preventDefault(); // needed so that the drop event fires (https://stackoverflow.com/questions/21339924/drop-event-not-firing-in-chrome) + + this.callbacks.onDragOver?.(e, e.timeStamp - this.dragStartTime); + })); + + this._register(addDisposableListener(this.element, EventType.DRAG_LEAVE, (e: DragEvent) => { + this.counter--; + + if (this.counter === 0) { + this.dragStartTime = 0; + + this.callbacks.onDragLeave?.(e); + } + })); + + this._register(addDisposableListener(this.element, EventType.DRAG_END, (e: DragEvent) => { + this.counter = 0; + this.dragStartTime = 0; + + this.callbacks.onDragEnd?.(e); + })); + + this._register(addDisposableListener(this.element, EventType.DROP, (e: DragEvent) => { + this.counter = 0; + this.dragStartTime = 0; + + this.callbacks.onDrop?.(e); + })); + } +} + +type HTMLElementAttributeKeys = Partial<{ [K in keyof T]: T[K] extends Function ? never : T[K] extends object ? HTMLElementAttributeKeys : T[K] }>; +type ElementAttributes = HTMLElementAttributeKeys & Record; +type RemoveHTMLElement = T extends HTMLElement ? never : T; +type UnionToIntersection = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never; +type ArrayToObj = UnionToIntersection>; +type HHTMLElementTagNameMap = HTMLElementTagNameMap & { '': HTMLDivElement }; + +type TagToElement = T extends `${infer TStart}#${string}` + ? TStart extends keyof HHTMLElementTagNameMap + ? HHTMLElementTagNameMap[TStart] + : HTMLElement + : T extends `${infer TStart}.${string}` + ? TStart extends keyof HHTMLElementTagNameMap + ? HHTMLElementTagNameMap[TStart] + : HTMLElement + : T extends keyof HTMLElementTagNameMap + ? HTMLElementTagNameMap[T] + : HTMLElement; + +type TagToElementAndId = TTag extends `${infer TTag}@${infer TId}` + ? { element: TagToElement; id: TId } + : { element: TagToElement; id: 'root' }; + +type TagToRecord = TagToElementAndId extends { element: infer TElement; id: infer TId } + ? Record<(TId extends string ? TId : never) | 'root', TElement> + : never; + +type Child = HTMLElement | string | Record; + +const H_REGEX = /(?[\w\-]+)?(?:#(?[\w\-]+))?(?(?:\.(?:[\w\-]+))*)(?:@(?(?:[\w\_])+))?/; + +/** + * A helper function to create nested dom nodes. + * + * + * ```ts + * const elements = h('div.code-view', [ + * h('div.title@title'), + * h('div.container', [ + * h('div.gutter@gutterDiv'), + * h('div@editor'), + * ]), + * ]); + * const editor = createEditor(elements.editor); + * ``` +*/ +export function h + (tag: TTag): + TagToRecord extends infer Y ? { [TKey in keyof Y]: Y[TKey] } : never; + +export function h + (tag: TTag, children: [...T]): + (ArrayToObj & TagToRecord) extends infer Y ? { [TKey in keyof Y]: Y[TKey] } : never; + +export function h + (tag: TTag, attributes: Partial>>): + TagToRecord extends infer Y ? { [TKey in keyof Y]: Y[TKey] } : never; + +export function h + (tag: TTag, attributes: Partial>>, children: [...T]): + (ArrayToObj & TagToRecord) extends infer Y ? { [TKey in keyof Y]: Y[TKey] } : never; + +export function h(tag: string, ...args: [] | [attributes: { $: string } & Partial> | Record, children?: any[]] | [children: any[]]): Record { + let attributes: { $?: string } & Partial>; + let children: (Record | HTMLElement)[] | undefined; + + if (Array.isArray(args[0])) { + attributes = {}; + children = args[0]; + } else { + attributes = args[0] as any || {}; + children = args[1]; + } + + const match = H_REGEX.exec(tag); + + if (!match || !match.groups) { + throw new Error('Bad use of h'); + } + + const tagName = match.groups['tag'] || 'div'; + const el = document.createElement(tagName); + + if (match.groups['id']) { + el.id = match.groups['id']; + } + + const classNames = []; + if (match.groups['class']) { + for (const className of match.groups['class'].split('.')) { + if (className !== '') { + classNames.push(className); + } + } + } + if (attributes.className !== undefined) { + for (const className of attributes.className.split('.')) { + if (className !== '') { + classNames.push(className); + } + } + } + if (classNames.length > 0) { + el.className = classNames.join(' '); + } + + const result: Record = {}; + + if (match.groups['name']) { + result[match.groups['name']] = el; + } + + if (children) { + for (const c of children) { + if (isHTMLElement(c)) { + el.appendChild(c); + } else if (typeof c === 'string') { + el.append(c); + } else if ('root' in c) { + Object.assign(result, c); + el.appendChild(c.root); + } + } + } + + for (const [key, value] of Object.entries(attributes)) { + if (key === 'className') { + continue; + } else if (key === 'style') { + for (const [cssKey, cssValue] of Object.entries(value)) { + el.style.setProperty( + camelCaseToHyphenCase(cssKey), + typeof cssValue === 'number' ? cssValue + 'px' : '' + cssValue + ); + } + } else if (key === 'tabIndex') { + el.tabIndex = value; + } else { + el.setAttribute(camelCaseToHyphenCase(key), value.toString()); + } + } + + result['root'] = el; + + return result; +} + +export function svgElem + (tag: TTag): + TagToRecord extends infer Y ? { [TKey in keyof Y]: Y[TKey] } : never; + +export function svgElem + (tag: TTag, children: [...T]): + (ArrayToObj & TagToRecord) extends infer Y ? { [TKey in keyof Y]: Y[TKey] } : never; + +export function svgElem + (tag: TTag, attributes: Partial>>): + TagToRecord extends infer Y ? { [TKey in keyof Y]: Y[TKey] } : never; + +export function svgElem + (tag: TTag, attributes: Partial>>, children: [...T]): + (ArrayToObj & TagToRecord) extends infer Y ? { [TKey in keyof Y]: Y[TKey] } : never; + +export function svgElem(tag: string, ...args: [] | [attributes: { $: string } & Partial> | Record, children?: any[]] | [children: any[]]): Record { + let attributes: { $?: string } & Partial>; + let children: (Record | HTMLElement)[] | undefined; + + if (Array.isArray(args[0])) { + attributes = {}; + children = args[0]; + } else { + attributes = args[0] as any || {}; + children = args[1]; + } + + const match = H_REGEX.exec(tag); + + if (!match || !match.groups) { + throw new Error('Bad use of h'); + } + + const tagName = match.groups['tag'] || 'div'; + const el = document.createElementNS('http://www.w3.org/2000/svg', tagName) as any as HTMLElement; + + if (match.groups['id']) { + el.id = match.groups['id']; + } + + const classNames = []; + if (match.groups['class']) { + for (const className of match.groups['class'].split('.')) { + if (className !== '') { + classNames.push(className); + } + } + } + if (attributes.className !== undefined) { + for (const className of attributes.className.split('.')) { + if (className !== '') { + classNames.push(className); + } + } + } + if (classNames.length > 0) { + el.className = classNames.join(' '); + } + + const result: Record = {}; + + if (match.groups['name']) { + result[match.groups['name']] = el; + } + + if (children) { + for (const c of children) { + if (isHTMLElement(c)) { + el.appendChild(c); + } else if (typeof c === 'string') { + el.append(c); + } else if ('root' in c) { + Object.assign(result, c); + el.appendChild(c.root); + } + } + } + + for (const [key, value] of Object.entries(attributes)) { + if (key === 'className') { + continue; + } else if (key === 'style') { + for (const [cssKey, cssValue] of Object.entries(value)) { + el.style.setProperty( + camelCaseToHyphenCase(cssKey), + typeof cssValue === 'number' ? cssValue + 'px' : '' + cssValue + ); + } + } else if (key === 'tabIndex') { + el.tabIndex = value; + } else { + el.setAttribute(camelCaseToHyphenCase(key), value.toString()); + } + } + + result['root'] = el; + + return result; +} + +function camelCaseToHyphenCase(str: string) { + return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase(); +} + +export function copyAttributes(from: Element, to: Element, filter?: string[]): void { + for (const { name, value } of from.attributes) { + if (!filter || filter.includes(name)) { + to.setAttribute(name, value); + } + } +} + +function copyAttribute(from: Element, to: Element, name: string): void { + const value = from.getAttribute(name); + if (value) { + to.setAttribute(name, value); + } else { + to.removeAttribute(name); + } +} + +export function trackAttributes(from: Element, to: Element, filter?: string[]): IDisposable { + copyAttributes(from, to, filter); + + const disposables = new DisposableStore(); + + disposables.add(sharedMutationObserver.observe(from, disposables, { attributes: true, attributeFilter: filter })(mutations => { + for (const mutation of mutations) { + if (mutation.type === 'attributes' && mutation.attributeName) { + copyAttribute(from, to, mutation.attributeName); + } + } + })); + + return disposables; +} + +/** + * Helper for calculating the "safe triangle" occluded by hovers to avoid early dismissal. + * @see https://www.smashingmagazine.com/2023/08/better-context-menus-safe-triangles/ for example + */ +export class SafeTriangle { + // 4 triangles, 2 points (x, y) stored for each + private triangles: number[] = []; + + constructor( + private readonly originX: number, + private readonly originY: number, + target: HTMLElement + ) { + const { top, left, right, bottom } = target.getBoundingClientRect(); + const t = this.triangles; + let i = 0; + + t[i++] = left; + t[i++] = top; + t[i++] = right; + t[i++] = top; + + t[i++] = left; + t[i++] = top; + t[i++] = left; + t[i++] = bottom; + + t[i++] = right; + t[i++] = top; + t[i++] = right; + t[i++] = bottom; + + t[i++] = left; + t[i++] = bottom; + t[i++] = right; + t[i++] = bottom; + } + + public contains(x: number, y: number) { + const { triangles, originX, originY } = this; + for (let i = 0; i < 4; i++) { + if (isPointWithinTriangle(x, y, originX, originY, triangles[2 * i], triangles[2 * i + 1], triangles[2 * i + 2], triangles[2 * i + 3])) { + return true; + } + } + + return false; + } +} diff --git a/node_modules/@xterm/xterm/src/vs/base/browser/fastDomNode.ts b/node_modules/@xterm/xterm/src/vs/base/browser/fastDomNode.ts new file mode 100644 index 0000000..1ef17e4 --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/browser/fastDomNode.ts @@ -0,0 +1,316 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +export class FastDomNode { + + private _maxWidth: string = ''; + private _width: string = ''; + private _height: string = ''; + private _top: string = ''; + private _left: string = ''; + private _bottom: string = ''; + private _right: string = ''; + private _paddingTop: string = ''; + private _paddingLeft: string = ''; + private _paddingBottom: string = ''; + private _paddingRight: string = ''; + private _fontFamily: string = ''; + private _fontWeight: string = ''; + private _fontSize: string = ''; + private _fontStyle: string = ''; + private _fontFeatureSettings: string = ''; + private _fontVariationSettings: string = ''; + private _textDecoration: string = ''; + private _lineHeight: string = ''; + private _letterSpacing: string = ''; + private _className: string = ''; + private _display: string = ''; + private _position: string = ''; + private _visibility: string = ''; + private _color: string = ''; + private _backgroundColor: string = ''; + private _layerHint: boolean = false; + private _contain: 'none' | 'strict' | 'content' | 'size' | 'layout' | 'style' | 'paint' = 'none'; + private _boxShadow: string = ''; + + constructor( + public readonly domNode: T + ) { } + + public setMaxWidth(_maxWidth: number | string): void { + const maxWidth = numberAsPixels(_maxWidth); + if (this._maxWidth === maxWidth) { + return; + } + this._maxWidth = maxWidth; + this.domNode.style.maxWidth = this._maxWidth; + } + + public setWidth(_width: number | string): void { + const width = numberAsPixels(_width); + if (this._width === width) { + return; + } + this._width = width; + this.domNode.style.width = this._width; + } + + public setHeight(_height: number | string): void { + const height = numberAsPixels(_height); + if (this._height === height) { + return; + } + this._height = height; + this.domNode.style.height = this._height; + } + + public setTop(_top: number | string): void { + const top = numberAsPixels(_top); + if (this._top === top) { + return; + } + this._top = top; + this.domNode.style.top = this._top; + } + + public setLeft(_left: number | string): void { + const left = numberAsPixels(_left); + if (this._left === left) { + return; + } + this._left = left; + this.domNode.style.left = this._left; + } + + public setBottom(_bottom: number | string): void { + const bottom = numberAsPixels(_bottom); + if (this._bottom === bottom) { + return; + } + this._bottom = bottom; + this.domNode.style.bottom = this._bottom; + } + + public setRight(_right: number | string): void { + const right = numberAsPixels(_right); + if (this._right === right) { + return; + } + this._right = right; + this.domNode.style.right = this._right; + } + + public setPaddingTop(_paddingTop: number | string): void { + const paddingTop = numberAsPixels(_paddingTop); + if (this._paddingTop === paddingTop) { + return; + } + this._paddingTop = paddingTop; + this.domNode.style.paddingTop = this._paddingTop; + } + + public setPaddingLeft(_paddingLeft: number | string): void { + const paddingLeft = numberAsPixels(_paddingLeft); + if (this._paddingLeft === paddingLeft) { + return; + } + this._paddingLeft = paddingLeft; + this.domNode.style.paddingLeft = this._paddingLeft; + } + + public setPaddingBottom(_paddingBottom: number | string): void { + const paddingBottom = numberAsPixels(_paddingBottom); + if (this._paddingBottom === paddingBottom) { + return; + } + this._paddingBottom = paddingBottom; + this.domNode.style.paddingBottom = this._paddingBottom; + } + + public setPaddingRight(_paddingRight: number | string): void { + const paddingRight = numberAsPixels(_paddingRight); + if (this._paddingRight === paddingRight) { + return; + } + this._paddingRight = paddingRight; + this.domNode.style.paddingRight = this._paddingRight; + } + + public setFontFamily(fontFamily: string): void { + if (this._fontFamily === fontFamily) { + return; + } + this._fontFamily = fontFamily; + this.domNode.style.fontFamily = this._fontFamily; + } + + public setFontWeight(fontWeight: string): void { + if (this._fontWeight === fontWeight) { + return; + } + this._fontWeight = fontWeight; + this.domNode.style.fontWeight = this._fontWeight; + } + + public setFontSize(_fontSize: number | string): void { + const fontSize = numberAsPixels(_fontSize); + if (this._fontSize === fontSize) { + return; + } + this._fontSize = fontSize; + this.domNode.style.fontSize = this._fontSize; + } + + public setFontStyle(fontStyle: string): void { + if (this._fontStyle === fontStyle) { + return; + } + this._fontStyle = fontStyle; + this.domNode.style.fontStyle = this._fontStyle; + } + + public setFontFeatureSettings(fontFeatureSettings: string): void { + if (this._fontFeatureSettings === fontFeatureSettings) { + return; + } + this._fontFeatureSettings = fontFeatureSettings; + this.domNode.style.fontFeatureSettings = this._fontFeatureSettings; + } + + public setFontVariationSettings(fontVariationSettings: string): void { + if (this._fontVariationSettings === fontVariationSettings) { + return; + } + this._fontVariationSettings = fontVariationSettings; + this.domNode.style.fontVariationSettings = this._fontVariationSettings; + } + + public setTextDecoration(textDecoration: string): void { + if (this._textDecoration === textDecoration) { + return; + } + this._textDecoration = textDecoration; + this.domNode.style.textDecoration = this._textDecoration; + } + + public setLineHeight(_lineHeight: number | string): void { + const lineHeight = numberAsPixels(_lineHeight); + if (this._lineHeight === lineHeight) { + return; + } + this._lineHeight = lineHeight; + this.domNode.style.lineHeight = this._lineHeight; + } + + public setLetterSpacing(_letterSpacing: number | string): void { + const letterSpacing = numberAsPixels(_letterSpacing); + if (this._letterSpacing === letterSpacing) { + return; + } + this._letterSpacing = letterSpacing; + this.domNode.style.letterSpacing = this._letterSpacing; + } + + public setClassName(className: string): void { + if (this._className === className) { + return; + } + this._className = className; + this.domNode.className = this._className; + } + + public toggleClassName(className: string, shouldHaveIt?: boolean): void { + this.domNode.classList.toggle(className, shouldHaveIt); + this._className = this.domNode.className; + } + + public setDisplay(display: string): void { + if (this._display === display) { + return; + } + this._display = display; + this.domNode.style.display = this._display; + } + + public setPosition(position: string): void { + if (this._position === position) { + return; + } + this._position = position; + this.domNode.style.position = this._position; + } + + public setVisibility(visibility: string): void { + if (this._visibility === visibility) { + return; + } + this._visibility = visibility; + this.domNode.style.visibility = this._visibility; + } + + public setColor(color: string): void { + if (this._color === color) { + return; + } + this._color = color; + this.domNode.style.color = this._color; + } + + public setBackgroundColor(backgroundColor: string): void { + if (this._backgroundColor === backgroundColor) { + return; + } + this._backgroundColor = backgroundColor; + this.domNode.style.backgroundColor = this._backgroundColor; + } + + public setLayerHinting(layerHint: boolean): void { + if (this._layerHint === layerHint) { + return; + } + this._layerHint = layerHint; + this.domNode.style.transform = this._layerHint ? 'translate3d(0px, 0px, 0px)' : ''; + } + + public setBoxShadow(boxShadow: string): void { + if (this._boxShadow === boxShadow) { + return; + } + this._boxShadow = boxShadow; + this.domNode.style.boxShadow = boxShadow; + } + + public setContain(contain: 'none' | 'strict' | 'content' | 'size' | 'layout' | 'style' | 'paint'): void { + if (this._contain === contain) { + return; + } + this._contain = contain; + (this.domNode.style).contain = this._contain; + } + + public setAttribute(name: string, value: string): void { + this.domNode.setAttribute(name, value); + } + + public removeAttribute(name: string): void { + this.domNode.removeAttribute(name); + } + + public appendChild(child: FastDomNode): void { + this.domNode.appendChild(child.domNode); + } + + public removeChild(child: FastDomNode): void { + this.domNode.removeChild(child.domNode); + } +} + +function numberAsPixels(value: number | string): string { + return (typeof value === 'number' ? `${value}px` : value); +} + +export function createFastDomNode(domNode: T): FastDomNode { + return new FastDomNode(domNode); +} diff --git a/node_modules/@xterm/xterm/src/vs/base/browser/globalPointerMoveMonitor.ts b/node_modules/@xterm/xterm/src/vs/base/browser/globalPointerMoveMonitor.ts new file mode 100644 index 0000000..9841596 --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/browser/globalPointerMoveMonitor.ts @@ -0,0 +1,112 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import * as dom from 'vs/base/browser/dom'; +import { DisposableStore, IDisposable, toDisposable } from 'vs/base/common/lifecycle'; + +export interface IPointerMoveCallback { + (event: PointerEvent): void; +} + +export interface IOnStopCallback { + (browserEvent?: PointerEvent | KeyboardEvent): void; +} + +export class GlobalPointerMoveMonitor implements IDisposable { + + private readonly _hooks = new DisposableStore(); + private _pointerMoveCallback: IPointerMoveCallback | null = null; + private _onStopCallback: IOnStopCallback | null = null; + + public dispose(): void { + this.stopMonitoring(false); + this._hooks.dispose(); + } + + public stopMonitoring(invokeStopCallback: boolean, browserEvent?: PointerEvent | KeyboardEvent): void { + if (!this.isMonitoring()) { + // Not monitoring + return; + } + + // Unhook + this._hooks.clear(); + this._pointerMoveCallback = null; + const onStopCallback = this._onStopCallback; + this._onStopCallback = null; + + if (invokeStopCallback && onStopCallback) { + onStopCallback(browserEvent); + } + } + + public isMonitoring(): boolean { + return !!this._pointerMoveCallback; + } + + public startMonitoring( + initialElement: Element, + pointerId: number, + initialButtons: number, + pointerMoveCallback: IPointerMoveCallback, + onStopCallback: IOnStopCallback + ): void { + if (this.isMonitoring()) { + this.stopMonitoring(false); + } + this._pointerMoveCallback = pointerMoveCallback; + this._onStopCallback = onStopCallback; + + let eventSource: Element | Window = initialElement; + + try { + initialElement.setPointerCapture(pointerId); + this._hooks.add(toDisposable(() => { + try { + initialElement.releasePointerCapture(pointerId); + } catch (err) { + // See https://github.com/microsoft/vscode/issues/161731 + // + // `releasePointerCapture` sometimes fails when being invoked with the exception: + // DOMException: Failed to execute 'releasePointerCapture' on 'Element': + // No active pointer with the given id is found. + // + // There's no need to do anything in case of failure + } + })); + } catch (err) { + // See https://github.com/microsoft/vscode/issues/144584 + // See https://github.com/microsoft/vscode/issues/146947 + // `setPointerCapture` sometimes fails when being invoked + // from a `mousedown` listener on macOS and Windows + // and it always fails on Linux with the exception: + // DOMException: Failed to execute 'setPointerCapture' on 'Element': + // No active pointer with the given id is found. + // In case of failure, we bind the listeners on the window + eventSource = dom.getWindow(initialElement); + } + + this._hooks.add(dom.addDisposableListener( + eventSource, + dom.EventType.POINTER_MOVE, + (e) => { + if (e.buttons !== initialButtons) { + // Buttons state has changed in the meantime + this.stopMonitoring(true); + return; + } + + e.preventDefault(); + this._pointerMoveCallback!(e); + } + )); + + this._hooks.add(dom.addDisposableListener( + eventSource, + dom.EventType.POINTER_UP, + (e: PointerEvent) => this.stopMonitoring(true) + )); + } +} diff --git a/node_modules/@xterm/xterm/src/vs/base/browser/iframe.ts b/node_modules/@xterm/xterm/src/vs/base/browser/iframe.ts new file mode 100644 index 0000000..e8522e0 --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/browser/iframe.ts @@ -0,0 +1,135 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +/** + * Represents a window in a possible chain of iframes + */ +interface IWindowChainElement { + /** + * The window object for it + */ + readonly window: WeakRef; + /** + * The iframe element inside the window.parent corresponding to window + */ + readonly iframeElement: Element | null; +} + +const sameOriginWindowChainCache = new WeakMap(); + +function getParentWindowIfSameOrigin(w: Window): Window | null { + if (!w.parent || w.parent === w) { + return null; + } + + // Cannot really tell if we have access to the parent window unless we try to access something in it + try { + const location = w.location; + const parentLocation = w.parent.location; + if (location.origin !== 'null' && parentLocation.origin !== 'null' && location.origin !== parentLocation.origin) { + return null; + } + } catch (e) { + return null; + } + + return w.parent; +} + +export class IframeUtils { + + /** + * Returns a chain of embedded windows with the same origin (which can be accessed programmatically). + * Having a chain of length 1 might mean that the current execution environment is running outside of an iframe or inside an iframe embedded in a window with a different origin. + */ + private static getSameOriginWindowChain(targetWindow: Window): IWindowChainElement[] { + let windowChainCache = sameOriginWindowChainCache.get(targetWindow); + if (!windowChainCache) { + windowChainCache = []; + sameOriginWindowChainCache.set(targetWindow, windowChainCache); + let w: Window | null = targetWindow; + let parent: Window | null; + do { + parent = getParentWindowIfSameOrigin(w); + if (parent) { + windowChainCache.push({ + window: new WeakRef(w), + iframeElement: w.frameElement || null + }); + } else { + windowChainCache.push({ + window: new WeakRef(w), + iframeElement: null + }); + } + w = parent; + } while (w); + } + return windowChainCache.slice(0); + } + + /** + * Returns the position of `childWindow` relative to `ancestorWindow` + */ + public static getPositionOfChildWindowRelativeToAncestorWindow(childWindow: Window, ancestorWindow: Window | null) { + + if (!ancestorWindow || childWindow === ancestorWindow) { + return { + top: 0, + left: 0 + }; + } + + let top = 0, left = 0; + + const windowChain = this.getSameOriginWindowChain(childWindow); + + for (const windowChainEl of windowChain) { + const windowInChain = windowChainEl.window.deref(); + top += windowInChain?.scrollY ?? 0; + left += windowInChain?.scrollX ?? 0; + + if (windowInChain === ancestorWindow) { + break; + } + + if (!windowChainEl.iframeElement) { + break; + } + + const boundingRect = windowChainEl.iframeElement.getBoundingClientRect(); + top += boundingRect.top; + left += boundingRect.left; + } + + return { + top: top, + left: left + }; + } +} + +/** + * Returns a sha-256 composed of `parentOrigin` and `salt` converted to base 32 + */ +export async function parentOriginHash(parentOrigin: string, salt: string): Promise { + // This same code is also inlined at `src/vs/workbench/services/extensions/worker/webWorkerExtensionHostIframe.html` + if (!crypto.subtle) { + throw new Error(`'crypto.subtle' is not available so webviews will not work. This is likely because the editor is not running in a secure context (https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts).`); + } + + const strData = JSON.stringify({ parentOrigin, salt }); + const encoder = new TextEncoder(); + const arrData = encoder.encode(strData); + const hash = await crypto.subtle.digest('sha-256', arrData); + return sha256AsBase32(hash); +} + +function sha256AsBase32(bytes: ArrayBuffer): string { + const array = Array.from(new Uint8Array(bytes)); + const hexArray = array.map(b => b.toString(16).padStart(2, '0')).join(''); + // sha256 has 256 bits, so we need at most ceil(lg(2^256-1)/lg(32)) = 52 chars to represent it in base 32 + return BigInt(`0x${hexArray}`).toString(32).padStart(52, '0'); +} diff --git a/node_modules/@xterm/xterm/src/vs/base/browser/keyboardEvent.ts b/node_modules/@xterm/xterm/src/vs/base/browser/keyboardEvent.ts new file mode 100644 index 0000000..6aa5bf5 --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/browser/keyboardEvent.ts @@ -0,0 +1,213 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import * as browser from 'vs/base/browser/browser'; +import { EVENT_KEY_CODE_MAP, KeyCode, KeyCodeUtils, KeyMod } from 'vs/base/common/keyCodes'; +import { KeyCodeChord } from 'vs/base/common/keybindings'; +import * as platform from 'vs/base/common/platform'; + + + +function extractKeyCode(e: KeyboardEvent): KeyCode { + if (e.charCode) { + // "keypress" events mostly + const char = String.fromCharCode(e.charCode).toUpperCase(); + return KeyCodeUtils.fromString(char); + } + + const keyCode = e.keyCode; + + // browser quirks + if (keyCode === 3) { + return KeyCode.PauseBreak; + } else if (browser.isFirefox) { + switch (keyCode) { + case 59: return KeyCode.Semicolon; + case 60: + if (platform.isLinux) { return KeyCode.IntlBackslash; } + break; + case 61: return KeyCode.Equal; + // based on: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode#numpad_keys + case 107: return KeyCode.NumpadAdd; + case 109: return KeyCode.NumpadSubtract; + case 173: return KeyCode.Minus; + case 224: + if (platform.isMacintosh) { return KeyCode.Meta; } + break; + } + } else if (browser.isWebKit) { + if (platform.isMacintosh && keyCode === 93) { + // the two meta keys in the Mac have different key codes (91 and 93) + return KeyCode.Meta; + } else if (!platform.isMacintosh && keyCode === 92) { + return KeyCode.Meta; + } + } + + // cross browser keycodes: + return EVENT_KEY_CODE_MAP[keyCode] || KeyCode.Unknown; +} + +export interface IKeyboardEvent { + + readonly _standardKeyboardEventBrand: true; + + readonly browserEvent: KeyboardEvent; + readonly target: HTMLElement; + + readonly ctrlKey: boolean; + readonly shiftKey: boolean; + readonly altKey: boolean; + readonly metaKey: boolean; + readonly altGraphKey: boolean; + readonly keyCode: KeyCode; + readonly code: string; + + /** + * @internal + */ + toKeyCodeChord(): KeyCodeChord; + equals(keybinding: number): boolean; + + preventDefault(): void; + stopPropagation(): void; +} + +const ctrlKeyMod = (platform.isMacintosh ? KeyMod.WinCtrl : KeyMod.CtrlCmd); +const altKeyMod = KeyMod.Alt; +const shiftKeyMod = KeyMod.Shift; +const metaKeyMod = (platform.isMacintosh ? KeyMod.CtrlCmd : KeyMod.WinCtrl); + +export function printKeyboardEvent(e: KeyboardEvent): string { + const modifiers: string[] = []; + if (e.ctrlKey) { + modifiers.push(`ctrl`); + } + if (e.shiftKey) { + modifiers.push(`shift`); + } + if (e.altKey) { + modifiers.push(`alt`); + } + if (e.metaKey) { + modifiers.push(`meta`); + } + return `modifiers: [${modifiers.join(',')}], code: ${e.code}, keyCode: ${e.keyCode}, key: ${e.key}`; +} + +export function printStandardKeyboardEvent(e: StandardKeyboardEvent): string { + const modifiers: string[] = []; + if (e.ctrlKey) { + modifiers.push(`ctrl`); + } + if (e.shiftKey) { + modifiers.push(`shift`); + } + if (e.altKey) { + modifiers.push(`alt`); + } + if (e.metaKey) { + modifiers.push(`meta`); + } + return `modifiers: [${modifiers.join(',')}], code: ${e.code}, keyCode: ${e.keyCode} ('${KeyCodeUtils.toString(e.keyCode)}')`; +} + +export class StandardKeyboardEvent implements IKeyboardEvent { + + readonly _standardKeyboardEventBrand = true; + + public readonly browserEvent: KeyboardEvent; + public readonly target: HTMLElement; + + public readonly ctrlKey: boolean; + public readonly shiftKey: boolean; + public readonly altKey: boolean; + public readonly metaKey: boolean; + public readonly altGraphKey: boolean; + public readonly keyCode: KeyCode; + public readonly code: string; + + private _asKeybinding: number; + private _asKeyCodeChord: KeyCodeChord; + + constructor(source: KeyboardEvent) { + const e = source; + + this.browserEvent = e; + this.target = e.target; + + this.ctrlKey = e.ctrlKey; + this.shiftKey = e.shiftKey; + this.altKey = e.altKey; + this.metaKey = e.metaKey; + this.altGraphKey = e.getModifierState?.('AltGraph'); + this.keyCode = extractKeyCode(e); + this.code = e.code; + + // console.info(e.type + ": keyCode: " + e.keyCode + ", which: " + e.which + ", charCode: " + e.charCode + ", detail: " + e.detail + " ====> " + this.keyCode + ' -- ' + KeyCode[this.keyCode]); + + this.ctrlKey = this.ctrlKey || this.keyCode === KeyCode.Ctrl; + this.altKey = this.altKey || this.keyCode === KeyCode.Alt; + this.shiftKey = this.shiftKey || this.keyCode === KeyCode.Shift; + this.metaKey = this.metaKey || this.keyCode === KeyCode.Meta; + + this._asKeybinding = this._computeKeybinding(); + this._asKeyCodeChord = this._computeKeyCodeChord(); + + // console.log(`code: ${e.code}, keyCode: ${e.keyCode}, key: ${e.key}`); + } + + public preventDefault(): void { + if (this.browserEvent && this.browserEvent.preventDefault) { + this.browserEvent.preventDefault(); + } + } + + public stopPropagation(): void { + if (this.browserEvent && this.browserEvent.stopPropagation) { + this.browserEvent.stopPropagation(); + } + } + + public toKeyCodeChord(): KeyCodeChord { + return this._asKeyCodeChord; + } + + public equals(other: number): boolean { + return this._asKeybinding === other; + } + + private _computeKeybinding(): number { + let key = KeyCode.Unknown; + if (this.keyCode !== KeyCode.Ctrl && this.keyCode !== KeyCode.Shift && this.keyCode !== KeyCode.Alt && this.keyCode !== KeyCode.Meta) { + key = this.keyCode; + } + + let result = 0; + if (this.ctrlKey) { + result |= ctrlKeyMod; + } + if (this.altKey) { + result |= altKeyMod; + } + if (this.shiftKey) { + result |= shiftKeyMod; + } + if (this.metaKey) { + result |= metaKeyMod; + } + result |= key; + + return result; + } + + private _computeKeyCodeChord(): KeyCodeChord { + let key = KeyCode.Unknown; + if (this.keyCode !== KeyCode.Ctrl && this.keyCode !== KeyCode.Shift && this.keyCode !== KeyCode.Alt && this.keyCode !== KeyCode.Meta) { + key = this.keyCode; + } + return new KeyCodeChord(this.ctrlKey, this.shiftKey, this.altKey, this.metaKey, key); + } +} diff --git a/node_modules/@xterm/xterm/src/vs/base/browser/mouseEvent.ts b/node_modules/@xterm/xterm/src/vs/base/browser/mouseEvent.ts new file mode 100644 index 0000000..51de015 --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/browser/mouseEvent.ts @@ -0,0 +1,229 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import * as browser from 'vs/base/browser/browser'; +import { IframeUtils } from 'vs/base/browser/iframe'; +import * as platform from 'vs/base/common/platform'; + +export interface IMouseEvent { + readonly browserEvent: MouseEvent; + readonly leftButton: boolean; + readonly middleButton: boolean; + readonly rightButton: boolean; + readonly buttons: number; + readonly target: HTMLElement; + readonly detail: number; + readonly posx: number; + readonly posy: number; + readonly ctrlKey: boolean; + readonly shiftKey: boolean; + readonly altKey: boolean; + readonly metaKey: boolean; + readonly timestamp: number; + + preventDefault(): void; + stopPropagation(): void; +} + +export class StandardMouseEvent implements IMouseEvent { + + public readonly browserEvent: MouseEvent; + + public readonly leftButton: boolean; + public readonly middleButton: boolean; + public readonly rightButton: boolean; + public readonly buttons: number; + public readonly target: HTMLElement; + public detail: number; + public readonly posx: number; + public readonly posy: number; + public readonly ctrlKey: boolean; + public readonly shiftKey: boolean; + public readonly altKey: boolean; + public readonly metaKey: boolean; + public readonly timestamp: number; + + constructor(targetWindow: Window, e: MouseEvent) { + this.timestamp = Date.now(); + this.browserEvent = e; + this.leftButton = e.button === 0; + this.middleButton = e.button === 1; + this.rightButton = e.button === 2; + this.buttons = e.buttons; + + this.target = e.target; + + this.detail = e.detail || 1; + if (e.type === 'dblclick') { + this.detail = 2; + } + this.ctrlKey = e.ctrlKey; + this.shiftKey = e.shiftKey; + this.altKey = e.altKey; + this.metaKey = e.metaKey; + + if (typeof e.pageX === 'number') { + this.posx = e.pageX; + this.posy = e.pageY; + } else { + // Probably hit by MSGestureEvent + this.posx = e.clientX + this.target.ownerDocument.body.scrollLeft + this.target.ownerDocument.documentElement.scrollLeft; + this.posy = e.clientY + this.target.ownerDocument.body.scrollTop + this.target.ownerDocument.documentElement.scrollTop; + } + + // Find the position of the iframe this code is executing in relative to the iframe where the event was captured. + const iframeOffsets = IframeUtils.getPositionOfChildWindowRelativeToAncestorWindow(targetWindow, e.view); + this.posx -= iframeOffsets.left; + this.posy -= iframeOffsets.top; + } + + public preventDefault(): void { + this.browserEvent.preventDefault(); + } + + public stopPropagation(): void { + this.browserEvent.stopPropagation(); + } +} + +export class DragMouseEvent extends StandardMouseEvent { + + public readonly dataTransfer: DataTransfer; + + constructor(targetWindow: Window, e: MouseEvent) { + super(targetWindow, e); + this.dataTransfer = (e).dataTransfer; + } +} + +export interface IMouseWheelEvent extends MouseEvent { + readonly wheelDelta: number; + readonly wheelDeltaX: number; + readonly wheelDeltaY: number; + + readonly deltaX: number; + readonly deltaY: number; + readonly deltaZ: number; + readonly deltaMode: number; +} + +interface IWebKitMouseWheelEvent { + wheelDeltaY: number; + wheelDeltaX: number; +} + +interface IGeckoMouseWheelEvent { + HORIZONTAL_AXIS: number; + VERTICAL_AXIS: number; + axis: number; + detail: number; +} + +export class StandardWheelEvent { + + public readonly browserEvent: IMouseWheelEvent | null; + public readonly deltaY: number; + public readonly deltaX: number; + public readonly target: Node; + + constructor(e: IMouseWheelEvent | null, deltaX: number = 0, deltaY: number = 0) { + + this.browserEvent = e || null; + this.target = e ? (e.target || (e).targetNode || e.srcElement) : null; + + this.deltaY = deltaY; + this.deltaX = deltaX; + + let shouldFactorDPR: boolean = false; + if (browser.isChrome) { + // Chrome version >= 123 contains the fix to factor devicePixelRatio into the wheel event. + // See https://chromium.googlesource.com/chromium/src.git/+/be51b448441ff0c9d1f17e0f25c4bf1ab3f11f61 + const chromeVersionMatch = navigator.userAgent.match(/Chrome\/(\d+)/); + const chromeMajorVersion = chromeVersionMatch ? parseInt(chromeVersionMatch[1]) : 123; + shouldFactorDPR = chromeMajorVersion <= 122; + } + + if (e) { + // Old (deprecated) wheel events + const e1 = e; + const e2 = e; + const devicePixelRatio = e.view?.devicePixelRatio || 1; + + // vertical delta scroll + if (typeof e1.wheelDeltaY !== 'undefined') { + if (shouldFactorDPR) { + // Refs https://github.com/microsoft/vscode/issues/146403#issuecomment-1854538928 + this.deltaY = e1.wheelDeltaY / (120 * devicePixelRatio); + } else { + this.deltaY = e1.wheelDeltaY / 120; + } + } else if (typeof e2.VERTICAL_AXIS !== 'undefined' && e2.axis === e2.VERTICAL_AXIS) { + this.deltaY = -e2.detail / 3; + } else if (e.type === 'wheel') { + // Modern wheel event + // https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent + const ev = e; + + if (ev.deltaMode === ev.DOM_DELTA_LINE) { + // the deltas are expressed in lines + if (browser.isFirefox && !platform.isMacintosh) { + this.deltaY = -e.deltaY / 3; + } else { + this.deltaY = -e.deltaY; + } + } else { + this.deltaY = -e.deltaY / 40; + } + } + + // horizontal delta scroll + if (typeof e1.wheelDeltaX !== 'undefined') { + if (browser.isSafari && platform.isWindows) { + this.deltaX = - (e1.wheelDeltaX / 120); + } else if (shouldFactorDPR) { + // Refs https://github.com/microsoft/vscode/issues/146403#issuecomment-1854538928 + this.deltaX = e1.wheelDeltaX / (120 * devicePixelRatio); + } else { + this.deltaX = e1.wheelDeltaX / 120; + } + } else if (typeof e2.HORIZONTAL_AXIS !== 'undefined' && e2.axis === e2.HORIZONTAL_AXIS) { + this.deltaX = -e.detail / 3; + } else if (e.type === 'wheel') { + // Modern wheel event + // https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent + const ev = e; + + if (ev.deltaMode === ev.DOM_DELTA_LINE) { + // the deltas are expressed in lines + if (browser.isFirefox && !platform.isMacintosh) { + this.deltaX = -e.deltaX / 3; + } else { + this.deltaX = -e.deltaX; + } + } else { + this.deltaX = -e.deltaX / 40; + } + } + + // Assume a vertical scroll if nothing else worked + if (this.deltaY === 0 && this.deltaX === 0 && e.wheelDelta) { + if (shouldFactorDPR) { + // Refs https://github.com/microsoft/vscode/issues/146403#issuecomment-1854538928 + this.deltaY = e.wheelDelta / (120 * devicePixelRatio); + } else { + this.deltaY = e.wheelDelta / 120; + } + } + } + } + + public preventDefault(): void { + this.browserEvent?.preventDefault(); + } + + public stopPropagation(): void { + this.browserEvent?.stopPropagation(); + } +} diff --git a/node_modules/@xterm/xterm/src/vs/base/browser/touch.ts b/node_modules/@xterm/xterm/src/vs/base/browser/touch.ts new file mode 100644 index 0000000..a4e8dff --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/browser/touch.ts @@ -0,0 +1,372 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import * as DomUtils from 'vs/base/browser/dom'; +import { mainWindow } from 'vs/base/browser/window'; +import * as arrays from 'vs/base/common/arrays'; +import { memoize } from 'vs/base/common/decorators'; +import { Event as EventUtils } from 'vs/base/common/event'; +import { Disposable, IDisposable, markAsSingleton, toDisposable } from 'vs/base/common/lifecycle'; +import { LinkedList } from 'vs/base/common/linkedList'; + +export namespace EventType { + export const Tap = '-xterm-gesturetap'; + export const Change = '-xterm-gesturechange'; + export const Start = '-xterm-gesturestart'; + export const End = '-xterm-gesturesend'; + export const Contextmenu = '-xterm-gesturecontextmenu'; +} + +interface TouchData { + id: number; + initialTarget: EventTarget; + initialTimeStamp: number; + initialPageX: number; + initialPageY: number; + rollingTimestamps: number[]; + rollingPageX: number[]; + rollingPageY: number[]; +} + +export interface GestureEvent extends MouseEvent { + initialTarget: EventTarget | undefined; + translationX: number; + translationY: number; + pageX: number; + pageY: number; + tapCount: number; +} + +interface Touch { + identifier: number; + screenX: number; + screenY: number; + clientX: number; + clientY: number; + pageX: number; + pageY: number; + radiusX: number; + radiusY: number; + rotationAngle: number; + force: number; + target: Element; +} + +interface TouchList { + [i: number]: Touch; + length: number; + item(index: number): Touch; + identifiedTouch(id: number): Touch; +} + +interface TouchEvent extends Event { + touches: TouchList; + targetTouches: TouchList; + changedTouches: TouchList; +} + +export class Gesture extends Disposable { + + private static readonly SCROLL_FRICTION = -0.005; + private static INSTANCE: Gesture; + private static readonly HOLD_DELAY = 700; + + private dispatched = false; + private readonly targets = new LinkedList(); + private readonly ignoreTargets = new LinkedList(); + private handle: IDisposable | null; + + private readonly activeTouches: { [id: number]: TouchData }; + + private _lastSetTapCountTime: number; + + private static readonly CLEAR_TAP_COUNT_TIME = 400; // ms + + + private constructor() { + super(); + + this.activeTouches = {}; + this.handle = null; + this._lastSetTapCountTime = 0; + + this._register(EventUtils.runAndSubscribe(DomUtils.onDidRegisterWindow, ({ window, disposables }) => { + disposables.add(DomUtils.addDisposableListener(window.document, 'touchstart', (e: TouchEvent) => this.onTouchStart(e), { passive: false })); + disposables.add(DomUtils.addDisposableListener(window.document, 'touchend', (e: TouchEvent) => this.onTouchEnd(window, e))); + disposables.add(DomUtils.addDisposableListener(window.document, 'touchmove', (e: TouchEvent) => this.onTouchMove(e), { passive: false })); + }, { window: mainWindow, disposables: this._store })); + } + + public static addTarget(element: HTMLElement): IDisposable { + if (!Gesture.isTouchDevice()) { + return Disposable.None; + } + if (!Gesture.INSTANCE) { + Gesture.INSTANCE = markAsSingleton(new Gesture()); + } + + const remove = Gesture.INSTANCE.targets.push(element); + return toDisposable(remove); + } + + public static ignoreTarget(element: HTMLElement): IDisposable { + if (!Gesture.isTouchDevice()) { + return Disposable.None; + } + if (!Gesture.INSTANCE) { + Gesture.INSTANCE = markAsSingleton(new Gesture()); + } + + const remove = Gesture.INSTANCE.ignoreTargets.push(element); + return toDisposable(remove); + } + + @memoize + static isTouchDevice(): boolean { + // `'ontouchstart' in window` always evaluates to true with typescript's modern typings. This causes `window` to be + // `never` later in `window.navigator`. That's why we need the explicit `window as Window` cast + return 'ontouchstart' in mainWindow || navigator.maxTouchPoints > 0; + } + + public override dispose(): void { + if (this.handle) { + this.handle.dispose(); + this.handle = null; + } + + super.dispose(); + } + + private onTouchStart(e: TouchEvent): void { + const timestamp = Date.now(); // use Date.now() because on FF e.timeStamp is not epoch based. + + if (this.handle) { + this.handle.dispose(); + this.handle = null; + } + + for (let i = 0, len = e.targetTouches.length; i < len; i++) { + const touch = e.targetTouches.item(i); + + this.activeTouches[touch.identifier] = { + id: touch.identifier, + initialTarget: touch.target, + initialTimeStamp: timestamp, + initialPageX: touch.pageX, + initialPageY: touch.pageY, + rollingTimestamps: [timestamp], + rollingPageX: [touch.pageX], + rollingPageY: [touch.pageY] + }; + + const evt = this.newGestureEvent(EventType.Start, touch.target); + evt.pageX = touch.pageX; + evt.pageY = touch.pageY; + this.dispatchEvent(evt); + } + + if (this.dispatched) { + e.preventDefault(); + e.stopPropagation(); + this.dispatched = false; + } + } + + private onTouchEnd(targetWindow: Window, e: TouchEvent): void { + const timestamp = Date.now(); // use Date.now() because on FF e.timeStamp is not epoch based. + + const activeTouchCount = Object.keys(this.activeTouches).length; + + for (let i = 0, len = e.changedTouches.length; i < len; i++) { + + const touch = e.changedTouches.item(i); + + if (!this.activeTouches.hasOwnProperty(String(touch.identifier))) { + console.warn('move of an UNKNOWN touch', touch); + continue; + } + + const data = this.activeTouches[touch.identifier], + holdTime = Date.now() - data.initialTimeStamp; + + if (holdTime < Gesture.HOLD_DELAY + && Math.abs(data.initialPageX - arrays.tail(data.rollingPageX)!) < 30 + && Math.abs(data.initialPageY - arrays.tail(data.rollingPageY)!) < 30) { + + const evt = this.newGestureEvent(EventType.Tap, data.initialTarget); + evt.pageX = arrays.tail(data.rollingPageX)!; + evt.pageY = arrays.tail(data.rollingPageY)!; + this.dispatchEvent(evt); + + } else if (holdTime >= Gesture.HOLD_DELAY + && Math.abs(data.initialPageX - arrays.tail(data.rollingPageX)!) < 30 + && Math.abs(data.initialPageY - arrays.tail(data.rollingPageY)!) < 30) { + + const evt = this.newGestureEvent(EventType.Contextmenu, data.initialTarget); + evt.pageX = arrays.tail(data.rollingPageX)!; + evt.pageY = arrays.tail(data.rollingPageY)!; + this.dispatchEvent(evt); + + } else if (activeTouchCount === 1) { + const finalX = arrays.tail(data.rollingPageX)!; + const finalY = arrays.tail(data.rollingPageY)!; + + const deltaT = arrays.tail(data.rollingTimestamps)! - data.rollingTimestamps[0]; + const deltaX = finalX - data.rollingPageX[0]; + const deltaY = finalY - data.rollingPageY[0]; + + // We need to get all the dispatch targets on the start of the inertia event + const dispatchTo = [...this.targets].filter(t => data.initialTarget instanceof Node && t.contains(data.initialTarget)); + this.inertia(targetWindow, dispatchTo, timestamp, // time now + Math.abs(deltaX) / deltaT, // speed + deltaX > 0 ? 1 : -1, // x direction + finalX, // x now + Math.abs(deltaY) / deltaT, // y speed + deltaY > 0 ? 1 : -1, // y direction + finalY // y now + ); + } + + + this.dispatchEvent(this.newGestureEvent(EventType.End, data.initialTarget)); + // forget about this touch + delete this.activeTouches[touch.identifier]; + } + + if (this.dispatched) { + e.preventDefault(); + e.stopPropagation(); + this.dispatched = false; + } + } + + private newGestureEvent(type: string, initialTarget?: EventTarget): GestureEvent { + const event = document.createEvent('CustomEvent') as unknown as GestureEvent; + event.initEvent(type, false, true); + event.initialTarget = initialTarget; + event.tapCount = 0; + return event; + } + + private dispatchEvent(event: GestureEvent): void { + if (event.type === EventType.Tap) { + const currentTime = (new Date()).getTime(); + let setTapCount = 0; + if (currentTime - this._lastSetTapCountTime > Gesture.CLEAR_TAP_COUNT_TIME) { + setTapCount = 1; + } else { + setTapCount = 2; + } + + this._lastSetTapCountTime = currentTime; + event.tapCount = setTapCount; + } else if (event.type === EventType.Change || event.type === EventType.Contextmenu) { + // tap is canceled by scrolling or context menu + this._lastSetTapCountTime = 0; + } + + if (event.initialTarget instanceof Node) { + for (const ignoreTarget of this.ignoreTargets) { + if (ignoreTarget.contains(event.initialTarget)) { + return; + } + } + + const targets: [number, HTMLElement][] = []; + for (const target of this.targets) { + if (target.contains(event.initialTarget)) { + let depth = 0; + let now: Node | null = event.initialTarget; + while (now && now !== target) { + depth++; + now = now.parentElement; + } + targets.push([depth, target]); + } + } + + targets.sort((a, b) => a[0] - b[0]); + + for (const [_, target] of targets) { + target.dispatchEvent(event); + this.dispatched = true; + } + } + } + + private inertia(targetWindow: Window, dispatchTo: readonly EventTarget[], t1: number, vX: number, dirX: number, x: number, vY: number, dirY: number, y: number): void { + this.handle = DomUtils.scheduleAtNextAnimationFrame(targetWindow, () => { + const now = Date.now(); + + // velocity: old speed + accel_over_time + const deltaT = now - t1; + let delta_pos_x = 0, delta_pos_y = 0; + let stopped = true; + + vX += Gesture.SCROLL_FRICTION * deltaT; + vY += Gesture.SCROLL_FRICTION * deltaT; + + if (vX > 0) { + stopped = false; + delta_pos_x = dirX * vX * deltaT; + } + + if (vY > 0) { + stopped = false; + delta_pos_y = dirY * vY * deltaT; + } + + // dispatch translation event + const evt = this.newGestureEvent(EventType.Change); + evt.translationX = delta_pos_x; + evt.translationY = delta_pos_y; + dispatchTo.forEach(d => d.dispatchEvent(evt)); + + if (!stopped) { + this.inertia(targetWindow, dispatchTo, now, vX, dirX, x + delta_pos_x, vY, dirY, y + delta_pos_y); + } + }); + } + + private onTouchMove(e: TouchEvent): void { + const timestamp = Date.now(); // use Date.now() because on FF e.timeStamp is not epoch based. + + for (let i = 0, len = e.changedTouches.length; i < len; i++) { + + const touch = e.changedTouches.item(i); + + if (!this.activeTouches.hasOwnProperty(String(touch.identifier))) { + console.warn('end of an UNKNOWN touch', touch); + continue; + } + + const data = this.activeTouches[touch.identifier]; + + const evt = this.newGestureEvent(EventType.Change, data.initialTarget); + evt.translationX = touch.pageX - arrays.tail(data.rollingPageX)!; + evt.translationY = touch.pageY - arrays.tail(data.rollingPageY)!; + evt.pageX = touch.pageX; + evt.pageY = touch.pageY; + this.dispatchEvent(evt); + + // only keep a few data points, to average the final speed + if (data.rollingPageX.length > 3) { + data.rollingPageX.shift(); + data.rollingPageY.shift(); + data.rollingTimestamps.shift(); + } + + data.rollingPageX.push(touch.pageX); + data.rollingPageY.push(touch.pageY); + data.rollingTimestamps.push(timestamp); + } + + if (this.dispatched) { + e.preventDefault(); + e.stopPropagation(); + this.dispatched = false; + } + } +} diff --git a/node_modules/@xterm/xterm/src/vs/base/browser/ui/scrollbar/abstractScrollbar.ts b/node_modules/@xterm/xterm/src/vs/base/browser/ui/scrollbar/abstractScrollbar.ts new file mode 100644 index 0000000..5ab7539 --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/browser/ui/scrollbar/abstractScrollbar.ts @@ -0,0 +1,303 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import * as dom from 'vs/base/browser/dom'; +import { createFastDomNode, FastDomNode } from 'vs/base/browser/fastDomNode'; +import { GlobalPointerMoveMonitor } from 'vs/base/browser/globalPointerMoveMonitor'; +import { StandardWheelEvent } from 'vs/base/browser/mouseEvent'; +import { ScrollbarArrow, ScrollbarArrowOptions } from 'vs/base/browser/ui/scrollbar/scrollbarArrow'; +import { ScrollbarState } from 'vs/base/browser/ui/scrollbar/scrollbarState'; +import { ScrollbarVisibilityController } from 'vs/base/browser/ui/scrollbar/scrollbarVisibilityController'; +import { Widget } from 'vs/base/browser/ui/widget'; +import * as platform from 'vs/base/common/platform'; +import { INewScrollPosition, Scrollable, ScrollbarVisibility } from 'vs/base/common/scrollable'; + +/** + * The orthogonal distance to the slider at which dragging "resets". This implements "snapping" + */ +const POINTER_DRAG_RESET_DISTANCE = 140; + +export interface ISimplifiedPointerEvent { + buttons: number; + pageX: number; + pageY: number; +} + +export interface ScrollbarHost { + onMouseWheel(mouseWheelEvent: StandardWheelEvent): void; + onDragStart(): void; + onDragEnd(): void; +} + +export interface AbstractScrollbarOptions { + lazyRender: boolean; + host: ScrollbarHost; + scrollbarState: ScrollbarState; + visibility: ScrollbarVisibility; + extraScrollbarClassName: string; + scrollable: Scrollable; + scrollByPage: boolean; +} + +export abstract class AbstractScrollbar extends Widget { + + protected _host: ScrollbarHost; + protected _scrollable: Scrollable; + protected _scrollByPage: boolean; + private _lazyRender: boolean; + protected _scrollbarState: ScrollbarState; + protected _visibilityController: ScrollbarVisibilityController; + private _pointerMoveMonitor: GlobalPointerMoveMonitor; + + public domNode: FastDomNode; + public slider!: FastDomNode; + + protected _shouldRender: boolean; + + constructor(opts: AbstractScrollbarOptions) { + super(); + this._lazyRender = opts.lazyRender; + this._host = opts.host; + this._scrollable = opts.scrollable; + this._scrollByPage = opts.scrollByPage; + this._scrollbarState = opts.scrollbarState; + this._visibilityController = this._register(new ScrollbarVisibilityController(opts.visibility, 'visible scrollbar ' + opts.extraScrollbarClassName, 'invisible scrollbar ' + opts.extraScrollbarClassName)); + this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()); + this._pointerMoveMonitor = this._register(new GlobalPointerMoveMonitor()); + this._shouldRender = true; + this.domNode = createFastDomNode(document.createElement('div')); + this.domNode.setAttribute('role', 'presentation'); + this.domNode.setAttribute('aria-hidden', 'true'); + + this._visibilityController.setDomNode(this.domNode); + this.domNode.setPosition('absolute'); + + this._register(dom.addDisposableListener(this.domNode.domNode, dom.EventType.POINTER_DOWN, (e: PointerEvent) => this._domNodePointerDown(e))); + } + + // ----------------- creation + + /** + * Creates the dom node for an arrow & adds it to the container + */ + protected _createArrow(opts: ScrollbarArrowOptions): void { + const arrow = this._register(new ScrollbarArrow(opts)); + this.domNode.domNode.appendChild(arrow.bgDomNode); + this.domNode.domNode.appendChild(arrow.domNode); + } + + /** + * Creates the slider dom node, adds it to the container & hooks up the events + */ + protected _createSlider(top: number, left: number, width: number | undefined, height: number | undefined): void { + this.slider = createFastDomNode(document.createElement('div')); + this.slider.setClassName('slider'); + this.slider.setPosition('absolute'); + this.slider.setTop(top); + this.slider.setLeft(left); + if (typeof width === 'number') { + this.slider.setWidth(width); + } + if (typeof height === 'number') { + this.slider.setHeight(height); + } + this.slider.setLayerHinting(true); + this.slider.setContain('strict'); + + this.domNode.domNode.appendChild(this.slider.domNode); + + this._register(dom.addDisposableListener( + this.slider.domNode, + dom.EventType.POINTER_DOWN, + (e: PointerEvent) => { + if (e.button === 0) { + e.preventDefault(); + this._sliderPointerDown(e); + } + } + )); + + this.onclick(this.slider.domNode, e => { + if (e.leftButton) { + e.stopPropagation(); + } + }); + } + + // ----------------- Update state + + protected _onElementSize(visibleSize: number): boolean { + if (this._scrollbarState.setVisibleSize(visibleSize)) { + this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()); + this._shouldRender = true; + if (!this._lazyRender) { + this.render(); + } + } + return this._shouldRender; + } + + protected _onElementScrollSize(elementScrollSize: number): boolean { + if (this._scrollbarState.setScrollSize(elementScrollSize)) { + this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()); + this._shouldRender = true; + if (!this._lazyRender) { + this.render(); + } + } + return this._shouldRender; + } + + protected _onElementScrollPosition(elementScrollPosition: number): boolean { + if (this._scrollbarState.setScrollPosition(elementScrollPosition)) { + this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()); + this._shouldRender = true; + if (!this._lazyRender) { + this.render(); + } + } + return this._shouldRender; + } + + // ----------------- rendering + + public beginReveal(): void { + this._visibilityController.setShouldBeVisible(true); + } + + public beginHide(): void { + this._visibilityController.setShouldBeVisible(false); + } + + public render(): void { + if (!this._shouldRender) { + return; + } + this._shouldRender = false; + + this._renderDomNode(this._scrollbarState.getRectangleLargeSize(), this._scrollbarState.getRectangleSmallSize()); + this._updateSlider(this._scrollbarState.getSliderSize(), this._scrollbarState.getArrowSize() + this._scrollbarState.getSliderPosition()); + } + // ----------------- DOM events + + private _domNodePointerDown(e: PointerEvent): void { + if (e.target !== this.domNode.domNode) { + return; + } + this._onPointerDown(e); + } + + public delegatePointerDown(e: PointerEvent): void { + const domTop = this.domNode.domNode.getClientRects()[0].top; + const sliderStart = domTop + this._scrollbarState.getSliderPosition(); + const sliderStop = domTop + this._scrollbarState.getSliderPosition() + this._scrollbarState.getSliderSize(); + const pointerPos = this._sliderPointerPosition(e); + if (sliderStart <= pointerPos && pointerPos <= sliderStop) { + // Act as if it was a pointer down on the slider + if (e.button === 0) { + e.preventDefault(); + this._sliderPointerDown(e); + } + } else { + // Act as if it was a pointer down on the scrollbar + this._onPointerDown(e); + } + } + + private _onPointerDown(e: PointerEvent): void { + let offsetX: number; + let offsetY: number; + if (e.target === this.domNode.domNode && typeof e.offsetX === 'number' && typeof e.offsetY === 'number') { + offsetX = e.offsetX; + offsetY = e.offsetY; + } else { + const domNodePosition = dom.getDomNodePagePosition(this.domNode.domNode); + offsetX = e.pageX - domNodePosition.left; + offsetY = e.pageY - domNodePosition.top; + } + + const offset = this._pointerDownRelativePosition(offsetX, offsetY); + this._setDesiredScrollPositionNow( + this._scrollByPage + ? this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(offset) + : this._scrollbarState.getDesiredScrollPositionFromOffset(offset) + ); + + if (e.button === 0) { + // left button + e.preventDefault(); + this._sliderPointerDown(e); + } + } + + private _sliderPointerDown(e: PointerEvent): void { + if (!e.target || !(e.target instanceof Element)) { + return; + } + const initialPointerPosition = this._sliderPointerPosition(e); + const initialPointerOrthogonalPosition = this._sliderOrthogonalPointerPosition(e); + const initialScrollbarState = this._scrollbarState.clone(); + this.slider.toggleClassName('active', true); + + this._pointerMoveMonitor.startMonitoring( + e.target, + e.pointerId, + e.buttons, + (pointerMoveData: PointerEvent) => { + const pointerOrthogonalPosition = this._sliderOrthogonalPointerPosition(pointerMoveData); + const pointerOrthogonalDelta = Math.abs(pointerOrthogonalPosition - initialPointerOrthogonalPosition); + + if (platform.isWindows && pointerOrthogonalDelta > POINTER_DRAG_RESET_DISTANCE) { + // The pointer has wondered away from the scrollbar => reset dragging + this._setDesiredScrollPositionNow(initialScrollbarState.getScrollPosition()); + return; + } + + const pointerPosition = this._sliderPointerPosition(pointerMoveData); + const pointerDelta = pointerPosition - initialPointerPosition; + this._setDesiredScrollPositionNow(initialScrollbarState.getDesiredScrollPositionFromDelta(pointerDelta)); + }, + () => { + this.slider.toggleClassName('active', false); + this._host.onDragEnd(); + } + ); + + this._host.onDragStart(); + } + + private _setDesiredScrollPositionNow(_desiredScrollPosition: number): void { + + const desiredScrollPosition: INewScrollPosition = {}; + this.writeScrollPosition(desiredScrollPosition, _desiredScrollPosition); + + this._scrollable.setScrollPositionNow(desiredScrollPosition); + } + + public updateScrollbarSize(scrollbarSize: number): void { + this._updateScrollbarSize(scrollbarSize); + this._scrollbarState.setScrollbarSize(scrollbarSize); + this._shouldRender = true; + if (!this._lazyRender) { + this.render(); + } + } + + public isNeeded(): boolean { + return this._scrollbarState.isNeeded(); + } + + // ----------------- Overwrite these + + protected abstract _renderDomNode(largeSize: number, smallSize: number): void; + protected abstract _updateSlider(sliderSize: number, sliderPosition: number): void; + + protected abstract _pointerDownRelativePosition(offsetX: number, offsetY: number): number; + protected abstract _sliderPointerPosition(e: ISimplifiedPointerEvent): number; + protected abstract _sliderOrthogonalPointerPosition(e: ISimplifiedPointerEvent): number; + protected abstract _updateScrollbarSize(size: number): void; + + public abstract writeScrollPosition(target: INewScrollPosition, scrollPosition: number): void; +} diff --git a/node_modules/@xterm/xterm/src/vs/base/browser/ui/scrollbar/horizontalScrollbar.ts b/node_modules/@xterm/xterm/src/vs/base/browser/ui/scrollbar/horizontalScrollbar.ts new file mode 100644 index 0000000..e64e422 --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/browser/ui/scrollbar/horizontalScrollbar.ts @@ -0,0 +1,114 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { AbstractScrollbar, ISimplifiedPointerEvent, ScrollbarHost } from 'vs/base/browser/ui/scrollbar/abstractScrollbar'; +import { ScrollableElementResolvedOptions } from 'vs/base/browser/ui/scrollbar/scrollableElementOptions'; +import { ScrollbarState } from 'vs/base/browser/ui/scrollbar/scrollbarState'; +import { INewScrollPosition, Scrollable, ScrollbarVisibility, ScrollEvent } from 'vs/base/common/scrollable'; + + + + +export class HorizontalScrollbar extends AbstractScrollbar { + + constructor(scrollable: Scrollable, options: ScrollableElementResolvedOptions, host: ScrollbarHost) { + const scrollDimensions = scrollable.getScrollDimensions(); + const scrollPosition = scrollable.getCurrentScrollPosition(); + super({ + lazyRender: options.lazyRender, + host: host, + scrollbarState: new ScrollbarState( + (options.horizontalHasArrows ? options.arrowSize : 0), + (options.horizontal === ScrollbarVisibility.Hidden ? 0 : options.horizontalScrollbarSize), + (options.vertical === ScrollbarVisibility.Hidden ? 0 : options.verticalScrollbarSize), + scrollDimensions.width, + scrollDimensions.scrollWidth, + scrollPosition.scrollLeft + ), + visibility: options.horizontal, + extraScrollbarClassName: 'horizontal', + scrollable: scrollable, + scrollByPage: options.scrollByPage + }); + + if (options.horizontalHasArrows) { + throw new Error('horizontalHasArrows is not supported in xterm.js'); + // const arrowDelta = (options.arrowSize - ARROW_IMG_SIZE) / 2; + // const scrollbarDelta = (options.horizontalScrollbarSize - ARROW_IMG_SIZE) / 2; + + // this._createArrow({ + // className: 'scra', + // icon: Codicon.scrollbarButtonLeft, + // top: scrollbarDelta, + // left: arrowDelta, + // bottom: undefined, + // right: undefined, + // bgWidth: options.arrowSize, + // bgHeight: options.horizontalScrollbarSize, + // onActivate: () => this._host.onMouseWheel(new StandardWheelEvent(null, 1, 0)), + // }); + + // this._createArrow({ + // className: 'scra', + // icon: Codicon.scrollbarButtonRight, + // top: scrollbarDelta, + // left: undefined, + // bottom: undefined, + // right: arrowDelta, + // bgWidth: options.arrowSize, + // bgHeight: options.horizontalScrollbarSize, + // onActivate: () => this._host.onMouseWheel(new StandardWheelEvent(null, -1, 0)), + // }); + } + + this._createSlider(Math.floor((options.horizontalScrollbarSize - options.horizontalSliderSize) / 2), 0, undefined, options.horizontalSliderSize); + } + + protected _updateSlider(sliderSize: number, sliderPosition: number): void { + this.slider.setWidth(sliderSize); + this.slider.setLeft(sliderPosition); + } + + protected _renderDomNode(largeSize: number, smallSize: number): void { + this.domNode.setWidth(largeSize); + this.domNode.setHeight(smallSize); + this.domNode.setLeft(0); + this.domNode.setBottom(0); + } + + public onDidScroll(e: ScrollEvent): boolean { + this._shouldRender = this._onElementScrollSize(e.scrollWidth) || this._shouldRender; + this._shouldRender = this._onElementScrollPosition(e.scrollLeft) || this._shouldRender; + this._shouldRender = this._onElementSize(e.width) || this._shouldRender; + return this._shouldRender; + } + + protected _pointerDownRelativePosition(offsetX: number, offsetY: number): number { + return offsetX; + } + + protected _sliderPointerPosition(e: ISimplifiedPointerEvent): number { + return e.pageX; + } + + protected _sliderOrthogonalPointerPosition(e: ISimplifiedPointerEvent): number { + return e.pageY; + } + + protected _updateScrollbarSize(size: number): void { + this.slider.setHeight(size); + } + + public writeScrollPosition(target: INewScrollPosition, scrollPosition: number): void { + target.scrollLeft = scrollPosition; + } + + public updateOptions(options: ScrollableElementResolvedOptions): void { + this.updateScrollbarSize(options.horizontal === ScrollbarVisibility.Hidden ? 0 : options.horizontalScrollbarSize); + this._scrollbarState.setOppositeScrollbarSize(options.vertical === ScrollbarVisibility.Hidden ? 0 : options.verticalScrollbarSize); + this._visibilityController.setVisibility(options.horizontal); + this._scrollByPage = options.scrollByPage; + } +} diff --git a/node_modules/@xterm/xterm/src/vs/base/browser/ui/scrollbar/scrollableElement.ts b/node_modules/@xterm/xterm/src/vs/base/browser/ui/scrollbar/scrollableElement.ts new file mode 100644 index 0000000..b18d802 --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/browser/ui/scrollbar/scrollableElement.ts @@ -0,0 +1,720 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { getZoomFactor, isChrome } from 'vs/base/browser/browser'; +import * as dom from 'vs/base/browser/dom'; +import { FastDomNode, createFastDomNode } from 'vs/base/browser/fastDomNode'; +import { IMouseEvent, IMouseWheelEvent, StandardWheelEvent } from 'vs/base/browser/mouseEvent'; +import { ScrollbarHost } from 'vs/base/browser/ui/scrollbar/abstractScrollbar'; +import { HorizontalScrollbar } from 'vs/base/browser/ui/scrollbar/horizontalScrollbar'; +import { ScrollableElementChangeOptions, ScrollableElementCreationOptions, ScrollableElementResolvedOptions } from 'vs/base/browser/ui/scrollbar/scrollableElementOptions'; +import { VerticalScrollbar } from 'vs/base/browser/ui/scrollbar/verticalScrollbar'; +import { Widget } from 'vs/base/browser/ui/widget'; +import { TimeoutTimer } from 'vs/base/common/async'; +import { Emitter, Event } from 'vs/base/common/event'; +import { IDisposable, dispose } from 'vs/base/common/lifecycle'; +import * as platform from 'vs/base/common/platform'; +import { INewScrollDimensions, INewScrollPosition, IScrollDimensions, IScrollPosition, ScrollEvent, Scrollable, ScrollbarVisibility } from 'vs/base/common/scrollable'; +// import 'vs/css!./media/scrollbars'; + +const HIDE_TIMEOUT = 500; +const SCROLL_WHEEL_SENSITIVITY = 50; +const SCROLL_WHEEL_SMOOTH_SCROLL_ENABLED = true; + +export interface IOverviewRulerLayoutInfo { + parent: HTMLElement; + insertBefore: HTMLElement; +} + +class MouseWheelClassifierItem { + public timestamp: number; + public deltaX: number; + public deltaY: number; + public score: number; + + constructor(timestamp: number, deltaX: number, deltaY: number) { + this.timestamp = timestamp; + this.deltaX = deltaX; + this.deltaY = deltaY; + this.score = 0; + } +} + +export class MouseWheelClassifier { + + public static readonly INSTANCE = new MouseWheelClassifier(); + + private readonly _capacity: number; + private _memory: MouseWheelClassifierItem[]; + private _front: number; + private _rear: number; + + constructor() { + this._capacity = 5; + this._memory = []; + this._front = -1; + this._rear = -1; + } + + public isPhysicalMouseWheel(): boolean { + if (this._front === -1 && this._rear === -1) { + // no elements + return false; + } + + // 0.5 * last + 0.25 * 2nd last + 0.125 * 3rd last + ... + let remainingInfluence = 1; + let score = 0; + let iteration = 1; + + let index = this._rear; + do { + const influence = (index === this._front ? remainingInfluence : Math.pow(2, -iteration)); + remainingInfluence -= influence; + score += this._memory[index].score * influence; + + if (index === this._front) { + break; + } + + index = (this._capacity + index - 1) % this._capacity; + iteration++; + } while (true); + + return (score <= 0.5); + } + + public acceptStandardWheelEvent(e: StandardWheelEvent): void { + if (isChrome) { + const targetWindow = dom.getWindow(e.browserEvent); + const pageZoomFactor = getZoomFactor(targetWindow); + // On Chrome, the incoming delta events are multiplied with the OS zoom factor. + // The OS zoom factor can be reverse engineered by using the device pixel ratio and the configured zoom factor into account. + this.accept(Date.now(), e.deltaX * pageZoomFactor, e.deltaY * pageZoomFactor); + } else { + this.accept(Date.now(), e.deltaX, e.deltaY); + } + } + + public accept(timestamp: number, deltaX: number, deltaY: number): void { + let previousItem = null; + const item = new MouseWheelClassifierItem(timestamp, deltaX, deltaY); + + if (this._front === -1 && this._rear === -1) { + this._memory[0] = item; + this._front = 0; + this._rear = 0; + } else { + previousItem = this._memory[this._rear]; + + this._rear = (this._rear + 1) % this._capacity; + if (this._rear === this._front) { + // Drop oldest + this._front = (this._front + 1) % this._capacity; + } + this._memory[this._rear] = item; + } + + item.score = this._computeScore(item, previousItem); + } + + /** + * A score between 0 and 1 for `item`. + * - a score towards 0 indicates that the source appears to be a physical mouse wheel + * - a score towards 1 indicates that the source appears to be a touchpad or magic mouse, etc. + */ + private _computeScore(item: MouseWheelClassifierItem, previousItem: MouseWheelClassifierItem | null): number { + + if (Math.abs(item.deltaX) > 0 && Math.abs(item.deltaY) > 0) { + // both axes exercised => definitely not a physical mouse wheel + return 1; + } + + let score: number = 0.5; + + if (!this._isAlmostInt(item.deltaX) || !this._isAlmostInt(item.deltaY)) { + // non-integer deltas => indicator that this is not a physical mouse wheel + score += 0.25; + } + + // Non-accelerating scroll => indicator that this is a physical mouse wheel + // These can be identified by seeing whether they are the module of one another. + if (previousItem) { + const absDeltaX = Math.abs(item.deltaX); + const absDeltaY = Math.abs(item.deltaY); + + const absPreviousDeltaX = Math.abs(previousItem.deltaX); + const absPreviousDeltaY = Math.abs(previousItem.deltaY); + + // Min 1 to avoid division by zero, module 1 will still be 0. + const minDeltaX = Math.max(Math.min(absDeltaX, absPreviousDeltaX), 1); + const minDeltaY = Math.max(Math.min(absDeltaY, absPreviousDeltaY), 1); + + const maxDeltaX = Math.max(absDeltaX, absPreviousDeltaX); + const maxDeltaY = Math.max(absDeltaY, absPreviousDeltaY); + + const isSameModulo = (maxDeltaX % minDeltaX === 0 && maxDeltaY % minDeltaY === 0); + if (isSameModulo) { + score -= 0.5; + } + } + + return Math.min(Math.max(score, 0), 1); + } + + private _isAlmostInt(value: number): boolean { + const delta = Math.abs(Math.round(value) - value); + return (delta < 0.01); + } +} + +export abstract class AbstractScrollableElement extends Widget { + + private readonly _options: ScrollableElementResolvedOptions; + protected readonly _scrollable: Scrollable; + private readonly _verticalScrollbar: VerticalScrollbar; + private readonly _horizontalScrollbar: HorizontalScrollbar; + private readonly _domNode: HTMLElement; + + private readonly _leftShadowDomNode: FastDomNode | null; + private readonly _topShadowDomNode: FastDomNode | null; + private readonly _topLeftShadowDomNode: FastDomNode | null; + + private readonly _listenOnDomNode: HTMLElement; + + private _mouseWheelToDispose: IDisposable[]; + + private _isDragging: boolean; + private _mouseIsOver: boolean; + + private readonly _hideTimeout: TimeoutTimer; + private _shouldRender: boolean; + + private _revealOnScroll: boolean; + + private readonly _onScroll = this._register(new Emitter()); + public readonly onScroll: Event = this._onScroll.event; + + private readonly _onWillScroll = this._register(new Emitter()); + public readonly onWillScroll: Event = this._onWillScroll.event; + + public get options(): Readonly { + return this._options; + } + + protected constructor(element: HTMLElement, options: ScrollableElementCreationOptions, scrollable: Scrollable) { + super(); + // HACK: xterm.js currnetly requires overflow to allow decorations to escape the container + // element.style.overflow = 'hidden'; + this._options = resolveOptions(options); + this._scrollable = scrollable; + + this._register(this._scrollable.onScroll((e) => { + this._onWillScroll.fire(e); + this._onDidScroll(e); + this._onScroll.fire(e); + })); + + const scrollbarHost: ScrollbarHost = { + onMouseWheel: (mouseWheelEvent: StandardWheelEvent) => this._onMouseWheel(mouseWheelEvent), + onDragStart: () => this._onDragStart(), + onDragEnd: () => this._onDragEnd(), + }; + this._verticalScrollbar = this._register(new VerticalScrollbar(this._scrollable, this._options, scrollbarHost)); + this._horizontalScrollbar = this._register(new HorizontalScrollbar(this._scrollable, this._options, scrollbarHost)); + + this._domNode = document.createElement('div'); + this._domNode.className = 'xterm-scrollable-element ' + this._options.className; + this._domNode.setAttribute('role', 'presentation'); + this._domNode.style.position = 'relative'; + // HACK: xterm.js currnetly requires overflow to allow decorations to escape the container + // this._domNode.style.overflow = 'hidden'; + this._domNode.appendChild(element); + this._domNode.appendChild(this._horizontalScrollbar.domNode.domNode); + this._domNode.appendChild(this._verticalScrollbar.domNode.domNode); + + if (this._options.useShadows) { + this._leftShadowDomNode = createFastDomNode(document.createElement('div')); + this._leftShadowDomNode.setClassName('shadow'); + this._domNode.appendChild(this._leftShadowDomNode.domNode); + + this._topShadowDomNode = createFastDomNode(document.createElement('div')); + this._topShadowDomNode.setClassName('shadow'); + this._domNode.appendChild(this._topShadowDomNode.domNode); + + this._topLeftShadowDomNode = createFastDomNode(document.createElement('div')); + this._topLeftShadowDomNode.setClassName('shadow'); + this._domNode.appendChild(this._topLeftShadowDomNode.domNode); + } else { + this._leftShadowDomNode = null; + this._topShadowDomNode = null; + this._topLeftShadowDomNode = null; + } + + this._listenOnDomNode = this._options.listenOnDomNode || this._domNode; + + this._mouseWheelToDispose = []; + this._setListeningToMouseWheel(this._options.handleMouseWheel); + + this.onmouseover(this._listenOnDomNode, (e) => this._onMouseOver(e)); + this.onmouseleave(this._listenOnDomNode, (e) => this._onMouseLeave(e)); + + this._hideTimeout = this._register(new TimeoutTimer()); + this._isDragging = false; + this._mouseIsOver = false; + + this._shouldRender = true; + + this._revealOnScroll = true; + } + + public override dispose(): void { + this._mouseWheelToDispose = dispose(this._mouseWheelToDispose); + super.dispose(); + } + + /** + * Get the generated 'scrollable' dom node + */ + public getDomNode(): HTMLElement { + return this._domNode; + } + + public getOverviewRulerLayoutInfo(): IOverviewRulerLayoutInfo { + return { + parent: this._domNode, + insertBefore: this._verticalScrollbar.domNode.domNode, + }; + } + + /** + * Delegate a pointer down event to the vertical scrollbar. + * This is to help with clicking somewhere else and having the scrollbar react. + */ + public delegateVerticalScrollbarPointerDown(browserEvent: PointerEvent): void { + this._verticalScrollbar.delegatePointerDown(browserEvent); + } + + public getScrollDimensions(): IScrollDimensions { + return this._scrollable.getScrollDimensions(); + } + + public setScrollDimensions(dimensions: INewScrollDimensions): void { + this._scrollable.setScrollDimensions(dimensions, false); + } + + /** + * Update the class name of the scrollable element. + */ + public updateClassName(newClassName: string): void { + this._options.className = newClassName; + // Defaults are different on Macs + if (platform.isMacintosh) { + this._options.className += ' mac'; + } + this._domNode.className = 'xterm-scrollable-element ' + this._options.className; + } + + /** + * Update configuration options for the scrollbar. + */ + public updateOptions(newOptions: ScrollableElementChangeOptions): void { + if (typeof newOptions.handleMouseWheel !== 'undefined') { + this._options.handleMouseWheel = newOptions.handleMouseWheel; + this._setListeningToMouseWheel(this._options.handleMouseWheel); + } + if (typeof newOptions.mouseWheelScrollSensitivity !== 'undefined') { + this._options.mouseWheelScrollSensitivity = newOptions.mouseWheelScrollSensitivity; + } + if (typeof newOptions.fastScrollSensitivity !== 'undefined') { + this._options.fastScrollSensitivity = newOptions.fastScrollSensitivity; + } + if (typeof newOptions.scrollPredominantAxis !== 'undefined') { + this._options.scrollPredominantAxis = newOptions.scrollPredominantAxis; + } + if (typeof newOptions.horizontal !== 'undefined') { + this._options.horizontal = newOptions.horizontal; + } + if (typeof newOptions.vertical !== 'undefined') { + this._options.vertical = newOptions.vertical; + } + if (typeof newOptions.horizontalScrollbarSize !== 'undefined') { + this._options.horizontalScrollbarSize = newOptions.horizontalScrollbarSize; + } + if (typeof newOptions.verticalScrollbarSize !== 'undefined') { + this._options.verticalScrollbarSize = newOptions.verticalScrollbarSize; + } + if (typeof newOptions.scrollByPage !== 'undefined') { + this._options.scrollByPage = newOptions.scrollByPage; + } + this._horizontalScrollbar.updateOptions(this._options); + this._verticalScrollbar.updateOptions(this._options); + + if (!this._options.lazyRender) { + this._render(); + } + } + + public setRevealOnScroll(value: boolean) { + this._revealOnScroll = value; + } + + public delegateScrollFromMouseWheelEvent(browserEvent: IMouseWheelEvent) { + this._onMouseWheel(new StandardWheelEvent(browserEvent)); + } + + // -------------------- mouse wheel scrolling -------------------- + + private _setListeningToMouseWheel(shouldListen: boolean): void { + const isListening = (this._mouseWheelToDispose.length > 0); + + if (isListening === shouldListen) { + // No change + return; + } + + // Stop listening (if necessary) + this._mouseWheelToDispose = dispose(this._mouseWheelToDispose); + + // Start listening (if necessary) + if (shouldListen) { + const onMouseWheel = (browserEvent: IMouseWheelEvent) => { + this._onMouseWheel(new StandardWheelEvent(browserEvent)); + }; + + this._mouseWheelToDispose.push(dom.addDisposableListener(this._listenOnDomNode, dom.EventType.MOUSE_WHEEL, onMouseWheel, { passive: false })); + } + } + + private _onMouseWheel(e: StandardWheelEvent): void { + if (e.browserEvent?.defaultPrevented) { + return; + } + + const classifier = MouseWheelClassifier.INSTANCE; + if (SCROLL_WHEEL_SMOOTH_SCROLL_ENABLED) { + classifier.acceptStandardWheelEvent(e); + } + + // useful for creating unit tests: + // console.log(`${Date.now()}, ${e.deltaY}, ${e.deltaX}`); + + let didScroll = false; + + if (e.deltaY || e.deltaX) { + let deltaY = e.deltaY * this._options.mouseWheelScrollSensitivity; + let deltaX = e.deltaX * this._options.mouseWheelScrollSensitivity; + + if (this._options.scrollPredominantAxis) { + if (this._options.scrollYToX && deltaX + deltaY === 0) { + // when configured to map Y to X and we both see + // no dominant axis and X and Y are competing with + // identical values into opposite directions, we + // ignore the delta as we cannot make a decision then + deltaX = deltaY = 0; + } else if (Math.abs(deltaY) >= Math.abs(deltaX)) { + deltaX = 0; + } else { + deltaY = 0; + } + } + + if (this._options.flipAxes) { + [deltaY, deltaX] = [deltaX, deltaY]; + } + + // Convert vertical scrolling to horizontal if shift is held, this + // is handled at a higher level on Mac + const shiftConvert = !platform.isMacintosh && e.browserEvent && e.browserEvent.shiftKey; + if ((this._options.scrollYToX || shiftConvert) && !deltaX) { + deltaX = deltaY; + deltaY = 0; + } + + if (e.browserEvent && e.browserEvent.altKey) { + // fastScrolling + deltaX = deltaX * this._options.fastScrollSensitivity; + deltaY = deltaY * this._options.fastScrollSensitivity; + } + + const futureScrollPosition = this._scrollable.getFutureScrollPosition(); + + let desiredScrollPosition: INewScrollPosition = {}; + if (deltaY) { + const deltaScrollTop = SCROLL_WHEEL_SENSITIVITY * deltaY; + // Here we convert values such as -0.3 to -1 or 0.3 to 1, otherwise low speed scrolling will never scroll + const desiredScrollTop = futureScrollPosition.scrollTop - (deltaScrollTop < 0 ? Math.floor(deltaScrollTop) : Math.ceil(deltaScrollTop)); + this._verticalScrollbar.writeScrollPosition(desiredScrollPosition, desiredScrollTop); + } + if (deltaX) { + const deltaScrollLeft = SCROLL_WHEEL_SENSITIVITY * deltaX; + // Here we convert values such as -0.3 to -1 or 0.3 to 1, otherwise low speed scrolling will never scroll + const desiredScrollLeft = futureScrollPosition.scrollLeft - (deltaScrollLeft < 0 ? Math.floor(deltaScrollLeft) : Math.ceil(deltaScrollLeft)); + this._horizontalScrollbar.writeScrollPosition(desiredScrollPosition, desiredScrollLeft); + } + + // Check that we are scrolling towards a location which is valid + desiredScrollPosition = this._scrollable.validateScrollPosition(desiredScrollPosition); + + if (futureScrollPosition.scrollLeft !== desiredScrollPosition.scrollLeft || futureScrollPosition.scrollTop !== desiredScrollPosition.scrollTop) { + + const canPerformSmoothScroll = ( + SCROLL_WHEEL_SMOOTH_SCROLL_ENABLED + && this._options.mouseWheelSmoothScroll + && classifier.isPhysicalMouseWheel() + ); + + if (canPerformSmoothScroll) { + this._scrollable.setScrollPositionSmooth(desiredScrollPosition); + } else { + this._scrollable.setScrollPositionNow(desiredScrollPosition); + } + + didScroll = true; + } + } + + let consumeMouseWheel = didScroll; + if (!consumeMouseWheel && this._options.alwaysConsumeMouseWheel) { + consumeMouseWheel = true; + } + if (!consumeMouseWheel && this._options.consumeMouseWheelIfScrollbarIsNeeded && (this._verticalScrollbar.isNeeded() || this._horizontalScrollbar.isNeeded())) { + consumeMouseWheel = true; + } + + if (consumeMouseWheel) { + e.preventDefault(); + e.stopPropagation(); + } + } + + private _onDidScroll(e: ScrollEvent): void { + this._shouldRender = this._horizontalScrollbar.onDidScroll(e) || this._shouldRender; + this._shouldRender = this._verticalScrollbar.onDidScroll(e) || this._shouldRender; + + if (this._options.useShadows) { + this._shouldRender = true; + } + + if (this._revealOnScroll) { + this._reveal(); + } + + if (!this._options.lazyRender) { + this._render(); + } + } + + /** + * Render / mutate the DOM now. + * Should be used together with the ctor option `lazyRender`. + */ + public renderNow(): void { + if (!this._options.lazyRender) { + throw new Error('Please use `lazyRender` together with `renderNow`!'); + } + + this._render(); + } + + private _render(): void { + if (!this._shouldRender) { + return; + } + + this._shouldRender = false; + + this._horizontalScrollbar.render(); + this._verticalScrollbar.render(); + + if (this._options.useShadows) { + const scrollState = this._scrollable.getCurrentScrollPosition(); + const enableTop = scrollState.scrollTop > 0; + const enableLeft = scrollState.scrollLeft > 0; + + const leftClassName = (enableLeft ? ' left' : ''); + const topClassName = (enableTop ? ' top' : ''); + const topLeftClassName = (enableLeft || enableTop ? ' top-left-corner' : ''); + this._leftShadowDomNode!.setClassName(`shadow${leftClassName}`); + this._topShadowDomNode!.setClassName(`shadow${topClassName}`); + this._topLeftShadowDomNode!.setClassName(`shadow${topLeftClassName}${topClassName}${leftClassName}`); + } + } + + // -------------------- fade in / fade out -------------------- + + private _onDragStart(): void { + this._isDragging = true; + this._reveal(); + } + + private _onDragEnd(): void { + this._isDragging = false; + this._hide(); + } + + private _onMouseLeave(e: IMouseEvent): void { + this._mouseIsOver = false; + this._hide(); + } + + private _onMouseOver(e: IMouseEvent): void { + this._mouseIsOver = true; + this._reveal(); + } + + private _reveal(): void { + this._verticalScrollbar.beginReveal(); + this._horizontalScrollbar.beginReveal(); + this._scheduleHide(); + } + + private _hide(): void { + if (!this._mouseIsOver && !this._isDragging) { + this._verticalScrollbar.beginHide(); + this._horizontalScrollbar.beginHide(); + } + } + + private _scheduleHide(): void { + if (!this._mouseIsOver && !this._isDragging) { + this._hideTimeout.cancelAndSet(() => this._hide(), HIDE_TIMEOUT); + } + } +} + +export class ScrollableElement extends AbstractScrollableElement { + + constructor(element: HTMLElement, options: ScrollableElementCreationOptions) { + options = options || {}; + options.mouseWheelSmoothScroll = false; + const scrollable = new Scrollable({ + forceIntegerValues: true, + smoothScrollDuration: 0, + scheduleAtNextAnimationFrame: (callback) => dom.scheduleAtNextAnimationFrame(dom.getWindow(element), callback) + }); + super(element, options, scrollable); + this._register(scrollable); + } + + public setScrollPosition(update: INewScrollPosition): void { + this._scrollable.setScrollPositionNow(update); + } + + public getScrollPosition(): IScrollPosition { + return this._scrollable.getCurrentScrollPosition(); + } +} + +export class SmoothScrollableElement extends AbstractScrollableElement { + + constructor(element: HTMLElement, options: ScrollableElementCreationOptions, scrollable: Scrollable) { + super(element, options, scrollable); + } + + public setScrollPosition(update: INewScrollPosition & { reuseAnimation?: boolean }): void { + if (update.reuseAnimation) { + this._scrollable.setScrollPositionSmooth(update, update.reuseAnimation); + } else { + this._scrollable.setScrollPositionNow(update); + } + } + + public getScrollPosition(): IScrollPosition { + return this._scrollable.getCurrentScrollPosition(); + } + +} + +export class DomScrollableElement extends AbstractScrollableElement { + + private _element: HTMLElement; + + constructor(element: HTMLElement, options: ScrollableElementCreationOptions) { + options = options || {}; + options.mouseWheelSmoothScroll = false; + const scrollable = new Scrollable({ + forceIntegerValues: false, // See https://github.com/microsoft/vscode/issues/139877 + smoothScrollDuration: 0, + scheduleAtNextAnimationFrame: (callback) => dom.scheduleAtNextAnimationFrame(dom.getWindow(element), callback) + }); + super(element, options, scrollable); + this._register(scrollable); + this._element = element; + this._register(this.onScroll((e) => { + if (e.scrollTopChanged) { + this._element.scrollTop = e.scrollTop; + } + if (e.scrollLeftChanged) { + this._element.scrollLeft = e.scrollLeft; + } + })); + this.scanDomNode(); + } + + public setScrollPosition(update: INewScrollPosition): void { + this._scrollable.setScrollPositionNow(update); + } + + public getScrollPosition(): IScrollPosition { + return this._scrollable.getCurrentScrollPosition(); + } + + public scanDomNode(): void { + // width, scrollLeft, scrollWidth, height, scrollTop, scrollHeight + this.setScrollDimensions({ + width: this._element.clientWidth, + scrollWidth: this._element.scrollWidth, + height: this._element.clientHeight, + scrollHeight: this._element.scrollHeight + }); + this.setScrollPosition({ + scrollLeft: this._element.scrollLeft, + scrollTop: this._element.scrollTop, + }); + } +} + +function resolveOptions(opts: ScrollableElementCreationOptions): ScrollableElementResolvedOptions { + const result: ScrollableElementResolvedOptions = { + lazyRender: (typeof opts.lazyRender !== 'undefined' ? opts.lazyRender : false), + className: (typeof opts.className !== 'undefined' ? opts.className : ''), + useShadows: (typeof opts.useShadows !== 'undefined' ? opts.useShadows : true), + handleMouseWheel: (typeof opts.handleMouseWheel !== 'undefined' ? opts.handleMouseWheel : true), + flipAxes: (typeof opts.flipAxes !== 'undefined' ? opts.flipAxes : false), + consumeMouseWheelIfScrollbarIsNeeded: (typeof opts.consumeMouseWheelIfScrollbarIsNeeded !== 'undefined' ? opts.consumeMouseWheelIfScrollbarIsNeeded : false), + alwaysConsumeMouseWheel: (typeof opts.alwaysConsumeMouseWheel !== 'undefined' ? opts.alwaysConsumeMouseWheel : false), + scrollYToX: (typeof opts.scrollYToX !== 'undefined' ? opts.scrollYToX : false), + mouseWheelScrollSensitivity: (typeof opts.mouseWheelScrollSensitivity !== 'undefined' ? opts.mouseWheelScrollSensitivity : 1), + fastScrollSensitivity: (typeof opts.fastScrollSensitivity !== 'undefined' ? opts.fastScrollSensitivity : 5), + scrollPredominantAxis: (typeof opts.scrollPredominantAxis !== 'undefined' ? opts.scrollPredominantAxis : true), + mouseWheelSmoothScroll: (typeof opts.mouseWheelSmoothScroll !== 'undefined' ? opts.mouseWheelSmoothScroll : true), + arrowSize: (typeof opts.arrowSize !== 'undefined' ? opts.arrowSize : 11), + + listenOnDomNode: (typeof opts.listenOnDomNode !== 'undefined' ? opts.listenOnDomNode : null), + + horizontal: (typeof opts.horizontal !== 'undefined' ? opts.horizontal : ScrollbarVisibility.Auto), + horizontalScrollbarSize: (typeof opts.horizontalScrollbarSize !== 'undefined' ? opts.horizontalScrollbarSize : 10), + horizontalSliderSize: (typeof opts.horizontalSliderSize !== 'undefined' ? opts.horizontalSliderSize : 0), + horizontalHasArrows: (typeof opts.horizontalHasArrows !== 'undefined' ? opts.horizontalHasArrows : false), + + vertical: (typeof opts.vertical !== 'undefined' ? opts.vertical : ScrollbarVisibility.Auto), + verticalScrollbarSize: (typeof opts.verticalScrollbarSize !== 'undefined' ? opts.verticalScrollbarSize : 10), + verticalHasArrows: (typeof opts.verticalHasArrows !== 'undefined' ? opts.verticalHasArrows : false), + verticalSliderSize: (typeof opts.verticalSliderSize !== 'undefined' ? opts.verticalSliderSize : 0), + + scrollByPage: (typeof opts.scrollByPage !== 'undefined' ? opts.scrollByPage : false) + }; + + result.horizontalSliderSize = (typeof opts.horizontalSliderSize !== 'undefined' ? opts.horizontalSliderSize : result.horizontalScrollbarSize); + result.verticalSliderSize = (typeof opts.verticalSliderSize !== 'undefined' ? opts.verticalSliderSize : result.verticalScrollbarSize); + + // Defaults are different on Macs + if (platform.isMacintosh) { + result.className += ' mac'; + } + + return result; +} diff --git a/node_modules/@xterm/xterm/src/vs/base/browser/ui/scrollbar/scrollableElementOptions.ts b/node_modules/@xterm/xterm/src/vs/base/browser/ui/scrollbar/scrollableElementOptions.ts new file mode 100644 index 0000000..8e75751 --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/browser/ui/scrollbar/scrollableElementOptions.ts @@ -0,0 +1,165 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { ScrollbarVisibility } from 'vs/base/common/scrollable'; + +export interface ScrollableElementCreationOptions { + /** + * The scrollable element should not do any DOM mutations until renderNow() is called. + * Defaults to false. + */ + lazyRender?: boolean; + /** + * CSS Class name for the scrollable element. + */ + className?: string; + /** + * Drop subtle horizontal and vertical shadows. + * Defaults to false. + */ + useShadows?: boolean; + /** + * Handle mouse wheel (listen to mouse wheel scrolling). + * Defaults to true + */ + handleMouseWheel?: boolean; + /** + * If mouse wheel is handled, make mouse wheel scrolling smooth. + * Defaults to true. + */ + mouseWheelSmoothScroll?: boolean; + /** + * Flip axes. Treat vertical scrolling like horizontal and vice-versa. + * Defaults to false. + */ + flipAxes?: boolean; + /** + * If enabled, will scroll horizontally when scrolling vertical. + * Defaults to false. + */ + scrollYToX?: boolean; + /** + * Consume all mouse wheel events if a scrollbar is needed (i.e. scrollSize > size). + * Defaults to false. + */ + consumeMouseWheelIfScrollbarIsNeeded?: boolean; + /** + * Always consume mouse wheel events, even when scrolling is no longer possible. + * Defaults to false. + */ + alwaysConsumeMouseWheel?: boolean; + /** + * A multiplier to be used on the `deltaX` and `deltaY` of mouse wheel scroll events. + * Defaults to 1. + */ + mouseWheelScrollSensitivity?: number; + /** + * FastScrolling mulitplier speed when pressing `Alt` + * Defaults to 5. + */ + fastScrollSensitivity?: number; + /** + * Whether the scrollable will only scroll along the predominant axis when scrolling both + * vertically and horizontally at the same time. + * Prevents horizontal drift when scrolling vertically on a trackpad. + * Defaults to true. + */ + scrollPredominantAxis?: boolean; + /** + * Height for vertical arrows (top/bottom) and width for horizontal arrows (left/right). + * Defaults to 11. + */ + arrowSize?: number; + /** + * The dom node events should be bound to. + * If no listenOnDomNode is provided, the dom node passed to the constructor will be used for event listening. + */ + listenOnDomNode?: HTMLElement; + /** + * Control the visibility of the horizontal scrollbar. + * Accepted values: 'auto' (on mouse over), 'visible' (always visible), 'hidden' (never visible) + * Defaults to 'auto'. + */ + horizontal?: ScrollbarVisibility; + /** + * Height (in px) of the horizontal scrollbar. + * Defaults to 10. + */ + horizontalScrollbarSize?: number; + /** + * Height (in px) of the horizontal scrollbar slider. + * Defaults to `horizontalScrollbarSize` + */ + horizontalSliderSize?: number; + /** + * Render arrows (left/right) for the horizontal scrollbar. + * Defaults to false. + */ + horizontalHasArrows?: boolean; + /** + * Control the visibility of the vertical scrollbar. + * Accepted values: 'auto' (on mouse over), 'visible' (always visible), 'hidden' (never visible) + * Defaults to 'auto'. + */ + vertical?: ScrollbarVisibility; + /** + * Width (in px) of the vertical scrollbar. + * Defaults to 10. + */ + verticalScrollbarSize?: number; + /** + * Width (in px) of the vertical scrollbar slider. + * Defaults to `verticalScrollbarSize` + */ + verticalSliderSize?: number; + /** + * Render arrows (top/bottom) for the vertical scrollbar. + * Defaults to false. + */ + verticalHasArrows?: boolean; + /** + * Scroll gutter clicks move by page vs. jump to position. + * Defaults to false. + */ + scrollByPage?: boolean; +} + +export interface ScrollableElementChangeOptions { + handleMouseWheel?: boolean; + mouseWheelScrollSensitivity?: number; + fastScrollSensitivity?: number; + scrollPredominantAxis?: boolean; + horizontal?: ScrollbarVisibility; + horizontalScrollbarSize?: number; + vertical?: ScrollbarVisibility; + verticalScrollbarSize?: number; + scrollByPage?: boolean; +} + +export interface ScrollableElementResolvedOptions { + lazyRender: boolean; + className: string; + useShadows: boolean; + handleMouseWheel: boolean; + flipAxes: boolean; + scrollYToX: boolean; + consumeMouseWheelIfScrollbarIsNeeded: boolean; + alwaysConsumeMouseWheel: boolean; + mouseWheelScrollSensitivity: number; + fastScrollSensitivity: number; + scrollPredominantAxis: boolean; + mouseWheelSmoothScroll: boolean; + arrowSize: number; + listenOnDomNode: HTMLElement | null; + horizontal: ScrollbarVisibility; + horizontalScrollbarSize: number; + horizontalSliderSize: number; + horizontalHasArrows: boolean; + vertical: ScrollbarVisibility; + verticalScrollbarSize: number; + verticalSliderSize: number; + verticalHasArrows: boolean; + scrollByPage: boolean; +} diff --git a/node_modules/@xterm/xterm/src/vs/base/browser/ui/scrollbar/scrollbarArrow.ts b/node_modules/@xterm/xterm/src/vs/base/browser/ui/scrollbar/scrollbarArrow.ts new file mode 100644 index 0000000..7bc7e9b --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/browser/ui/scrollbar/scrollbarArrow.ts @@ -0,0 +1,114 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { GlobalPointerMoveMonitor } from 'vs/base/browser/globalPointerMoveMonitor'; +import { Widget } from 'vs/base/browser/ui/widget'; +import { TimeoutTimer } from 'vs/base/common/async'; +import * as dom from 'vs/base/browser/dom'; + +/** + * The arrow image size. + */ +export const ARROW_IMG_SIZE = 11; + +export interface ScrollbarArrowOptions { + onActivate: () => void; + className: string; + // icon: ThemeIcon; + + bgWidth: number; + bgHeight: number; + + top?: number; + left?: number; + bottom?: number; + right?: number; +} + +export class ScrollbarArrow extends Widget { + + private _onActivate: () => void; + public bgDomNode: HTMLElement; + public domNode: HTMLElement; + private _pointerdownRepeatTimer: dom.WindowIntervalTimer; + private _pointerdownScheduleRepeatTimer: TimeoutTimer; + private _pointerMoveMonitor: GlobalPointerMoveMonitor; + + constructor(opts: ScrollbarArrowOptions) { + super(); + this._onActivate = opts.onActivate; + + this.bgDomNode = document.createElement('div'); + this.bgDomNode.className = 'arrow-background'; + this.bgDomNode.style.position = 'absolute'; + this.bgDomNode.style.width = opts.bgWidth + 'px'; + this.bgDomNode.style.height = opts.bgHeight + 'px'; + if (typeof opts.top !== 'undefined') { + this.bgDomNode.style.top = '0px'; + } + if (typeof opts.left !== 'undefined') { + this.bgDomNode.style.left = '0px'; + } + if (typeof opts.bottom !== 'undefined') { + this.bgDomNode.style.bottom = '0px'; + } + if (typeof opts.right !== 'undefined') { + this.bgDomNode.style.right = '0px'; + } + + this.domNode = document.createElement('div'); + this.domNode.className = opts.className; + // this.domNode.classList.add(...ThemeIcon.asClassNameArray(opts.icon)); + + this.domNode.style.position = 'absolute'; + this.domNode.style.width = ARROW_IMG_SIZE + 'px'; + this.domNode.style.height = ARROW_IMG_SIZE + 'px'; + if (typeof opts.top !== 'undefined') { + this.domNode.style.top = opts.top + 'px'; + } + if (typeof opts.left !== 'undefined') { + this.domNode.style.left = opts.left + 'px'; + } + if (typeof opts.bottom !== 'undefined') { + this.domNode.style.bottom = opts.bottom + 'px'; + } + if (typeof opts.right !== 'undefined') { + this.domNode.style.right = opts.right + 'px'; + } + + this._pointerMoveMonitor = this._register(new GlobalPointerMoveMonitor()); + this._register(dom.addStandardDisposableListener(this.bgDomNode, dom.EventType.POINTER_DOWN, (e) => this._arrowPointerDown(e))); + this._register(dom.addStandardDisposableListener(this.domNode, dom.EventType.POINTER_DOWN, (e) => this._arrowPointerDown(e))); + + this._pointerdownRepeatTimer = this._register(new dom.WindowIntervalTimer()); + this._pointerdownScheduleRepeatTimer = this._register(new TimeoutTimer()); + } + + private _arrowPointerDown(e: PointerEvent): void { + if (!e.target || !(e.target instanceof Element)) { + return; + } + const scheduleRepeater = () => { + this._pointerdownRepeatTimer.cancelAndSet(() => this._onActivate(), 1000 / 24, dom.getWindow(e)); + }; + + this._onActivate(); + this._pointerdownRepeatTimer.cancel(); + this._pointerdownScheduleRepeatTimer.cancelAndSet(scheduleRepeater, 200); + + this._pointerMoveMonitor.startMonitoring( + e.target, + e.pointerId, + e.buttons, + (pointerMoveData) => { /* Intentional empty */ }, + () => { + this._pointerdownRepeatTimer.cancel(); + this._pointerdownScheduleRepeatTimer.cancel(); + } + ); + + e.preventDefault(); + } +} diff --git a/node_modules/@xterm/xterm/src/vs/base/browser/ui/scrollbar/scrollbarState.ts b/node_modules/@xterm/xterm/src/vs/base/browser/ui/scrollbar/scrollbarState.ts new file mode 100644 index 0000000..9a4f4e2 --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/browser/ui/scrollbar/scrollbarState.ts @@ -0,0 +1,243 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +/** + * The minimal size of the slider (such that it can still be clickable) -- it is artificially enlarged. + */ +const MINIMUM_SLIDER_SIZE = 20; + +export class ScrollbarState { + + /** + * For the vertical scrollbar: the width. + * For the horizontal scrollbar: the height. + */ + private _scrollbarSize: number; + + /** + * For the vertical scrollbar: the height of the pair horizontal scrollbar. + * For the horizontal scrollbar: the width of the pair vertical scrollbar. + */ + private _oppositeScrollbarSize: number; + + /** + * For the vertical scrollbar: the height of the scrollbar's arrows. + * For the horizontal scrollbar: the width of the scrollbar's arrows. + */ + private readonly _arrowSize: number; + + // --- variables + /** + * For the vertical scrollbar: the viewport height. + * For the horizontal scrollbar: the viewport width. + */ + private _visibleSize: number; + + /** + * For the vertical scrollbar: the scroll height. + * For the horizontal scrollbar: the scroll width. + */ + private _scrollSize: number; + + /** + * For the vertical scrollbar: the scroll top. + * For the horizontal scrollbar: the scroll left. + */ + private _scrollPosition: number; + + // --- computed variables + + /** + * `visibleSize` - `oppositeScrollbarSize` + */ + private _computedAvailableSize: number; + /** + * (`scrollSize` > 0 && `scrollSize` > `visibleSize`) + */ + private _computedIsNeeded: boolean; + + private _computedSliderSize: number; + private _computedSliderRatio: number; + private _computedSliderPosition: number; + + constructor(arrowSize: number, scrollbarSize: number, oppositeScrollbarSize: number, visibleSize: number, scrollSize: number, scrollPosition: number) { + this._scrollbarSize = Math.round(scrollbarSize); + this._oppositeScrollbarSize = Math.round(oppositeScrollbarSize); + this._arrowSize = Math.round(arrowSize); + + this._visibleSize = visibleSize; + this._scrollSize = scrollSize; + this._scrollPosition = scrollPosition; + + this._computedAvailableSize = 0; + this._computedIsNeeded = false; + this._computedSliderSize = 0; + this._computedSliderRatio = 0; + this._computedSliderPosition = 0; + + this._refreshComputedValues(); + } + + public clone(): ScrollbarState { + return new ScrollbarState(this._arrowSize, this._scrollbarSize, this._oppositeScrollbarSize, this._visibleSize, this._scrollSize, this._scrollPosition); + } + + public setVisibleSize(visibleSize: number): boolean { + const iVisibleSize = Math.round(visibleSize); + if (this._visibleSize !== iVisibleSize) { + this._visibleSize = iVisibleSize; + this._refreshComputedValues(); + return true; + } + return false; + } + + public setScrollSize(scrollSize: number): boolean { + const iScrollSize = Math.round(scrollSize); + if (this._scrollSize !== iScrollSize) { + this._scrollSize = iScrollSize; + this._refreshComputedValues(); + return true; + } + return false; + } + + public setScrollPosition(scrollPosition: number): boolean { + const iScrollPosition = Math.round(scrollPosition); + if (this._scrollPosition !== iScrollPosition) { + this._scrollPosition = iScrollPosition; + this._refreshComputedValues(); + return true; + } + return false; + } + + public setScrollbarSize(scrollbarSize: number): void { + this._scrollbarSize = Math.round(scrollbarSize); + } + + public setOppositeScrollbarSize(oppositeScrollbarSize: number): void { + this._oppositeScrollbarSize = Math.round(oppositeScrollbarSize); + } + + private static _computeValues(oppositeScrollbarSize: number, arrowSize: number, visibleSize: number, scrollSize: number, scrollPosition: number) { + const computedAvailableSize = Math.max(0, visibleSize - oppositeScrollbarSize); + const computedRepresentableSize = Math.max(0, computedAvailableSize - 2 * arrowSize); + const computedIsNeeded = (scrollSize > 0 && scrollSize > visibleSize); + + if (!computedIsNeeded) { + // There is no need for a slider + return { + computedAvailableSize: Math.round(computedAvailableSize), + computedIsNeeded: computedIsNeeded, + computedSliderSize: Math.round(computedRepresentableSize), + computedSliderRatio: 0, + computedSliderPosition: 0, + }; + } + + // We must artificially increase the size of the slider if needed, since the slider would be too small to grab with the mouse otherwise + const computedSliderSize = Math.round(Math.max(MINIMUM_SLIDER_SIZE, Math.floor(visibleSize * computedRepresentableSize / scrollSize))); + + // The slider can move from 0 to `computedRepresentableSize` - `computedSliderSize` + // in the same way `scrollPosition` can move from 0 to `scrollSize` - `visibleSize`. + const computedSliderRatio = (computedRepresentableSize - computedSliderSize) / (scrollSize - visibleSize); + const computedSliderPosition = (scrollPosition * computedSliderRatio); + + return { + computedAvailableSize: Math.round(computedAvailableSize), + computedIsNeeded: computedIsNeeded, + computedSliderSize: Math.round(computedSliderSize), + computedSliderRatio: computedSliderRatio, + computedSliderPosition: Math.round(computedSliderPosition), + }; + } + + private _refreshComputedValues(): void { + const r = ScrollbarState._computeValues(this._oppositeScrollbarSize, this._arrowSize, this._visibleSize, this._scrollSize, this._scrollPosition); + this._computedAvailableSize = r.computedAvailableSize; + this._computedIsNeeded = r.computedIsNeeded; + this._computedSliderSize = r.computedSliderSize; + this._computedSliderRatio = r.computedSliderRatio; + this._computedSliderPosition = r.computedSliderPosition; + } + + public getArrowSize(): number { + return this._arrowSize; + } + + public getScrollPosition(): number { + return this._scrollPosition; + } + + public getRectangleLargeSize(): number { + return this._computedAvailableSize; + } + + public getRectangleSmallSize(): number { + return this._scrollbarSize; + } + + public isNeeded(): boolean { + return this._computedIsNeeded; + } + + public getSliderSize(): number { + return this._computedSliderSize; + } + + public getSliderPosition(): number { + return this._computedSliderPosition; + } + + /** + * Compute a desired `scrollPosition` such that `offset` ends up in the center of the slider. + * `offset` is based on the same coordinate system as the `sliderPosition`. + */ + public getDesiredScrollPositionFromOffset(offset: number): number { + if (!this._computedIsNeeded) { + // no need for a slider + return 0; + } + + const desiredSliderPosition = offset - this._arrowSize - this._computedSliderSize / 2; + return Math.round(desiredSliderPosition / this._computedSliderRatio); + } + + /** + * Compute a desired `scrollPosition` from if offset is before or after the slider position. + * If offset is before slider, treat as a page up (or left). If after, page down (or right). + * `offset` and `_computedSliderPosition` are based on the same coordinate system. + * `_visibleSize` corresponds to a "page" of lines in the returned coordinate system. + */ + public getDesiredScrollPositionFromOffsetPaged(offset: number): number { + if (!this._computedIsNeeded) { + // no need for a slider + return 0; + } + + const correctedOffset = offset - this._arrowSize; // compensate if has arrows + let desiredScrollPosition = this._scrollPosition; + if (correctedOffset < this._computedSliderPosition) { + desiredScrollPosition -= this._visibleSize; // page up/left + } else { + desiredScrollPosition += this._visibleSize; // page down/right + } + return desiredScrollPosition; + } + + /** + * Compute a desired `scrollPosition` such that the slider moves by `delta`. + */ + public getDesiredScrollPositionFromDelta(delta: number): number { + if (!this._computedIsNeeded) { + // no need for a slider + return 0; + } + + const desiredSliderPosition = this._computedSliderPosition + delta; + return Math.round(desiredSliderPosition / this._computedSliderRatio); + } +} diff --git a/node_modules/@xterm/xterm/src/vs/base/browser/ui/scrollbar/scrollbarVisibilityController.ts b/node_modules/@xterm/xterm/src/vs/base/browser/ui/scrollbar/scrollbarVisibilityController.ts new file mode 100644 index 0000000..791c733 --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/browser/ui/scrollbar/scrollbarVisibilityController.ts @@ -0,0 +1,118 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { FastDomNode } from 'vs/base/browser/fastDomNode'; +import { TimeoutTimer } from 'vs/base/common/async'; +import { Disposable } from 'vs/base/common/lifecycle'; +import { ScrollbarVisibility } from 'vs/base/common/scrollable'; + +export class ScrollbarVisibilityController extends Disposable { + private _visibility: ScrollbarVisibility; + private _visibleClassName: string; + private _invisibleClassName: string; + private _domNode: FastDomNode | null; + private _rawShouldBeVisible: boolean; + private _shouldBeVisible: boolean; + private _isNeeded: boolean; + private _isVisible: boolean; + private _revealTimer: TimeoutTimer; + + constructor(visibility: ScrollbarVisibility, visibleClassName: string, invisibleClassName: string) { + super(); + this._visibility = visibility; + this._visibleClassName = visibleClassName; + this._invisibleClassName = invisibleClassName; + this._domNode = null; + this._isVisible = false; + this._isNeeded = false; + this._rawShouldBeVisible = false; + this._shouldBeVisible = false; + this._revealTimer = this._register(new TimeoutTimer()); + } + + public setVisibility(visibility: ScrollbarVisibility): void { + if (this._visibility !== visibility) { + this._visibility = visibility; + this._updateShouldBeVisible(); + } + } + + // ----------------- Hide / Reveal + + public setShouldBeVisible(rawShouldBeVisible: boolean): void { + this._rawShouldBeVisible = rawShouldBeVisible; + this._updateShouldBeVisible(); + } + + private _applyVisibilitySetting(): boolean { + if (this._visibility === ScrollbarVisibility.Hidden) { + return false; + } + if (this._visibility === ScrollbarVisibility.Visible) { + return true; + } + return this._rawShouldBeVisible; + } + + private _updateShouldBeVisible(): void { + const shouldBeVisible = this._applyVisibilitySetting(); + + if (this._shouldBeVisible !== shouldBeVisible) { + this._shouldBeVisible = shouldBeVisible; + this.ensureVisibility(); + } + } + + public setIsNeeded(isNeeded: boolean): void { + if (this._isNeeded !== isNeeded) { + this._isNeeded = isNeeded; + this.ensureVisibility(); + } + } + + public setDomNode(domNode: FastDomNode): void { + this._domNode = domNode; + this._domNode.setClassName(this._invisibleClassName); + + // Now that the flags & the dom node are in a consistent state, ensure the Hidden/Visible configuration + this.setShouldBeVisible(false); + } + + public ensureVisibility(): void { + + if (!this._isNeeded) { + // Nothing to be rendered + this._hide(false); + return; + } + + if (this._shouldBeVisible) { + this._reveal(); + } else { + this._hide(true); + } + } + + private _reveal(): void { + if (this._isVisible) { + return; + } + this._isVisible = true; + + // The CSS animation doesn't play otherwise + this._revealTimer.setIfNotSet(() => { + this._domNode?.setClassName(this._visibleClassName); + }, 0); + } + + private _hide(withFadeAway: boolean): void { + this._revealTimer.cancel(); + if (!this._isVisible) { + return; + } + this._isVisible = false; + this._domNode?.setClassName(this._invisibleClassName + (withFadeAway ? ' fade' : '')); + } +} diff --git a/node_modules/@xterm/xterm/src/vs/base/browser/ui/scrollbar/verticalScrollbar.ts b/node_modules/@xterm/xterm/src/vs/base/browser/ui/scrollbar/verticalScrollbar.ts new file mode 100644 index 0000000..331654a --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/browser/ui/scrollbar/verticalScrollbar.ts @@ -0,0 +1,116 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { AbstractScrollbar, ISimplifiedPointerEvent, ScrollbarHost } from 'vs/base/browser/ui/scrollbar/abstractScrollbar'; +import { ScrollableElementResolvedOptions } from 'vs/base/browser/ui/scrollbar/scrollableElementOptions'; +import { ScrollbarState } from 'vs/base/browser/ui/scrollbar/scrollbarState'; +import { INewScrollPosition, Scrollable, ScrollbarVisibility, ScrollEvent } from 'vs/base/common/scrollable'; + + + +export class VerticalScrollbar extends AbstractScrollbar { + + constructor(scrollable: Scrollable, options: ScrollableElementResolvedOptions, host: ScrollbarHost) { + const scrollDimensions = scrollable.getScrollDimensions(); + const scrollPosition = scrollable.getCurrentScrollPosition(); + super({ + lazyRender: options.lazyRender, + host: host, + scrollbarState: new ScrollbarState( + (options.verticalHasArrows ? options.arrowSize : 0), + (options.vertical === ScrollbarVisibility.Hidden ? 0 : options.verticalScrollbarSize), + // give priority to vertical scroll bar over horizontal and let it scroll all the way to the bottom + 0, + scrollDimensions.height, + scrollDimensions.scrollHeight, + scrollPosition.scrollTop + ), + visibility: options.vertical, + extraScrollbarClassName: 'vertical', + scrollable: scrollable, + scrollByPage: options.scrollByPage + }); + + if (options.verticalHasArrows) { + throw new Error('horizontalHasArrows is not supported in xterm.js'); + // const arrowDelta = (options.arrowSize - ARROW_IMG_SIZE) / 2; + // const scrollbarDelta = (options.verticalScrollbarSize - ARROW_IMG_SIZE) / 2; + + // this._createArrow({ + // className: 'scra', + // icon: Codicon.scrollbarButtonUp, + // top: arrowDelta, + // left: scrollbarDelta, + // bottom: undefined, + // right: undefined, + // bgWidth: options.verticalScrollbarSize, + // bgHeight: options.arrowSize, + // onActivate: () => this._host.onMouseWheel(new StandardWheelEvent(null, 0, 1)), + // }); + + // this._createArrow({ + // className: 'scra', + // icon: Codicon.scrollbarButtonDown, + // top: undefined, + // left: scrollbarDelta, + // bottom: arrowDelta, + // right: undefined, + // bgWidth: options.verticalScrollbarSize, + // bgHeight: options.arrowSize, + // onActivate: () => this._host.onMouseWheel(new StandardWheelEvent(null, 0, -1)), + // }); + } + + this._createSlider(0, Math.floor((options.verticalScrollbarSize - options.verticalSliderSize) / 2), options.verticalSliderSize, undefined); + } + + protected _updateSlider(sliderSize: number, sliderPosition: number): void { + this.slider.setHeight(sliderSize); + this.slider.setTop(sliderPosition); + } + + protected _renderDomNode(largeSize: number, smallSize: number): void { + this.domNode.setWidth(smallSize); + this.domNode.setHeight(largeSize); + this.domNode.setRight(0); + this.domNode.setTop(0); + } + + public onDidScroll(e: ScrollEvent): boolean { + this._shouldRender = this._onElementScrollSize(e.scrollHeight) || this._shouldRender; + this._shouldRender = this._onElementScrollPosition(e.scrollTop) || this._shouldRender; + this._shouldRender = this._onElementSize(e.height) || this._shouldRender; + return this._shouldRender; + } + + protected _pointerDownRelativePosition(offsetX: number, offsetY: number): number { + return offsetY; + } + + protected _sliderPointerPosition(e: ISimplifiedPointerEvent): number { + return e.pageY; + } + + protected _sliderOrthogonalPointerPosition(e: ISimplifiedPointerEvent): number { + return e.pageX; + } + + protected _updateScrollbarSize(size: number): void { + this.slider.setWidth(size); + } + + public writeScrollPosition(target: INewScrollPosition, scrollPosition: number): void { + target.scrollTop = scrollPosition; + } + + public updateOptions(options: ScrollableElementResolvedOptions): void { + this.updateScrollbarSize(options.vertical === ScrollbarVisibility.Hidden ? 0 : options.verticalScrollbarSize); + // give priority to vertical scroll bar over horizontal and let it scroll all the way to the bottom + this._scrollbarState.setOppositeScrollbarSize(0); + this._visibilityController.setVisibility(options.vertical); + this._scrollByPage = options.scrollByPage; + } + +} diff --git a/node_modules/@xterm/xterm/src/vs/base/browser/ui/widget.ts b/node_modules/@xterm/xterm/src/vs/base/browser/ui/widget.ts new file mode 100644 index 0000000..440a9ac --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/browser/ui/widget.ts @@ -0,0 +1,57 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import * as dom from 'vs/base/browser/dom'; +import { IKeyboardEvent, StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; +import { IMouseEvent, StandardMouseEvent } from 'vs/base/browser/mouseEvent'; +import { Gesture } from 'vs/base/browser/touch'; +import { Disposable, IDisposable } from 'vs/base/common/lifecycle'; + +export abstract class Widget extends Disposable { + + protected onclick(domNode: HTMLElement, listener: (e: IMouseEvent) => void): void { + this._register(dom.addDisposableListener(domNode, dom.EventType.CLICK, (e: MouseEvent) => listener(new StandardMouseEvent(dom.getWindow(domNode), e)))); + } + + protected onmousedown(domNode: HTMLElement, listener: (e: IMouseEvent) => void): void { + this._register(dom.addDisposableListener(domNode, dom.EventType.MOUSE_DOWN, (e: MouseEvent) => listener(new StandardMouseEvent(dom.getWindow(domNode), e)))); + } + + protected onmouseover(domNode: HTMLElement, listener: (e: IMouseEvent) => void): void { + this._register(dom.addDisposableListener(domNode, dom.EventType.MOUSE_OVER, (e: MouseEvent) => listener(new StandardMouseEvent(dom.getWindow(domNode), e)))); + } + + protected onmouseleave(domNode: HTMLElement, listener: (e: IMouseEvent) => void): void { + this._register(dom.addDisposableListener(domNode, dom.EventType.MOUSE_LEAVE, (e: MouseEvent) => listener(new StandardMouseEvent(dom.getWindow(domNode), e)))); + } + + protected onkeydown(domNode: HTMLElement, listener: (e: IKeyboardEvent) => void): void { + this._register(dom.addDisposableListener(domNode, dom.EventType.KEY_DOWN, (e: KeyboardEvent) => listener(new StandardKeyboardEvent(e)))); + } + + protected onkeyup(domNode: HTMLElement, listener: (e: IKeyboardEvent) => void): void { + this._register(dom.addDisposableListener(domNode, dom.EventType.KEY_UP, (e: KeyboardEvent) => listener(new StandardKeyboardEvent(e)))); + } + + protected oninput(domNode: HTMLElement, listener: (e: Event) => void): void { + this._register(dom.addDisposableListener(domNode, dom.EventType.INPUT, listener)); + } + + protected onblur(domNode: HTMLElement, listener: (e: Event) => void): void { + this._register(dom.addDisposableListener(domNode, dom.EventType.BLUR, listener)); + } + + protected onfocus(domNode: HTMLElement, listener: (e: Event) => void): void { + this._register(dom.addDisposableListener(domNode, dom.EventType.FOCUS, listener)); + } + + protected onchange(domNode: HTMLElement, listener: (e: Event) => void): void { + this._register(dom.addDisposableListener(domNode, dom.EventType.CHANGE, listener)); + } + + protected ignoreGesture(domNode: HTMLElement): IDisposable { + return Gesture.ignoreTarget(domNode); + } +} diff --git a/node_modules/@xterm/xterm/src/vs/base/browser/window.ts b/node_modules/@xterm/xterm/src/vs/base/browser/window.ts new file mode 100644 index 0000000..3a377a8 --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/browser/window.ts @@ -0,0 +1,14 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +export type CodeWindow = Window & typeof globalThis & { + readonly vscodeWindowId: number; +}; + +export function ensureCodeWindow(targetWindow: Window, fallbackWindowId: number): asserts targetWindow is CodeWindow { +} + +// eslint-disable-next-line no-restricted-globals +export const mainWindow = (typeof window === 'object' ? window : globalThis) as CodeWindow; diff --git a/node_modules/@xterm/xterm/src/vs/base/common/arrays.ts b/node_modules/@xterm/xterm/src/vs/base/common/arrays.ts new file mode 100644 index 0000000..52e542c --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/common/arrays.ts @@ -0,0 +1,887 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { CancellationToken } from 'vs/base/common/cancellation'; +import { CancellationError } from 'vs/base/common/errors'; +import { ISplice } from 'vs/base/common/sequence'; +import { findFirstIdxMonotonousOrArrLen } from './arraysFind'; + +/** + * Returns the last element of an array. + * @param array The array. + * @param n Which element from the end (default is zero). + */ +export function tail(array: ArrayLike, n: number = 0): T | undefined { + return array[array.length - (1 + n)]; +} + +export function tail2(arr: T[]): [T[], T] { + if (arr.length === 0) { + throw new Error('Invalid tail call'); + } + + return [arr.slice(0, arr.length - 1), arr[arr.length - 1]]; +} + +export function equals(one: ReadonlyArray | undefined, other: ReadonlyArray | undefined, itemEquals: (a: T, b: T) => boolean = (a, b) => a === b): boolean { + if (one === other) { + return true; + } + + if (!one || !other) { + return false; + } + + if (one.length !== other.length) { + return false; + } + + for (let i = 0, len = one.length; i < len; i++) { + if (!itemEquals(one[i], other[i])) { + return false; + } + } + + return true; +} + +/** + * Remove the element at `index` by replacing it with the last element. This is faster than `splice` + * but changes the order of the array + */ +export function removeFastWithoutKeepingOrder(array: T[], index: number) { + const last = array.length - 1; + if (index < last) { + array[index] = array[last]; + } + array.pop(); +} + +/** + * Performs a binary search algorithm over a sorted array. + * + * @param array The array being searched. + * @param key The value we search for. + * @param comparator A function that takes two array elements and returns zero + * if they are equal, a negative number if the first element precedes the + * second one in the sorting order, or a positive number if the second element + * precedes the first one. + * @return See {@link binarySearch2} + */ +export function binarySearch(array: ReadonlyArray, key: T, comparator: (op1: T, op2: T) => number): number { + return binarySearch2(array.length, i => comparator(array[i], key)); +} + +/** + * Performs a binary search algorithm over a sorted collection. Useful for cases + * when we need to perform a binary search over something that isn't actually an + * array, and converting data to an array would defeat the use of binary search + * in the first place. + * + * @param length The collection length. + * @param compareToKey A function that takes an index of an element in the + * collection and returns zero if the value at this index is equal to the + * search key, a negative number if the value precedes the search key in the + * sorting order, or a positive number if the search key precedes the value. + * @return A non-negative index of an element, if found. If not found, the + * result is -(n+1) (or ~n, using bitwise notation), where n is the index + * where the key should be inserted to maintain the sorting order. + */ +export function binarySearch2(length: number, compareToKey: (index: number) => number): number { + let low = 0, + high = length - 1; + + while (low <= high) { + const mid = ((low + high) / 2) | 0; + const comp = compareToKey(mid); + if (comp < 0) { + low = mid + 1; + } else if (comp > 0) { + high = mid - 1; + } else { + return mid; + } + } + return -(low + 1); +} + +type Compare = (a: T, b: T) => number; + + +export function quickSelect(nth: number, data: T[], compare: Compare): T { + + nth = nth | 0; + + if (nth >= data.length) { + throw new TypeError('invalid index'); + } + + const pivotValue = data[Math.floor(data.length * Math.random())]; + const lower: T[] = []; + const higher: T[] = []; + const pivots: T[] = []; + + for (const value of data) { + const val = compare(value, pivotValue); + if (val < 0) { + lower.push(value); + } else if (val > 0) { + higher.push(value); + } else { + pivots.push(value); + } + } + + if (nth < lower.length) { + return quickSelect(nth, lower, compare); + } else if (nth < lower.length + pivots.length) { + return pivots[0]; + } else { + return quickSelect(nth - (lower.length + pivots.length), higher, compare); + } +} + +export function groupBy(data: ReadonlyArray, compare: (a: T, b: T) => number): T[][] { + const result: T[][] = []; + let currentGroup: T[] | undefined = undefined; + for (const element of data.slice(0).sort(compare)) { + if (!currentGroup || compare(currentGroup[0], element) !== 0) { + currentGroup = [element]; + result.push(currentGroup); + } else { + currentGroup.push(element); + } + } + return result; +} + +/** + * Splits the given items into a list of (non-empty) groups. + * `shouldBeGrouped` is used to decide if two consecutive items should be in the same group. + * The order of the items is preserved. + */ +export function* groupAdjacentBy(items: Iterable, shouldBeGrouped: (item1: T, item2: T) => boolean): Iterable { + let currentGroup: T[] | undefined; + let last: T | undefined; + for (const item of items) { + if (last !== undefined && shouldBeGrouped(last, item)) { + currentGroup!.push(item); + } else { + if (currentGroup) { + yield currentGroup; + } + currentGroup = [item]; + } + last = item; + } + if (currentGroup) { + yield currentGroup; + } +} + +export function forEachAdjacent(arr: T[], f: (item1: T | undefined, item2: T | undefined) => void): void { + for (let i = 0; i <= arr.length; i++) { + f(i === 0 ? undefined : arr[i - 1], i === arr.length ? undefined : arr[i]); + } +} + +export function forEachWithNeighbors(arr: T[], f: (before: T | undefined, element: T, after: T | undefined) => void): void { + for (let i = 0; i < arr.length; i++) { + f(i === 0 ? undefined : arr[i - 1], arr[i], i + 1 === arr.length ? undefined : arr[i + 1]); + } +} + +interface IMutableSplice extends ISplice { + readonly toInsert: T[]; + deleteCount: number; +} + +/** + * Diffs two *sorted* arrays and computes the splices which apply the diff. + */ +export function sortedDiff(before: ReadonlyArray, after: ReadonlyArray, compare: (a: T, b: T) => number): ISplice[] { + const result: IMutableSplice[] = []; + + function pushSplice(start: number, deleteCount: number, toInsert: T[]): void { + if (deleteCount === 0 && toInsert.length === 0) { + return; + } + + const latest = result[result.length - 1]; + + if (latest && latest.start + latest.deleteCount === start) { + latest.deleteCount += deleteCount; + latest.toInsert.push(...toInsert); + } else { + result.push({ start, deleteCount, toInsert }); + } + } + + let beforeIdx = 0; + let afterIdx = 0; + + while (true) { + if (beforeIdx === before.length) { + pushSplice(beforeIdx, 0, after.slice(afterIdx)); + break; + } + if (afterIdx === after.length) { + pushSplice(beforeIdx, before.length - beforeIdx, []); + break; + } + + const beforeElement = before[beforeIdx]; + const afterElement = after[afterIdx]; + const n = compare(beforeElement, afterElement); + if (n === 0) { + // equal + beforeIdx += 1; + afterIdx += 1; + } else if (n < 0) { + // beforeElement is smaller -> before element removed + pushSplice(beforeIdx, 1, []); + beforeIdx += 1; + } else if (n > 0) { + // beforeElement is greater -> after element added + pushSplice(beforeIdx, 0, [afterElement]); + afterIdx += 1; + } + } + + return result; +} + +/** + * Takes two *sorted* arrays and computes their delta (removed, added elements). + * Finishes in `Math.min(before.length, after.length)` steps. + */ +export function delta(before: ReadonlyArray, after: ReadonlyArray, compare: (a: T, b: T) => number): { removed: T[]; added: T[] } { + const splices = sortedDiff(before, after, compare); + const removed: T[] = []; + const added: T[] = []; + + for (const splice of splices) { + removed.push(...before.slice(splice.start, splice.start + splice.deleteCount)); + added.push(...splice.toInsert); + } + + return { removed, added }; +} + +/** + * Returns the top N elements from the array. + * + * Faster than sorting the entire array when the array is a lot larger than N. + * + * @param array The unsorted array. + * @param compare A sort function for the elements. + * @param n The number of elements to return. + * @return The first n elements from array when sorted with compare. + */ +export function top(array: ReadonlyArray, compare: (a: T, b: T) => number, n: number): T[] { + if (n === 0) { + return []; + } + const result = array.slice(0, n).sort(compare); + topStep(array, compare, result, n, array.length); + return result; +} + +/** + * Asynchronous variant of `top()` allowing for splitting up work in batches between which the event loop can run. + * + * Returns the top N elements from the array. + * + * Faster than sorting the entire array when the array is a lot larger than N. + * + * @param array The unsorted array. + * @param compare A sort function for the elements. + * @param n The number of elements to return. + * @param batch The number of elements to examine before yielding to the event loop. + * @return The first n elements from array when sorted with compare. + */ +export function topAsync(array: T[], compare: (a: T, b: T) => number, n: number, batch: number, token?: CancellationToken): Promise { + if (n === 0) { + return Promise.resolve([]); + } + + return new Promise((resolve, reject) => { + (async () => { + const o = array.length; + const result = array.slice(0, n).sort(compare); + for (let i = n, m = Math.min(n + batch, o); i < o; i = m, m = Math.min(m + batch, o)) { + if (i > n) { + await new Promise(resolve => setTimeout(resolve)); // any other delay function would starve I/O + } + if (token && token.isCancellationRequested) { + throw new CancellationError(); + } + topStep(array, compare, result, i, m); + } + return result; + })() + .then(resolve, reject); + }); +} + +function topStep(array: ReadonlyArray, compare: (a: T, b: T) => number, result: T[], i: number, m: number): void { + for (const n = result.length; i < m; i++) { + const element = array[i]; + if (compare(element, result[n - 1]) < 0) { + result.pop(); + const j = findFirstIdxMonotonousOrArrLen(result, e => compare(element, e) < 0); + result.splice(j, 0, element); + } + } +} + +/** + * @returns New array with all falsy values removed. The original array IS NOT modified. + */ +export function coalesce(array: ReadonlyArray): T[] { + return array.filter((e): e is T => !!e); +} + +/** + * Remove all falsy values from `array`. The original array IS modified. + */ +export function coalesceInPlace(array: Array): asserts array is Array { + let to = 0; + for (let i = 0; i < array.length; i++) { + if (!!array[i]) { + array[to] = array[i]; + to += 1; + } + } + array.length = to; +} + +/** + * @deprecated Use `Array.copyWithin` instead + */ +export function move(array: any[], from: number, to: number): void { + array.splice(to, 0, array.splice(from, 1)[0]); +} + +/** + * @returns false if the provided object is an array and not empty. + */ +export function isFalsyOrEmpty(obj: any): boolean { + return !Array.isArray(obj) || obj.length === 0; +} + +/** + * @returns True if the provided object is an array and has at least one element. + */ +export function isNonEmptyArray(obj: T[] | undefined | null): obj is T[]; +export function isNonEmptyArray(obj: readonly T[] | undefined | null): obj is readonly T[]; +export function isNonEmptyArray(obj: T[] | readonly T[] | undefined | null): obj is T[] | readonly T[] { + return Array.isArray(obj) && obj.length > 0; +} + +/** + * Removes duplicates from the given array. The optional keyFn allows to specify + * how elements are checked for equality by returning an alternate value for each. + */ +export function distinct(array: ReadonlyArray, keyFn: (value: T) => any = value => value): T[] { + const seen = new Set(); + + return array.filter(element => { + const key = keyFn!(element); + if (seen.has(key)) { + return false; + } + seen.add(key); + return true; + }); +} + +export function uniqueFilter(keyFn: (t: T) => R): (t: T) => boolean { + const seen = new Set(); + + return element => { + const key = keyFn(element); + + if (seen.has(key)) { + return false; + } + + seen.add(key); + return true; + }; +} + +export function firstOrDefault(array: ReadonlyArray, notFoundValue: NotFound): T | NotFound; +export function firstOrDefault(array: ReadonlyArray): T | undefined; +export function firstOrDefault(array: ReadonlyArray, notFoundValue?: NotFound): T | NotFound | undefined { + return array.length > 0 ? array[0] : notFoundValue; +} + +export function lastOrDefault(array: ReadonlyArray, notFoundValue: NotFound): T | NotFound; +export function lastOrDefault(array: ReadonlyArray): T | undefined; +export function lastOrDefault(array: ReadonlyArray, notFoundValue?: NotFound): T | NotFound | undefined { + return array.length > 0 ? array[array.length - 1] : notFoundValue; +} + +export function commonPrefixLength(one: ReadonlyArray, other: ReadonlyArray, equals: (a: T, b: T) => boolean = (a, b) => a === b): number { + let result = 0; + + for (let i = 0, len = Math.min(one.length, other.length); i < len && equals(one[i], other[i]); i++) { + result++; + } + + return result; +} + +export function range(to: number): number[]; +export function range(from: number, to: number): number[]; +export function range(arg: number, to?: number): number[] { + let from = typeof to === 'number' ? arg : 0; + + if (typeof to === 'number') { + from = arg; + } else { + from = 0; + to = arg; + } + + const result: number[] = []; + + if (from <= to) { + for (let i = from; i < to; i++) { + result.push(i); + } + } else { + for (let i = from; i > to; i--) { + result.push(i); + } + } + + return result; +} + +export function index(array: ReadonlyArray, indexer: (t: T) => string): { [key: string]: T }; +export function index(array: ReadonlyArray, indexer: (t: T) => string, mapper: (t: T) => R): { [key: string]: R }; +export function index(array: ReadonlyArray, indexer: (t: T) => string, mapper?: (t: T) => R): { [key: string]: R } { + return array.reduce((r, t) => { + r[indexer(t)] = mapper ? mapper(t) : t; + return r; + }, Object.create(null)); +} + +/** + * Inserts an element into an array. Returns a function which, when + * called, will remove that element from the array. + * + * @deprecated In almost all cases, use a `Set` instead. + */ +export function insert(array: T[], element: T): () => void { + array.push(element); + + return () => remove(array, element); +} + +/** + * Removes an element from an array if it can be found. + * + * @deprecated In almost all cases, use a `Set` instead. + */ +export function remove(array: T[], element: T): T | undefined { + const index = array.indexOf(element); + if (index > -1) { + array.splice(index, 1); + + return element; + } + + return undefined; +} + +/** + * Insert `insertArr` inside `target` at `insertIndex`. + * Please don't touch unless you understand https://jsperf.com/inserting-an-array-within-an-array + */ +export function arrayInsert(target: T[], insertIndex: number, insertArr: T[]): T[] { + const before = target.slice(0, insertIndex); + const after = target.slice(insertIndex); + return before.concat(insertArr, after); +} + +/** + * Uses Fisher-Yates shuffle to shuffle the given array + */ +export function shuffle(array: T[], _seed?: number): void { + let rand: () => number; + + if (typeof _seed === 'number') { + let seed = _seed; + // Seeded random number generator in JS. Modified from: + // https://stackoverflow.com/questions/521295/seeding-the-random-number-generator-in-javascript + rand = () => { + const x = Math.sin(seed++) * 179426549; // throw away most significant digits and reduce any potential bias + return x - Math.floor(x); + }; + } else { + rand = Math.random; + } + + for (let i = array.length - 1; i > 0; i -= 1) { + const j = Math.floor(rand() * (i + 1)); + const temp = array[i]; + array[i] = array[j]; + array[j] = temp; + } +} + +/** + * Pushes an element to the start of the array, if found. + */ +export function pushToStart(arr: T[], value: T): void { + const index = arr.indexOf(value); + + if (index > -1) { + arr.splice(index, 1); + arr.unshift(value); + } +} + +/** + * Pushes an element to the end of the array, if found. + */ +export function pushToEnd(arr: T[], value: T): void { + const index = arr.indexOf(value); + + if (index > -1) { + arr.splice(index, 1); + arr.push(value); + } +} + +export function pushMany(arr: T[], items: ReadonlyArray): void { + for (const item of items) { + arr.push(item); + } +} + +export function mapArrayOrNot(items: T | T[], fn: (_: T) => U): U | U[] { + return Array.isArray(items) ? + items.map(fn) : + fn(items); +} + +export function asArray(x: T | T[]): T[]; +export function asArray(x: T | readonly T[]): readonly T[]; +export function asArray(x: T | T[]): T[] { + return Array.isArray(x) ? x : [x]; +} + +export function getRandomElement(arr: T[]): T | undefined { + return arr[Math.floor(Math.random() * arr.length)]; +} + +/** + * Insert the new items in the array. + * @param array The original array. + * @param start The zero-based location in the array from which to start inserting elements. + * @param newItems The items to be inserted + */ +export function insertInto(array: T[], start: number, newItems: T[]): void { + const startIdx = getActualStartIndex(array, start); + const originalLength = array.length; + const newItemsLength = newItems.length; + array.length = originalLength + newItemsLength; + // Move the items after the start index, start from the end so that we don't overwrite any value. + for (let i = originalLength - 1; i >= startIdx; i--) { + array[i + newItemsLength] = array[i]; + } + + for (let i = 0; i < newItemsLength; i++) { + array[i + startIdx] = newItems[i]; + } +} + +/** + * Removes elements from an array and inserts new elements in their place, returning the deleted elements. Alternative to the native Array.splice method, it + * can only support limited number of items due to the maximum call stack size limit. + * @param array The original array. + * @param start The zero-based location in the array from which to start removing elements. + * @param deleteCount The number of elements to remove. + * @returns An array containing the elements that were deleted. + */ +export function splice(array: T[], start: number, deleteCount: number, newItems: T[]): T[] { + const index = getActualStartIndex(array, start); + let result = array.splice(index, deleteCount); + if (result === undefined) { + // see https://bugs.webkit.org/show_bug.cgi?id=261140 + result = []; + } + insertInto(array, index, newItems); + return result; +} + +/** + * Determine the actual start index (same logic as the native splice() or slice()) + * If greater than the length of the array, start will be set to the length of the array. In this case, no element will be deleted but the method will behave as an adding function, adding as many element as item[n*] provided. + * If negative, it will begin that many elements from the end of the array. (In this case, the origin -1, meaning -n is the index of the nth last element, and is therefore equivalent to the index of array.length - n.) If array.length + start is less than 0, it will begin from index 0. + * @param array The target array. + * @param start The operation index. + */ +function getActualStartIndex(array: T[], start: number): number { + return start < 0 ? Math.max(start + array.length, 0) : Math.min(start, array.length); +} + +/** + * When comparing two values, + * a negative number indicates that the first value is less than the second, + * a positive number indicates that the first value is greater than the second, + * and zero indicates that neither is the case. +*/ +export type CompareResult = number; + +export namespace CompareResult { + export function isLessThan(result: CompareResult): boolean { + return result < 0; + } + + export function isLessThanOrEqual(result: CompareResult): boolean { + return result <= 0; + } + + export function isGreaterThan(result: CompareResult): boolean { + return result > 0; + } + + export function isNeitherLessOrGreaterThan(result: CompareResult): boolean { + return result === 0; + } + + export const greaterThan = 1; + export const lessThan = -1; + export const neitherLessOrGreaterThan = 0; +} + +/** + * A comparator `c` defines a total order `<=` on `T` as following: + * `c(a, b) <= 0` iff `a` <= `b`. + * We also have `c(a, b) == 0` iff `c(b, a) == 0`. +*/ +export type Comparator = (a: T, b: T) => CompareResult; + +export function compareBy(selector: (item: TItem) => TCompareBy, comparator: Comparator): Comparator { + return (a, b) => comparator(selector(a), selector(b)); +} + +export function tieBreakComparators(...comparators: Comparator[]): Comparator { + return (item1, item2) => { + for (const comparator of comparators) { + const result = comparator(item1, item2); + if (!CompareResult.isNeitherLessOrGreaterThan(result)) { + return result; + } + } + return CompareResult.neitherLessOrGreaterThan; + }; +} + +/** + * The natural order on numbers. +*/ +export const numberComparator: Comparator = (a, b) => a - b; + +export const booleanComparator: Comparator = (a, b) => numberComparator(a ? 1 : 0, b ? 1 : 0); + +export function reverseOrder(comparator: Comparator): Comparator { + return (a, b) => -comparator(a, b); +} + +export class ArrayQueue { + private firstIdx = 0; + private lastIdx = this.items.length - 1; + + /** + * Constructs a queue that is backed by the given array. Runtime is O(1). + */ + constructor(private readonly items: readonly T[]) { } + + get length(): number { + return this.lastIdx - this.firstIdx + 1; + } + + /** + * Consumes elements from the beginning of the queue as long as the predicate returns true. + * If no elements were consumed, `null` is returned. Has a runtime of O(result.length). + */ + takeWhile(predicate: (value: T) => boolean): T[] | null { + // P(k) := k <= this.lastIdx && predicate(this.items[k]) + // Find s := min { k | k >= this.firstIdx && !P(k) } and return this.data[this.firstIdx...s) + + let startIdx = this.firstIdx; + while (startIdx < this.items.length && predicate(this.items[startIdx])) { + startIdx++; + } + const result = startIdx === this.firstIdx ? null : this.items.slice(this.firstIdx, startIdx); + this.firstIdx = startIdx; + return result; + } + + /** + * Consumes elements from the end of the queue as long as the predicate returns true. + * If no elements were consumed, `null` is returned. + * The result has the same order as the underlying array! + */ + takeFromEndWhile(predicate: (value: T) => boolean): T[] | null { + // P(k) := this.firstIdx >= k && predicate(this.items[k]) + // Find s := max { k | k <= this.lastIdx && !P(k) } and return this.data(s...this.lastIdx] + + let endIdx = this.lastIdx; + while (endIdx >= 0 && predicate(this.items[endIdx])) { + endIdx--; + } + const result = endIdx === this.lastIdx ? null : this.items.slice(endIdx + 1, this.lastIdx + 1); + this.lastIdx = endIdx; + return result; + } + + peek(): T | undefined { + if (this.length === 0) { + return undefined; + } + return this.items[this.firstIdx]; + } + + peekLast(): T | undefined { + if (this.length === 0) { + return undefined; + } + return this.items[this.lastIdx]; + } + + dequeue(): T | undefined { + const result = this.items[this.firstIdx]; + this.firstIdx++; + return result; + } + + removeLast(): T | undefined { + const result = this.items[this.lastIdx]; + this.lastIdx--; + return result; + } + + takeCount(count: number): T[] { + const result = this.items.slice(this.firstIdx, this.firstIdx + count); + this.firstIdx += count; + return result; + } +} + +/** + * This class is faster than an iterator and array for lazy computed data. +*/ +export class CallbackIterable { + public static readonly empty = new CallbackIterable(_callback => { }); + + constructor( + /** + * Calls the callback for every item. + * Stops when the callback returns false. + */ + public readonly iterate: (callback: (item: T) => boolean) => void + ) { + } + + forEach(handler: (item: T) => void) { + this.iterate(item => { handler(item); return true; }); + } + + toArray(): T[] { + const result: T[] = []; + this.iterate(item => { result.push(item); return true; }); + return result; + } + + filter(predicate: (item: T) => boolean): CallbackIterable { + return new CallbackIterable(cb => this.iterate(item => predicate(item) ? cb(item) : true)); + } + + map(mapFn: (item: T) => TResult): CallbackIterable { + return new CallbackIterable(cb => this.iterate(item => cb(mapFn(item)))); + } + + some(predicate: (item: T) => boolean): boolean { + let result = false; + this.iterate(item => { result = predicate(item); return !result; }); + return result; + } + + findFirst(predicate: (item: T) => boolean): T | undefined { + let result: T | undefined; + this.iterate(item => { + if (predicate(item)) { + result = item; + return false; + } + return true; + }); + return result; + } + + findLast(predicate: (item: T) => boolean): T | undefined { + let result: T | undefined; + this.iterate(item => { + if (predicate(item)) { + result = item; + } + return true; + }); + return result; + } + + findLastMaxBy(comparator: Comparator): T | undefined { + let result: T | undefined; + let first = true; + this.iterate(item => { + if (first || CompareResult.isGreaterThan(comparator(item, result!))) { + first = false; + result = item; + } + return true; + }); + return result; + } +} + +/** + * Represents a re-arrangement of items in an array. + */ +export class Permutation { + constructor(private readonly _indexMap: readonly number[]) { } + + /** + * Returns a permutation that sorts the given array according to the given compare function. + */ + public static createSortPermutation(arr: readonly T[], compareFn: (a: T, b: T) => number): Permutation { + const sortIndices = Array.from(arr.keys()).sort((index1, index2) => compareFn(arr[index1], arr[index2])); + return new Permutation(sortIndices); + } + + /** + * Returns a new array with the elements of the given array re-arranged according to this permutation. + */ + apply(arr: readonly T[]): T[] { + return arr.map((_, index) => arr[this._indexMap[index]]); + } + + /** + * Returns a new permutation that undoes the re-arrangement of this permutation. + */ + inverse(): Permutation { + const inverseIndexMap = this._indexMap.slice(); + for (let i = 0; i < this._indexMap.length; i++) { + inverseIndexMap[this._indexMap[i]] = i; + } + return new Permutation(inverseIndexMap); + } +} diff --git a/node_modules/@xterm/xterm/src/vs/base/common/arraysFind.ts b/node_modules/@xterm/xterm/src/vs/base/common/arraysFind.ts new file mode 100644 index 0000000..1dd102e --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/common/arraysFind.ts @@ -0,0 +1,202 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { Comparator } from './arrays'; + +export function findLast(array: readonly T[], predicate: (item: T) => boolean): T | undefined { + const idx = findLastIdx(array, predicate); + if (idx === -1) { + return undefined; + } + return array[idx]; +} + +export function findLastIdx(array: readonly T[], predicate: (item: T) => boolean, fromIndex = array.length - 1): number { + for (let i = fromIndex; i >= 0; i--) { + const element = array[i]; + + if (predicate(element)) { + return i; + } + } + + return -1; +} + +/** + * Finds the last item where predicate is true using binary search. + * `predicate` must be monotonous, i.e. `arr.map(predicate)` must be like `[true, ..., true, false, ..., false]`! + * + * @returns `undefined` if no item matches, otherwise the last item that matches the predicate. + */ +export function findLastMonotonous(array: readonly T[], predicate: (item: T) => boolean): T | undefined { + const idx = findLastIdxMonotonous(array, predicate); + return idx === -1 ? undefined : array[idx]; +} + +/** + * Finds the last item where predicate is true using binary search. + * `predicate` must be monotonous, i.e. `arr.map(predicate)` must be like `[true, ..., true, false, ..., false]`! + * + * @returns `startIdx - 1` if predicate is false for all items, otherwise the index of the last item that matches the predicate. + */ +export function findLastIdxMonotonous(array: readonly T[], predicate: (item: T) => boolean, startIdx = 0, endIdxEx = array.length): number { + let i = startIdx; + let j = endIdxEx; + while (i < j) { + const k = Math.floor((i + j) / 2); + if (predicate(array[k])) { + i = k + 1; + } else { + j = k; + } + } + return i - 1; +} + +/** + * Finds the first item where predicate is true using binary search. + * `predicate` must be monotonous, i.e. `arr.map(predicate)` must be like `[false, ..., false, true, ..., true]`! + * + * @returns `undefined` if no item matches, otherwise the first item that matches the predicate. + */ +export function findFirstMonotonous(array: readonly T[], predicate: (item: T) => boolean): T | undefined { + const idx = findFirstIdxMonotonousOrArrLen(array, predicate); + return idx === array.length ? undefined : array[idx]; +} + +/** + * Finds the first item where predicate is true using binary search. + * `predicate` must be monotonous, i.e. `arr.map(predicate)` must be like `[false, ..., false, true, ..., true]`! + * + * @returns `endIdxEx` if predicate is false for all items, otherwise the index of the first item that matches the predicate. + */ +export function findFirstIdxMonotonousOrArrLen(array: readonly T[], predicate: (item: T) => boolean, startIdx = 0, endIdxEx = array.length): number { + let i = startIdx; + let j = endIdxEx; + while (i < j) { + const k = Math.floor((i + j) / 2); + if (predicate(array[k])) { + j = k; + } else { + i = k + 1; + } + } + return i; +} + +export function findFirstIdxMonotonous(array: readonly T[], predicate: (item: T) => boolean, startIdx = 0, endIdxEx = array.length): number { + const idx = findFirstIdxMonotonousOrArrLen(array, predicate, startIdx, endIdxEx); + return idx === array.length ? -1 : idx; +} + +/** + * Use this when + * * You have a sorted array + * * You query this array with a monotonous predicate to find the last item that has a certain property. + * * You query this array multiple times with monotonous predicates that get weaker and weaker. + */ +export class MonotonousArray { + public static assertInvariants = false; + + private _findLastMonotonousLastIdx = 0; + private _prevFindLastPredicate: ((item: T) => boolean) | undefined; + + constructor(private readonly _array: readonly T[]) { + } + + /** + * The predicate must be monotonous, i.e. `arr.map(predicate)` must be like `[true, ..., true, false, ..., false]`! + * For subsequent calls, current predicate must be weaker than (or equal to) the previous predicate, i.e. more entries must be `true`. + */ + findLastMonotonous(predicate: (item: T) => boolean): T | undefined { + if (MonotonousArray.assertInvariants) { + if (this._prevFindLastPredicate) { + for (const item of this._array) { + if (this._prevFindLastPredicate(item) && !predicate(item)) { + throw new Error('MonotonousArray: current predicate must be weaker than (or equal to) the previous predicate.'); + } + } + } + this._prevFindLastPredicate = predicate; + } + + const idx = findLastIdxMonotonous(this._array, predicate, this._findLastMonotonousLastIdx); + this._findLastMonotonousLastIdx = idx + 1; + return idx === -1 ? undefined : this._array[idx]; + } +} + +/** + * Returns the first item that is equal to or greater than every other item. +*/ +export function findFirstMax(array: readonly T[], comparator: Comparator): T | undefined { + if (array.length === 0) { + return undefined; + } + + let max = array[0]; + for (let i = 1; i < array.length; i++) { + const item = array[i]; + if (comparator(item, max) > 0) { + max = item; + } + } + return max; +} + +/** + * Returns the last item that is equal to or greater than every other item. +*/ +export function findLastMax(array: readonly T[], comparator: Comparator): T | undefined { + if (array.length === 0) { + return undefined; + } + + let max = array[0]; + for (let i = 1; i < array.length; i++) { + const item = array[i]; + if (comparator(item, max) >= 0) { + max = item; + } + } + return max; +} + +/** + * Returns the first item that is equal to or less than every other item. +*/ +export function findFirstMin(array: readonly T[], comparator: Comparator): T | undefined { + return findFirstMax(array, (a, b) => -comparator(a, b)); +} + +export function findMaxIdx(array: readonly T[], comparator: Comparator): number { + if (array.length === 0) { + return -1; + } + + let maxIdx = 0; + for (let i = 1; i < array.length; i++) { + const item = array[i]; + if (comparator(item, array[maxIdx]) > 0) { + maxIdx = i; + } + } + return maxIdx; +} + +/** + * Returns the first mapped value of the array which is not undefined. + */ +export function mapFindFirst(items: Iterable, mapFn: (value: T) => R | undefined): R | undefined { + for (const value of items) { + const mapped = mapFn(value); + if (mapped !== undefined) { + return mapped; + } + } + + return undefined; +} diff --git a/node_modules/@xterm/xterm/src/vs/base/common/assert.ts b/node_modules/@xterm/xterm/src/vs/base/common/assert.ts new file mode 100644 index 0000000..bbd344d --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/common/assert.ts @@ -0,0 +1,71 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { BugIndicatingError, onUnexpectedError } from 'vs/base/common/errors'; + +/** + * Throws an error with the provided message if the provided value does not evaluate to a true Javascript value. + * + * @deprecated Use `assert(...)` instead. + * This method is usually used like this: + * ```ts + * import * as assert from 'vs/base/common/assert'; + * assert.ok(...); + * ``` + * + * However, `assert` in that example is a user chosen name. + * There is no tooling for generating such an import statement. + * Thus, the `assert(...)` function should be used instead. + */ +export function ok(value?: unknown, message?: string) { + if (!value) { + throw new Error(message ? `Assertion failed (${message})` : 'Assertion Failed'); + } +} + +export function assertNever(value: never, message = 'Unreachable'): never { + throw new Error(message); +} + +export function assert(condition: boolean, message = 'unexpected state'): asserts condition { + if (!condition) { + throw new BugIndicatingError(`Assertion Failed: ${message}`); + } +} + +/** + * Like assert, but doesn't throw. + */ +export function softAssert(condition: boolean): void { + if (!condition) { + onUnexpectedError(new BugIndicatingError('Soft Assertion Failed')); + } +} + +/** + * condition must be side-effect free! + */ +export function assertFn(condition: () => boolean): void { + if (!condition()) { + // eslint-disable-next-line no-debugger + debugger; + // Reevaluate `condition` again to make debugging easier + condition(); + onUnexpectedError(new BugIndicatingError('Assertion Failed')); + } +} + +export function checkAdjacentItems(items: readonly T[], predicate: (item1: T, item2: T) => boolean): boolean { + let i = 0; + while (i < items.length - 1) { + const a = items[i]; + const b = items[i + 1]; + if (!predicate(a, b)) { + return false; + } + i++; + } + return true; +} diff --git a/node_modules/@xterm/xterm/src/vs/base/common/async.ts b/node_modules/@xterm/xterm/src/vs/base/common/async.ts new file mode 100644 index 0000000..c0b2669 --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/common/async.ts @@ -0,0 +1,1992 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { CancellationToken, CancellationTokenSource } from 'vs/base/common/cancellation'; +import { BugIndicatingError, CancellationError } from 'vs/base/common/errors'; +import { Emitter, Event } from 'vs/base/common/event'; +import { Disposable, DisposableStore, IDisposable, MutableDisposable, toDisposable } from 'vs/base/common/lifecycle'; +import { setTimeout0 } from 'vs/base/common/platform'; +import { MicrotaskDelay } from './symbols'; +import { Lazy } from 'vs/base/common/lazy'; + +export function isThenable(obj: unknown): obj is Promise { + return !!obj && typeof (obj as unknown as Promise).then === 'function'; +} + +export interface CancelablePromise extends Promise { + cancel(): void; +} + +export function createCancelablePromise(callback: (token: CancellationToken) => Promise): CancelablePromise { + const source = new CancellationTokenSource(); + + const thenable = callback(source.token); + const promise = new Promise((resolve, reject) => { + const subscription = source.token.onCancellationRequested(() => { + subscription.dispose(); + reject(new CancellationError()); + }); + Promise.resolve(thenable).then(value => { + subscription.dispose(); + source.dispose(); + resolve(value); + }, err => { + subscription.dispose(); + source.dispose(); + reject(err); + }); + }); + + return >new class { + cancel() { + source.cancel(); + source.dispose(); + } + then(resolve?: ((value: T) => TResult1 | Promise) | undefined | null, reject?: ((reason: any) => TResult2 | Promise) | undefined | null): Promise { + return promise.then(resolve, reject); + } + catch(reject?: ((reason: any) => TResult | Promise) | undefined | null): Promise { + return this.then(undefined, reject); + } + finally(onfinally?: (() => void) | undefined | null): Promise { + return promise.finally(onfinally); + } + }; +} + +/** + * Returns a promise that resolves with `undefined` as soon as the passed token is cancelled. + * @see {@link raceCancellationError} + */ +export function raceCancellation(promise: Promise, token: CancellationToken): Promise; + +/** + * Returns a promise that resolves with `defaultValue` as soon as the passed token is cancelled. + * @see {@link raceCancellationError} + */ +export function raceCancellation(promise: Promise, token: CancellationToken, defaultValue: T): Promise; + +export function raceCancellation(promise: Promise, token: CancellationToken, defaultValue?: T): Promise { + return new Promise((resolve, reject) => { + const ref = token.onCancellationRequested(() => { + ref.dispose(); + resolve(defaultValue); + }); + promise.then(resolve, reject).finally(() => ref.dispose()); + }); +} + +/** + * Returns a promise that rejects with an {@CancellationError} as soon as the passed token is cancelled. + * @see {@link raceCancellation} + */ +export function raceCancellationError(promise: Promise, token: CancellationToken): Promise { + return new Promise((resolve, reject) => { + const ref = token.onCancellationRequested(() => { + ref.dispose(); + reject(new CancellationError()); + }); + promise.then(resolve, reject).finally(() => ref.dispose()); + }); +} + +/** + * Returns as soon as one of the promises resolves or rejects and cancels remaining promises + */ +export async function raceCancellablePromises(cancellablePromises: CancelablePromise[]): Promise { + let resolvedPromiseIndex = -1; + const promises = cancellablePromises.map((promise, index) => promise.then(result => { resolvedPromiseIndex = index; return result; })); + try { + const result = await Promise.race(promises); + return result; + } finally { + cancellablePromises.forEach((cancellablePromise, index) => { + if (index !== resolvedPromiseIndex) { + cancellablePromise.cancel(); + } + }); + } +} + +export function raceTimeout(promise: Promise, timeout: number, onTimeout?: () => void): Promise { + let promiseResolve: ((value: T | undefined) => void) | undefined = undefined; + + const timer = setTimeout(() => { + promiseResolve?.(undefined); + onTimeout?.(); + }, timeout); + + return Promise.race([ + promise.finally(() => clearTimeout(timer)), + new Promise(resolve => promiseResolve = resolve) + ]); +} + +export function asPromise(callback: () => T | PromiseLike): Promise { + return new Promise((resolve, reject) => { + const item = callback(); + if (isThenable(item)) { + item.then(resolve, reject); + } else { + resolve(item); + } + }); +} + +/** + * Creates and returns a new promise, plus its `resolve` and `reject` callbacks. + * + * Replace with standardized [`Promise.withResolvers`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/withResolvers) once it is supported + */ +export function promiseWithResolvers(): { promise: Promise; resolve: (value: T | PromiseLike) => void; reject: (err?: any) => void } { + let resolve: (value: T | PromiseLike) => void; + let reject: (reason?: any) => void; + const promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + return { promise, resolve: resolve!, reject: reject! }; +} + +export interface ITask { + (): T; +} + +/** + * A helper to prevent accumulation of sequential async tasks. + * + * Imagine a mail man with the sole task of delivering letters. As soon as + * a letter submitted for delivery, he drives to the destination, delivers it + * and returns to his base. Imagine that during the trip, N more letters were submitted. + * When the mail man returns, he picks those N letters and delivers them all in a + * single trip. Even though N+1 submissions occurred, only 2 deliveries were made. + * + * The throttler implements this via the queue() method, by providing it a task + * factory. Following the example: + * + * const throttler = new Throttler(); + * const letters = []; + * + * function deliver() { + * const lettersToDeliver = letters; + * letters = []; + * return makeTheTrip(lettersToDeliver); + * } + * + * function onLetterReceived(l) { + * letters.push(l); + * throttler.queue(deliver); + * } + */ +export class Throttler implements IDisposable { + + private activePromise: Promise | null; + private queuedPromise: Promise | null; + private queuedPromiseFactory: ITask> | null; + + private isDisposed = false; + + constructor() { + this.activePromise = null; + this.queuedPromise = null; + this.queuedPromiseFactory = null; + } + + queue(promiseFactory: ITask>): Promise { + if (this.isDisposed) { + return Promise.reject(new Error('Throttler is disposed')); + } + + if (this.activePromise) { + this.queuedPromiseFactory = promiseFactory; + + if (!this.queuedPromise) { + const onComplete = () => { + this.queuedPromise = null; + + if (this.isDisposed) { + return; + } + + const result = this.queue(this.queuedPromiseFactory!); + this.queuedPromiseFactory = null; + + return result; + }; + + this.queuedPromise = new Promise(resolve => { + this.activePromise!.then(onComplete, onComplete).then(resolve); + }); + } + + return new Promise((resolve, reject) => { + this.queuedPromise!.then(resolve, reject); + }); + } + + this.activePromise = promiseFactory(); + + return new Promise((resolve, reject) => { + this.activePromise!.then((result: T) => { + this.activePromise = null; + resolve(result); + }, (err: unknown) => { + this.activePromise = null; + reject(err); + }); + }); + } + + dispose(): void { + this.isDisposed = true; + } +} + +export class Sequencer { + + private current: Promise = Promise.resolve(null); + + queue(promiseTask: ITask>): Promise { + return this.current = this.current.then(() => promiseTask(), () => promiseTask()); + } +} + +export class SequencerByKey { + + private promiseMap = new Map>(); + + queue(key: TKey, promiseTask: ITask>): Promise { + const runningPromise = this.promiseMap.get(key) ?? Promise.resolve(); + const newPromise = runningPromise + .catch(() => { }) + .then(promiseTask) + .finally(() => { + if (this.promiseMap.get(key) === newPromise) { + this.promiseMap.delete(key); + } + }); + this.promiseMap.set(key, newPromise); + return newPromise; + } +} + +interface IScheduledLater extends IDisposable { + isTriggered(): boolean; +} + +const timeoutDeferred = (timeout: number, fn: () => void): IScheduledLater => { + let scheduled = true; + const handle = setTimeout(() => { + scheduled = false; + fn(); + }, timeout); + return { + isTriggered: () => scheduled, + dispose: () => { + clearTimeout(handle); + scheduled = false; + }, + }; +}; + +const microtaskDeferred = (fn: () => void): IScheduledLater => { + let scheduled = true; + queueMicrotask(() => { + if (scheduled) { + scheduled = false; + fn(); + } + }); + + return { + isTriggered: () => scheduled, + dispose: () => { scheduled = false; }, + }; +}; + +/** + * A helper to delay (debounce) execution of a task that is being requested often. + * + * Following the throttler, now imagine the mail man wants to optimize the number of + * trips proactively. The trip itself can be long, so he decides not to make the trip + * as soon as a letter is submitted. Instead he waits a while, in case more + * letters are submitted. After said waiting period, if no letters were submitted, he + * decides to make the trip. Imagine that N more letters were submitted after the first + * one, all within a short period of time between each other. Even though N+1 + * submissions occurred, only 1 delivery was made. + * + * The delayer offers this behavior via the trigger() method, into which both the task + * to be executed and the waiting period (delay) must be passed in as arguments. Following + * the example: + * + * const delayer = new Delayer(WAITING_PERIOD); + * const letters = []; + * + * function letterReceived(l) { + * letters.push(l); + * delayer.trigger(() => { return makeTheTrip(); }); + * } + */ +export class Delayer implements IDisposable { + + private deferred: IScheduledLater | null; + private completionPromise: Promise | null; + private doResolve: ((value?: any | Promise) => void) | null; + private doReject: ((err: any) => void) | null; + private task: ITask> | null; + + constructor(public defaultDelay: number | typeof MicrotaskDelay) { + this.deferred = null; + this.completionPromise = null; + this.doResolve = null; + this.doReject = null; + this.task = null; + } + + trigger(task: ITask>, delay = this.defaultDelay): Promise { + this.task = task; + this.cancelTimeout(); + + if (!this.completionPromise) { + this.completionPromise = new Promise((resolve, reject) => { + this.doResolve = resolve; + this.doReject = reject; + }).then(() => { + this.completionPromise = null; + this.doResolve = null; + if (this.task) { + const task = this.task; + this.task = null; + return task(); + } + return undefined; + }); + } + + const fn = () => { + this.deferred = null; + this.doResolve?.(null); + }; + + this.deferred = delay === MicrotaskDelay ? microtaskDeferred(fn) : timeoutDeferred(delay, fn); + + return this.completionPromise; + } + + isTriggered(): boolean { + return !!this.deferred?.isTriggered(); + } + + cancel(): void { + this.cancelTimeout(); + + if (this.completionPromise) { + this.doReject?.(new CancellationError()); + this.completionPromise = null; + } + } + + private cancelTimeout(): void { + this.deferred?.dispose(); + this.deferred = null; + } + + dispose(): void { + this.cancel(); + } +} + +/** + * A helper to delay execution of a task that is being requested often, while + * preventing accumulation of consecutive executions, while the task runs. + * + * The mail man is clever and waits for a certain amount of time, before going + * out to deliver letters. While the mail man is going out, more letters arrive + * and can only be delivered once he is back. Once he is back the mail man will + * do one more trip to deliver the letters that have accumulated while he was out. + */ +export class ThrottledDelayer { + + private delayer: Delayer>; + private throttler: Throttler; + + constructor(defaultDelay: number) { + this.delayer = new Delayer(defaultDelay); + this.throttler = new Throttler(); + } + + trigger(promiseFactory: ITask>, delay?: number): Promise { + return this.delayer.trigger(() => this.throttler.queue(promiseFactory), delay) as unknown as Promise; + } + + isTriggered(): boolean { + return this.delayer.isTriggered(); + } + + cancel(): void { + this.delayer.cancel(); + } + + dispose(): void { + this.delayer.dispose(); + this.throttler.dispose(); + } +} + +/** + * A barrier that is initially closed and then becomes opened permanently. + */ +export class Barrier { + private _isOpen: boolean; + private _promise: Promise; + private _completePromise!: (v: boolean) => void; + + constructor() { + this._isOpen = false; + this._promise = new Promise((c, e) => { + this._completePromise = c; + }); + } + + isOpen(): boolean { + return this._isOpen; + } + + open(): void { + this._isOpen = true; + this._completePromise(true); + } + + wait(): Promise { + return this._promise; + } +} + +/** + * A barrier that is initially closed and then becomes opened permanently after a certain period of + * time or when open is called explicitly + */ +export class AutoOpenBarrier extends Barrier { + + private readonly _timeout: any; + + constructor(autoOpenTimeMs: number) { + super(); + this._timeout = setTimeout(() => this.open(), autoOpenTimeMs); + } + + override open(): void { + clearTimeout(this._timeout); + super.open(); + } +} + +export function timeout(millis: number): CancelablePromise; +export function timeout(millis: number, token: CancellationToken): Promise; +export function timeout(millis: number, token?: CancellationToken): CancelablePromise | Promise { + if (!token) { + return createCancelablePromise(token => timeout(millis, token)); + } + + return new Promise((resolve, reject) => { + const handle = setTimeout(() => { + disposable.dispose(); + resolve(); + }, millis); + const disposable = token.onCancellationRequested(() => { + clearTimeout(handle); + disposable.dispose(); + reject(new CancellationError()); + }); + }); +} + +/** + * Creates a timeout that can be disposed using its returned value. + * @param handler The timeout handler. + * @param timeout An optional timeout in milliseconds. + * @param store An optional {@link DisposableStore} that will have the timeout disposable managed automatically. + * + * @example + * const store = new DisposableStore; + * // Call the timeout after 1000ms at which point it will be automatically + * // evicted from the store. + * const timeoutDisposable = disposableTimeout(() => {}, 1000, store); + * + * if (foo) { + * // Cancel the timeout and evict it from store. + * timeoutDisposable.dispose(); + * } + */ +export function disposableTimeout(handler: () => void, timeout = 0, store?: DisposableStore): IDisposable { + const timer = setTimeout(() => { + handler(); + if (store) { + disposable.dispose(); + } + }, timeout); + const disposable = toDisposable(() => { + clearTimeout(timer); + store?.deleteAndLeak(disposable); + }); + store?.add(disposable); + return disposable; +} + +/** + * Runs the provided list of promise factories in sequential order. The returned + * promise will complete to an array of results from each promise. + */ + +export function sequence(promiseFactories: ITask>[]): Promise { + const results: T[] = []; + let index = 0; + const len = promiseFactories.length; + + function next(): Promise | null { + return index < len ? promiseFactories[index++]() : null; + } + + function thenHandler(result: any): Promise { + if (result !== undefined && result !== null) { + results.push(result); + } + + const n = next(); + if (n) { + return n.then(thenHandler); + } + + return Promise.resolve(results); + } + + return Promise.resolve(null).then(thenHandler); +} + +export function first(promiseFactories: ITask>[], shouldStop: (t: T) => boolean = t => !!t, defaultValue: T | null = null): Promise { + let index = 0; + const len = promiseFactories.length; + + const loop: () => Promise = () => { + if (index >= len) { + return Promise.resolve(defaultValue); + } + + const factory = promiseFactories[index++]; + const promise = Promise.resolve(factory()); + + return promise.then(result => { + if (shouldStop(result)) { + return Promise.resolve(result); + } + + return loop(); + }); + }; + + return loop(); +} + +/** + * Returns the result of the first promise that matches the "shouldStop", + * running all promises in parallel. Supports cancelable promises. + */ +export function firstParallel(promiseList: Promise[], shouldStop?: (t: T) => boolean, defaultValue?: T | null): Promise; +export function firstParallel(promiseList: Promise[], shouldStop: (t: T) => t is R, defaultValue?: R | null): Promise; +export function firstParallel(promiseList: Promise[], shouldStop: (t: T) => boolean = t => !!t, defaultValue: T | null = null) { + if (promiseList.length === 0) { + return Promise.resolve(defaultValue); + } + + let todo = promiseList.length; + const finish = () => { + todo = -1; + for (const promise of promiseList) { + (promise as Partial>).cancel?.(); + } + }; + + return new Promise((resolve, reject) => { + for (const promise of promiseList) { + promise.then(result => { + if (--todo >= 0 && shouldStop(result)) { + finish(); + resolve(result); + } else if (todo === 0) { + resolve(defaultValue); + } + }) + .catch(err => { + if (--todo >= 0) { + finish(); + reject(err); + } + }); + } + }); +} + +interface ILimitedTaskFactory { + factory: ITask>; + c: (value: T | Promise) => void; + e: (error?: unknown) => void; +} + +export interface ILimiter { + + readonly size: number; + + queue(factory: ITask>): Promise; + + clear(): void; +} + +/** + * A helper to queue N promises and run them all with a max degree of parallelism. The helper + * ensures that at any time no more than M promises are running at the same time. + */ +export class Limiter implements ILimiter { + + private _size = 0; + private _isDisposed = false; + private runningPromises: number; + private readonly maxDegreeOfParalellism: number; + private readonly outstandingPromises: ILimitedTaskFactory[]; + private readonly _onDrained: Emitter; + + constructor(maxDegreeOfParalellism: number) { + this.maxDegreeOfParalellism = maxDegreeOfParalellism; + this.outstandingPromises = []; + this.runningPromises = 0; + this._onDrained = new Emitter(); + } + + /** + * + * @returns A promise that resolved when all work is done (onDrained) or when + * there is nothing to do + */ + whenIdle(): Promise { + return this.size > 0 + ? Event.toPromise(this.onDrained) + : Promise.resolve(); + } + + get onDrained(): Event { + return this._onDrained.event; + } + + get size(): number { + return this._size; + } + + queue(factory: ITask>): Promise { + if (this._isDisposed) { + throw new Error('Object has been disposed'); + } + this._size++; + + return new Promise((c, e) => { + this.outstandingPromises.push({ factory, c, e }); + this.consume(); + }); + } + + private consume(): void { + while (this.outstandingPromises.length && this.runningPromises < this.maxDegreeOfParalellism) { + const iLimitedTask = this.outstandingPromises.shift()!; + this.runningPromises++; + + const promise = iLimitedTask.factory(); + promise.then(iLimitedTask.c, iLimitedTask.e); + promise.then(() => this.consumed(), () => this.consumed()); + } + } + + private consumed(): void { + if (this._isDisposed) { + return; + } + this.runningPromises--; + if (--this._size === 0) { + this._onDrained.fire(); + } + + if (this.outstandingPromises.length > 0) { + this.consume(); + } + } + + clear(): void { + if (this._isDisposed) { + throw new Error('Object has been disposed'); + } + this.outstandingPromises.length = 0; + this._size = this.runningPromises; + } + + dispose(): void { + this._isDisposed = true; + this.outstandingPromises.length = 0; // stop further processing + this._size = 0; + this._onDrained.dispose(); + } +} + +/** + * A queue is handles one promise at a time and guarantees that at any time only one promise is executing. + */ +export class Queue extends Limiter { + + constructor() { + super(1); + } +} + +/** + * Same as `Queue`, ensures that only 1 task is executed at the same time. The difference to `Queue` is that + * there is only 1 task about to be scheduled next. As such, calling `queue` while a task is executing will + * replace the currently queued task until it executes. + * + * As such, the returned promise may not be from the factory that is passed in but from the next factory that + * is running after having called `queue`. + */ +export class LimitedQueue { + + private readonly sequentializer = new TaskSequentializer(); + + private tasks = 0; + + queue(factory: ITask>): Promise { + if (!this.sequentializer.isRunning()) { + return this.sequentializer.run(this.tasks++, factory()); + } + + return this.sequentializer.queue(() => { + return this.sequentializer.run(this.tasks++, factory()); + }); + } +} + +export class TimeoutTimer implements IDisposable { + private _token: any; + private _isDisposed = false; + + constructor(); + constructor(runner: () => void, timeout: number); + constructor(runner?: () => void, timeout?: number) { + this._token = -1; + + if (typeof runner === 'function' && typeof timeout === 'number') { + this.setIfNotSet(runner, timeout); + } + } + + dispose(): void { + this.cancel(); + this._isDisposed = true; + } + + cancel(): void { + if (this._token !== -1) { + clearTimeout(this._token); + this._token = -1; + } + } + + cancelAndSet(runner: () => void, timeout: number): void { + if (this._isDisposed) { + throw new BugIndicatingError(`Calling 'cancelAndSet' on a disposed TimeoutTimer`); + } + + this.cancel(); + this._token = setTimeout(() => { + this._token = -1; + runner(); + }, timeout); + } + + setIfNotSet(runner: () => void, timeout: number): void { + if (this._isDisposed) { + throw new BugIndicatingError(`Calling 'setIfNotSet' on a disposed TimeoutTimer`); + } + + if (this._token !== -1) { + // timer is already set + return; + } + this._token = setTimeout(() => { + this._token = -1; + runner(); + }, timeout); + } +} + +export class IntervalTimer implements IDisposable { + + private disposable: IDisposable | undefined = undefined; + private isDisposed = false; + + cancel(): void { + this.disposable?.dispose(); + this.disposable = undefined; + } + + cancelAndSet(runner: () => void, interval: number, context = globalThis): void { + if (this.isDisposed) { + throw new BugIndicatingError(`Calling 'cancelAndSet' on a disposed IntervalTimer`); + } + + this.cancel(); + const handle = context.setInterval(() => { + runner(); + }, interval); + + this.disposable = toDisposable(() => { + context.clearInterval(handle); + this.disposable = undefined; + }); + } + + dispose(): void { + this.cancel(); + this.isDisposed = true; + } +} + +export class RunOnceScheduler implements IDisposable { + + protected runner: ((...args: unknown[]) => void) | null; + + private timeoutToken: any; + private timeout: number; + private timeoutHandler: () => void; + + constructor(runner: (...args: any[]) => void, delay: number) { + this.timeoutToken = -1; + this.runner = runner; + this.timeout = delay; + this.timeoutHandler = this.onTimeout.bind(this); + } + + /** + * Dispose RunOnceScheduler + */ + dispose(): void { + this.cancel(); + this.runner = null; + } + + /** + * Cancel current scheduled runner (if any). + */ + cancel(): void { + if (this.isScheduled()) { + clearTimeout(this.timeoutToken); + this.timeoutToken = -1; + } + } + + /** + * Cancel previous runner (if any) & schedule a new runner. + */ + schedule(delay = this.timeout): void { + this.cancel(); + this.timeoutToken = setTimeout(this.timeoutHandler, delay); + } + + get delay(): number { + return this.timeout; + } + + set delay(value: number) { + this.timeout = value; + } + + /** + * Returns true if scheduled. + */ + isScheduled(): boolean { + return this.timeoutToken !== -1; + } + + flush(): void { + if (this.isScheduled()) { + this.cancel(); + this.doRun(); + } + } + + private onTimeout() { + this.timeoutToken = -1; + if (this.runner) { + this.doRun(); + } + } + + protected doRun(): void { + this.runner?.(); + } +} + +/** + * Same as `RunOnceScheduler`, but doesn't count the time spent in sleep mode. + * > **NOTE**: Only offers 1s resolution. + * + * When calling `setTimeout` with 3hrs, and putting the computer immediately to sleep + * for 8hrs, `setTimeout` will fire **as soon as the computer wakes from sleep**. But + * this scheduler will execute 3hrs **after waking the computer from sleep**. + */ +export class ProcessTimeRunOnceScheduler { + + private runner: (() => void) | null; + private timeout: number; + + private counter: number; + private intervalToken: any; + private intervalHandler: () => void; + + constructor(runner: () => void, delay: number) { + if (delay % 1000 !== 0) { + console.warn(`ProcessTimeRunOnceScheduler resolution is 1s, ${delay}ms is not a multiple of 1000ms.`); + } + this.runner = runner; + this.timeout = delay; + this.counter = 0; + this.intervalToken = -1; + this.intervalHandler = this.onInterval.bind(this); + } + + dispose(): void { + this.cancel(); + this.runner = null; + } + + cancel(): void { + if (this.isScheduled()) { + clearInterval(this.intervalToken); + this.intervalToken = -1; + } + } + + /** + * Cancel previous runner (if any) & schedule a new runner. + */ + schedule(delay = this.timeout): void { + if (delay % 1000 !== 0) { + console.warn(`ProcessTimeRunOnceScheduler resolution is 1s, ${delay}ms is not a multiple of 1000ms.`); + } + this.cancel(); + this.counter = Math.ceil(delay / 1000); + this.intervalToken = setInterval(this.intervalHandler, 1000); + } + + /** + * Returns true if scheduled. + */ + isScheduled(): boolean { + return this.intervalToken !== -1; + } + + private onInterval() { + this.counter--; + if (this.counter > 0) { + // still need to wait + return; + } + + // time elapsed + clearInterval(this.intervalToken); + this.intervalToken = -1; + this.runner?.(); + } +} + +export class RunOnceWorker extends RunOnceScheduler { + + private units: T[] = []; + + constructor(runner: (units: T[]) => void, timeout: number) { + super(runner, timeout); + } + + work(unit: T): void { + this.units.push(unit); + + if (!this.isScheduled()) { + this.schedule(); + } + } + + protected override doRun(): void { + const units = this.units; + this.units = []; + + this.runner?.(units); + } + + override dispose(): void { + this.units = []; + + super.dispose(); + } +} + +export interface IThrottledWorkerOptions { + + /** + * maximum of units the worker will pass onto handler at once + */ + maxWorkChunkSize: number; + + /** + * maximum of units the worker will keep in memory for processing + */ + maxBufferedWork: number | undefined; + + /** + * delay before processing the next round of chunks when chunk size exceeds limits + */ + throttleDelay: number; +} + +/** + * The `ThrottledWorker` will accept units of work `T` + * to handle. The contract is: + * * there is a maximum of units the worker can handle at once (via `maxWorkChunkSize`) + * * there is a maximum of units the worker will keep in memory for processing (via `maxBufferedWork`) + * * after having handled `maxWorkChunkSize` units, the worker needs to rest (via `throttleDelay`) + */ +export class ThrottledWorker extends Disposable { + + private readonly pendingWork: T[] = []; + + private readonly throttler = this._register(new MutableDisposable()); + private disposed = false; + + constructor( + private options: IThrottledWorkerOptions, + private readonly handler: (units: T[]) => void + ) { + super(); + } + + /** + * The number of work units that are pending to be processed. + */ + get pending(): number { return this.pendingWork.length; } + + /** + * Add units to be worked on. Use `pending` to figure out + * how many units are not yet processed after this method + * was called. + * + * @returns whether the work was accepted or not. If the + * worker is disposed, it will not accept any more work. + * If the number of pending units would become larger + * than `maxPendingWork`, more work will also not be accepted. + */ + work(units: readonly T[]): boolean { + if (this.disposed) { + return false; // work not accepted: disposed + } + + // Check for reaching maximum of pending work + if (typeof this.options.maxBufferedWork === 'number') { + + // Throttled: simple check if pending + units exceeds max pending + if (this.throttler.value) { + if (this.pending + units.length > this.options.maxBufferedWork) { + return false; // work not accepted: too much pending work + } + } + + // Unthrottled: same as throttled, but account for max chunk getting + // worked on directly without being pending + else { + if (this.pending + units.length - this.options.maxWorkChunkSize > this.options.maxBufferedWork) { + return false; // work not accepted: too much pending work + } + } + } + + // Add to pending units first + for (const unit of units) { + this.pendingWork.push(unit); + } + + // If not throttled, start working directly + // Otherwise, when the throttle delay has + // past, pending work will be worked again. + if (!this.throttler.value) { + this.doWork(); + } + + return true; // work accepted + } + + private doWork(): void { + + // Extract chunk to handle and handle it + this.handler(this.pendingWork.splice(0, this.options.maxWorkChunkSize)); + + // If we have remaining work, schedule it after a delay + if (this.pendingWork.length > 0) { + this.throttler.value = new RunOnceScheduler(() => { + this.throttler.clear(); + + this.doWork(); + }, this.options.throttleDelay); + this.throttler.value.schedule(); + } + } + + override dispose(): void { + super.dispose(); + + this.disposed = true; + } +} + +//#region -- run on idle tricks ------------ + +export interface IdleDeadline { + readonly didTimeout: boolean; + timeRemaining(): number; +} + +type IdleApi = Pick; + + +/** + * Execute the callback the next time the browser is idle, returning an + * {@link IDisposable} that will cancel the callback when disposed. This wraps + * [requestIdleCallback] so it will fallback to [setTimeout] if the environment + * doesn't support it. + * + * @param callback The callback to run when idle, this includes an + * [IdleDeadline] that provides the time alloted for the idle callback by the + * browser. Not respecting this deadline will result in a degraded user + * experience. + * @param timeout A timeout at which point to queue no longer wait for an idle + * callback but queue it on the regular event loop (like setTimeout). Typically + * this should not be used. + * + * [IdleDeadline]: https://developer.mozilla.org/en-US/docs/Web/API/IdleDeadline + * [requestIdleCallback]: https://developer.mozilla.org/en-US/docs/Web/API/Window/requestIdleCallback + * [setTimeout]: https://developer.mozilla.org/en-US/docs/Web/API/Window/setTimeout + * + * **Note** that there is `dom.ts#runWhenWindowIdle` which is better suited when running inside a browser + * context + */ +export let runWhenGlobalIdle: (callback: (idle: IdleDeadline) => void, timeout?: number) => IDisposable; + +export let _runWhenIdle: (targetWindow: IdleApi, callback: (idle: IdleDeadline) => void, timeout?: number) => IDisposable; + +(function () { + if (typeof globalThis.requestIdleCallback !== 'function' || typeof globalThis.cancelIdleCallback !== 'function') { + _runWhenIdle = (_targetWindow, runner) => { + setTimeout0(() => { + if (disposed) { + return; + } + const end = Date.now() + 15; // one frame at 64fps + const deadline: IdleDeadline = { + didTimeout: true, + timeRemaining() { + return Math.max(0, end - Date.now()); + } + }; + runner(Object.freeze(deadline)); + }); + let disposed = false; + return { + dispose() { + if (disposed) { + return; + } + disposed = true; + } + }; + }; + } else { + _runWhenIdle = (targetWindow: IdleApi, runner, timeout?) => { + const handle: number = targetWindow.requestIdleCallback(runner, typeof timeout === 'number' ? { timeout } : undefined); + let disposed = false; + return { + dispose() { + if (disposed) { + return; + } + disposed = true; + targetWindow.cancelIdleCallback(handle); + } + }; + }; + } + runWhenGlobalIdle = (runner) => _runWhenIdle(globalThis, runner); +})(); + +export abstract class AbstractIdleValue { + + private readonly _executor: () => void; + private readonly _handle: IDisposable; + + private _didRun: boolean = false; + private _value?: T; + private _error: unknown; + + constructor(targetWindow: IdleApi, executor: () => T) { + this._executor = () => { + try { + this._value = executor(); + } catch (err) { + this._error = err; + } finally { + this._didRun = true; + } + }; + this._handle = _runWhenIdle(targetWindow, () => this._executor()); + } + + dispose(): void { + this._handle.dispose(); + } + + get value(): T { + if (!this._didRun) { + this._handle.dispose(); + this._executor(); + } + if (this._error) { + throw this._error; + } + return this._value!; + } + + get isInitialized(): boolean { + return this._didRun; + } +} + +/** + * An `IdleValue` that always uses the current window (which might be throttled or inactive) + * + * **Note** that there is `dom.ts#WindowIdleValue` which is better suited when running inside a browser + * context + */ +export class GlobalIdleValue extends AbstractIdleValue { + + constructor(executor: () => T) { + super(globalThis, executor); + } +} + +//#endregion + +export async function retry(task: ITask>, delay: number, retries: number): Promise { + let lastError: Error | undefined; + + for (let i = 0; i < retries; i++) { + try { + return await task(); + } catch (error) { + lastError = error; + + await timeout(delay); + } + } + + throw lastError; +} + +//#region Task Sequentializer + +interface IRunningTask { + readonly taskId: number; + readonly cancel: () => void; + readonly promise: Promise; +} + +interface IQueuedTask { + readonly promise: Promise; + readonly promiseResolve: () => void; + readonly promiseReject: (error: Error) => void; + run: ITask>; +} + +export interface ITaskSequentializerWithRunningTask { + readonly running: Promise; +} + +export interface ITaskSequentializerWithQueuedTask { + readonly queued: IQueuedTask; +} + +/** + * @deprecated use `LimitedQueue` instead for an easier to use API + */ +export class TaskSequentializer { + + private _running?: IRunningTask; + private _queued?: IQueuedTask; + + isRunning(taskId?: number): this is ITaskSequentializerWithRunningTask { + if (typeof taskId === 'number') { + return this._running?.taskId === taskId; + } + + return !!this._running; + } + + get running(): Promise | undefined { + return this._running?.promise; + } + + cancelRunning(): void { + this._running?.cancel(); + } + + run(taskId: number, promise: Promise, onCancel?: () => void,): Promise { + this._running = { taskId, cancel: () => onCancel?.(), promise }; + + promise.then(() => this.doneRunning(taskId), () => this.doneRunning(taskId)); + + return promise; + } + + private doneRunning(taskId: number): void { + if (this._running && taskId === this._running.taskId) { + + // only set running to done if the promise finished that is associated with that taskId + this._running = undefined; + + // schedule the queued task now that we are free if we have any + this.runQueued(); + } + } + + private runQueued(): void { + if (this._queued) { + const queued = this._queued; + this._queued = undefined; + + // Run queued task and complete on the associated promise + queued.run().then(queued.promiseResolve, queued.promiseReject); + } + } + + /** + * Note: the promise to schedule as next run MUST itself call `run`. + * Otherwise, this sequentializer will report `false` for `isRunning` + * even when this task is running. Missing this detail means that + * suddenly multiple tasks will run in parallel. + */ + queue(run: ITask>): Promise { + + // this is our first queued task, so we create associated promise with it + // so that we can return a promise that completes when the task has + // completed. + if (!this._queued) { + const { promise, resolve: promiseResolve, reject: promiseReject } = promiseWithResolvers(); + this._queued = { + run, + promise, + promiseResolve: promiseResolve!, + promiseReject: promiseReject! + }; + } + + // we have a previous queued task, just overwrite it + else { + this._queued.run = run; + } + + return this._queued.promise; + } + + hasQueued(): this is ITaskSequentializerWithQueuedTask { + return !!this._queued; + } + + async join(): Promise { + return this._queued?.promise ?? this._running?.promise; + } +} + +//#endregion + +//#region + +/** + * The `IntervalCounter` allows to count the number + * of calls to `increment()` over a duration of + * `interval`. This utility can be used to conditionally + * throttle a frequent task when a certain threshold + * is reached. + */ +export class IntervalCounter { + + private lastIncrementTime = 0; + + private value = 0; + + constructor(private readonly interval: number, private readonly nowFn = () => Date.now()) { } + + increment(): number { + const now = this.nowFn(); + + // We are outside of the range of `interval` and as such + // start counting from 0 and remember the time + if (now - this.lastIncrementTime > this.interval) { + this.lastIncrementTime = now; + this.value = 0; + } + + this.value++; + + return this.value; + } +} + +//#endregion + +//#region + +export type ValueCallback = (value: T | Promise) => void; + +const enum DeferredOutcome { + Resolved, + Rejected +} + +/** + * Creates a promise whose resolution or rejection can be controlled imperatively. + */ +export class DeferredPromise { + + private completeCallback!: ValueCallback; + private errorCallback!: (err: unknown) => void; + private outcome?: { outcome: DeferredOutcome.Rejected; value: any } | { outcome: DeferredOutcome.Resolved; value: T }; + + public get isRejected() { + return this.outcome?.outcome === DeferredOutcome.Rejected; + } + + public get isResolved() { + return this.outcome?.outcome === DeferredOutcome.Resolved; + } + + public get isSettled() { + return !!this.outcome; + } + + public get value() { + return this.outcome?.outcome === DeferredOutcome.Resolved ? this.outcome?.value : undefined; + } + + public readonly p: Promise; + + constructor() { + this.p = new Promise((c, e) => { + this.completeCallback = c; + this.errorCallback = e; + }); + } + + public complete(value: T) { + return new Promise(resolve => { + this.completeCallback(value); + this.outcome = { outcome: DeferredOutcome.Resolved, value }; + resolve(); + }); + } + + public error(err: unknown) { + return new Promise(resolve => { + this.errorCallback(err); + this.outcome = { outcome: DeferredOutcome.Rejected, value: err }; + resolve(); + }); + } + + public cancel() { + return this.error(new CancellationError()); + } +} + +//#endregion + +//#region Promises + +export namespace Promises { + + /** + * A drop-in replacement for `Promise.all` with the only difference + * that the method awaits every promise to either fulfill or reject. + * + * Similar to `Promise.all`, only the first error will be returned + * if any. + */ + export async function settled(promises: Promise[]): Promise { + let firstError: Error | undefined = undefined; + + const result = await Promise.all(promises.map(promise => promise.then(value => value, error => { + if (!firstError) { + firstError = error; + } + + return undefined; // do not rethrow so that other promises can settle + }))); + + if (typeof firstError !== 'undefined') { + throw firstError; + } + + return result as unknown as T[]; // cast is needed and protected by the `throw` above + } + + /** + * A helper to create a new `Promise` with a body that is a promise + * itself. By default, an error that raises from the async body will + * end up as a unhandled rejection, so this utility properly awaits the + * body and rejects the promise as a normal promise does without async + * body. + * + * This method should only be used in rare cases where otherwise `async` + * cannot be used (e.g. when callbacks are involved that require this). + */ + export function withAsyncBody(bodyFn: (resolve: (value: T) => unknown, reject: (error: E) => unknown) => Promise): Promise { + // eslint-disable-next-line no-async-promise-executor + return new Promise(async (resolve, reject) => { + try { + await bodyFn(resolve, reject); + } catch (error) { + reject(error); + } + }); + } +} + +export class StatefulPromise { + private _value: T | undefined = undefined; + get value(): T | undefined { return this._value; } + + private _error: unknown = undefined; + get error(): unknown { return this._error; } + + private _isResolved = false; + get isResolved() { return this._isResolved; } + + public readonly promise: Promise; + + constructor(promise: Promise) { + this.promise = promise.then( + value => { + this._value = value; + this._isResolved = true; + return value; + }, + error => { + this._error = error; + this._isResolved = true; + throw error; + } + ); + } + + /** + * Returns the resolved value. + * Throws if the promise is not resolved yet. + */ + public requireValue(): T { + if (!this._isResolved) { + throw new BugIndicatingError('Promise is not resolved yet'); + } + if (this._error) { + throw this._error; + } + return this._value!; + } +} + +export class LazyStatefulPromise { + private readonly _promise = new Lazy(() => new StatefulPromise(this._compute())); + + constructor( + private readonly _compute: () => Promise, + ) { } + + /** + * Returns the resolved value. + * Throws if the promise is not resolved yet. + */ + public requireValue(): T { + return this._promise.value.requireValue(); + } + + /** + * Returns the promise (and triggers a computation of the promise if not yet done so). + */ + public getPromise(): Promise { + return this._promise.value.promise; + } + + /** + * Reads the current value without triggering a computation of the promise. + */ + public get currentValue(): T | undefined { + return this._promise.rawValue?.value; + } +} + +//#endregion + +//#region + +const enum AsyncIterableSourceState { + Initial, + DoneOK, + DoneError, +} + +/** + * An object that allows to emit async values asynchronously or bring the iterable to an error state using `reject()`. + * This emitter is valid only for the duration of the executor (until the promise returned by the executor settles). + */ +export interface AsyncIterableEmitter { + /** + * The value will be appended at the end. + * + * **NOTE** If `reject()` has already been called, this method has no effect. + */ + emitOne(value: T): void; + /** + * The values will be appended at the end. + * + * **NOTE** If `reject()` has already been called, this method has no effect. + */ + emitMany(values: T[]): void; + /** + * Writing an error will permanently invalidate this iterable. + * The current users will receive an error thrown, as will all future users. + * + * **NOTE** If `reject()` have already been called, this method has no effect. + */ + reject(error: Error): void; +} + +/** + * An executor for the `AsyncIterableObject` that has access to an emitter. + */ +export interface AsyncIterableExecutor { + /** + * @param emitter An object that allows to emit async values valid only for the duration of the executor. + */ + (emitter: AsyncIterableEmitter): void | Promise; +} + +/** + * A rich implementation for an `AsyncIterable`. + */ +export class AsyncIterableObject implements AsyncIterable { + + public static fromArray(items: T[]): AsyncIterableObject { + return new AsyncIterableObject((writer) => { + writer.emitMany(items); + }); + } + + public static fromPromise(promise: Promise): AsyncIterableObject { + return new AsyncIterableObject(async (emitter) => { + emitter.emitMany(await promise); + }); + } + + public static fromPromises(promises: Promise[]): AsyncIterableObject { + return new AsyncIterableObject(async (emitter) => { + await Promise.all(promises.map(async (p) => emitter.emitOne(await p))); + }); + } + + public static merge(iterables: AsyncIterable[]): AsyncIterableObject { + return new AsyncIterableObject(async (emitter) => { + await Promise.all(iterables.map(async (iterable) => { + for await (const item of iterable) { + emitter.emitOne(item); + } + })); + }); + } + + public static EMPTY = AsyncIterableObject.fromArray([]); + + private _state: AsyncIterableSourceState; + private _results: T[]; + private _error: Error | null; + private readonly _onReturn?: () => void | Promise; + private readonly _onStateChanged: Emitter; + + constructor(executor: AsyncIterableExecutor, onReturn?: () => void | Promise) { + this._state = AsyncIterableSourceState.Initial; + this._results = []; + this._error = null; + this._onReturn = onReturn; + this._onStateChanged = new Emitter(); + + queueMicrotask(async () => { + const writer: AsyncIterableEmitter = { + emitOne: (item) => this.emitOne(item), + emitMany: (items) => this.emitMany(items), + reject: (error) => this.reject(error) + }; + try { + await Promise.resolve(executor(writer)); + this.resolve(); + } catch (err) { + this.reject(err); + } finally { + writer.emitOne = undefined!; + writer.emitMany = undefined!; + writer.reject = undefined!; + } + }); + } + + [Symbol.asyncIterator](): AsyncIterator { + let i = 0; + return { + next: async () => { + do { + if (this._state === AsyncIterableSourceState.DoneError) { + throw this._error; + } + if (i < this._results.length) { + return { done: false, value: this._results[i++] }; + } + if (this._state === AsyncIterableSourceState.DoneOK) { + return { done: true, value: undefined }; + } + await Event.toPromise(this._onStateChanged.event); + } while (true); + }, + return: async () => { + this._onReturn?.(); + return { done: true, value: undefined }; + } + }; + } + + public static map(iterable: AsyncIterable, mapFn: (item: T) => R): AsyncIterableObject { + return new AsyncIterableObject(async (emitter) => { + for await (const item of iterable) { + emitter.emitOne(mapFn(item)); + } + }); + } + + public map(mapFn: (item: T) => R): AsyncIterableObject { + return AsyncIterableObject.map(this, mapFn); + } + + public static filter(iterable: AsyncIterable, filterFn: (item: T) => boolean): AsyncIterableObject { + return new AsyncIterableObject(async (emitter) => { + for await (const item of iterable) { + if (filterFn(item)) { + emitter.emitOne(item); + } + } + }); + } + + public filter(filterFn: (item: T) => boolean): AsyncIterableObject { + return AsyncIterableObject.filter(this, filterFn); + } + + public static coalesce(iterable: AsyncIterable): AsyncIterableObject { + return >AsyncIterableObject.filter(iterable, item => !!item); + } + + public coalesce(): AsyncIterableObject> { + return AsyncIterableObject.coalesce(this) as AsyncIterableObject>; + } + + public static async toPromise(iterable: AsyncIterable): Promise { + const result: T[] = []; + for await (const item of iterable) { + result.push(item); + } + return result; + } + + public toPromise(): Promise { + return AsyncIterableObject.toPromise(this); + } + + /** + * The value will be appended at the end. + * + * **NOTE** If `resolve()` or `reject()` have already been called, this method has no effect. + */ + private emitOne(value: T): void { + if (this._state !== AsyncIterableSourceState.Initial) { + return; + } + // it is important to add new values at the end, + // as we may have iterators already running on the array + this._results.push(value); + this._onStateChanged.fire(); + } + + /** + * The values will be appended at the end. + * + * **NOTE** If `resolve()` or `reject()` have already been called, this method has no effect. + */ + private emitMany(values: T[]): void { + if (this._state !== AsyncIterableSourceState.Initial) { + return; + } + // it is important to add new values at the end, + // as we may have iterators already running on the array + this._results = this._results.concat(values); + this._onStateChanged.fire(); + } + + /** + * Calling `resolve()` will mark the result array as complete. + * + * **NOTE** `resolve()` must be called, otherwise all consumers of this iterable will hang indefinitely, similar to a non-resolved promise. + * **NOTE** If `resolve()` or `reject()` have already been called, this method has no effect. + */ + private resolve(): void { + if (this._state !== AsyncIterableSourceState.Initial) { + return; + } + this._state = AsyncIterableSourceState.DoneOK; + this._onStateChanged.fire(); + } + + /** + * Writing an error will permanently invalidate this iterable. + * The current users will receive an error thrown, as will all future users. + * + * **NOTE** If `resolve()` or `reject()` have already been called, this method has no effect. + */ + private reject(error: Error) { + if (this._state !== AsyncIterableSourceState.Initial) { + return; + } + this._state = AsyncIterableSourceState.DoneError; + this._error = error; + this._onStateChanged.fire(); + } +} + +export class CancelableAsyncIterableObject extends AsyncIterableObject { + constructor( + private readonly _source: CancellationTokenSource, + executor: AsyncIterableExecutor + ) { + super(executor); + } + + cancel(): void { + this._source.cancel(); + } +} + +export function createCancelableAsyncIterable(callback: (token: CancellationToken) => AsyncIterable): CancelableAsyncIterableObject { + const source = new CancellationTokenSource(); + const innerIterable = callback(source.token); + + return new CancelableAsyncIterableObject(source, async (emitter) => { + const subscription = source.token.onCancellationRequested(() => { + subscription.dispose(); + source.dispose(); + emitter.reject(new CancellationError()); + }); + try { + for await (const item of innerIterable) { + if (source.token.isCancellationRequested) { + // canceled in the meantime + return; + } + emitter.emitOne(item); + } + subscription.dispose(); + source.dispose(); + } catch (err) { + subscription.dispose(); + source.dispose(); + emitter.reject(err); + } + }); +} + +export class AsyncIterableSource { + + private readonly _deferred = new DeferredPromise(); + private readonly _asyncIterable: AsyncIterableObject; + + private _errorFn: (error: Error) => void; + private _emitFn: (item: T) => void; + + /** + * + * @param onReturn A function that will be called when consuming the async iterable + * has finished by the consumer, e.g the for-await-loop has be existed (break, return) early. + * This is NOT called when resolving this source by its owner. + */ + constructor(onReturn?: () => Promise | void) { + this._asyncIterable = new AsyncIterableObject(emitter => { + + if (earlyError) { + emitter.reject(earlyError); + return; + } + if (earlyItems) { + emitter.emitMany(earlyItems); + } + this._errorFn = (error: Error) => emitter.reject(error); + this._emitFn = (item: T) => emitter.emitOne(item); + return this._deferred.p; + }, onReturn); + + let earlyError: Error | undefined; + let earlyItems: T[] | undefined; + + this._emitFn = (item: T) => { + if (!earlyItems) { + earlyItems = []; + } + earlyItems.push(item); + }; + this._errorFn = (error: Error) => { + if (!earlyError) { + earlyError = error; + } + }; + } + + get asyncIterable(): AsyncIterableObject { + return this._asyncIterable; + } + + resolve(): void { + this._deferred.complete(); + } + + reject(error: Error): void { + this._errorFn(error); + this._deferred.complete(); + } + + emitOne(item: T): void { + this._emitFn(item); + } +} + +//#endregion diff --git a/node_modules/@xterm/xterm/src/vs/base/common/cancellation.ts b/node_modules/@xterm/xterm/src/vs/base/common/cancellation.ts new file mode 100644 index 0000000..4b45fd2 --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/common/cancellation.ts @@ -0,0 +1,148 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { Emitter, Event } from 'vs/base/common/event'; +import { DisposableStore, IDisposable } from 'vs/base/common/lifecycle'; + +export interface CancellationToken { + + /** + * A flag signalling is cancellation has been requested. + */ + readonly isCancellationRequested: boolean; + + /** + * An event which fires when cancellation is requested. This event + * only ever fires `once` as cancellation can only happen once. Listeners + * that are registered after cancellation will be called (next event loop run), + * but also only once. + * + * @event + */ + readonly onCancellationRequested: (listener: (e: any) => any, thisArgs?: any, disposables?: IDisposable[]) => IDisposable; +} + +const shortcutEvent: Event = Object.freeze(function (callback, context?): IDisposable { + const handle = setTimeout(callback.bind(context), 0); + return { dispose() { clearTimeout(handle); } }; +}); + +export namespace CancellationToken { + + export function isCancellationToken(thing: unknown): thing is CancellationToken { + if (thing === CancellationToken.None || thing === CancellationToken.Cancelled) { + return true; + } + if (thing instanceof MutableToken) { + return true; + } + if (!thing || typeof thing !== 'object') { + return false; + } + return typeof (thing as CancellationToken).isCancellationRequested === 'boolean' + && typeof (thing as CancellationToken).onCancellationRequested === 'function'; + } + + + export const None = Object.freeze({ + isCancellationRequested: false, + onCancellationRequested: Event.None + }); + + export const Cancelled = Object.freeze({ + isCancellationRequested: true, + onCancellationRequested: shortcutEvent + }); +} + +class MutableToken implements CancellationToken { + + private _isCancelled: boolean = false; + private _emitter: Emitter | null = null; + + public cancel() { + if (!this._isCancelled) { + this._isCancelled = true; + if (this._emitter) { + this._emitter.fire(undefined); + this.dispose(); + } + } + } + + get isCancellationRequested(): boolean { + return this._isCancelled; + } + + get onCancellationRequested(): Event { + if (this._isCancelled) { + return shortcutEvent; + } + if (!this._emitter) { + this._emitter = new Emitter(); + } + return this._emitter.event; + } + + public dispose(): void { + if (this._emitter) { + this._emitter.dispose(); + this._emitter = null; + } + } +} + +export class CancellationTokenSource { + + private _token?: CancellationToken = undefined; + private _parentListener?: IDisposable = undefined; + + constructor(parent?: CancellationToken) { + this._parentListener = parent && parent.onCancellationRequested(this.cancel, this); + } + + get token(): CancellationToken { + if (!this._token) { + // be lazy and create the token only when + // actually needed + this._token = new MutableToken(); + } + return this._token; + } + + cancel(): void { + if (!this._token) { + // save an object by returning the default + // cancelled token when cancellation happens + // before someone asks for the token + this._token = CancellationToken.Cancelled; + + } else if (this._token instanceof MutableToken) { + // actually cancel + this._token.cancel(); + } + } + + dispose(cancel: boolean = false): void { + if (cancel) { + this.cancel(); + } + this._parentListener?.dispose(); + if (!this._token) { + // ensure to initialize with an empty token if we had none + this._token = CancellationToken.None; + + } else if (this._token instanceof MutableToken) { + // actually dispose + this._token.dispose(); + } + } +} + +export function cancelOnDispose(store: DisposableStore): CancellationToken { + const source = new CancellationTokenSource(); + store.add({ dispose() { source.cancel(); } }); + return source.token; +} diff --git a/node_modules/@xterm/xterm/src/vs/base/common/charCode.ts b/node_modules/@xterm/xterm/src/vs/base/common/charCode.ts new file mode 100644 index 0000000..de0a25b --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/common/charCode.ts @@ -0,0 +1,450 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +// Names from https://blog.codinghorror.com/ascii-pronunciation-rules-for-programmers/ + +/** + * An inlined enum containing useful character codes (to be used with String.charCodeAt). + * Please leave the const keyword such that it gets inlined when compiled to JavaScript! + */ +export const enum CharCode { + Null = 0, + /** + * The `\b` character. + */ + Backspace = 8, + /** + * The `\t` character. + */ + Tab = 9, + /** + * The `\n` character. + */ + LineFeed = 10, + /** + * The `\r` character. + */ + CarriageReturn = 13, + Space = 32, + /** + * The `!` character. + */ + ExclamationMark = 33, + /** + * The `"` character. + */ + DoubleQuote = 34, + /** + * The `#` character. + */ + Hash = 35, + /** + * The `$` character. + */ + DollarSign = 36, + /** + * The `%` character. + */ + PercentSign = 37, + /** + * The `&` character. + */ + Ampersand = 38, + /** + * The `'` character. + */ + SingleQuote = 39, + /** + * The `(` character. + */ + OpenParen = 40, + /** + * The `)` character. + */ + CloseParen = 41, + /** + * The `*` character. + */ + Asterisk = 42, + /** + * The `+` character. + */ + Plus = 43, + /** + * The `,` character. + */ + Comma = 44, + /** + * The `-` character. + */ + Dash = 45, + /** + * The `.` character. + */ + Period = 46, + /** + * The `/` character. + */ + Slash = 47, + + Digit0 = 48, + Digit1 = 49, + Digit2 = 50, + Digit3 = 51, + Digit4 = 52, + Digit5 = 53, + Digit6 = 54, + Digit7 = 55, + Digit8 = 56, + Digit9 = 57, + + /** + * The `:` character. + */ + Colon = 58, + /** + * The `;` character. + */ + Semicolon = 59, + /** + * The `<` character. + */ + LessThan = 60, + /** + * The `=` character. + */ + Equals = 61, + /** + * The `>` character. + */ + GreaterThan = 62, + /** + * The `?` character. + */ + QuestionMark = 63, + /** + * The `@` character. + */ + AtSign = 64, + + A = 65, + B = 66, + C = 67, + D = 68, + E = 69, + F = 70, + G = 71, + H = 72, + I = 73, + J = 74, + K = 75, + L = 76, + M = 77, + N = 78, + O = 79, + P = 80, + Q = 81, + R = 82, + S = 83, + T = 84, + U = 85, + V = 86, + W = 87, + X = 88, + Y = 89, + Z = 90, + + /** + * The `[` character. + */ + OpenSquareBracket = 91, + /** + * The `\` character. + */ + Backslash = 92, + /** + * The `]` character. + */ + CloseSquareBracket = 93, + /** + * The `^` character. + */ + Caret = 94, + /** + * The `_` character. + */ + Underline = 95, + /** + * The ``(`)`` character. + */ + BackTick = 96, + + a = 97, + b = 98, + c = 99, + d = 100, + e = 101, + f = 102, + g = 103, + h = 104, + i = 105, + j = 106, + k = 107, + l = 108, + m = 109, + n = 110, + o = 111, + p = 112, + q = 113, + r = 114, + s = 115, + t = 116, + u = 117, + v = 118, + w = 119, + x = 120, + y = 121, + z = 122, + + /** + * The `{` character. + */ + OpenCurlyBrace = 123, + /** + * The `|` character. + */ + Pipe = 124, + /** + * The `}` character. + */ + CloseCurlyBrace = 125, + /** + * The `~` character. + */ + Tilde = 126, + + /** + * The   (no-break space) character. + * Unicode Character 'NO-BREAK SPACE' (U+00A0) + */ + NoBreakSpace = 160, + + U_Combining_Grave_Accent = 0x0300, // U+0300 Combining Grave Accent + U_Combining_Acute_Accent = 0x0301, // U+0301 Combining Acute Accent + U_Combining_Circumflex_Accent = 0x0302, // U+0302 Combining Circumflex Accent + U_Combining_Tilde = 0x0303, // U+0303 Combining Tilde + U_Combining_Macron = 0x0304, // U+0304 Combining Macron + U_Combining_Overline = 0x0305, // U+0305 Combining Overline + U_Combining_Breve = 0x0306, // U+0306 Combining Breve + U_Combining_Dot_Above = 0x0307, // U+0307 Combining Dot Above + U_Combining_Diaeresis = 0x0308, // U+0308 Combining Diaeresis + U_Combining_Hook_Above = 0x0309, // U+0309 Combining Hook Above + U_Combining_Ring_Above = 0x030A, // U+030A Combining Ring Above + U_Combining_Double_Acute_Accent = 0x030B, // U+030B Combining Double Acute Accent + U_Combining_Caron = 0x030C, // U+030C Combining Caron + U_Combining_Vertical_Line_Above = 0x030D, // U+030D Combining Vertical Line Above + U_Combining_Double_Vertical_Line_Above = 0x030E, // U+030E Combining Double Vertical Line Above + U_Combining_Double_Grave_Accent = 0x030F, // U+030F Combining Double Grave Accent + U_Combining_Candrabindu = 0x0310, // U+0310 Combining Candrabindu + U_Combining_Inverted_Breve = 0x0311, // U+0311 Combining Inverted Breve + U_Combining_Turned_Comma_Above = 0x0312, // U+0312 Combining Turned Comma Above + U_Combining_Comma_Above = 0x0313, // U+0313 Combining Comma Above + U_Combining_Reversed_Comma_Above = 0x0314, // U+0314 Combining Reversed Comma Above + U_Combining_Comma_Above_Right = 0x0315, // U+0315 Combining Comma Above Right + U_Combining_Grave_Accent_Below = 0x0316, // U+0316 Combining Grave Accent Below + U_Combining_Acute_Accent_Below = 0x0317, // U+0317 Combining Acute Accent Below + U_Combining_Left_Tack_Below = 0x0318, // U+0318 Combining Left Tack Below + U_Combining_Right_Tack_Below = 0x0319, // U+0319 Combining Right Tack Below + U_Combining_Left_Angle_Above = 0x031A, // U+031A Combining Left Angle Above + U_Combining_Horn = 0x031B, // U+031B Combining Horn + U_Combining_Left_Half_Ring_Below = 0x031C, // U+031C Combining Left Half Ring Below + U_Combining_Up_Tack_Below = 0x031D, // U+031D Combining Up Tack Below + U_Combining_Down_Tack_Below = 0x031E, // U+031E Combining Down Tack Below + U_Combining_Plus_Sign_Below = 0x031F, // U+031F Combining Plus Sign Below + U_Combining_Minus_Sign_Below = 0x0320, // U+0320 Combining Minus Sign Below + U_Combining_Palatalized_Hook_Below = 0x0321, // U+0321 Combining Palatalized Hook Below + U_Combining_Retroflex_Hook_Below = 0x0322, // U+0322 Combining Retroflex Hook Below + U_Combining_Dot_Below = 0x0323, // U+0323 Combining Dot Below + U_Combining_Diaeresis_Below = 0x0324, // U+0324 Combining Diaeresis Below + U_Combining_Ring_Below = 0x0325, // U+0325 Combining Ring Below + U_Combining_Comma_Below = 0x0326, // U+0326 Combining Comma Below + U_Combining_Cedilla = 0x0327, // U+0327 Combining Cedilla + U_Combining_Ogonek = 0x0328, // U+0328 Combining Ogonek + U_Combining_Vertical_Line_Below = 0x0329, // U+0329 Combining Vertical Line Below + U_Combining_Bridge_Below = 0x032A, // U+032A Combining Bridge Below + U_Combining_Inverted_Double_Arch_Below = 0x032B, // U+032B Combining Inverted Double Arch Below + U_Combining_Caron_Below = 0x032C, // U+032C Combining Caron Below + U_Combining_Circumflex_Accent_Below = 0x032D, // U+032D Combining Circumflex Accent Below + U_Combining_Breve_Below = 0x032E, // U+032E Combining Breve Below + U_Combining_Inverted_Breve_Below = 0x032F, // U+032F Combining Inverted Breve Below + U_Combining_Tilde_Below = 0x0330, // U+0330 Combining Tilde Below + U_Combining_Macron_Below = 0x0331, // U+0331 Combining Macron Below + U_Combining_Low_Line = 0x0332, // U+0332 Combining Low Line + U_Combining_Double_Low_Line = 0x0333, // U+0333 Combining Double Low Line + U_Combining_Tilde_Overlay = 0x0334, // U+0334 Combining Tilde Overlay + U_Combining_Short_Stroke_Overlay = 0x0335, // U+0335 Combining Short Stroke Overlay + U_Combining_Long_Stroke_Overlay = 0x0336, // U+0336 Combining Long Stroke Overlay + U_Combining_Short_Solidus_Overlay = 0x0337, // U+0337 Combining Short Solidus Overlay + U_Combining_Long_Solidus_Overlay = 0x0338, // U+0338 Combining Long Solidus Overlay + U_Combining_Right_Half_Ring_Below = 0x0339, // U+0339 Combining Right Half Ring Below + U_Combining_Inverted_Bridge_Below = 0x033A, // U+033A Combining Inverted Bridge Below + U_Combining_Square_Below = 0x033B, // U+033B Combining Square Below + U_Combining_Seagull_Below = 0x033C, // U+033C Combining Seagull Below + U_Combining_X_Above = 0x033D, // U+033D Combining X Above + U_Combining_Vertical_Tilde = 0x033E, // U+033E Combining Vertical Tilde + U_Combining_Double_Overline = 0x033F, // U+033F Combining Double Overline + U_Combining_Grave_Tone_Mark = 0x0340, // U+0340 Combining Grave Tone Mark + U_Combining_Acute_Tone_Mark = 0x0341, // U+0341 Combining Acute Tone Mark + U_Combining_Greek_Perispomeni = 0x0342, // U+0342 Combining Greek Perispomeni + U_Combining_Greek_Koronis = 0x0343, // U+0343 Combining Greek Koronis + U_Combining_Greek_Dialytika_Tonos = 0x0344, // U+0344 Combining Greek Dialytika Tonos + U_Combining_Greek_Ypogegrammeni = 0x0345, // U+0345 Combining Greek Ypogegrammeni + U_Combining_Bridge_Above = 0x0346, // U+0346 Combining Bridge Above + U_Combining_Equals_Sign_Below = 0x0347, // U+0347 Combining Equals Sign Below + U_Combining_Double_Vertical_Line_Below = 0x0348, // U+0348 Combining Double Vertical Line Below + U_Combining_Left_Angle_Below = 0x0349, // U+0349 Combining Left Angle Below + U_Combining_Not_Tilde_Above = 0x034A, // U+034A Combining Not Tilde Above + U_Combining_Homothetic_Above = 0x034B, // U+034B Combining Homothetic Above + U_Combining_Almost_Equal_To_Above = 0x034C, // U+034C Combining Almost Equal To Above + U_Combining_Left_Right_Arrow_Below = 0x034D, // U+034D Combining Left Right Arrow Below + U_Combining_Upwards_Arrow_Below = 0x034E, // U+034E Combining Upwards Arrow Below + U_Combining_Grapheme_Joiner = 0x034F, // U+034F Combining Grapheme Joiner + U_Combining_Right_Arrowhead_Above = 0x0350, // U+0350 Combining Right Arrowhead Above + U_Combining_Left_Half_Ring_Above = 0x0351, // U+0351 Combining Left Half Ring Above + U_Combining_Fermata = 0x0352, // U+0352 Combining Fermata + U_Combining_X_Below = 0x0353, // U+0353 Combining X Below + U_Combining_Left_Arrowhead_Below = 0x0354, // U+0354 Combining Left Arrowhead Below + U_Combining_Right_Arrowhead_Below = 0x0355, // U+0355 Combining Right Arrowhead Below + U_Combining_Right_Arrowhead_And_Up_Arrowhead_Below = 0x0356, // U+0356 Combining Right Arrowhead And Up Arrowhead Below + U_Combining_Right_Half_Ring_Above = 0x0357, // U+0357 Combining Right Half Ring Above + U_Combining_Dot_Above_Right = 0x0358, // U+0358 Combining Dot Above Right + U_Combining_Asterisk_Below = 0x0359, // U+0359 Combining Asterisk Below + U_Combining_Double_Ring_Below = 0x035A, // U+035A Combining Double Ring Below + U_Combining_Zigzag_Above = 0x035B, // U+035B Combining Zigzag Above + U_Combining_Double_Breve_Below = 0x035C, // U+035C Combining Double Breve Below + U_Combining_Double_Breve = 0x035D, // U+035D Combining Double Breve + U_Combining_Double_Macron = 0x035E, // U+035E Combining Double Macron + U_Combining_Double_Macron_Below = 0x035F, // U+035F Combining Double Macron Below + U_Combining_Double_Tilde = 0x0360, // U+0360 Combining Double Tilde + U_Combining_Double_Inverted_Breve = 0x0361, // U+0361 Combining Double Inverted Breve + U_Combining_Double_Rightwards_Arrow_Below = 0x0362, // U+0362 Combining Double Rightwards Arrow Below + U_Combining_Latin_Small_Letter_A = 0x0363, // U+0363 Combining Latin Small Letter A + U_Combining_Latin_Small_Letter_E = 0x0364, // U+0364 Combining Latin Small Letter E + U_Combining_Latin_Small_Letter_I = 0x0365, // U+0365 Combining Latin Small Letter I + U_Combining_Latin_Small_Letter_O = 0x0366, // U+0366 Combining Latin Small Letter O + U_Combining_Latin_Small_Letter_U = 0x0367, // U+0367 Combining Latin Small Letter U + U_Combining_Latin_Small_Letter_C = 0x0368, // U+0368 Combining Latin Small Letter C + U_Combining_Latin_Small_Letter_D = 0x0369, // U+0369 Combining Latin Small Letter D + U_Combining_Latin_Small_Letter_H = 0x036A, // U+036A Combining Latin Small Letter H + U_Combining_Latin_Small_Letter_M = 0x036B, // U+036B Combining Latin Small Letter M + U_Combining_Latin_Small_Letter_R = 0x036C, // U+036C Combining Latin Small Letter R + U_Combining_Latin_Small_Letter_T = 0x036D, // U+036D Combining Latin Small Letter T + U_Combining_Latin_Small_Letter_V = 0x036E, // U+036E Combining Latin Small Letter V + U_Combining_Latin_Small_Letter_X = 0x036F, // U+036F Combining Latin Small Letter X + + /** + * Unicode Character 'LINE SEPARATOR' (U+2028) + * http://www.fileformat.info/info/unicode/char/2028/index.htm + */ + LINE_SEPARATOR = 0x2028, + /** + * Unicode Character 'PARAGRAPH SEPARATOR' (U+2029) + * http://www.fileformat.info/info/unicode/char/2029/index.htm + */ + PARAGRAPH_SEPARATOR = 0x2029, + /** + * Unicode Character 'NEXT LINE' (U+0085) + * http://www.fileformat.info/info/unicode/char/0085/index.htm + */ + NEXT_LINE = 0x0085, + + // http://www.fileformat.info/info/unicode/category/Sk/list.htm + U_CIRCUMFLEX = 0x005E, // U+005E CIRCUMFLEX + U_GRAVE_ACCENT = 0x0060, // U+0060 GRAVE ACCENT + U_DIAERESIS = 0x00A8, // U+00A8 DIAERESIS + U_MACRON = 0x00AF, // U+00AF MACRON + U_ACUTE_ACCENT = 0x00B4, // U+00B4 ACUTE ACCENT + U_CEDILLA = 0x00B8, // U+00B8 CEDILLA + U_MODIFIER_LETTER_LEFT_ARROWHEAD = 0x02C2, // U+02C2 MODIFIER LETTER LEFT ARROWHEAD + U_MODIFIER_LETTER_RIGHT_ARROWHEAD = 0x02C3, // U+02C3 MODIFIER LETTER RIGHT ARROWHEAD + U_MODIFIER_LETTER_UP_ARROWHEAD = 0x02C4, // U+02C4 MODIFIER LETTER UP ARROWHEAD + U_MODIFIER_LETTER_DOWN_ARROWHEAD = 0x02C5, // U+02C5 MODIFIER LETTER DOWN ARROWHEAD + U_MODIFIER_LETTER_CENTRED_RIGHT_HALF_RING = 0x02D2, // U+02D2 MODIFIER LETTER CENTRED RIGHT HALF RING + U_MODIFIER_LETTER_CENTRED_LEFT_HALF_RING = 0x02D3, // U+02D3 MODIFIER LETTER CENTRED LEFT HALF RING + U_MODIFIER_LETTER_UP_TACK = 0x02D4, // U+02D4 MODIFIER LETTER UP TACK + U_MODIFIER_LETTER_DOWN_TACK = 0x02D5, // U+02D5 MODIFIER LETTER DOWN TACK + U_MODIFIER_LETTER_PLUS_SIGN = 0x02D6, // U+02D6 MODIFIER LETTER PLUS SIGN + U_MODIFIER_LETTER_MINUS_SIGN = 0x02D7, // U+02D7 MODIFIER LETTER MINUS SIGN + U_BREVE = 0x02D8, // U+02D8 BREVE + U_DOT_ABOVE = 0x02D9, // U+02D9 DOT ABOVE + U_RING_ABOVE = 0x02DA, // U+02DA RING ABOVE + U_OGONEK = 0x02DB, // U+02DB OGONEK + U_SMALL_TILDE = 0x02DC, // U+02DC SMALL TILDE + U_DOUBLE_ACUTE_ACCENT = 0x02DD, // U+02DD DOUBLE ACUTE ACCENT + U_MODIFIER_LETTER_RHOTIC_HOOK = 0x02DE, // U+02DE MODIFIER LETTER RHOTIC HOOK + U_MODIFIER_LETTER_CROSS_ACCENT = 0x02DF, // U+02DF MODIFIER LETTER CROSS ACCENT + U_MODIFIER_LETTER_EXTRA_HIGH_TONE_BAR = 0x02E5, // U+02E5 MODIFIER LETTER EXTRA-HIGH TONE BAR + U_MODIFIER_LETTER_HIGH_TONE_BAR = 0x02E6, // U+02E6 MODIFIER LETTER HIGH TONE BAR + U_MODIFIER_LETTER_MID_TONE_BAR = 0x02E7, // U+02E7 MODIFIER LETTER MID TONE BAR + U_MODIFIER_LETTER_LOW_TONE_BAR = 0x02E8, // U+02E8 MODIFIER LETTER LOW TONE BAR + U_MODIFIER_LETTER_EXTRA_LOW_TONE_BAR = 0x02E9, // U+02E9 MODIFIER LETTER EXTRA-LOW TONE BAR + U_MODIFIER_LETTER_YIN_DEPARTING_TONE_MARK = 0x02EA, // U+02EA MODIFIER LETTER YIN DEPARTING TONE MARK + U_MODIFIER_LETTER_YANG_DEPARTING_TONE_MARK = 0x02EB, // U+02EB MODIFIER LETTER YANG DEPARTING TONE MARK + U_MODIFIER_LETTER_UNASPIRATED = 0x02ED, // U+02ED MODIFIER LETTER UNASPIRATED + U_MODIFIER_LETTER_LOW_DOWN_ARROWHEAD = 0x02EF, // U+02EF MODIFIER LETTER LOW DOWN ARROWHEAD + U_MODIFIER_LETTER_LOW_UP_ARROWHEAD = 0x02F0, // U+02F0 MODIFIER LETTER LOW UP ARROWHEAD + U_MODIFIER_LETTER_LOW_LEFT_ARROWHEAD = 0x02F1, // U+02F1 MODIFIER LETTER LOW LEFT ARROWHEAD + U_MODIFIER_LETTER_LOW_RIGHT_ARROWHEAD = 0x02F2, // U+02F2 MODIFIER LETTER LOW RIGHT ARROWHEAD + U_MODIFIER_LETTER_LOW_RING = 0x02F3, // U+02F3 MODIFIER LETTER LOW RING + U_MODIFIER_LETTER_MIDDLE_GRAVE_ACCENT = 0x02F4, // U+02F4 MODIFIER LETTER MIDDLE GRAVE ACCENT + U_MODIFIER_LETTER_MIDDLE_DOUBLE_GRAVE_ACCENT = 0x02F5, // U+02F5 MODIFIER LETTER MIDDLE DOUBLE GRAVE ACCENT + U_MODIFIER_LETTER_MIDDLE_DOUBLE_ACUTE_ACCENT = 0x02F6, // U+02F6 MODIFIER LETTER MIDDLE DOUBLE ACUTE ACCENT + U_MODIFIER_LETTER_LOW_TILDE = 0x02F7, // U+02F7 MODIFIER LETTER LOW TILDE + U_MODIFIER_LETTER_RAISED_COLON = 0x02F8, // U+02F8 MODIFIER LETTER RAISED COLON + U_MODIFIER_LETTER_BEGIN_HIGH_TONE = 0x02F9, // U+02F9 MODIFIER LETTER BEGIN HIGH TONE + U_MODIFIER_LETTER_END_HIGH_TONE = 0x02FA, // U+02FA MODIFIER LETTER END HIGH TONE + U_MODIFIER_LETTER_BEGIN_LOW_TONE = 0x02FB, // U+02FB MODIFIER LETTER BEGIN LOW TONE + U_MODIFIER_LETTER_END_LOW_TONE = 0x02FC, // U+02FC MODIFIER LETTER END LOW TONE + U_MODIFIER_LETTER_SHELF = 0x02FD, // U+02FD MODIFIER LETTER SHELF + U_MODIFIER_LETTER_OPEN_SHELF = 0x02FE, // U+02FE MODIFIER LETTER OPEN SHELF + U_MODIFIER_LETTER_LOW_LEFT_ARROW = 0x02FF, // U+02FF MODIFIER LETTER LOW LEFT ARROW + U_GREEK_LOWER_NUMERAL_SIGN = 0x0375, // U+0375 GREEK LOWER NUMERAL SIGN + U_GREEK_TONOS = 0x0384, // U+0384 GREEK TONOS + U_GREEK_DIALYTIKA_TONOS = 0x0385, // U+0385 GREEK DIALYTIKA TONOS + U_GREEK_KORONIS = 0x1FBD, // U+1FBD GREEK KORONIS + U_GREEK_PSILI = 0x1FBF, // U+1FBF GREEK PSILI + U_GREEK_PERISPOMENI = 0x1FC0, // U+1FC0 GREEK PERISPOMENI + U_GREEK_DIALYTIKA_AND_PERISPOMENI = 0x1FC1, // U+1FC1 GREEK DIALYTIKA AND PERISPOMENI + U_GREEK_PSILI_AND_VARIA = 0x1FCD, // U+1FCD GREEK PSILI AND VARIA + U_GREEK_PSILI_AND_OXIA = 0x1FCE, // U+1FCE GREEK PSILI AND OXIA + U_GREEK_PSILI_AND_PERISPOMENI = 0x1FCF, // U+1FCF GREEK PSILI AND PERISPOMENI + U_GREEK_DASIA_AND_VARIA = 0x1FDD, // U+1FDD GREEK DASIA AND VARIA + U_GREEK_DASIA_AND_OXIA = 0x1FDE, // U+1FDE GREEK DASIA AND OXIA + U_GREEK_DASIA_AND_PERISPOMENI = 0x1FDF, // U+1FDF GREEK DASIA AND PERISPOMENI + U_GREEK_DIALYTIKA_AND_VARIA = 0x1FED, // U+1FED GREEK DIALYTIKA AND VARIA + U_GREEK_DIALYTIKA_AND_OXIA = 0x1FEE, // U+1FEE GREEK DIALYTIKA AND OXIA + U_GREEK_VARIA = 0x1FEF, // U+1FEF GREEK VARIA + U_GREEK_OXIA = 0x1FFD, // U+1FFD GREEK OXIA + U_GREEK_DASIA = 0x1FFE, // U+1FFE GREEK DASIA + + U_IDEOGRAPHIC_FULL_STOP = 0x3002, // U+3002 IDEOGRAPHIC FULL STOP + U_LEFT_CORNER_BRACKET = 0x300C, // U+300C LEFT CORNER BRACKET + U_RIGHT_CORNER_BRACKET = 0x300D, // U+300D RIGHT CORNER BRACKET + U_LEFT_BLACK_LENTICULAR_BRACKET = 0x3010, // U+3010 LEFT BLACK LENTICULAR BRACKET + U_RIGHT_BLACK_LENTICULAR_BRACKET = 0x3011, // U+3011 RIGHT BLACK LENTICULAR BRACKET + + + U_OVERLINE = 0x203E, // Unicode Character 'OVERLINE' + + /** + * UTF-8 BOM + * Unicode Character 'ZERO WIDTH NO-BREAK SPACE' (U+FEFF) + * http://www.fileformat.info/info/unicode/char/feff/index.htm + */ + UTF8_BOM = 65279, + + U_FULLWIDTH_SEMICOLON = 0xFF1B, // U+FF1B FULLWIDTH SEMICOLON + U_FULLWIDTH_COMMA = 0xFF0C, // U+FF0C FULLWIDTH COMMA +} diff --git a/node_modules/@xterm/xterm/src/vs/base/common/collections.ts b/node_modules/@xterm/xterm/src/vs/base/common/collections.ts new file mode 100644 index 0000000..d0df190 --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/common/collections.ts @@ -0,0 +1,140 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +/** + * An interface for a JavaScript object that + * acts a dictionary. The keys are strings. + */ +export type IStringDictionary = Record; + +/** + * An interface for a JavaScript object that + * acts a dictionary. The keys are numbers. + */ +export type INumberDictionary = Record; + +/** + * Groups the collection into a dictionary based on the provided + * group function. + */ +export function groupBy(data: V[], groupFn: (element: V) => K): Record { + const result: Record = Object.create(null); + for (const element of data) { + const key = groupFn(element); + let target = result[key]; + if (!target) { + target = result[key] = []; + } + target.push(element); + } + return result; +} + +export function diffSets(before: Set, after: Set): { removed: T[]; added: T[] } { + const removed: T[] = []; + const added: T[] = []; + for (const element of before) { + if (!after.has(element)) { + removed.push(element); + } + } + for (const element of after) { + if (!before.has(element)) { + added.push(element); + } + } + return { removed, added }; +} + +export function diffMaps(before: Map, after: Map): { removed: V[]; added: V[] } { + const removed: V[] = []; + const added: V[] = []; + for (const [index, value] of before) { + if (!after.has(index)) { + removed.push(value); + } + } + for (const [index, value] of after) { + if (!before.has(index)) { + added.push(value); + } + } + return { removed, added }; +} + +/** + * Computes the intersection of two sets. + * + * @param setA - The first set. + * @param setB - The second iterable. + * @returns A new set containing the elements that are in both `setA` and `setB`. + */ +export function intersection(setA: Set, setB: Iterable): Set { + const result = new Set(); + for (const elem of setB) { + if (setA.has(elem)) { + result.add(elem); + } + } + return result; +} + +export class SetWithKey implements Set { + private _map = new Map(); + + constructor(values: T[], private toKey: (t: T) => any) { + for (const value of values) { + this.add(value); + } + } + + get size(): number { + return this._map.size; + } + + add(value: T): this { + const key = this.toKey(value); + this._map.set(key, value); + return this; + } + + delete(value: T): boolean { + return this._map.delete(this.toKey(value)); + } + + has(value: T): boolean { + return this._map.has(this.toKey(value)); + } + + *entries(): IterableIterator<[T, T]> { + for (const entry of this._map.values()) { + yield [entry, entry]; + } + } + + keys(): IterableIterator { + return this.values(); + } + + *values(): IterableIterator { + for (const entry of this._map.values()) { + yield entry; + } + } + + clear(): void { + this._map.clear(); + } + + forEach(callbackfn: (value: T, value2: T, set: Set) => void, thisArg?: any): void { + this._map.forEach(entry => callbackfn.call(thisArg, entry, entry, this)); + } + + [Symbol.iterator](): IterableIterator { + return this.values(); + } + + [Symbol.toStringTag]: string = 'SetWithKey'; +} diff --git a/node_modules/@xterm/xterm/src/vs/base/common/decorators.ts b/node_modules/@xterm/xterm/src/vs/base/common/decorators.ts new file mode 100644 index 0000000..34592a7 --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/common/decorators.ts @@ -0,0 +1,130 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +function createDecorator(mapFn: (fn: Function, key: string) => Function): Function { + return (target: any, key: string, descriptor: any) => { + let fnKey: string | null = null; + let fn: Function | null = null; + + if (typeof descriptor.value === 'function') { + fnKey = 'value'; + fn = descriptor.value; + } else if (typeof descriptor.get === 'function') { + fnKey = 'get'; + fn = descriptor.get; + } + + if (!fn) { + throw new Error('not supported'); + } + + descriptor[fnKey!] = mapFn(fn, key); + }; +} + +export function memoize(_target: any, key: string, descriptor: any) { + let fnKey: string | null = null; + let fn: Function | null = null; + + if (typeof descriptor.value === 'function') { + fnKey = 'value'; + fn = descriptor.value; + + if (fn!.length !== 0) { + console.warn('Memoize should only be used in functions with zero parameters'); + } + } else if (typeof descriptor.get === 'function') { + fnKey = 'get'; + fn = descriptor.get; + } + + if (!fn) { + throw new Error('not supported'); + } + + const memoizeKey = `$memoize$${key}`; + descriptor[fnKey!] = function (...args: any[]) { + if (!this.hasOwnProperty(memoizeKey)) { + Object.defineProperty(this, memoizeKey, { + configurable: false, + enumerable: false, + writable: false, + value: fn.apply(this, args) + }); + } + + return this[memoizeKey]; + }; +} + +export interface IDebounceReducer { + (previousValue: T, ...args: any[]): T; +} + +export function debounce(delay: number, reducer?: IDebounceReducer, initialValueProvider?: () => T): Function { + return createDecorator((fn, key) => { + const timerKey = `$debounce$${key}`; + const resultKey = `$debounce$result$${key}`; + + return function (this: any, ...args: any[]) { + if (!this[resultKey]) { + this[resultKey] = initialValueProvider ? initialValueProvider() : undefined; + } + + clearTimeout(this[timerKey]); + + if (reducer) { + this[resultKey] = reducer(this[resultKey], ...args); + args = [this[resultKey]]; + } + + this[timerKey] = setTimeout(() => { + fn.apply(this, args); + this[resultKey] = initialValueProvider ? initialValueProvider() : undefined; + }, delay); + }; + }); +} + +export function throttle(delay: number, reducer?: IDebounceReducer, initialValueProvider?: () => T): Function { + return createDecorator((fn, key) => { + const timerKey = `$throttle$timer$${key}`; + const resultKey = `$throttle$result$${key}`; + const lastRunKey = `$throttle$lastRun$${key}`; + const pendingKey = `$throttle$pending$${key}`; + + return function (this: any, ...args: any[]) { + if (!this[resultKey]) { + this[resultKey] = initialValueProvider ? initialValueProvider() : undefined; + } + if (this[lastRunKey] === null || this[lastRunKey] === undefined) { + this[lastRunKey] = -Number.MAX_VALUE; + } + + if (reducer) { + this[resultKey] = reducer(this[resultKey], ...args); + } + + if (this[pendingKey]) { + return; + } + + const nextTime = this[lastRunKey] + delay; + if (nextTime <= Date.now()) { + this[lastRunKey] = Date.now(); + fn.apply(this, [this[resultKey]]); + this[resultKey] = initialValueProvider ? initialValueProvider() : undefined; + } else { + this[pendingKey] = true; + this[timerKey] = setTimeout(() => { + this[pendingKey] = false; + this[lastRunKey] = Date.now(); + fn.apply(this, [this[resultKey]]); + this[resultKey] = initialValueProvider ? initialValueProvider() : undefined; + }, nextTime - Date.now()); + } + }; + }); +} diff --git a/node_modules/@xterm/xterm/src/vs/base/common/equals.ts b/node_modules/@xterm/xterm/src/vs/base/common/equals.ts new file mode 100644 index 0000000..6e2ae85 --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/common/equals.ts @@ -0,0 +1,146 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import * as arrays from 'vs/base/common/arrays'; + +export type EqualityComparer = (a: T, b: T) => boolean; + +/** + * Compares two items for equality using strict equality. +*/ +export const strictEquals: EqualityComparer = (a, b) => a === b; + +/** + * Checks if the items of two arrays are equal. + * By default, strict equality is used to compare elements, but a custom equality comparer can be provided. + */ +export function itemsEquals(itemEquals: EqualityComparer = strictEquals): EqualityComparer { + return (a, b) => arrays.equals(a, b, itemEquals); +} + +/** + * Two items are considered equal, if their stringified representations are equal. +*/ +export function jsonStringifyEquals(): EqualityComparer { + return (a, b) => JSON.stringify(a) === JSON.stringify(b); +} + +/** + * Uses `item.equals(other)` to determine equality. + */ +export function itemEquals(): EqualityComparer { + return (a, b) => a.equals(b); +} + +/** + * Checks if two items are both null or undefined, or are equal according to the provided equality comparer. +*/ +export function equalsIfDefined(v1: T | undefined | null, v2: T | undefined | null, equals: EqualityComparer): boolean; +/** + * Returns an equality comparer that checks if two items are both null or undefined, or are equal according to the provided equality comparer. +*/ +export function equalsIfDefined(equals: EqualityComparer): EqualityComparer; +export function equalsIfDefined(equalsOrV1: EqualityComparer | T, v2?: T | undefined | null, equals?: EqualityComparer): EqualityComparer | boolean { + if (equals !== undefined) { + const v1 = equalsOrV1 as T | undefined; + if (v1 === undefined || v1 === null || v2 === undefined || v2 === null) { + return v2 === v1; + } + return equals(v1, v2); + } else { + const equals = equalsOrV1 as EqualityComparer; + return (v1, v2) => { + if (v1 === undefined || v1 === null || v2 === undefined || v2 === null) { + return v2 === v1; + } + return equals(v1, v2); + }; + } +} + +/** + * Drills into arrays (items ordered) and objects (keys unordered) and uses strict equality on everything else. +*/ +export function structuralEquals(a: T, b: T): boolean { + if (a === b) { + return true; + } + + if (Array.isArray(a) && Array.isArray(b)) { + if (a.length !== b.length) { + return false; + } + for (let i = 0; i < a.length; i++) { + if (!structuralEquals(a[i], b[i])) { + return false; + } + } + return true; + } + + if (a && typeof a === 'object' && b && typeof b === 'object') { + if (Object.getPrototypeOf(a) === Object.prototype && Object.getPrototypeOf(b) === Object.prototype) { + const aObj = a as Record; + const bObj = b as Record; + const keysA = Object.keys(aObj); + const keysB = Object.keys(bObj); + const keysBSet = new Set(keysB); + + if (keysA.length !== keysB.length) { + return false; + } + + for (const key of keysA) { + if (!keysBSet.has(key)) { + return false; + } + if (!structuralEquals(aObj[key], bObj[key])) { + return false; + } + } + + return true; + } + } + + return false; +} + +/** + * `getStructuralKey(a) === getStructuralKey(b) <=> structuralEquals(a, b)` + * (assuming that a and b are not cyclic structures and nothing extends globalThis Array). +*/ +export function getStructuralKey(t: unknown): string { + return JSON.stringify(toNormalizedJsonStructure(t)); +} + +let objectId = 0; +const objIds = new WeakMap(); + +function toNormalizedJsonStructure(t: unknown): unknown { + if (Array.isArray(t)) { + return t.map(toNormalizedJsonStructure); + } + + if (t && typeof t === 'object') { + if (Object.getPrototypeOf(t) === Object.prototype) { + const tObj = t as Record; + const res: Record = Object.create(null); + for (const key of Object.keys(tObj).sort()) { + res[key] = toNormalizedJsonStructure(tObj[key]); + } + return res; + } else { + let objId = objIds.get(t); + if (objId === undefined) { + objId = objectId++; + objIds.set(t, objId); + } + // Random string to prevent collisions + return objId + '----2b76a038c20c4bcc'; + } + } + return t; +} diff --git a/node_modules/@xterm/xterm/src/vs/base/common/errors.ts b/node_modules/@xterm/xterm/src/vs/base/common/errors.ts new file mode 100644 index 0000000..ce5d8b2 --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/common/errors.ts @@ -0,0 +1,303 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +export interface ErrorListenerCallback { + (error: any): void; +} + +export interface ErrorListenerUnbind { + (): void; +} + +// Avoid circular dependency on EventEmitter by implementing a subset of the interface. +export class ErrorHandler { + private unexpectedErrorHandler: (e: any) => void; + private listeners: ErrorListenerCallback[]; + + constructor() { + + this.listeners = []; + + this.unexpectedErrorHandler = function (e: any) { + setTimeout(() => { + if (e.stack) { + if (ErrorNoTelemetry.isErrorNoTelemetry(e)) { + throw new ErrorNoTelemetry(e.message + '\n\n' + e.stack); + } + + throw new Error(e.message + '\n\n' + e.stack); + } + + throw e; + }, 0); + }; + } + + addListener(listener: ErrorListenerCallback): ErrorListenerUnbind { + this.listeners.push(listener); + + return () => { + this._removeListener(listener); + }; + } + + private emit(e: any): void { + this.listeners.forEach((listener) => { + listener(e); + }); + } + + private _removeListener(listener: ErrorListenerCallback): void { + this.listeners.splice(this.listeners.indexOf(listener), 1); + } + + setUnexpectedErrorHandler(newUnexpectedErrorHandler: (e: any) => void): void { + this.unexpectedErrorHandler = newUnexpectedErrorHandler; + } + + getUnexpectedErrorHandler(): (e: any) => void { + return this.unexpectedErrorHandler; + } + + onUnexpectedError(e: any): void { + this.unexpectedErrorHandler(e); + this.emit(e); + } + + // For external errors, we don't want the listeners to be called + onUnexpectedExternalError(e: any): void { + this.unexpectedErrorHandler(e); + } +} + +export const errorHandler = new ErrorHandler(); + +/** @skipMangle */ +export function setUnexpectedErrorHandler(newUnexpectedErrorHandler: (e: any) => void): void { + errorHandler.setUnexpectedErrorHandler(newUnexpectedErrorHandler); +} + +/** + * Returns if the error is a SIGPIPE error. SIGPIPE errors should generally be + * logged at most once, to avoid a loop. + * + * @see https://github.com/microsoft/vscode-remote-release/issues/6481 + */ +export function isSigPipeError(e: unknown): e is Error { + if (!e || typeof e !== 'object') { + return false; + } + + const cast = e as Record; + return cast.code === 'EPIPE' && cast.syscall?.toUpperCase() === 'WRITE'; +} + +export function onUnexpectedError(e: any): undefined { + // ignore errors from cancelled promises + if (!isCancellationError(e)) { + errorHandler.onUnexpectedError(e); + } + return undefined; +} + +export function onUnexpectedExternalError(e: any): undefined { + // ignore errors from cancelled promises + if (!isCancellationError(e)) { + errorHandler.onUnexpectedExternalError(e); + } + return undefined; +} + +export interface SerializedError { + readonly $isError: true; + readonly name: string; + readonly message: string; + readonly stack: string; + readonly noTelemetry: boolean; +} + +export function transformErrorForSerialization(error: Error): SerializedError; +export function transformErrorForSerialization(error: any): any; +export function transformErrorForSerialization(error: any): any { + if (error instanceof Error) { + const { name, message } = error; + const stack: string = (error).stacktrace || (error).stack; + return { + $isError: true, + name, + message, + stack, + noTelemetry: ErrorNoTelemetry.isErrorNoTelemetry(error) + }; + } + + // return as is + return error; +} + +export function transformErrorFromSerialization(data: SerializedError): Error { + let error: Error; + if (data.noTelemetry) { + error = new ErrorNoTelemetry(); + } else { + error = new Error(); + error.name = data.name; + } + error.message = data.message; + error.stack = data.stack; + return error; +} + +// see https://github.com/v8/v8/wiki/Stack%20Trace%20API#basic-stack-traces +export interface V8CallSite { + getThis(): unknown; + getTypeName(): string | null; + getFunction(): Function | undefined; + getFunctionName(): string | null; + getMethodName(): string | null; + getFileName(): string | null; + getLineNumber(): number | null; + getColumnNumber(): number | null; + getEvalOrigin(): string | undefined; + isToplevel(): boolean; + isEval(): boolean; + isNative(): boolean; + isConstructor(): boolean; + toString(): string; +} + +const canceledName = 'Canceled'; + +/** + * Checks if the given error is a promise in canceled state + */ +export function isCancellationError(error: any): boolean { + if (error instanceof CancellationError) { + return true; + } + return error instanceof Error && error.name === canceledName && error.message === canceledName; +} + +// !!!IMPORTANT!!! +// Do NOT change this class because it is also used as an API-type. +export class CancellationError extends Error { + constructor() { + super(canceledName); + this.name = this.message; + } +} + +/** + * @deprecated use {@link CancellationError `new CancellationError()`} instead + */ +export function canceled(): Error { + const error = new Error(canceledName); + error.name = error.message; + return error; +} + +export function illegalArgument(name?: string): Error { + if (name) { + return new Error(`Illegal argument: ${name}`); + } else { + return new Error('Illegal argument'); + } +} + +export function illegalState(name?: string): Error { + if (name) { + return new Error(`Illegal state: ${name}`); + } else { + return new Error('Illegal state'); + } +} + +export class ReadonlyError extends TypeError { + constructor(name?: string) { + super(name ? `${name} is read-only and cannot be changed` : 'Cannot change read-only property'); + } +} + +export function getErrorMessage(err: any): string { + if (!err) { + return 'Error'; + } + + if (err.message) { + return err.message; + } + + if (err.stack) { + return err.stack.split('\n')[0]; + } + + return String(err); +} + +export class NotImplementedError extends Error { + constructor(message?: string) { + super('NotImplemented'); + if (message) { + this.message = message; + } + } +} + +export class NotSupportedError extends Error { + constructor(message?: string) { + super('NotSupported'); + if (message) { + this.message = message; + } + } +} + +export class ExpectedError extends Error { + readonly isExpected = true; +} + +/** + * Error that when thrown won't be logged in telemetry as an unhandled error. + */ +export class ErrorNoTelemetry extends Error { + override readonly name: string; + + constructor(msg?: string) { + super(msg); + this.name = 'CodeExpectedError'; + } + + public static fromError(err: Error): ErrorNoTelemetry { + if (err instanceof ErrorNoTelemetry) { + return err; + } + + const result = new ErrorNoTelemetry(); + result.message = err.message; + result.stack = err.stack; + return result; + } + + public static isErrorNoTelemetry(err: Error): err is ErrorNoTelemetry { + return err.name === 'CodeExpectedError'; + } +} + +/** + * This error indicates a bug. + * Do not throw this for invalid user input. + * Only catch this error to recover gracefully from bugs. + */ +export class BugIndicatingError extends Error { + constructor(message?: string) { + super(message || 'An unexpected bug occurred.'); + Object.setPrototypeOf(this, BugIndicatingError.prototype); + + // Because we know for sure only buggy code throws this, + // we definitely want to break here and fix the bug. + // eslint-disable-next-line no-debugger + // debugger; + } +} diff --git a/node_modules/@xterm/xterm/src/vs/base/common/event.ts b/node_modules/@xterm/xterm/src/vs/base/common/event.ts new file mode 100644 index 0000000..5900c7d --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/common/event.ts @@ -0,0 +1,1778 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { CancellationToken } from 'vs/base/common/cancellation'; +import { onUnexpectedError } from 'vs/base/common/errors'; +import { createSingleCallFunction } from 'vs/base/common/functional'; +import { combinedDisposable, Disposable, DisposableMap, DisposableStore, IDisposable, toDisposable } from 'vs/base/common/lifecycle'; +import { LinkedList } from 'vs/base/common/linkedList'; +import { IObservable, IObserver } from 'vs/base/common/observable'; +import { StopWatch } from 'vs/base/common/stopwatch'; +import { MicrotaskDelay } from 'vs/base/common/symbols'; + + +// ----------------------------------------------------------------------------------------------------------------------- +// Uncomment the next line to print warnings whenever a listener is GC'ed without having been disposed. This is a LEAK. +// ----------------------------------------------------------------------------------------------------------------------- +const _enableListenerGCedWarning = false + // || Boolean("TRUE") // causes a linter warning so that it cannot be pushed + ; + +// ----------------------------------------------------------------------------------------------------------------------- +// Uncomment the next line to print warnings whenever an emitter with listeners is disposed. That is a sign of code smell. +// ----------------------------------------------------------------------------------------------------------------------- +const _enableDisposeWithListenerWarning = false + // || Boolean("TRUE") // causes a linter warning so that it cannot be pushed + ; + + +// ----------------------------------------------------------------------------------------------------------------------- +// Uncomment the next line to print warnings whenever a snapshotted event is used repeatedly without cleanup. +// See https://github.com/microsoft/vscode/issues/142851 +// ----------------------------------------------------------------------------------------------------------------------- +const _enableSnapshotPotentialLeakWarning = false + // || Boolean("TRUE") // causes a linter warning so that it cannot be pushed + ; + +/** + * An event with zero or one parameters that can be subscribed to. The event is a function itself. + */ +export interface Event { + (listener: (e: T) => any, thisArgs?: any, disposables?: IDisposable[] | DisposableStore): IDisposable; +} + +export namespace Event { + export const None: Event = () => Disposable.None; + + function _addLeakageTraceLogic(options: EmitterOptions) { + if (_enableSnapshotPotentialLeakWarning) { + const { onDidAddListener: origListenerDidAdd } = options; + const stack = Stacktrace.create(); + let count = 0; + options.onDidAddListener = () => { + if (++count === 2) { + console.warn('snapshotted emitter LIKELY used public and SHOULD HAVE BEEN created with DisposableStore. snapshotted here'); + stack.print(); + } + origListenerDidAdd?.(); + }; + } + } + + /** + * Given an event, returns another event which debounces calls and defers the listeners to a later task via a shared + * `setTimeout`. The event is converted into a signal (`Event`) to avoid additional object creation as a + * result of merging events and to try prevent race conditions that could arise when using related deferred and + * non-deferred events. + * + * This is useful for deferring non-critical work (eg. general UI updates) to ensure it does not block critical work + * (eg. latency of keypress to text rendered). + * + * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned + * event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the + * returned event causes this utility to leak a listener on the original event. + * + * @param event The event source for the new event. + * @param disposable A disposable store to add the new EventEmitter to. + */ + export function defer(event: Event, disposable?: DisposableStore): Event { + return debounce(event, () => void 0, 0, undefined, true, undefined, disposable); + } + + /** + * Given an event, returns another event which only fires once. + * + * @param event The event source for the new event. + */ + export function once(event: Event): Event { + return (listener, thisArgs = null, disposables?) => { + // we need this, in case the event fires during the listener call + let didFire = false; + let result: IDisposable | undefined = undefined; + result = event(e => { + if (didFire) { + return; + } else if (result) { + result.dispose(); + } else { + didFire = true; + } + + return listener.call(thisArgs, e); + }, null, disposables); + + if (didFire) { + result.dispose(); + } + + return result; + }; + } + + /** + * Maps an event of one type into an event of another type using a mapping function, similar to how + * `Array.prototype.map` works. + * + * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned + * event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the + * returned event causes this utility to leak a listener on the original event. + * + * @param event The event source for the new event. + * @param map The mapping function. + * @param disposable A disposable store to add the new EventEmitter to. + */ + export function map(event: Event, map: (i: I) => O, disposable?: DisposableStore): Event { + return snapshot((listener, thisArgs = null, disposables?) => event(i => listener.call(thisArgs, map(i)), null, disposables), disposable); + } + + /** + * Wraps an event in another event that performs some function on the event object before firing. + * + * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned + * event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the + * returned event causes this utility to leak a listener on the original event. + * + * @param event The event source for the new event. + * @param each The function to perform on the event object. + * @param disposable A disposable store to add the new EventEmitter to. + */ + export function forEach(event: Event, each: (i: I) => void, disposable?: DisposableStore): Event { + return snapshot((listener, thisArgs = null, disposables?) => event(i => { each(i); listener.call(thisArgs, i); }, null, disposables), disposable); + } + + /** + * Wraps an event in another event that fires only when some condition is met. + * + * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned + * event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the + * returned event causes this utility to leak a listener on the original event. + * + * @param event The event source for the new event. + * @param filter The filter function that defines the condition. The event will fire for the object if this function + * returns true. + * @param disposable A disposable store to add the new EventEmitter to. + */ + export function filter(event: Event, filter: (e: T | U) => e is T, disposable?: DisposableStore): Event; + export function filter(event: Event, filter: (e: T) => boolean, disposable?: DisposableStore): Event; + export function filter(event: Event, filter: (e: T | R) => e is R, disposable?: DisposableStore): Event; + export function filter(event: Event, filter: (e: T) => boolean, disposable?: DisposableStore): Event { + return snapshot((listener, thisArgs = null, disposables?) => event(e => filter(e) && listener.call(thisArgs, e), null, disposables), disposable); + } + + /** + * Given an event, returns the same event but typed as `Event`. + */ + export function signal(event: Event): Event { + return event as Event as Event; + } + + /** + * Given a collection of events, returns a single event which emits whenever any of the provided events emit. + */ + export function any(...events: Event[]): Event; + export function any(...events: Event[]): Event; + export function any(...events: Event[]): Event { + return (listener, thisArgs = null, disposables?) => { + const disposable = combinedDisposable(...events.map(event => event(e => listener.call(thisArgs, e)))); + return addAndReturnDisposable(disposable, disposables); + }; + } + + /** + * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned + * event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the + * returned event causes this utility to leak a listener on the original event. + */ + export function reduce(event: Event, merge: (last: O | undefined, event: I) => O, initial?: O, disposable?: DisposableStore): Event { + let output: O | undefined = initial; + + return map(event, e => { + output = merge(output, e); + return output; + }, disposable); + } + + function snapshot(event: Event, disposable: DisposableStore | undefined): Event { + let listener: IDisposable | undefined; + + const options: EmitterOptions | undefined = { + onWillAddFirstListener() { + listener = event(emitter.fire, emitter); + }, + onDidRemoveLastListener() { + listener?.dispose(); + } + }; + + if (!disposable) { + _addLeakageTraceLogic(options); + } + + const emitter = new Emitter(options); + + disposable?.add(emitter); + + return emitter.event; + } + + /** + * Adds the IDisposable to the store if it's set, and returns it. Useful to + * Event function implementation. + */ + function addAndReturnDisposable(d: T, store: DisposableStore | IDisposable[] | undefined): T { + if (store instanceof Array) { + store.push(d); + } else if (store) { + store.add(d); + } + return d; + } + + /** + * Given an event, creates a new emitter that event that will debounce events based on {@link delay} and give an + * array event object of all events that fired. + * + * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned + * event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the + * returned event causes this utility to leak a listener on the original event. + * + * @param event The original event to debounce. + * @param merge A function that reduces all events into a single event. + * @param delay The number of milliseconds to debounce. + * @param leading Whether to fire a leading event without debouncing. + * @param flushOnListenerRemove Whether to fire all debounced events when a listener is removed. If this is not + * specified, some events could go missing. Use this if it's important that all events are processed, even if the + * listener gets disposed before the debounced event fires. + * @param leakWarningThreshold See {@link EmitterOptions.leakWarningThreshold}. + * @param disposable A disposable store to register the debounce emitter to. + */ + export function debounce(event: Event, merge: (last: T | undefined, event: T) => T, delay?: number | typeof MicrotaskDelay, leading?: boolean, flushOnListenerRemove?: boolean, leakWarningThreshold?: number, disposable?: DisposableStore): Event; + export function debounce(event: Event, merge: (last: O | undefined, event: I) => O, delay?: number | typeof MicrotaskDelay, leading?: boolean, flushOnListenerRemove?: boolean, leakWarningThreshold?: number, disposable?: DisposableStore): Event; + export function debounce(event: Event, merge: (last: O | undefined, event: I) => O, delay: number | typeof MicrotaskDelay = 100, leading = false, flushOnListenerRemove = false, leakWarningThreshold?: number, disposable?: DisposableStore): Event { + let subscription: IDisposable; + let output: O | undefined = undefined; + let handle: any = undefined; + let numDebouncedCalls = 0; + let doFire: (() => void) | undefined; + + const options: EmitterOptions | undefined = { + leakWarningThreshold, + onWillAddFirstListener() { + subscription = event(cur => { + numDebouncedCalls++; + output = merge(output, cur); + + if (leading && !handle) { + emitter.fire(output); + output = undefined; + } + + doFire = () => { + const _output = output; + output = undefined; + handle = undefined; + if (!leading || numDebouncedCalls > 1) { + emitter.fire(_output!); + } + numDebouncedCalls = 0; + }; + + if (typeof delay === 'number') { + clearTimeout(handle); + handle = setTimeout(doFire, delay); + } else { + if (handle === undefined) { + handle = 0; + queueMicrotask(doFire); + } + } + }); + }, + onWillRemoveListener() { + if (flushOnListenerRemove && numDebouncedCalls > 0) { + doFire?.(); + } + }, + onDidRemoveLastListener() { + doFire = undefined; + subscription.dispose(); + } + }; + + if (!disposable) { + _addLeakageTraceLogic(options); + } + + const emitter = new Emitter(options); + + disposable?.add(emitter); + + return emitter.event; + } + + /** + * Debounces an event, firing after some delay (default=0) with an array of all event original objects. + * + * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned + * event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the + * returned event causes this utility to leak a listener on the original event. + */ + export function accumulate(event: Event, delay: number = 0, disposable?: DisposableStore): Event { + return Event.debounce(event, (last, e) => { + if (!last) { + return [e]; + } + last.push(e); + return last; + }, delay, undefined, true, undefined, disposable); + } + + /** + * Filters an event such that some condition is _not_ met more than once in a row, effectively ensuring duplicate + * event objects from different sources do not fire the same event object. + * + * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned + * event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the + * returned event causes this utility to leak a listener on the original event. + * + * @param event The event source for the new event. + * @param equals The equality condition. + * @param disposable A disposable store to add the new EventEmitter to. + * + * @example + * ``` + * // Fire only one time when a single window is opened or focused + * Event.latch(Event.any(onDidOpenWindow, onDidFocusWindow)) + * ``` + */ + export function latch(event: Event, equals: (a: T, b: T) => boolean = (a, b) => a === b, disposable?: DisposableStore): Event { + let firstCall = true; + let cache: T; + + return filter(event, value => { + const shouldEmit = firstCall || !equals(value, cache); + firstCall = false; + cache = value; + return shouldEmit; + }, disposable); + } + + /** + * Splits an event whose parameter is a union type into 2 separate events for each type in the union. + * + * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned + * event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the + * returned event causes this utility to leak a listener on the original event. + * + * @example + * ``` + * const event = new EventEmitter().event; + * const [numberEvent, undefinedEvent] = Event.split(event, isUndefined); + * ``` + * + * @param event The event source for the new event. + * @param isT A function that determines what event is of the first type. + * @param disposable A disposable store to add the new EventEmitter to. + */ + export function split(event: Event, isT: (e: T | U) => e is T, disposable?: DisposableStore): [Event, Event] { + return [ + Event.filter(event, isT, disposable), + Event.filter(event, e => !isT(e), disposable) as Event, + ]; + } + + /** + * Buffers an event until it has a listener attached. + * + * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned + * event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the + * returned event causes this utility to leak a listener on the original event. + * + * @param event The event source for the new event. + * @param flushAfterTimeout Determines whether to flush the buffer after a timeout immediately or after a + * `setTimeout` when the first event listener is added. + * @param _buffer Internal: A source event array used for tests. + * + * @example + * ``` + * // Start accumulating events, when the first listener is attached, flush + * // the event after a timeout such that multiple listeners attached before + * // the timeout would receive the event + * this.onInstallExtension = Event.buffer(service.onInstallExtension, true); + * ``` + */ + export function buffer(event: Event, flushAfterTimeout = false, _buffer: T[] = [], disposable?: DisposableStore): Event { + let buffer: T[] | null = _buffer.slice(); + + let listener: IDisposable | null = event(e => { + if (buffer) { + buffer.push(e); + } else { + emitter.fire(e); + } + }); + + if (disposable) { + disposable.add(listener); + } + + const flush = () => { + buffer?.forEach(e => emitter.fire(e)); + buffer = null; + }; + + const emitter = new Emitter({ + onWillAddFirstListener() { + if (!listener) { + listener = event(e => emitter.fire(e)); + if (disposable) { + disposable.add(listener); + } + } + }, + + onDidAddFirstListener() { + if (buffer) { + if (flushAfterTimeout) { + setTimeout(flush); + } else { + flush(); + } + } + }, + + onDidRemoveLastListener() { + if (listener) { + listener.dispose(); + } + listener = null; + } + }); + + if (disposable) { + disposable.add(emitter); + } + + return emitter.event; + } + /** + * Wraps the event in an {@link IChainableEvent}, allowing a more functional programming style. + * + * @example + * ``` + * // Normal + * const onEnterPressNormal = Event.filter( + * Event.map(onKeyPress.event, e => new StandardKeyboardEvent(e)), + * e.keyCode === KeyCode.Enter + * ).event; + * + * // Using chain + * const onEnterPressChain = Event.chain(onKeyPress.event, $ => $ + * .map(e => new StandardKeyboardEvent(e)) + * .filter(e => e.keyCode === KeyCode.Enter) + * ); + * ``` + */ + export function chain(event: Event, sythensize: ($: IChainableSythensis) => IChainableSythensis): Event { + const fn: Event = (listener, thisArgs, disposables) => { + const cs = sythensize(new ChainableSynthesis()) as ChainableSynthesis; + return event(function (value) { + const result = cs.evaluate(value); + if (result !== HaltChainable) { + listener.call(thisArgs, result); + } + }, undefined, disposables); + }; + + return fn; + } + + const HaltChainable = Symbol('HaltChainable'); + + class ChainableSynthesis implements IChainableSythensis { + private readonly steps: ((input: any) => any)[] = []; + + map(fn: (i: any) => O): this { + this.steps.push(fn); + return this; + } + + forEach(fn: (i: any) => void): this { + this.steps.push(v => { + fn(v); + return v; + }); + return this; + } + + filter(fn: (e: any) => boolean): this { + this.steps.push(v => fn(v) ? v : HaltChainable); + return this; + } + + reduce(merge: (last: R | undefined, event: any) => R, initial?: R | undefined): this { + let last = initial; + this.steps.push(v => { + last = merge(last, v); + return last; + }); + return this; + } + + latch(equals: (a: any, b: any) => boolean = (a, b) => a === b): ChainableSynthesis { + let firstCall = true; + let cache: any; + this.steps.push(value => { + const shouldEmit = firstCall || !equals(value, cache); + firstCall = false; + cache = value; + return shouldEmit ? value : HaltChainable; + }); + + return this; + } + + public evaluate(value: any) { + for (const step of this.steps) { + value = step(value); + if (value === HaltChainable) { + break; + } + } + + return value; + } + } + + export interface IChainableSythensis { + map(fn: (i: T) => O): IChainableSythensis; + forEach(fn: (i: T) => void): IChainableSythensis; + filter(fn: (e: T) => e is R): IChainableSythensis; + filter(fn: (e: T) => boolean): IChainableSythensis; + reduce(merge: (last: R, event: T) => R, initial: R): IChainableSythensis; + reduce(merge: (last: R | undefined, event: T) => R): IChainableSythensis; + latch(equals?: (a: T, b: T) => boolean): IChainableSythensis; + } + + export interface NodeEventEmitter { + on(event: string | symbol, listener: Function): unknown; + removeListener(event: string | symbol, listener: Function): unknown; + } + + /** + * Creates an {@link Event} from a node event emitter. + */ + export function fromNodeEventEmitter(emitter: NodeEventEmitter, eventName: string, map: (...args: any[]) => T = id => id): Event { + const fn = (...args: any[]) => result.fire(map(...args)); + const onFirstListenerAdd = () => emitter.on(eventName, fn); + const onLastListenerRemove = () => emitter.removeListener(eventName, fn); + const result = new Emitter({ onWillAddFirstListener: onFirstListenerAdd, onDidRemoveLastListener: onLastListenerRemove }); + + return result.event; + } + + export interface DOMEventEmitter { + addEventListener(event: string | symbol, listener: Function): void; + removeEventListener(event: string | symbol, listener: Function): void; + } + + /** + * Creates an {@link Event} from a DOM event emitter. + */ + export function fromDOMEventEmitter(emitter: DOMEventEmitter, eventName: string, map: (...args: any[]) => T = id => id): Event { + const fn = (...args: any[]) => result.fire(map(...args)); + const onFirstListenerAdd = () => emitter.addEventListener(eventName, fn); + const onLastListenerRemove = () => emitter.removeEventListener(eventName, fn); + const result = new Emitter({ onWillAddFirstListener: onFirstListenerAdd, onDidRemoveLastListener: onLastListenerRemove }); + + return result.event; + } + + /** + * Creates a promise out of an event, using the {@link Event.once} helper. + */ + export function toPromise(event: Event): Promise { + return new Promise(resolve => once(event)(resolve)); + } + + /** + * Creates an event out of a promise that fires once when the promise is + * resolved with the result of the promise or `undefined`. + */ + export function fromPromise(promise: Promise): Event { + const result = new Emitter(); + + promise.then(res => { + result.fire(res); + }, () => { + result.fire(undefined); + }).finally(() => { + result.dispose(); + }); + + return result.event; + } + + /** + * A convenience function for forwarding an event to another emitter which + * improves readability.allows Event.forward(event, emitter) instead of `event(e => emitter.fire(e))`. + * @param from The event to forward. + * @param to The emitter to forward the event to. + * @example + * Event.forward(event, emitter); + * // equivalent to + * event(e => emitter.fire(e)); + * // equivalent to + * event(emitter.fire, emitter); + */ + export function forward(from: Event, to: Emitter): IDisposable { + return from(e => to.fire(e)); + } + + /** + * Adds a listener to an event and calls the listener immediately with undefined as the event object. + * + * @example + * ``` + * // Initialize the UI and update it when dataChangeEvent fires + * runAndSubscribe(dataChangeEvent, () => this._updateUI()); + * ``` + */ + export function runAndSubscribe(event: Event, handler: (e: T) => any, initial: T): IDisposable; + export function runAndSubscribe(event: Event, handler: (e: T | undefined) => any): IDisposable; + export function runAndSubscribe(event: Event, handler: (e: T | undefined) => any, initial?: T): IDisposable { + handler(initial); + return event(e => handler(e)); + } + + class EmitterObserver implements IObserver { + + readonly emitter: Emitter; + + private _counter = 0; + private _hasChanged = false; + + constructor(readonly _observable: IObservable, store: DisposableStore | undefined) { + const options: EmitterOptions = { + onWillAddFirstListener: () => { + _observable.addObserver(this); + }, + onDidRemoveLastListener: () => { + _observable.removeObserver(this); + } + }; + if (!store) { + _addLeakageTraceLogic(options); + } + this.emitter = new Emitter(options); + if (store) { + store.add(this.emitter); + } + } + + beginUpdate(_observable: IObservable): void { + // assert(_observable === this.obs); + this._counter++; + } + + handlePossibleChange(_observable: IObservable): void { + // assert(_observable === this.obs); + } + + handleChange(_observable: IObservable, _change: TChange): void { + // assert(_observable === this.obs); + this._hasChanged = true; + } + + endUpdate(_observable: IObservable): void { + // assert(_observable === this.obs); + this._counter--; + if (this._counter === 0) { + this._observable.reportChanges(); + if (this._hasChanged) { + this._hasChanged = false; + this.emitter.fire(this._observable.get()); + } + } + } + } + + /** + * Creates an event emitter that is fired when the observable changes. + * Each listeners subscribes to the emitter. + */ + export function fromObservable(obs: IObservable, store?: DisposableStore): Event { + const observer = new EmitterObserver(obs, store); + return observer.emitter.event; + } + + /** + * Each listener is attached to the observable directly. + */ + export function fromObservableLight(observable: IObservable): Event { + return (listener, thisArgs, disposables) => { + let count = 0; + let didChange = false; + const observer: IObserver = { + beginUpdate() { + count++; + }, + endUpdate() { + count--; + if (count === 0) { + observable.reportChanges(); + if (didChange) { + didChange = false; + listener.call(thisArgs); + } + } + }, + handlePossibleChange() { + // noop + }, + handleChange() { + didChange = true; + } + }; + observable.addObserver(observer); + observable.reportChanges(); + const disposable = { + dispose() { + observable.removeObserver(observer); + } + }; + + if (disposables instanceof DisposableStore) { + disposables.add(disposable); + } else if (Array.isArray(disposables)) { + disposables.push(disposable); + } + + return disposable; + }; + } +} + +export interface EmitterOptions { + /** + * Optional function that's called *before* the very first listener is added + */ + onWillAddFirstListener?: Function; + /** + * Optional function that's called *after* the very first listener is added + */ + onDidAddFirstListener?: Function; + /** + * Optional function that's called after a listener is added + */ + onDidAddListener?: Function; + /** + * Optional function that's called *after* remove the very last listener + */ + onDidRemoveLastListener?: Function; + /** + * Optional function that's called *before* a listener is removed + */ + onWillRemoveListener?: Function; + /** + * Optional function that's called when a listener throws an error. Defaults to + * {@link onUnexpectedError} + */ + onListenerError?: (e: any) => void; + /** + * Number of listeners that are allowed before assuming a leak. Default to + * a globally configured value + * + * @see setGlobalLeakWarningThreshold + */ + leakWarningThreshold?: number; + /** + * Pass in a delivery queue, which is useful for ensuring + * in order event delivery across multiple emitters. + */ + deliveryQueue?: EventDeliveryQueue; + + /** ONLY enable this during development */ + _profName?: string; +} + + +export class EventProfiling { + + static readonly all = new Set(); + + private static _idPool = 0; + + readonly name: string; + public listenerCount: number = 0; + public invocationCount = 0; + public elapsedOverall = 0; + public durations: number[] = []; + + private _stopWatch?: StopWatch; + + constructor(name: string) { + this.name = `${name}_${EventProfiling._idPool++}`; + EventProfiling.all.add(this); + } + + start(listenerCount: number): void { + this._stopWatch = new StopWatch(); + this.listenerCount = listenerCount; + } + + stop(): void { + if (this._stopWatch) { + const elapsed = this._stopWatch.elapsed(); + this.durations.push(elapsed); + this.elapsedOverall += elapsed; + this.invocationCount += 1; + this._stopWatch = undefined; + } + } +} + +let _globalLeakWarningThreshold = -1; +export function setGlobalLeakWarningThreshold(n: number): IDisposable { + const oldValue = _globalLeakWarningThreshold; + _globalLeakWarningThreshold = n; + return { + dispose() { + _globalLeakWarningThreshold = oldValue; + } + }; +} + +class LeakageMonitor { + + private static _idPool = 1; + + private _stacks: Map | undefined; + private _warnCountdown: number = 0; + + constructor( + private readonly _errorHandler: (err: Error) => void, + readonly threshold: number, + readonly name: string = (LeakageMonitor._idPool++).toString(16).padStart(3, '0') + ) { } + + dispose(): void { + this._stacks?.clear(); + } + + check(stack: Stacktrace, listenerCount: number): undefined | (() => void) { + + const threshold = this.threshold; + if (threshold <= 0 || listenerCount < threshold) { + return undefined; + } + + if (!this._stacks) { + this._stacks = new Map(); + } + const count = (this._stacks.get(stack.value) || 0); + this._stacks.set(stack.value, count + 1); + this._warnCountdown -= 1; + + if (this._warnCountdown <= 0) { + // only warn on first exceed and then every time the limit + // is exceeded by 50% again + this._warnCountdown = threshold * 0.5; + + const [topStack, topCount] = this.getMostFrequentStack()!; + const message = `[${this.name}] potential listener LEAK detected, having ${listenerCount} listeners already. MOST frequent listener (${topCount}):`; + console.warn(message); + console.warn(topStack!); + + const error = new ListenerLeakError(message, topStack); + this._errorHandler(error); + } + + return () => { + const count = (this._stacks!.get(stack.value) || 0); + this._stacks!.set(stack.value, count - 1); + }; + } + + getMostFrequentStack(): [string, number] | undefined { + if (!this._stacks) { + return undefined; + } + let topStack: [string, number] | undefined; + let topCount: number = 0; + for (const [stack, count] of this._stacks) { + if (!topStack || topCount < count) { + topStack = [stack, count]; + topCount = count; + } + } + return topStack; + } +} + +class Stacktrace { + + static create() { + const err = new Error(); + return new Stacktrace(err.stack ?? ''); + } + + private constructor(readonly value: string) { } + + print() { + console.warn(this.value.split('\n').slice(2).join('\n')); + } +} + +// error that is logged when going over the configured listener threshold +export class ListenerLeakError extends Error { + constructor(message: string, stack: string) { + super(message); + this.name = 'ListenerLeakError'; + this.stack = stack; + } +} + +// SEVERE error that is logged when having gone way over the configured listener +// threshold so that the emitter refuses to accept more listeners +export class ListenerRefusalError extends Error { + constructor(message: string, stack: string) { + super(message); + this.name = 'ListenerRefusalError'; + this.stack = stack; + } +} + +let id = 0; +class UniqueContainer { + stack?: Stacktrace; + public id = id++; + constructor(public readonly value: T) { } +} +const compactionThreshold = 2; + +type ListenerContainer = UniqueContainer<(data: T) => void>; +type ListenerOrListeners = (ListenerContainer | undefined)[] | ListenerContainer; + +const forEachListener = (listeners: ListenerOrListeners, fn: (c: ListenerContainer) => void) => { + if (listeners instanceof UniqueContainer) { + fn(listeners); + } else { + for (let i = 0; i < listeners.length; i++) { + const l = listeners[i]; + if (l) { + fn(l); + } + } + } +}; + + +let _listenerFinalizers: FinalizationRegistry | undefined; + +if (_enableListenerGCedWarning) { + const leaks: string[] = []; + + setInterval(() => { + if (leaks.length === 0) { + return; + } + console.warn('[LEAKING LISTENERS] GC\'ed these listeners that were NOT yet disposed:'); + console.warn(leaks.join('\n')); + leaks.length = 0; + }, 3000); + + _listenerFinalizers = new FinalizationRegistry(heldValue => { + if (typeof heldValue === 'string') { + leaks.push(heldValue); + } + }); +} + +/** + * The Emitter can be used to expose an Event to the public + * to fire it from the insides. + * Sample: + class Document { + + private readonly _onDidChange = new Emitter<(value:string)=>any>(); + + public onDidChange = this._onDidChange.event; + + // getter-style + // get onDidChange(): Event<(value:string)=>any> { + // return this._onDidChange.event; + // } + + private _doIt() { + //... + this._onDidChange.fire(value); + } + } + */ +export class Emitter { + + private readonly _options?: EmitterOptions; + private readonly _leakageMon?: LeakageMonitor; + private readonly _perfMon?: EventProfiling; + private _disposed?: true; + private _event?: Event; + + /** + * A listener, or list of listeners. A single listener is the most common + * for event emitters (#185789), so we optimize that special case to avoid + * wrapping it in an array (just like Node.js itself.) + * + * A list of listeners never 'downgrades' back to a plain function if + * listeners are removed, for two reasons: + * + * 1. That's complicated (especially with the deliveryQueue) + * 2. A listener with >1 listener is likely to have >1 listener again at + * some point, and swapping between arrays and functions may[citation needed] + * introduce unnecessary work and garbage. + * + * The array listeners can be 'sparse', to avoid reallocating the array + * whenever any listener is added or removed. If more than `1 / compactionThreshold` + * of the array is empty, only then is it resized. + */ + protected _listeners?: ListenerOrListeners; + + /** + * Always to be defined if _listeners is an array. It's no longer a true + * queue, but holds the dispatching 'state'. If `fire()` is called on an + * emitter, any work left in the _deliveryQueue is finished first. + */ + private _deliveryQueue?: EventDeliveryQueuePrivate; + protected _size = 0; + + constructor(options?: EmitterOptions) { + this._options = options; + this._leakageMon = (_globalLeakWarningThreshold > 0 || this._options?.leakWarningThreshold) + ? new LeakageMonitor(options?.onListenerError ?? onUnexpectedError, this._options?.leakWarningThreshold ?? _globalLeakWarningThreshold) : + undefined; + this._perfMon = this._options?._profName ? new EventProfiling(this._options._profName) : undefined; + this._deliveryQueue = this._options?.deliveryQueue as EventDeliveryQueuePrivate | undefined; + } + + dispose() { + if (!this._disposed) { + this._disposed = true; + + // It is bad to have listeners at the time of disposing an emitter, it is worst to have listeners keep the emitter + // alive via the reference that's embedded in their disposables. Therefore we loop over all remaining listeners and + // unset their subscriptions/disposables. Looping and blaming remaining listeners is done on next tick because the + // the following programming pattern is very popular: + // + // const someModel = this._disposables.add(new ModelObject()); // (1) create and register model + // this._disposables.add(someModel.onDidChange(() => { ... }); // (2) subscribe and register model-event listener + // ...later... + // this._disposables.dispose(); disposes (1) then (2): don't warn after (1) but after the "overall dispose" is done + + if (this._deliveryQueue?.current === this) { + this._deliveryQueue.reset(); + } + if (this._listeners) { + if (_enableDisposeWithListenerWarning) { + const listeners = this._listeners; + queueMicrotask(() => { + forEachListener(listeners, l => l.stack?.print()); + }); + } + + this._listeners = undefined; + this._size = 0; + } + this._options?.onDidRemoveLastListener?.(); + this._leakageMon?.dispose(); + } + } + + /** + * For the public to allow to subscribe + * to events from this Emitter + */ + get event(): Event { + this._event ??= (callback: (e: T) => any, thisArgs?: any, disposables?: IDisposable[] | DisposableStore) => { + if (this._leakageMon && this._size > this._leakageMon.threshold ** 2) { + const message = `[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`; + console.warn(message); + + const tuple = this._leakageMon.getMostFrequentStack() ?? ['UNKNOWN stack', -1]; + const error = new ListenerRefusalError(`${message}. HINT: Stack shows most frequent listener (${tuple[1]}-times)`, tuple[0]); + const errorHandler = this._options?.onListenerError || onUnexpectedError; + errorHandler(error); + + return Disposable.None; + } + + if (this._disposed) { + // todo: should we warn if a listener is added to a disposed emitter? This happens often + return Disposable.None; + } + + if (thisArgs) { + callback = callback.bind(thisArgs); + } + + const contained = new UniqueContainer(callback); + + let removeMonitor: Function | undefined; + let stack: Stacktrace | undefined; + if (this._leakageMon && this._size >= Math.ceil(this._leakageMon.threshold * 0.2)) { + // check and record this emitter for potential leakage + contained.stack = Stacktrace.create(); + removeMonitor = this._leakageMon.check(contained.stack, this._size + 1); + } + + if (_enableDisposeWithListenerWarning) { + contained.stack = stack ?? Stacktrace.create(); + } + + if (!this._listeners) { + this._options?.onWillAddFirstListener?.(this); + this._listeners = contained; + this._options?.onDidAddFirstListener?.(this); + } else if (this._listeners instanceof UniqueContainer) { + this._deliveryQueue ??= new EventDeliveryQueuePrivate(); + this._listeners = [this._listeners, contained]; + } else { + this._listeners.push(contained); + } + + this._size++; + + + const result = toDisposable(() => { + _listenerFinalizers?.unregister(result); + removeMonitor?.(); + this._removeListener(contained); + }); + if (disposables instanceof DisposableStore) { + disposables.add(result); + } else if (Array.isArray(disposables)) { + disposables.push(result); + } + + if (_listenerFinalizers) { + const stack = new Error().stack!.split('\n').slice(2, 3).join('\n').trim(); + const match = /(file:|vscode-file:\/\/vscode-app)?(\/[^:]*:\d+:\d+)/.exec(stack); + _listenerFinalizers.register(result, match?.[2] ?? stack, result); + } + + return result; + }; + + return this._event; + } + + private _removeListener(listener: ListenerContainer) { + this._options?.onWillRemoveListener?.(this); + + if (!this._listeners) { + return; // expected if a listener gets disposed + } + + if (this._size === 1) { + this._listeners = undefined; + this._options?.onDidRemoveLastListener?.(this); + this._size = 0; + return; + } + + // size > 1 which requires that listeners be a list: + const listeners = this._listeners as (ListenerContainer | undefined)[]; + + const index = listeners.indexOf(listener); + if (index === -1) { + console.log('disposed?', this._disposed); + console.log('size?', this._size); + console.log('arr?', JSON.stringify(this._listeners)); + throw new Error('Attempted to dispose unknown listener'); + } + + this._size--; + listeners[index] = undefined; + + const adjustDeliveryQueue = this._deliveryQueue!.current === this; + if (this._size * compactionThreshold <= listeners.length) { + let n = 0; + for (let i = 0; i < listeners.length; i++) { + if (listeners[i]) { + listeners[n++] = listeners[i]; + } else if (adjustDeliveryQueue) { + this._deliveryQueue!.end--; + if (n < this._deliveryQueue!.i) { + this._deliveryQueue!.i--; + } + } + } + listeners.length = n; + } + } + + private _deliver(listener: undefined | UniqueContainer<(value: T) => void>, value: T) { + if (!listener) { + return; + } + + const errorHandler = this._options?.onListenerError || onUnexpectedError; + if (!errorHandler) { + listener.value(value); + return; + } + + try { + listener.value(value); + } catch (e) { + errorHandler(e); + } + } + + /** Delivers items in the queue. Assumes the queue is ready to go. */ + private _deliverQueue(dq: EventDeliveryQueuePrivate) { + const listeners = dq.current!._listeners! as (ListenerContainer | undefined)[]; + while (dq.i < dq.end) { + // important: dq.i is incremented before calling deliver() because it might reenter deliverQueue() + this._deliver(listeners[dq.i++], dq.value as T); + } + dq.reset(); + } + + /** + * To be kept private to fire an event to + * subscribers + */ + fire(event: T): void { + if (this._deliveryQueue?.current) { + this._deliverQueue(this._deliveryQueue); + this._perfMon?.stop(); // last fire() will have starting perfmon, stop it before starting the next dispatch + } + + this._perfMon?.start(this._size); + + if (!this._listeners) { + // no-op + } else if (this._listeners instanceof UniqueContainer) { + this._deliver(this._listeners, event); + } else { + const dq = this._deliveryQueue!; + dq.enqueue(this, event, this._listeners.length); + this._deliverQueue(dq); + } + + this._perfMon?.stop(); + } + + hasListeners(): boolean { + return this._size > 0; + } +} + +export interface EventDeliveryQueue { + _isEventDeliveryQueue: true; +} + +export const createEventDeliveryQueue = (): EventDeliveryQueue => new EventDeliveryQueuePrivate(); + +class EventDeliveryQueuePrivate implements EventDeliveryQueue { + declare _isEventDeliveryQueue: true; + + /** + * Index in current's listener list. + */ + public i = -1; + + /** + * The last index in the listener's list to deliver. + */ + public end = 0; + + /** + * Emitter currently being dispatched on. Emitter._listeners is always an array. + */ + public current?: Emitter; + /** + * Currently emitting value. Defined whenever `current` is. + */ + public value?: unknown; + + public enqueue(emitter: Emitter, value: T, end: number) { + this.i = 0; + this.end = end; + this.current = emitter; + this.value = value; + } + + public reset() { + this.i = this.end; // force any current emission loop to stop, mainly for during dispose + this.current = undefined; + this.value = undefined; + } +} + +export interface IWaitUntil { + token: CancellationToken; + waitUntil(thenable: Promise): void; +} + +export type IWaitUntilData = Omit, 'token'>; + +export class AsyncEmitter extends Emitter { + + private _asyncDeliveryQueue?: LinkedList<[(ev: T) => void, IWaitUntilData]>; + + async fireAsync(data: IWaitUntilData, token: CancellationToken, promiseJoin?: (p: Promise, listener: Function) => Promise): Promise { + if (!this._listeners) { + return; + } + + if (!this._asyncDeliveryQueue) { + this._asyncDeliveryQueue = new LinkedList(); + } + + forEachListener(this._listeners, listener => this._asyncDeliveryQueue!.push([listener.value, data])); + + while (this._asyncDeliveryQueue.size > 0 && !token.isCancellationRequested) { + + const [listener, data] = this._asyncDeliveryQueue.shift()!; + const thenables: Promise[] = []; + + const event = { + ...data, + token, + waitUntil: (p: Promise): void => { + if (Object.isFrozen(thenables)) { + throw new Error('waitUntil can NOT be called asynchronous'); + } + if (promiseJoin) { + p = promiseJoin(p, listener); + } + thenables.push(p); + } + }; + + try { + listener(event); + } catch (e) { + onUnexpectedError(e); + continue; + } + + // freeze thenables-collection to enforce sync-calls to + // wait until and then wait for all thenables to resolve + Object.freeze(thenables); + + await Promise.allSettled(thenables).then(values => { + for (const value of values) { + if (value.status === 'rejected') { + onUnexpectedError(value.reason); + } + } + }); + } + } +} + + +export class PauseableEmitter extends Emitter { + + private _isPaused = 0; + protected _eventQueue = new LinkedList(); + private _mergeFn?: (input: T[]) => T; + + public get isPaused(): boolean { + return this._isPaused !== 0; + } + + constructor(options?: EmitterOptions & { merge?: (input: T[]) => T }) { + super(options); + this._mergeFn = options?.merge; + } + + pause(): void { + this._isPaused++; + } + + resume(): void { + if (this._isPaused !== 0 && --this._isPaused === 0) { + if (this._mergeFn) { + // use the merge function to create a single composite + // event. make a copy in case firing pauses this emitter + if (this._eventQueue.size > 0) { + const events = Array.from(this._eventQueue); + this._eventQueue.clear(); + super.fire(this._mergeFn(events)); + } + + } else { + // no merging, fire each event individually and test + // that this emitter isn't paused halfway through + while (!this._isPaused && this._eventQueue.size !== 0) { + super.fire(this._eventQueue.shift()!); + } + } + } + } + + override fire(event: T): void { + if (this._size) { + if (this._isPaused !== 0) { + this._eventQueue.push(event); + } else { + super.fire(event); + } + } + } +} + +export class DebounceEmitter extends PauseableEmitter { + + private readonly _delay: number; + private _handle: any | undefined; + + constructor(options: EmitterOptions & { merge: (input: T[]) => T; delay?: number }) { + super(options); + this._delay = options.delay ?? 100; + } + + override fire(event: T): void { + if (!this._handle) { + this.pause(); + this._handle = setTimeout(() => { + this._handle = undefined; + this.resume(); + }, this._delay); + } + super.fire(event); + } +} + +/** + * An emitter which queue all events and then process them at the + * end of the event loop. + */ +export class MicrotaskEmitter extends Emitter { + private _queuedEvents: T[] = []; + private _mergeFn?: (input: T[]) => T; + + constructor(options?: EmitterOptions & { merge?: (input: T[]) => T }) { + super(options); + this._mergeFn = options?.merge; + } + override fire(event: T): void { + + if (!this.hasListeners()) { + return; + } + + this._queuedEvents.push(event); + if (this._queuedEvents.length === 1) { + queueMicrotask(() => { + if (this._mergeFn) { + super.fire(this._mergeFn(this._queuedEvents)); + } else { + this._queuedEvents.forEach(e => super.fire(e)); + } + this._queuedEvents = []; + }); + } + } +} + +/** + * An event emitter that multiplexes many events into a single event. + * + * @example Listen to the `onData` event of all `Thing`s, dynamically adding and removing `Thing`s + * to the multiplexer as needed. + * + * ```typescript + * const anythingDataMultiplexer = new EventMultiplexer<{ data: string }>(); + * + * const thingListeners = DisposableMap(); + * + * thingService.onDidAddThing(thing => { + * thingListeners.set(thing, anythingDataMultiplexer.add(thing.onData); + * }); + * thingService.onDidRemoveThing(thing => { + * thingListeners.deleteAndDispose(thing); + * }); + * + * anythingDataMultiplexer.event(e => { + * console.log('Something fired data ' + e.data) + * }); + * ``` + */ +export class EventMultiplexer implements IDisposable { + + private readonly emitter: Emitter; + private hasListeners = false; + private events: { event: Event; listener: IDisposable | null }[] = []; + + constructor() { + this.emitter = new Emitter({ + onWillAddFirstListener: () => this.onFirstListenerAdd(), + onDidRemoveLastListener: () => this.onLastListenerRemove() + }); + } + + get event(): Event { + return this.emitter.event; + } + + add(event: Event): IDisposable { + const e = { event: event, listener: null }; + this.events.push(e); + + if (this.hasListeners) { + this.hook(e); + } + + const dispose = () => { + if (this.hasListeners) { + this.unhook(e); + } + + const idx = this.events.indexOf(e); + this.events.splice(idx, 1); + }; + + return toDisposable(createSingleCallFunction(dispose)); + } + + private onFirstListenerAdd(): void { + this.hasListeners = true; + this.events.forEach(e => this.hook(e)); + } + + private onLastListenerRemove(): void { + this.hasListeners = false; + this.events.forEach(e => this.unhook(e)); + } + + private hook(e: { event: Event; listener: IDisposable | null }): void { + e.listener = e.event(r => this.emitter.fire(r)); + } + + private unhook(e: { event: Event; listener: IDisposable | null }): void { + e.listener?.dispose(); + e.listener = null; + } + + dispose(): void { + this.emitter.dispose(); + + for (const e of this.events) { + e.listener?.dispose(); + } + this.events = []; + } +} + +export interface IDynamicListEventMultiplexer extends IDisposable { + readonly event: Event; +} +export class DynamicListEventMultiplexer implements IDynamicListEventMultiplexer { + private readonly _store = new DisposableStore(); + + readonly event: Event; + + constructor( + items: TItem[], + onAddItem: Event, + onRemoveItem: Event, + getEvent: (item: TItem) => Event + ) { + const multiplexer = this._store.add(new EventMultiplexer()); + const itemListeners = this._store.add(new DisposableMap()); + + function addItem(instance: TItem) { + itemListeners.set(instance, multiplexer.add(getEvent(instance))); + } + + // Existing items + for (const instance of items) { + addItem(instance); + } + + // Added items + this._store.add(onAddItem(instance => { + addItem(instance); + })); + + // Removed items + this._store.add(onRemoveItem(instance => { + itemListeners.deleteAndDispose(instance); + })); + + this.event = multiplexer.event; + } + + dispose() { + this._store.dispose(); + } +} + +/** + * The EventBufferer is useful in situations in which you want + * to delay firing your events during some code. + * You can wrap that code and be sure that the event will not + * be fired during that wrap. + * + * ``` + * const emitter: Emitter; + * const delayer = new EventDelayer(); + * const delayedEvent = delayer.wrapEvent(emitter.event); + * + * delayedEvent(console.log); + * + * delayer.bufferEvents(() => { + * emitter.fire(); // event will not be fired yet + * }); + * + * // event will only be fired at this point + * ``` + */ +export class EventBufferer { + + private data: { buffers: Function[] }[] = []; + + wrapEvent(event: Event): Event; + wrapEvent(event: Event, reduce: (last: T | undefined, event: T) => T): Event; + wrapEvent(event: Event, reduce: (last: O | undefined, event: T) => O, initial: O): Event; + wrapEvent(event: Event, reduce?: (last: T | O | undefined, event: T) => T | O, initial?: O): Event { + return (listener, thisArgs?, disposables?) => { + return event(i => { + const data = this.data[this.data.length - 1]; + + // Non-reduce scenario + if (!reduce) { + // Buffering case + if (data) { + data.buffers.push(() => listener.call(thisArgs, i)); + } else { + // Not buffering case + listener.call(thisArgs, i); + } + return; + } + + // Reduce scenario + const reduceData = data as typeof data & { + /** + * The accumulated items that will be reduced. + */ + items?: T[]; + /** + * The reduced result cached to be shared with other listeners. + */ + reducedResult?: T | O; + }; + + // Not buffering case + if (!reduceData) { + // TODO: Is there a way to cache this reduce call for all listeners? + listener.call(thisArgs, reduce(initial, i)); + return; + } + + // Buffering case + reduceData.items ??= []; + reduceData.items.push(i); + if (reduceData.buffers.length === 0) { + // Include a single buffered function that will reduce all events when we're done buffering events + data.buffers.push(() => { + // cache the reduced result so that the value can be shared across all listeners + reduceData.reducedResult ??= initial + ? reduceData.items!.reduce(reduce as (last: O | undefined, event: T) => O, initial) + : reduceData.items!.reduce(reduce as (last: T | undefined, event: T) => T); + listener.call(thisArgs, reduceData.reducedResult); + }); + } + }, undefined, disposables); + }; + } + + bufferEvents(fn: () => R): R { + const data = { buffers: new Array() }; + this.data.push(data); + const r = fn(); + this.data.pop(); + data.buffers.forEach(flush => flush()); + return r; + } +} + +/** + * A Relay is an event forwarder which functions as a replugabble event pipe. + * Once created, you can connect an input event to it and it will simply forward + * events from that input event through its own `event` property. The `input` + * can be changed at any point in time. + */ +export class Relay implements IDisposable { + + private listening = false; + private inputEvent: Event = Event.None; + private inputEventListener: IDisposable = Disposable.None; + + private readonly emitter = new Emitter({ + onDidAddFirstListener: () => { + this.listening = true; + this.inputEventListener = this.inputEvent(this.emitter.fire, this.emitter); + }, + onDidRemoveLastListener: () => { + this.listening = false; + this.inputEventListener.dispose(); + } + }); + + readonly event: Event = this.emitter.event; + + set input(event: Event) { + this.inputEvent = event; + + if (this.listening) { + this.inputEventListener.dispose(); + this.inputEventListener = event(this.emitter.fire, this.emitter); + } + } + + dispose() { + this.inputEventListener.dispose(); + this.emitter.dispose(); + } +} + +export interface IValueWithChangeEvent { + readonly onDidChange: Event; + get value(): T; +} + +export class ValueWithChangeEvent implements IValueWithChangeEvent { + public static const(value: T): IValueWithChangeEvent { + return new ConstValueWithChangeEvent(value); + } + + private readonly _onDidChange = new Emitter(); + readonly onDidChange: Event = this._onDidChange.event; + + constructor(private _value: T) { } + + get value(): T { + return this._value; + } + + set value(value: T) { + if (value !== this._value) { + this._value = value; + this._onDidChange.fire(undefined); + } + } +} + +class ConstValueWithChangeEvent implements IValueWithChangeEvent { + public readonly onDidChange: Event = Event.None; + + constructor(readonly value: T) { } +} diff --git a/node_modules/@xterm/xterm/src/vs/base/common/functional.ts b/node_modules/@xterm/xterm/src/vs/base/common/functional.ts new file mode 100644 index 0000000..d580cf3 --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/common/functional.ts @@ -0,0 +1,32 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +/** + * Given a function, returns a function that is only calling that function once. + */ +export function createSingleCallFunction(this: unknown, fn: T, fnDidRunCallback?: () => void): T { + const _this = this; + let didCall = false; + let result: unknown; + + return function () { + if (didCall) { + return result; + } + + didCall = true; + if (fnDidRunCallback) { + try { + result = fn.apply(_this, arguments); + } finally { + fnDidRunCallback(); + } + } else { + result = fn.apply(_this, arguments); + } + + return result; + } as unknown as T; +} diff --git a/node_modules/@xterm/xterm/src/vs/base/common/hash.ts b/node_modules/@xterm/xterm/src/vs/base/common/hash.ts new file mode 100644 index 0000000..76217c4 --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/common/hash.ts @@ -0,0 +1,316 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import * as strings from 'vs/base/common/strings'; + +/** + * Return a hash value for an object. + */ +export function hash(obj: any): number { + return doHash(obj, 0); +} + +export function doHash(obj: any, hashVal: number): number { + switch (typeof obj) { + case 'object': + if (obj === null) { + return numberHash(349, hashVal); + } else if (Array.isArray(obj)) { + return arrayHash(obj, hashVal); + } + return objectHash(obj, hashVal); + case 'string': + return stringHash(obj, hashVal); + case 'boolean': + return booleanHash(obj, hashVal); + case 'number': + return numberHash(obj, hashVal); + case 'undefined': + return numberHash(937, hashVal); + default: + return numberHash(617, hashVal); + } +} + +export function numberHash(val: number, initialHashVal: number): number { + return (((initialHashVal << 5) - initialHashVal) + val) | 0; // hashVal * 31 + ch, keep as int32 +} + +function booleanHash(b: boolean, initialHashVal: number): number { + return numberHash(b ? 433 : 863, initialHashVal); +} + +export function stringHash(s: string, hashVal: number) { + hashVal = numberHash(149417, hashVal); + for (let i = 0, length = s.length; i < length; i++) { + hashVal = numberHash(s.charCodeAt(i), hashVal); + } + return hashVal; +} + +function arrayHash(arr: any[], initialHashVal: number): number { + initialHashVal = numberHash(104579, initialHashVal); + return arr.reduce((hashVal, item) => doHash(item, hashVal), initialHashVal); +} + +function objectHash(obj: any, initialHashVal: number): number { + initialHashVal = numberHash(181387, initialHashVal); + return Object.keys(obj).sort().reduce((hashVal, key) => { + hashVal = stringHash(key, hashVal); + return doHash(obj[key], hashVal); + }, initialHashVal); +} + +export class Hasher { + + private _value = 0; + + get value(): number { + return this._value; + } + + hash(obj: any): number { + this._value = doHash(obj, this._value); + return this._value; + } +} + +const enum SHA1Constant { + BLOCK_SIZE = 64, // 512 / 8 + UNICODE_REPLACEMENT = 0xFFFD, +} + +function leftRotate(value: number, bits: number, totalBits: number = 32): number { + // delta + bits = totalBits + const delta = totalBits - bits; + + // All ones, expect `delta` zeros aligned to the right + const mask = ~((1 << delta) - 1); + + // Join (value left-shifted `bits` bits) with (masked value right-shifted `delta` bits) + return ((value << bits) | ((mask & value) >>> delta)) >>> 0; +} + +function fill(dest: Uint8Array, index: number = 0, count: number = dest.byteLength, value: number = 0): void { + for (let i = 0; i < count; i++) { + dest[index + i] = value; + } +} + +function leftPad(value: string, length: number, char: string = '0'): string { + while (value.length < length) { + value = char + value; + } + return value; +} + +export function toHexString(buffer: ArrayBuffer): string; +export function toHexString(value: number, bitsize?: number): string; +export function toHexString(bufferOrValue: ArrayBuffer | number, bitsize: number = 32): string { + if (bufferOrValue instanceof ArrayBuffer) { + return Array.from(new Uint8Array(bufferOrValue)).map(b => b.toString(16).padStart(2, '0')).join(''); + } + + return leftPad((bufferOrValue >>> 0).toString(16), bitsize / 4); +} + +/** + * A SHA1 implementation that works with strings and does not allocate. + */ +export class StringSHA1 { + private static _bigBlock32 = new DataView(new ArrayBuffer(320)); // 80 * 4 = 320 + + private _h0 = 0x67452301; + private _h1 = 0xEFCDAB89; + private _h2 = 0x98BADCFE; + private _h3 = 0x10325476; + private _h4 = 0xC3D2E1F0; + + private readonly _buff: Uint8Array; + private readonly _buffDV: DataView; + private _buffLen: number; + private _totalLen: number; + private _leftoverHighSurrogate: number; + private _finished: boolean; + + constructor() { + this._buff = new Uint8Array(SHA1Constant.BLOCK_SIZE + 3 /* to fit any utf-8 */); + this._buffDV = new DataView(this._buff.buffer); + this._buffLen = 0; + this._totalLen = 0; + this._leftoverHighSurrogate = 0; + this._finished = false; + } + + public update(str: string): void { + const strLen = str.length; + if (strLen === 0) { + return; + } + + const buff = this._buff; + let buffLen = this._buffLen; + let leftoverHighSurrogate = this._leftoverHighSurrogate; + let charCode: number; + let offset: number; + + if (leftoverHighSurrogate !== 0) { + charCode = leftoverHighSurrogate; + offset = -1; + leftoverHighSurrogate = 0; + } else { + charCode = str.charCodeAt(0); + offset = 0; + } + + while (true) { + let codePoint = charCode; + if (strings.isHighSurrogate(charCode)) { + if (offset + 1 < strLen) { + const nextCharCode = str.charCodeAt(offset + 1); + if (strings.isLowSurrogate(nextCharCode)) { + offset++; + codePoint = strings.computeCodePoint(charCode, nextCharCode); + } else { + // illegal => unicode replacement character + codePoint = SHA1Constant.UNICODE_REPLACEMENT; + } + } else { + // last character is a surrogate pair + leftoverHighSurrogate = charCode; + break; + } + } else if (strings.isLowSurrogate(charCode)) { + // illegal => unicode replacement character + codePoint = SHA1Constant.UNICODE_REPLACEMENT; + } + + buffLen = this._push(buff, buffLen, codePoint); + offset++; + if (offset < strLen) { + charCode = str.charCodeAt(offset); + } else { + break; + } + } + + this._buffLen = buffLen; + this._leftoverHighSurrogate = leftoverHighSurrogate; + } + + private _push(buff: Uint8Array, buffLen: number, codePoint: number): number { + if (codePoint < 0x0080) { + buff[buffLen++] = codePoint; + } else if (codePoint < 0x0800) { + buff[buffLen++] = 0b11000000 | ((codePoint & 0b00000000000000000000011111000000) >>> 6); + buff[buffLen++] = 0b10000000 | ((codePoint & 0b00000000000000000000000000111111) >>> 0); + } else if (codePoint < 0x10000) { + buff[buffLen++] = 0b11100000 | ((codePoint & 0b00000000000000001111000000000000) >>> 12); + buff[buffLen++] = 0b10000000 | ((codePoint & 0b00000000000000000000111111000000) >>> 6); + buff[buffLen++] = 0b10000000 | ((codePoint & 0b00000000000000000000000000111111) >>> 0); + } else { + buff[buffLen++] = 0b11110000 | ((codePoint & 0b00000000000111000000000000000000) >>> 18); + buff[buffLen++] = 0b10000000 | ((codePoint & 0b00000000000000111111000000000000) >>> 12); + buff[buffLen++] = 0b10000000 | ((codePoint & 0b00000000000000000000111111000000) >>> 6); + buff[buffLen++] = 0b10000000 | ((codePoint & 0b00000000000000000000000000111111) >>> 0); + } + + if (buffLen >= SHA1Constant.BLOCK_SIZE) { + this._step(); + buffLen -= SHA1Constant.BLOCK_SIZE; + this._totalLen += SHA1Constant.BLOCK_SIZE; + // take last 3 in case of UTF8 overflow + buff[0] = buff[SHA1Constant.BLOCK_SIZE + 0]; + buff[1] = buff[SHA1Constant.BLOCK_SIZE + 1]; + buff[2] = buff[SHA1Constant.BLOCK_SIZE + 2]; + } + + return buffLen; + } + + public digest(): string { + if (!this._finished) { + this._finished = true; + if (this._leftoverHighSurrogate) { + // illegal => unicode replacement character + this._leftoverHighSurrogate = 0; + this._buffLen = this._push(this._buff, this._buffLen, SHA1Constant.UNICODE_REPLACEMENT); + } + this._totalLen += this._buffLen; + this._wrapUp(); + } + + return toHexString(this._h0) + toHexString(this._h1) + toHexString(this._h2) + toHexString(this._h3) + toHexString(this._h4); + } + + private _wrapUp(): void { + this._buff[this._buffLen++] = 0x80; + fill(this._buff, this._buffLen); + + if (this._buffLen > 56) { + this._step(); + fill(this._buff); + } + + // this will fit because the mantissa can cover up to 52 bits + const ml = 8 * this._totalLen; + + this._buffDV.setUint32(56, Math.floor(ml / 4294967296), false); + this._buffDV.setUint32(60, ml % 4294967296, false); + + this._step(); + } + + private _step(): void { + const bigBlock32 = StringSHA1._bigBlock32; + const data = this._buffDV; + + for (let j = 0; j < 64 /* 16*4 */; j += 4) { + bigBlock32.setUint32(j, data.getUint32(j, false), false); + } + + for (let j = 64; j < 320 /* 80*4 */; j += 4) { + bigBlock32.setUint32(j, leftRotate((bigBlock32.getUint32(j - 12, false) ^ bigBlock32.getUint32(j - 32, false) ^ bigBlock32.getUint32(j - 56, false) ^ bigBlock32.getUint32(j - 64, false)), 1), false); + } + + let a = this._h0; + let b = this._h1; + let c = this._h2; + let d = this._h3; + let e = this._h4; + + let f: number, k: number; + let temp: number; + + for (let j = 0; j < 80; j++) { + if (j < 20) { + f = (b & c) | ((~b) & d); + k = 0x5A827999; + } else if (j < 40) { + f = b ^ c ^ d; + k = 0x6ED9EBA1; + } else if (j < 60) { + f = (b & c) | (b & d) | (c & d); + k = 0x8F1BBCDC; + } else { + f = b ^ c ^ d; + k = 0xCA62C1D6; + } + + temp = (leftRotate(a, 5) + f + e + k + bigBlock32.getUint32(j * 4, false)) & 0xffffffff; + e = d; + d = c; + c = leftRotate(b, 30); + b = a; + a = temp; + } + + this._h0 = (this._h0 + a) & 0xffffffff; + this._h1 = (this._h1 + b) & 0xffffffff; + this._h2 = (this._h2 + c) & 0xffffffff; + this._h3 = (this._h3 + d) & 0xffffffff; + this._h4 = (this._h4 + e) & 0xffffffff; + } +} diff --git a/node_modules/@xterm/xterm/src/vs/base/common/iterator.ts b/node_modules/@xterm/xterm/src/vs/base/common/iterator.ts new file mode 100644 index 0000000..c329ed6 --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/common/iterator.ts @@ -0,0 +1,159 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +export namespace Iterable { + + export function is(thing: any): thing is Iterable { + return thing && typeof thing === 'object' && typeof thing[Symbol.iterator] === 'function'; + } + + const _empty: Iterable = Object.freeze([]); + export function empty(): Iterable { + return _empty; + } + + export function* single(element: T): Iterable { + yield element; + } + + export function wrap(iterableOrElement: Iterable | T): Iterable { + if (is(iterableOrElement)) { + return iterableOrElement; + } else { + return single(iterableOrElement); + } + } + + export function from(iterable: Iterable | undefined | null): Iterable { + return iterable || _empty; + } + + export function* reverse(array: Array): Iterable { + for (let i = array.length - 1; i >= 0; i--) { + yield array[i]; + } + } + + export function isEmpty(iterable: Iterable | undefined | null): boolean { + return !iterable || iterable[Symbol.iterator]().next().done === true; + } + + export function first(iterable: Iterable): T | undefined { + return iterable[Symbol.iterator]().next().value; + } + + export function some(iterable: Iterable, predicate: (t: T, i: number) => unknown): boolean { + let i = 0; + for (const element of iterable) { + if (predicate(element, i++)) { + return true; + } + } + return false; + } + + export function find(iterable: Iterable, predicate: (t: T) => t is R): R | undefined; + export function find(iterable: Iterable, predicate: (t: T) => boolean): T | undefined; + export function find(iterable: Iterable, predicate: (t: T) => boolean): T | undefined { + for (const element of iterable) { + if (predicate(element)) { + return element; + } + } + + return undefined; + } + + export function filter(iterable: Iterable, predicate: (t: T) => t is R): Iterable; + export function filter(iterable: Iterable, predicate: (t: T) => boolean): Iterable; + export function* filter(iterable: Iterable, predicate: (t: T) => boolean): Iterable { + for (const element of iterable) { + if (predicate(element)) { + yield element; + } + } + } + + export function* map(iterable: Iterable, fn: (t: T, index: number) => R): Iterable { + let index = 0; + for (const element of iterable) { + yield fn(element, index++); + } + } + + export function* flatMap(iterable: Iterable, fn: (t: T, index: number) => Iterable): Iterable { + let index = 0; + for (const element of iterable) { + yield* fn(element, index++); + } + } + + export function* concat(...iterables: Iterable[]): Iterable { + for (const iterable of iterables) { + yield* iterable; + } + } + + export function reduce(iterable: Iterable, reducer: (previousValue: R, currentValue: T) => R, initialValue: R): R { + let value = initialValue; + for (const element of iterable) { + value = reducer(value, element); + } + return value; + } + + /** + * Returns an iterable slice of the array, with the same semantics as `array.slice()`. + */ + export function* slice(arr: ReadonlyArray, from: number, to = arr.length): Iterable { + if (from < 0) { + from += arr.length; + } + + if (to < 0) { + to += arr.length; + } else if (to > arr.length) { + to = arr.length; + } + + for (; from < to; from++) { + yield arr[from]; + } + } + + /** + * Consumes `atMost` elements from iterable and returns the consumed elements, + * and an iterable for the rest of the elements. + */ + export function consume(iterable: Iterable, atMost: number = Number.POSITIVE_INFINITY): [T[], Iterable] { + const consumed: T[] = []; + + if (atMost === 0) { + return [consumed, iterable]; + } + + const iterator = iterable[Symbol.iterator](); + + for (let i = 0; i < atMost; i++) { + const next = iterator.next(); + + if (next.done) { + return [consumed, Iterable.empty()]; + } + + consumed.push(next.value); + } + + return [consumed, { [Symbol.iterator]() { return iterator; } }]; + } + + export async function asyncToArray(iterable: AsyncIterable): Promise { + const result: T[] = []; + for await (const item of iterable) { + result.push(item); + } + return Promise.resolve(result); + } +} diff --git a/node_modules/@xterm/xterm/src/vs/base/common/keyCodes.ts b/node_modules/@xterm/xterm/src/vs/base/common/keyCodes.ts new file mode 100644 index 0000000..1d336df --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/common/keyCodes.ts @@ -0,0 +1,526 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +/** + * Virtual Key Codes, the value does not hold any inherent meaning. + * Inspired somewhat from https://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx + * But these are "more general", as they should work across browsers & OS`s. + */ +export const enum KeyCode { + DependsOnKbLayout = -1, + + /** + * Placed first to cover the 0 value of the enum. + */ + Unknown = 0, + + Backspace, + Tab, + Enter, + Shift, + Ctrl, + Alt, + PauseBreak, + CapsLock, + Escape, + Space, + PageUp, + PageDown, + End, + Home, + LeftArrow, + UpArrow, + RightArrow, + DownArrow, + Insert, + Delete, + + Digit0, + Digit1, + Digit2, + Digit3, + Digit4, + Digit5, + Digit6, + Digit7, + Digit8, + Digit9, + + KeyA, + KeyB, + KeyC, + KeyD, + KeyE, + KeyF, + KeyG, + KeyH, + KeyI, + KeyJ, + KeyK, + KeyL, + KeyM, + KeyN, + KeyO, + KeyP, + KeyQ, + KeyR, + KeyS, + KeyT, + KeyU, + KeyV, + KeyW, + KeyX, + KeyY, + KeyZ, + + Meta, + ContextMenu, + + F1, + F2, + F3, + F4, + F5, + F6, + F7, + F8, + F9, + F10, + F11, + F12, + F13, + F14, + F15, + F16, + F17, + F18, + F19, + F20, + F21, + F22, + F23, + F24, + + NumLock, + ScrollLock, + + /** + * Used for miscellaneous characters; it can vary by keyboard. + * For the US standard keyboard, the ';:' key + */ + Semicolon, + /** + * For any country/region, the '+' key + * For the US standard keyboard, the '=+' key + */ + Equal, + /** + * For any country/region, the ',' key + * For the US standard keyboard, the ',<' key + */ + Comma, + /** + * For any country/region, the '-' key + * For the US standard keyboard, the '-_' key + */ + Minus, + /** + * For any country/region, the '.' key + * For the US standard keyboard, the '.>' key + */ + Period, + /** + * Used for miscellaneous characters; it can vary by keyboard. + * For the US standard keyboard, the '/?' key + */ + Slash, + /** + * Used for miscellaneous characters; it can vary by keyboard. + * For the US standard keyboard, the '`~' key + */ + Backquote, + /** + * Used for miscellaneous characters; it can vary by keyboard. + * For the US standard keyboard, the '[{' key + */ + BracketLeft, + /** + * Used for miscellaneous characters; it can vary by keyboard. + * For the US standard keyboard, the '\|' key + */ + Backslash, + /** + * Used for miscellaneous characters; it can vary by keyboard. + * For the US standard keyboard, the ']}' key + */ + BracketRight, + /** + * Used for miscellaneous characters; it can vary by keyboard. + * For the US standard keyboard, the ''"' key + */ + Quote, + /** + * Used for miscellaneous characters; it can vary by keyboard. + */ + OEM_8, + /** + * Either the angle bracket key or the backslash key on the RT 102-key keyboard. + */ + IntlBackslash, + + Numpad0, // VK_NUMPAD0, 0x60, Numeric keypad 0 key + Numpad1, // VK_NUMPAD1, 0x61, Numeric keypad 1 key + Numpad2, // VK_NUMPAD2, 0x62, Numeric keypad 2 key + Numpad3, // VK_NUMPAD3, 0x63, Numeric keypad 3 key + Numpad4, // VK_NUMPAD4, 0x64, Numeric keypad 4 key + Numpad5, // VK_NUMPAD5, 0x65, Numeric keypad 5 key + Numpad6, // VK_NUMPAD6, 0x66, Numeric keypad 6 key + Numpad7, // VK_NUMPAD7, 0x67, Numeric keypad 7 key + Numpad8, // VK_NUMPAD8, 0x68, Numeric keypad 8 key + Numpad9, // VK_NUMPAD9, 0x69, Numeric keypad 9 key + + NumpadMultiply, // VK_MULTIPLY, 0x6A, Multiply key + NumpadAdd, // VK_ADD, 0x6B, Add key + NUMPAD_SEPARATOR, // VK_SEPARATOR, 0x6C, Separator key + NumpadSubtract, // VK_SUBTRACT, 0x6D, Subtract key + NumpadDecimal, // VK_DECIMAL, 0x6E, Decimal key + NumpadDivide, // VK_DIVIDE, 0x6F, + + /** + * Cover all key codes when IME is processing input. + */ + KEY_IN_COMPOSITION, + + ABNT_C1, // Brazilian (ABNT) Keyboard + ABNT_C2, // Brazilian (ABNT) Keyboard + + AudioVolumeMute, + AudioVolumeUp, + AudioVolumeDown, + + BrowserSearch, + BrowserHome, + BrowserBack, + BrowserForward, + + MediaTrackNext, + MediaTrackPrevious, + MediaStop, + MediaPlayPause, + LaunchMediaPlayer, + LaunchMail, + LaunchApp2, + + /** + * VK_CLEAR, 0x0C, CLEAR key + */ + Clear, + + /** + * Placed last to cover the length of the enum. + * Please do not depend on this value! + */ + MAX_VALUE +} + +/** + * keyboardEvent.code + */ +export const enum ScanCode { + DependsOnKbLayout = -1, + None, + Hyper, + Super, + Fn, + FnLock, + Suspend, + Resume, + Turbo, + Sleep, + WakeUp, + KeyA, + KeyB, + KeyC, + KeyD, + KeyE, + KeyF, + KeyG, + KeyH, + KeyI, + KeyJ, + KeyK, + KeyL, + KeyM, + KeyN, + KeyO, + KeyP, + KeyQ, + KeyR, + KeyS, + KeyT, + KeyU, + KeyV, + KeyW, + KeyX, + KeyY, + KeyZ, + Digit1, + Digit2, + Digit3, + Digit4, + Digit5, + Digit6, + Digit7, + Digit8, + Digit9, + Digit0, + Enter, + Escape, + Backspace, + Tab, + Space, + Minus, + Equal, + BracketLeft, + BracketRight, + Backslash, + IntlHash, + Semicolon, + Quote, + Backquote, + Comma, + Period, + Slash, + CapsLock, + F1, + F2, + F3, + F4, + F5, + F6, + F7, + F8, + F9, + F10, + F11, + F12, + PrintScreen, + ScrollLock, + Pause, + Insert, + Home, + PageUp, + Delete, + End, + PageDown, + ArrowRight, + ArrowLeft, + ArrowDown, + ArrowUp, + NumLock, + NumpadDivide, + NumpadMultiply, + NumpadSubtract, + NumpadAdd, + NumpadEnter, + Numpad1, + Numpad2, + Numpad3, + Numpad4, + Numpad5, + Numpad6, + Numpad7, + Numpad8, + Numpad9, + Numpad0, + NumpadDecimal, + IntlBackslash, + ContextMenu, + Power, + NumpadEqual, + F13, + F14, + F15, + F16, + F17, + F18, + F19, + F20, + F21, + F22, + F23, + F24, + Open, + Help, + Select, + Again, + Undo, + Cut, + Copy, + Paste, + Find, + AudioVolumeMute, + AudioVolumeUp, + AudioVolumeDown, + NumpadComma, + IntlRo, + KanaMode, + IntlYen, + Convert, + NonConvert, + Lang1, + Lang2, + Lang3, + Lang4, + Lang5, + Abort, + Props, + NumpadParenLeft, + NumpadParenRight, + NumpadBackspace, + NumpadMemoryStore, + NumpadMemoryRecall, + NumpadMemoryClear, + NumpadMemoryAdd, + NumpadMemorySubtract, + NumpadClear, + NumpadClearEntry, + ControlLeft, + ShiftLeft, + AltLeft, + MetaLeft, + ControlRight, + ShiftRight, + AltRight, + MetaRight, + BrightnessUp, + BrightnessDown, + MediaPlay, + MediaRecord, + MediaFastForward, + MediaRewind, + MediaTrackNext, + MediaTrackPrevious, + MediaStop, + Eject, + MediaPlayPause, + MediaSelect, + LaunchMail, + LaunchApp2, + LaunchApp1, + SelectTask, + LaunchScreenSaver, + BrowserSearch, + BrowserHome, + BrowserBack, + BrowserForward, + BrowserStop, + BrowserRefresh, + BrowserFavorites, + ZoomToggle, + MailReply, + MailForward, + MailSend, + + MAX_VALUE +} + +class KeyCodeStrMap { + + public _keyCodeToStr: string[]; + public _strToKeyCode: { [str: string]: KeyCode }; + + constructor() { + this._keyCodeToStr = []; + this._strToKeyCode = Object.create(null); + } + + define(keyCode: KeyCode, str: string): void { + this._keyCodeToStr[keyCode] = str; + this._strToKeyCode[str.toLowerCase()] = keyCode; + } + + keyCodeToStr(keyCode: KeyCode): string { + return this._keyCodeToStr[keyCode]; + } + + strToKeyCode(str: string): KeyCode { + return this._strToKeyCode[str.toLowerCase()] || KeyCode.Unknown; + } +} + +const uiMap = new KeyCodeStrMap(); +const userSettingsUSMap = new KeyCodeStrMap(); +const userSettingsGeneralMap = new KeyCodeStrMap(); +export const EVENT_KEY_CODE_MAP: { [keyCode: number]: KeyCode } = new Array(230); +export const NATIVE_WINDOWS_KEY_CODE_TO_KEY_CODE: { [nativeKeyCode: string]: KeyCode } = {}; +const scanCodeIntToStr: string[] = []; +const scanCodeStrToInt: { [code: string]: number } = Object.create(null); +const scanCodeLowerCaseStrToInt: { [code: string]: number } = Object.create(null); + +export const ScanCodeUtils = { + lowerCaseToEnum: (scanCode: string) => scanCodeLowerCaseStrToInt[scanCode] || ScanCode.None, + toEnum: (scanCode: string) => scanCodeStrToInt[scanCode] || ScanCode.None, + toString: (scanCode: ScanCode) => scanCodeIntToStr[scanCode] || 'None' +}; + + +export namespace KeyCodeUtils { + export function toString(keyCode: KeyCode): string { + return uiMap.keyCodeToStr(keyCode); + } + export function fromString(key: string): KeyCode { + return uiMap.strToKeyCode(key); + } + + export function toUserSettingsUS(keyCode: KeyCode): string { + return userSettingsUSMap.keyCodeToStr(keyCode); + } + export function toUserSettingsGeneral(keyCode: KeyCode): string { + return userSettingsGeneralMap.keyCodeToStr(keyCode); + } + export function fromUserSettings(key: string): KeyCode { + return userSettingsUSMap.strToKeyCode(key) || userSettingsGeneralMap.strToKeyCode(key); + } + + export function toElectronAccelerator(keyCode: KeyCode): string | null { + if (keyCode >= KeyCode.Numpad0 && keyCode <= KeyCode.NumpadDivide) { + // [Electron Accelerators] Electron is able to parse numpad keys, but unfortunately it + // renders them just as regular keys in menus. For example, num0 is rendered as "0", + // numdiv is rendered as "/", numsub is rendered as "-". + // + // This can lead to incredible confusion, as it makes numpad based keybindings indistinguishable + // from keybindings based on regular keys. + // + // We therefore need to fall back to custom rendering for numpad keys. + return null; + } + + switch (keyCode) { + case KeyCode.UpArrow: + return 'Up'; + case KeyCode.DownArrow: + return 'Down'; + case KeyCode.LeftArrow: + return 'Left'; + case KeyCode.RightArrow: + return 'Right'; + } + + return uiMap.keyCodeToStr(keyCode); + } +} + +export const enum KeyMod { + CtrlCmd = (1 << 11) >>> 0, + Shift = (1 << 10) >>> 0, + Alt = (1 << 9) >>> 0, + WinCtrl = (1 << 8) >>> 0, +} + +export function KeyChord(firstPart: number, secondPart: number): number { + const chordPart = ((secondPart & 0x0000FFFF) << 16) >>> 0; + return (firstPart | chordPart) >>> 0; +} diff --git a/node_modules/@xterm/xterm/src/vs/base/common/keybindings.ts b/node_modules/@xterm/xterm/src/vs/base/common/keybindings.ts new file mode 100644 index 0000000..3752562 --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/common/keybindings.ts @@ -0,0 +1,284 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { illegalArgument } from 'vs/base/common/errors'; +import { KeyCode, ScanCode } from 'vs/base/common/keyCodes'; +import { OperatingSystem } from 'vs/base/common/platform'; + +/** + * Binary encoding strategy: + * ``` + * 1111 11 + * 5432 1098 7654 3210 + * ---- CSAW KKKK KKKK + * C = bit 11 = ctrlCmd flag + * S = bit 10 = shift flag + * A = bit 9 = alt flag + * W = bit 8 = winCtrl flag + * K = bits 0-7 = key code + * ``` + */ +const enum BinaryKeybindingsMask { + CtrlCmd = (1 << 11) >>> 0, + Shift = (1 << 10) >>> 0, + Alt = (1 << 9) >>> 0, + WinCtrl = (1 << 8) >>> 0, + KeyCode = 0x000000FF +} + +export function decodeKeybinding(keybinding: number | number[], OS: OperatingSystem): Keybinding | null { + if (typeof keybinding === 'number') { + if (keybinding === 0) { + return null; + } + const firstChord = (keybinding & 0x0000FFFF) >>> 0; + const secondChord = (keybinding & 0xFFFF0000) >>> 16; + if (secondChord !== 0) { + return new Keybinding([ + createSimpleKeybinding(firstChord, OS), + createSimpleKeybinding(secondChord, OS) + ]); + } + return new Keybinding([createSimpleKeybinding(firstChord, OS)]); + } else { + const chords = []; + for (let i = 0; i < keybinding.length; i++) { + chords.push(createSimpleKeybinding(keybinding[i], OS)); + } + return new Keybinding(chords); + } +} + +export function createSimpleKeybinding(keybinding: number, OS: OperatingSystem): KeyCodeChord { + + const ctrlCmd = (keybinding & BinaryKeybindingsMask.CtrlCmd ? true : false); + const winCtrl = (keybinding & BinaryKeybindingsMask.WinCtrl ? true : false); + + const ctrlKey = (OS === OperatingSystem.Macintosh ? winCtrl : ctrlCmd); + const shiftKey = (keybinding & BinaryKeybindingsMask.Shift ? true : false); + const altKey = (keybinding & BinaryKeybindingsMask.Alt ? true : false); + const metaKey = (OS === OperatingSystem.Macintosh ? ctrlCmd : winCtrl); + const keyCode = (keybinding & BinaryKeybindingsMask.KeyCode); + + return new KeyCodeChord(ctrlKey, shiftKey, altKey, metaKey, keyCode); +} + +export interface Modifiers { + readonly ctrlKey: boolean; + readonly shiftKey: boolean; + readonly altKey: boolean; + readonly metaKey: boolean; +} + +/** + * Represents a chord which uses the `keyCode` field of keyboard events. + * A chord is a combination of keys pressed simultaneously. + */ +export class KeyCodeChord implements Modifiers { + + constructor( + public readonly ctrlKey: boolean, + public readonly shiftKey: boolean, + public readonly altKey: boolean, + public readonly metaKey: boolean, + public readonly keyCode: KeyCode + ) { } + + public equals(other: Chord): boolean { + return ( + other instanceof KeyCodeChord + && this.ctrlKey === other.ctrlKey + && this.shiftKey === other.shiftKey + && this.altKey === other.altKey + && this.metaKey === other.metaKey + && this.keyCode === other.keyCode + ); + } + + public getHashCode(): string { + const ctrl = this.ctrlKey ? '1' : '0'; + const shift = this.shiftKey ? '1' : '0'; + const alt = this.altKey ? '1' : '0'; + const meta = this.metaKey ? '1' : '0'; + return `K${ctrl}${shift}${alt}${meta}${this.keyCode}`; + } + + public isModifierKey(): boolean { + return ( + this.keyCode === KeyCode.Unknown + || this.keyCode === KeyCode.Ctrl + || this.keyCode === KeyCode.Meta + || this.keyCode === KeyCode.Alt + || this.keyCode === KeyCode.Shift + ); + } + + public toKeybinding(): Keybinding { + return new Keybinding([this]); + } + + /** + * Does this keybinding refer to the key code of a modifier and it also has the modifier flag? + */ + public isDuplicateModifierCase(): boolean { + return ( + (this.ctrlKey && this.keyCode === KeyCode.Ctrl) + || (this.shiftKey && this.keyCode === KeyCode.Shift) + || (this.altKey && this.keyCode === KeyCode.Alt) + || (this.metaKey && this.keyCode === KeyCode.Meta) + ); + } +} + +/** + * Represents a chord which uses the `code` field of keyboard events. + * A chord is a combination of keys pressed simultaneously. + */ +export class ScanCodeChord implements Modifiers { + + constructor( + public readonly ctrlKey: boolean, + public readonly shiftKey: boolean, + public readonly altKey: boolean, + public readonly metaKey: boolean, + public readonly scanCode: ScanCode + ) { } + + public equals(other: Chord): boolean { + return ( + other instanceof ScanCodeChord + && this.ctrlKey === other.ctrlKey + && this.shiftKey === other.shiftKey + && this.altKey === other.altKey + && this.metaKey === other.metaKey + && this.scanCode === other.scanCode + ); + } + + public getHashCode(): string { + const ctrl = this.ctrlKey ? '1' : '0'; + const shift = this.shiftKey ? '1' : '0'; + const alt = this.altKey ? '1' : '0'; + const meta = this.metaKey ? '1' : '0'; + return `S${ctrl}${shift}${alt}${meta}${this.scanCode}`; + } + + /** + * Does this keybinding refer to the key code of a modifier and it also has the modifier flag? + */ + public isDuplicateModifierCase(): boolean { + return ( + (this.ctrlKey && (this.scanCode === ScanCode.ControlLeft || this.scanCode === ScanCode.ControlRight)) + || (this.shiftKey && (this.scanCode === ScanCode.ShiftLeft || this.scanCode === ScanCode.ShiftRight)) + || (this.altKey && (this.scanCode === ScanCode.AltLeft || this.scanCode === ScanCode.AltRight)) + || (this.metaKey && (this.scanCode === ScanCode.MetaLeft || this.scanCode === ScanCode.MetaRight)) + ); + } +} + +export type Chord = KeyCodeChord | ScanCodeChord; + +/** + * A keybinding is a sequence of chords. + */ +export class Keybinding { + + public readonly chords: Chord[]; + + constructor(chords: Chord[]) { + if (chords.length === 0) { + throw illegalArgument(`chords`); + } + this.chords = chords; + } + + public getHashCode(): string { + let result = ''; + for (let i = 0, len = this.chords.length; i < len; i++) { + if (i !== 0) { + result += ';'; + } + result += this.chords[i].getHashCode(); + } + return result; + } + + public equals(other: Keybinding | null): boolean { + if (other === null) { + return false; + } + if (this.chords.length !== other.chords.length) { + return false; + } + for (let i = 0; i < this.chords.length; i++) { + if (!this.chords[i].equals(other.chords[i])) { + return false; + } + } + return true; + } +} + +export class ResolvedChord { + constructor( + public readonly ctrlKey: boolean, + public readonly shiftKey: boolean, + public readonly altKey: boolean, + public readonly metaKey: boolean, + public readonly keyLabel: string | null, + public readonly keyAriaLabel: string | null + ) { } +} + +export type SingleModifierChord = 'ctrl' | 'shift' | 'alt' | 'meta'; + +/** + * A resolved keybinding. Consists of one or multiple chords. + */ +export abstract class ResolvedKeybinding { + /** + * This prints the binding in a format suitable for displaying in the UI. + */ + public abstract getLabel(): string | null; + /** + * This prints the binding in a format suitable for ARIA. + */ + public abstract getAriaLabel(): string | null; + /** + * This prints the binding in a format suitable for electron's accelerators. + * See https://github.com/electron/electron/blob/master/docs/api/accelerator.md + */ + public abstract getElectronAccelerator(): string | null; + /** + * This prints the binding in a format suitable for user settings. + */ + public abstract getUserSettingsLabel(): string | null; + /** + * Is the user settings label reflecting the label? + */ + public abstract isWYSIWYG(): boolean; + /** + * Does the keybinding consist of more than one chord? + */ + public abstract hasMultipleChords(): boolean; + /** + * Returns the chords that comprise of the keybinding. + */ + public abstract getChords(): ResolvedChord[]; + /** + * Returns the chords as strings useful for dispatching. + * Returns null for modifier only chords. + * @example keybinding "Shift" -> null + * @example keybinding ("D" with shift == true) -> "shift+D" + */ + public abstract getDispatchChords(): (string | null)[]; + /** + * Returns the modifier only chords as strings useful for dispatching. + * Returns null for chords that contain more than one modifier or a regular key. + * @example keybinding "Shift" -> "shift" + * @example keybinding ("D" with shift == true") -> null + */ + public abstract getSingleModifierDispatchChords(): (SingleModifierChord | null)[]; +} diff --git a/node_modules/@xterm/xterm/src/vs/base/common/lazy.ts b/node_modules/@xterm/xterm/src/vs/base/common/lazy.ts new file mode 100644 index 0000000..7114ece --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/common/lazy.ts @@ -0,0 +1,47 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +export class Lazy { + + private _didRun: boolean = false; + private _value?: T; + private _error: Error | undefined; + + constructor( + private readonly executor: () => T, + ) { } + + /** + * True if the lazy value has been resolved. + */ + get hasValue() { return this._didRun; } + + /** + * Get the wrapped value. + * + * This will force evaluation of the lazy value if it has not been resolved yet. Lazy values are only + * resolved once. `getValue` will re-throw exceptions that are hit while resolving the value + */ + get value(): T { + if (!this._didRun) { + try { + this._value = this.executor(); + } catch (err) { + this._error = err; + } finally { + this._didRun = true; + } + } + if (this._error) { + throw this._error; + } + return this._value!; + } + + /** + * Get the wrapped value without forcing evaluation. + */ + get rawValue(): T | undefined { return this._value; } +} diff --git a/node_modules/@xterm/xterm/src/vs/base/common/lifecycle.ts b/node_modules/@xterm/xterm/src/vs/base/common/lifecycle.ts new file mode 100644 index 0000000..568a012 --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/common/lifecycle.ts @@ -0,0 +1,801 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { compareBy, numberComparator } from 'vs/base/common/arrays'; +import { groupBy } from 'vs/base/common/collections'; +import { SetMap } from './map'; +import { createSingleCallFunction } from 'vs/base/common/functional'; +import { Iterable } from 'vs/base/common/iterator'; + +// #region Disposable Tracking + +/** + * Enables logging of potentially leaked disposables. + * + * A disposable is considered leaked if it is not disposed or not registered as the child of + * another disposable. This tracking is very simple an only works for classes that either + * extend Disposable or use a DisposableStore. This means there are a lot of false positives. + */ +const TRACK_DISPOSABLES = false; +let disposableTracker: IDisposableTracker | null = null; + +export interface IDisposableTracker { + /** + * Is called on construction of a disposable. + */ + trackDisposable(disposable: IDisposable): void; + + /** + * Is called when a disposable is registered as child of another disposable (e.g. {@link DisposableStore}). + * If parent is `null`, the disposable is removed from its former parent. + */ + setParent(child: IDisposable, parent: IDisposable | null): void; + + /** + * Is called after a disposable is disposed. + */ + markAsDisposed(disposable: IDisposable): void; + + /** + * Indicates that the given object is a singleton which does not need to be disposed. + */ + markAsSingleton(disposable: IDisposable): void; +} + +export interface DisposableInfo { + value: IDisposable; + source: string | null; + parent: IDisposable | null; + isSingleton: boolean; + idx: number; +} + +export class DisposableTracker implements IDisposableTracker { + private static idx = 0; + + private readonly livingDisposables = new Map(); + + private getDisposableData(d: IDisposable): DisposableInfo { + let val = this.livingDisposables.get(d); + if (!val) { + val = { parent: null, source: null, isSingleton: false, value: d, idx: DisposableTracker.idx++ }; + this.livingDisposables.set(d, val); + } + return val; + } + + trackDisposable(d: IDisposable): void { + const data = this.getDisposableData(d); + if (!data.source) { + data.source = + new Error().stack!; + } + } + + setParent(child: IDisposable, parent: IDisposable | null): void { + const data = this.getDisposableData(child); + data.parent = parent; + } + + markAsDisposed(x: IDisposable): void { + this.livingDisposables.delete(x); + } + + markAsSingleton(disposable: IDisposable): void { + this.getDisposableData(disposable).isSingleton = true; + } + + private getRootParent(data: DisposableInfo, cache: Map): DisposableInfo { + const cacheValue = cache.get(data); + if (cacheValue) { + return cacheValue; + } + + const result = data.parent ? this.getRootParent(this.getDisposableData(data.parent), cache) : data; + cache.set(data, result); + return result; + } + + getTrackedDisposables(): IDisposable[] { + const rootParentCache = new Map(); + + const leaking = [...this.livingDisposables.entries()] + .filter(([, v]) => v.source !== null && !this.getRootParent(v, rootParentCache).isSingleton) + .flatMap(([k]) => k); + + return leaking; + } + + computeLeakingDisposables(maxReported = 10, preComputedLeaks?: DisposableInfo[]): { leaks: DisposableInfo[]; details: string } | undefined { + let uncoveredLeakingObjs: DisposableInfo[] | undefined; + if (preComputedLeaks) { + uncoveredLeakingObjs = preComputedLeaks; + } else { + const rootParentCache = new Map(); + + const leakingObjects = [...this.livingDisposables.values()] + .filter((info) => info.source !== null && !this.getRootParent(info, rootParentCache).isSingleton); + + if (leakingObjects.length === 0) { + return; + } + const leakingObjsSet = new Set(leakingObjects.map(o => o.value)); + + // Remove all objects that are a child of other leaking objects. Assumes there are no cycles. + uncoveredLeakingObjs = leakingObjects.filter(l => { + return !(l.parent && leakingObjsSet.has(l.parent)); + }); + + if (uncoveredLeakingObjs.length === 0) { + throw new Error('There are cyclic diposable chains!'); + } + } + + if (!uncoveredLeakingObjs) { + return undefined; + } + + function getStackTracePath(leaking: DisposableInfo): string[] { + function removePrefix(array: string[], linesToRemove: (string | RegExp)[]) { + while (array.length > 0 && linesToRemove.some(regexp => typeof regexp === 'string' ? regexp === array[0] : array[0].match(regexp))) { + array.shift(); + } + } + + const lines = leaking.source!.split('\n').map(p => p.trim().replace('at ', '')).filter(l => l !== ''); + removePrefix(lines, ['Error', /^trackDisposable \(.*\)$/, /^DisposableTracker.trackDisposable \(.*\)$/]); + return lines.reverse(); + } + + const stackTraceStarts = new SetMap(); + for (const leaking of uncoveredLeakingObjs) { + const stackTracePath = getStackTracePath(leaking); + for (let i = 0; i <= stackTracePath.length; i++) { + stackTraceStarts.add(stackTracePath.slice(0, i).join('\n'), leaking); + } + } + + // Put earlier leaks first + uncoveredLeakingObjs.sort(compareBy(l => l.idx, numberComparator)); + + let message = ''; + + let i = 0; + for (const leaking of uncoveredLeakingObjs.slice(0, maxReported)) { + i++; + const stackTracePath = getStackTracePath(leaking); + const stackTraceFormattedLines = []; + + for (let i = 0; i < stackTracePath.length; i++) { + let line = stackTracePath[i]; + const starts = stackTraceStarts.get(stackTracePath.slice(0, i + 1).join('\n')); + line = `(shared with ${starts.size}/${uncoveredLeakingObjs.length} leaks) at ${line}`; + + const prevStarts = stackTraceStarts.get(stackTracePath.slice(0, i).join('\n')); + const continuations = groupBy([...prevStarts].map(d => getStackTracePath(d)[i]), v => v); + delete continuations[stackTracePath[i]]; + for (const [cont, set] of Object.entries(continuations)) { + stackTraceFormattedLines.unshift(` - stacktraces of ${set.length} other leaks continue with ${cont}`); + } + + stackTraceFormattedLines.unshift(line); + } + + message += `\n\n\n==================== Leaking disposable ${i}/${uncoveredLeakingObjs.length}: ${leaking.value.constructor.name} ====================\n${stackTraceFormattedLines.join('\n')}\n============================================================\n\n`; + } + + if (uncoveredLeakingObjs.length > maxReported) { + message += `\n\n\n... and ${uncoveredLeakingObjs.length - maxReported} more leaking disposables\n\n`; + } + + return { leaks: uncoveredLeakingObjs, details: message }; + } +} + +export function setDisposableTracker(tracker: IDisposableTracker | null): void { + disposableTracker = tracker; +} + +if (TRACK_DISPOSABLES) { + const __is_disposable_tracked__ = '__is_disposable_tracked__'; + setDisposableTracker(new class implements IDisposableTracker { + trackDisposable(x: IDisposable): void { + const stack = new Error('Potentially leaked disposable').stack!; + setTimeout(() => { + if (!(x as any)[__is_disposable_tracked__]) { + console.log(stack); + } + }, 3000); + } + + setParent(child: IDisposable, parent: IDisposable | null): void { + if (child && child !== Disposable.None) { + try { + (child as any)[__is_disposable_tracked__] = true; + } catch { + // noop + } + } + } + + markAsDisposed(disposable: IDisposable): void { + if (disposable && disposable !== Disposable.None) { + try { + (disposable as any)[__is_disposable_tracked__] = true; + } catch { + // noop + } + } + } + markAsSingleton(disposable: IDisposable): void { } + }); +} + +export function trackDisposable(x: T): T { + disposableTracker?.trackDisposable(x); + return x; +} + +export function markAsDisposed(disposable: IDisposable): void { + disposableTracker?.markAsDisposed(disposable); +} + +function setParentOfDisposable(child: IDisposable, parent: IDisposable | null): void { + disposableTracker?.setParent(child, parent); +} + +function setParentOfDisposables(children: IDisposable[], parent: IDisposable | null): void { + if (!disposableTracker) { + return; + } + for (const child of children) { + disposableTracker.setParent(child, parent); + } +} + +/** + * Indicates that the given object is a singleton which does not need to be disposed. +*/ +export function markAsSingleton(singleton: T): T { + disposableTracker?.markAsSingleton(singleton); + return singleton; +} + +// #endregion + +/** + * An object that performs a cleanup operation when `.dispose()` is called. + * + * Some examples of how disposables are used: + * + * - An event listener that removes itself when `.dispose()` is called. + * - A resource such as a file system watcher that cleans up the resource when `.dispose()` is called. + * - The return value from registering a provider. When `.dispose()` is called, the provider is unregistered. + */ +export interface IDisposable { + dispose(): void; +} + +/** + * Check if `thing` is {@link IDisposable disposable}. + */ +export function isDisposable(thing: E): thing is E & IDisposable { + return typeof thing === 'object' && thing !== null && typeof (thing).dispose === 'function' && (thing).dispose.length === 0; +} + +/** + * Disposes of the value(s) passed in. + */ +export function dispose(disposable: T): T; +export function dispose(disposable: T | undefined): T | undefined; +export function dispose = Iterable>(disposables: A): A; +export function dispose(disposables: Array): Array; +export function dispose(disposables: ReadonlyArray): ReadonlyArray; +export function dispose(arg: T | Iterable | undefined): any { + if (Iterable.is(arg)) { + const errors: any[] = []; + + for (const d of arg) { + if (d) { + try { + d.dispose(); + } catch (e) { + errors.push(e); + } + } + } + + if (errors.length === 1) { + throw errors[0]; + } else if (errors.length > 1) { + throw new AggregateError(errors, 'Encountered errors while disposing of store'); + } + + return Array.isArray(arg) ? [] : arg; + } else if (arg) { + arg.dispose(); + return arg; + } +} + +export function disposeIfDisposable(disposables: Array): Array { + for (const d of disposables) { + if (isDisposable(d)) { + d.dispose(); + } + } + return []; +} + +/** + * Combine multiple disposable values into a single {@link IDisposable}. + */ +export function combinedDisposable(...disposables: IDisposable[]): IDisposable { + const parent = toDisposable(() => dispose(disposables)); + setParentOfDisposables(disposables, parent); + return parent; +} + +/** + * Turn a function that implements dispose into an {@link IDisposable}. + * + * @param fn Clean up function, guaranteed to be called only **once**. + */ +export function toDisposable(fn: () => void): IDisposable { + const self = trackDisposable({ + dispose: createSingleCallFunction(() => { + markAsDisposed(self); + fn(); + }) + }); + return self; +} + +/** + * Manages a collection of disposable values. + * + * This is the preferred way to manage multiple disposables. A `DisposableStore` is safer to work with than an + * `IDisposable[]` as it considers edge cases, such as registering the same value multiple times or adding an item to a + * store that has already been disposed of. + */ +export class DisposableStore implements IDisposable { + + static DISABLE_DISPOSED_WARNING = false; + + private readonly _toDispose = new Set(); + private _isDisposed = false; + + constructor() { + trackDisposable(this); + } + + /** + * Dispose of all registered disposables and mark this object as disposed. + * + * Any future disposables added to this object will be disposed of on `add`. + */ + public dispose(): void { + if (this._isDisposed) { + return; + } + + markAsDisposed(this); + this._isDisposed = true; + this.clear(); + } + + /** + * @return `true` if this object has been disposed of. + */ + public get isDisposed(): boolean { + return this._isDisposed; + } + + /** + * Dispose of all registered disposables but do not mark this object as disposed. + */ + public clear(): void { + if (this._toDispose.size === 0) { + return; + } + + try { + dispose(this._toDispose); + } finally { + this._toDispose.clear(); + } + } + + /** + * Add a new {@link IDisposable disposable} to the collection. + */ + public add(o: T): T { + if (!o) { + return o; + } + if ((o as unknown as DisposableStore) === this) { + throw new Error('Cannot register a disposable on itself!'); + } + + setParentOfDisposable(o, this); + if (this._isDisposed) { + if (!DisposableStore.DISABLE_DISPOSED_WARNING) { + console.warn(new Error('Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!').stack); + } + } else { + this._toDispose.add(o); + } + + return o; + } + + /** + * Deletes a disposable from store and disposes of it. This will not throw or warn and proceed to dispose the + * disposable even when the disposable is not part in the store. + */ + public delete(o: T): void { + if (!o) { + return; + } + if ((o as unknown as DisposableStore) === this) { + throw new Error('Cannot dispose a disposable on itself!'); + } + this._toDispose.delete(o); + o.dispose(); + } + + /** + * Deletes the value from the store, but does not dispose it. + */ + public deleteAndLeak(o: T): void { + if (!o) { + return; + } + if (this._toDispose.has(o)) { + this._toDispose.delete(o); + setParentOfDisposable(o, null); + } + } +} + +/** + * Abstract base class for a {@link IDisposable disposable} object. + * + * Subclasses can {@linkcode _register} disposables that will be automatically cleaned up when this object is disposed of. + */ +export abstract class Disposable implements IDisposable { + + /** + * A disposable that does nothing when it is disposed of. + * + * TODO: This should not be a static property. + */ + static readonly None = Object.freeze({ dispose() { } }); + + protected readonly _store = new DisposableStore(); + + constructor() { + trackDisposable(this); + setParentOfDisposable(this._store, this); + } + + public dispose(): void { + markAsDisposed(this); + + this._store.dispose(); + } + + /** + * Adds `o` to the collection of disposables managed by this object. + */ + protected _register(o: T): T { + if ((o as unknown as Disposable) === this) { + throw new Error('Cannot register a disposable on itself!'); + } + return this._store.add(o); + } +} + +/** + * Manages the lifecycle of a disposable value that may be changed. + * + * This ensures that when the disposable value is changed, the previously held disposable is disposed of. You can + * also register a `MutableDisposable` on a `Disposable` to ensure it is automatically cleaned up. + */ +export class MutableDisposable implements IDisposable { + private _value?: T; + private _isDisposed = false; + + constructor() { + trackDisposable(this); + } + + get value(): T | undefined { + return this._isDisposed ? undefined : this._value; + } + + set value(value: T | undefined) { + if (this._isDisposed || value === this._value) { + return; + } + + this._value?.dispose(); + if (value) { + setParentOfDisposable(value, this); + } + this._value = value; + } + + /** + * Resets the stored value and disposed of the previously stored value. + */ + clear(): void { + this.value = undefined; + } + + dispose(): void { + this._isDisposed = true; + markAsDisposed(this); + this._value?.dispose(); + this._value = undefined; + } + + /** + * Clears the value, but does not dispose it. + * The old value is returned. + */ + clearAndLeak(): T | undefined { + const oldValue = this._value; + this._value = undefined; + if (oldValue) { + setParentOfDisposable(oldValue, null); + } + return oldValue; + } +} + +/** + * Manages the lifecycle of a disposable value that may be changed like {@link MutableDisposable}, but the value must + * exist and cannot be undefined. + */ +export class MandatoryMutableDisposable implements IDisposable { + private readonly _disposable = new MutableDisposable(); + private _isDisposed = false; + + constructor(initialValue: T) { + this._disposable.value = initialValue; + } + + get value(): T { + return this._disposable.value!; + } + + set value(value: T) { + if (this._isDisposed || value === this._disposable.value) { + return; + } + this._disposable.value = value; + } + + dispose() { + this._isDisposed = true; + this._disposable.dispose(); + } +} + +export class RefCountedDisposable { + + private _counter: number = 1; + + constructor( + private readonly _disposable: IDisposable, + ) { } + + acquire() { + this._counter++; + return this; + } + + release() { + if (--this._counter === 0) { + this._disposable.dispose(); + } + return this; + } +} + +/** + * A safe disposable can be `unset` so that a leaked reference (listener) + * can be cut-off. + */ +export class SafeDisposable implements IDisposable { + + dispose: () => void = () => { }; + unset: () => void = () => { }; + isset: () => boolean = () => false; + + constructor() { + trackDisposable(this); + } + + set(fn: Function) { + let callback: Function | undefined = fn; + this.unset = () => callback = undefined; + this.isset = () => callback !== undefined; + this.dispose = () => { + if (callback) { + callback(); + callback = undefined; + markAsDisposed(this); + } + }; + return this; + } +} + +export interface IReference extends IDisposable { + readonly object: T; +} + +export abstract class ReferenceCollection { + + private readonly references: Map = new Map(); + + acquire(key: string, ...args: any[]): IReference { + let reference = this.references.get(key); + + if (!reference) { + reference = { counter: 0, object: this.createReferencedObject(key, ...args) }; + this.references.set(key, reference); + } + + const { object } = reference; + const dispose = createSingleCallFunction(() => { + if (--reference.counter === 0) { + this.destroyReferencedObject(key, reference.object); + this.references.delete(key); + } + }); + + reference.counter++; + + return { object, dispose }; + } + + protected abstract createReferencedObject(key: string, ...args: any[]): T; + protected abstract destroyReferencedObject(key: string, object: T): void; +} + +/** + * Unwraps a reference collection of promised values. Makes sure + * references are disposed whenever promises get rejected. + */ +export class AsyncReferenceCollection { + + constructor(private referenceCollection: ReferenceCollection>) { } + + async acquire(key: string, ...args: any[]): Promise> { + const ref = this.referenceCollection.acquire(key, ...args); + + try { + const object = await ref.object; + + return { + object, + dispose: () => ref.dispose() + }; + } catch (error) { + ref.dispose(); + throw error; + } + } +} + +export class ImmortalReference implements IReference { + constructor(public object: T) { } + dispose(): void { /* noop */ } +} + +export function disposeOnReturn(fn: (store: DisposableStore) => void): void { + const store = new DisposableStore(); + try { + fn(store); + } finally { + store.dispose(); + } +} + +/** + * A map the manages the lifecycle of the values that it stores. + */ +export class DisposableMap implements IDisposable { + + private readonly _store = new Map(); + private _isDisposed = false; + + constructor() { + trackDisposable(this); + } + + /** + * Disposes of all stored values and mark this object as disposed. + * + * Trying to use this object after it has been disposed of is an error. + */ + dispose(): void { + markAsDisposed(this); + this._isDisposed = true; + this.clearAndDisposeAll(); + } + + /** + * Disposes of all stored values and clear the map, but DO NOT mark this object as disposed. + */ + clearAndDisposeAll(): void { + if (!this._store.size) { + return; + } + + try { + dispose(this._store.values()); + } finally { + this._store.clear(); + } + } + + has(key: K): boolean { + return this._store.has(key); + } + + get size(): number { + return this._store.size; + } + + get(key: K): V | undefined { + return this._store.get(key); + } + + set(key: K, value: V, skipDisposeOnOverwrite = false): void { + if (this._isDisposed) { + console.warn(new Error('Trying to add a disposable to a DisposableMap that has already been disposed of. The added object will be leaked!').stack); + } + + if (!skipDisposeOnOverwrite) { + this._store.get(key)?.dispose(); + } + + this._store.set(key, value); + } + + /** + * Delete the value stored for `key` from this map and also dispose of it. + */ + deleteAndDispose(key: K): void { + this._store.get(key)?.dispose(); + this._store.delete(key); + } + + /** + * Delete the value stored for `key` from this map but return it. The caller is + * responsible for disposing of the value. + */ + deleteAndLeak(key: K): V | undefined { + const value = this._store.get(key); + this._store.delete(key); + return value; + } + + keys(): IterableIterator { + return this._store.keys(); + } + + values(): IterableIterator { + return this._store.values(); + } + + [Symbol.iterator](): IterableIterator<[K, V]> { + return this._store[Symbol.iterator](); + } +} diff --git a/node_modules/@xterm/xterm/src/vs/base/common/linkedList.ts b/node_modules/@xterm/xterm/src/vs/base/common/linkedList.ts new file mode 100644 index 0000000..42a1c2a --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/common/linkedList.ts @@ -0,0 +1,142 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +class Node { + + static readonly Undefined = new Node(undefined); + + element: E; + next: Node; + prev: Node; + + constructor(element: E) { + this.element = element; + this.next = Node.Undefined; + this.prev = Node.Undefined; + } +} + +export class LinkedList { + + private _first: Node = Node.Undefined; + private _last: Node = Node.Undefined; + private _size: number = 0; + + get size(): number { + return this._size; + } + + isEmpty(): boolean { + return this._first === Node.Undefined; + } + + clear(): void { + let node = this._first; + while (node !== Node.Undefined) { + const next = node.next; + node.prev = Node.Undefined; + node.next = Node.Undefined; + node = next; + } + + this._first = Node.Undefined; + this._last = Node.Undefined; + this._size = 0; + } + + unshift(element: E): () => void { + return this._insert(element, false); + } + + push(element: E): () => void { + return this._insert(element, true); + } + + private _insert(element: E, atTheEnd: boolean): () => void { + const newNode = new Node(element); + if (this._first === Node.Undefined) { + this._first = newNode; + this._last = newNode; + + } else if (atTheEnd) { + // push + const oldLast = this._last; + this._last = newNode; + newNode.prev = oldLast; + oldLast.next = newNode; + + } else { + // unshift + const oldFirst = this._first; + this._first = newNode; + newNode.next = oldFirst; + oldFirst.prev = newNode; + } + this._size += 1; + + let didRemove = false; + return () => { + if (!didRemove) { + didRemove = true; + this._remove(newNode); + } + }; + } + + shift(): E | undefined { + if (this._first === Node.Undefined) { + return undefined; + } else { + const res = this._first.element; + this._remove(this._first); + return res; + } + } + + pop(): E | undefined { + if (this._last === Node.Undefined) { + return undefined; + } else { + const res = this._last.element; + this._remove(this._last); + return res; + } + } + + private _remove(node: Node): void { + if (node.prev !== Node.Undefined && node.next !== Node.Undefined) { + // middle + const anchor = node.prev; + anchor.next = node.next; + node.next.prev = anchor; + + } else if (node.prev === Node.Undefined && node.next === Node.Undefined) { + // only node + this._first = Node.Undefined; + this._last = Node.Undefined; + + } else if (node.next === Node.Undefined) { + // last + this._last = this._last.prev!; + this._last.next = Node.Undefined; + + } else if (node.prev === Node.Undefined) { + // first + this._first = this._first.next!; + this._first.prev = Node.Undefined; + } + + // done + this._size -= 1; + } + + *[Symbol.iterator](): Iterator { + let node = this._first; + while (node !== Node.Undefined) { + yield node.element; + node = node.next; + } + } +} diff --git a/node_modules/@xterm/xterm/src/vs/base/common/map.ts b/node_modules/@xterm/xterm/src/vs/base/common/map.ts new file mode 100644 index 0000000..5aa55f4 --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/common/map.ts @@ -0,0 +1,202 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +export function getOrSet(map: Map, key: K, value: V): V { + let result = map.get(key); + if (result === undefined) { + result = value; + map.set(key, result); + } + + return result; +} + +export function mapToString(map: Map): string { + const entries: string[] = []; + map.forEach((value, key) => { + entries.push(`${key} => ${value}`); + }); + + return `Map(${map.size}) {${entries.join(', ')}}`; +} + +export function setToString(set: Set): string { + const entries: K[] = []; + set.forEach(value => { + entries.push(value); + }); + + return `Set(${set.size}) {${entries.join(', ')}}`; +} + +export const enum Touch { + None = 0, + AsOld = 1, + AsNew = 2 +} + +export class CounterSet { + + private map = new Map(); + + add(value: T): CounterSet { + this.map.set(value, (this.map.get(value) || 0) + 1); + return this; + } + + delete(value: T): boolean { + let counter = this.map.get(value) || 0; + + if (counter === 0) { + return false; + } + + counter--; + + if (counter === 0) { + this.map.delete(value); + } else { + this.map.set(value, counter); + } + + return true; + } + + has(value: T): boolean { + return this.map.has(value); + } +} + +/** + * A map that allows access both by keys and values. + * **NOTE**: values need to be unique. + */ +export class BidirectionalMap { + + private readonly _m1 = new Map(); + private readonly _m2 = new Map(); + + constructor(entries?: readonly (readonly [K, V])[]) { + if (entries) { + for (const [key, value] of entries) { + this.set(key, value); + } + } + } + + clear(): void { + this._m1.clear(); + this._m2.clear(); + } + + set(key: K, value: V): void { + this._m1.set(key, value); + this._m2.set(value, key); + } + + get(key: K): V | undefined { + return this._m1.get(key); + } + + getKey(value: V): K | undefined { + return this._m2.get(value); + } + + delete(key: K): boolean { + const value = this._m1.get(key); + if (value === undefined) { + return false; + } + this._m1.delete(key); + this._m2.delete(value); + return true; + } + + forEach(callbackfn: (value: V, key: K, map: BidirectionalMap) => void, thisArg?: any): void { + this._m1.forEach((value, key) => { + callbackfn.call(thisArg, value, key, this); + }); + } + + keys(): IterableIterator { + return this._m1.keys(); + } + + values(): IterableIterator { + return this._m1.values(); + } +} + +export class SetMap { + + private map = new Map>(); + + add(key: K, value: V): void { + let values = this.map.get(key); + + if (!values) { + values = new Set(); + this.map.set(key, values); + } + + values.add(value); + } + + delete(key: K, value: V): void { + const values = this.map.get(key); + + if (!values) { + return; + } + + values.delete(value); + + if (values.size === 0) { + this.map.delete(key); + } + } + + forEach(key: K, fn: (value: V) => void): void { + const values = this.map.get(key); + + if (!values) { + return; + } + + values.forEach(fn); + } + + get(key: K): ReadonlySet { + const values = this.map.get(key); + if (!values) { + return new Set(); + } + return values; + } +} + +export function mapsStrictEqualIgnoreOrder(a: Map, b: Map): boolean { + if (a === b) { + return true; + } + + if (a.size !== b.size) { + return false; + } + + for (const [key, value] of a) { + if (!b.has(key) || b.get(key) !== value) { + return false; + } + } + + for (const [key] of b) { + if (!a.has(key)) { + return false; + } + } + + return true; +} diff --git a/node_modules/@xterm/xterm/src/vs/base/common/numbers.ts b/node_modules/@xterm/xterm/src/vs/base/common/numbers.ts new file mode 100644 index 0000000..ab4c9f9 --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/common/numbers.ts @@ -0,0 +1,98 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +export function clamp(value: number, min: number, max: number): number { + return Math.min(Math.max(value, min), max); +} + +export function rot(index: number, modulo: number): number { + return (modulo + (index % modulo)) % modulo; +} + +export class Counter { + private _next = 0; + + getNext(): number { + return this._next++; + } +} + +export class MovingAverage { + + private _n = 1; + private _val = 0; + + update(value: number): number { + this._val = this._val + (value - this._val) / this._n; + this._n += 1; + return this._val; + } + + get value(): number { + return this._val; + } +} + +export class SlidingWindowAverage { + + private _n: number = 0; + private _val = 0; + + private readonly _values: number[] = []; + private _index: number = 0; + private _sum = 0; + + constructor(size: number) { + this._values = new Array(size); + this._values.fill(0, 0, size); + } + + update(value: number): number { + const oldValue = this._values[this._index]; + this._values[this._index] = value; + this._index = (this._index + 1) % this._values.length; + + this._sum -= oldValue; + this._sum += value; + + if (this._n < this._values.length) { + this._n += 1; + } + + this._val = this._sum / this._n; + return this._val; + } + + get value(): number { + return this._val; + } +} + +/** Returns whether the point is within the triangle formed by the following 6 x/y point pairs */ +export function isPointWithinTriangle( + x: number, y: number, + ax: number, ay: number, + bx: number, by: number, + cx: number, cy: number +) { + const v0x = cx - ax; + const v0y = cy - ay; + const v1x = bx - ax; + const v1y = by - ay; + const v2x = x - ax; + const v2y = y - ay; + + const dot00 = v0x * v0x + v0y * v0y; + const dot01 = v0x * v1x + v0y * v1y; + const dot02 = v0x * v2x + v0y * v2y; + const dot11 = v1x * v1x + v1y * v1y; + const dot12 = v1x * v2x + v1y * v2y; + + const invDenom = 1 / (dot00 * dot11 - dot01 * dot01); + const u = (dot11 * dot02 - dot01 * dot12) * invDenom; + const v = (dot00 * dot12 - dot01 * dot02) * invDenom; + + return u >= 0 && v >= 0 && u + v < 1; +} diff --git a/node_modules/@xterm/xterm/src/vs/base/common/observable.ts b/node_modules/@xterm/xterm/src/vs/base/common/observable.ts new file mode 100644 index 0000000..c090a27 --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/common/observable.ts @@ -0,0 +1,76 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +// This is a facade for the observable implementation. Only import from here! + +export type { + IObservable, + IObserver, + IReader, + ISettable, + ISettableObservable, + ITransaction, + IChangeContext, + IChangeTracker, +} from 'vs/base/common/observableInternal/base'; + +export { + observableValue, + disposableObservableValue, + transaction, + subtransaction, +} from 'vs/base/common/observableInternal/base'; +export { + derived, + derivedOpts, + derivedHandleChanges, + derivedWithStore, +} from 'vs/base/common/observableInternal/derived'; +export { + autorun, + autorunDelta, + autorunHandleChanges, + autorunWithStore, + autorunOpts, + autorunWithStoreHandleChanges, +} from 'vs/base/common/observableInternal/autorun'; +export type { + IObservableSignal, +} from 'vs/base/common/observableInternal/utils'; +export { + constObservable, + debouncedObservable, + derivedObservableWithCache, + derivedObservableWithWritableCache, + keepObserved, + recomputeInitiallyAndOnChange, + observableFromEvent, + observableFromPromise, + observableSignal, + observableSignalFromEvent, + wasEventTriggeredRecently, +} from 'vs/base/common/observableInternal/utils'; +export { + ObservableLazy, + ObservableLazyPromise, + ObservablePromise, + PromiseResult, + waitForState, + derivedWithCancellationToken, +} from 'vs/base/common/observableInternal/promise'; +export { + observableValueOpts +} from 'vs/base/common/observableInternal/api'; + +import { ConsoleObservableLogger, setLogger } from 'vs/base/common/observableInternal/logging'; + +// Remove "//" in the next line to enable logging +const enableLogging = false + // || Boolean("true") // done "weirdly" so that a lint warning prevents you from pushing this + ; + +if (enableLogging) { + setLogger(new ConsoleObservableLogger()); +} diff --git a/node_modules/@xterm/xterm/src/vs/base/common/observableInternal/api.ts b/node_modules/@xterm/xterm/src/vs/base/common/observableInternal/api.ts new file mode 100644 index 0000000..6e56671 --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/common/observableInternal/api.ts @@ -0,0 +1,31 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { EqualityComparer, strictEquals } from 'vs/base/common/equals'; +import { ISettableObservable } from 'vs/base/common/observable'; +import { ObservableValue } from 'vs/base/common/observableInternal/base'; +import { IDebugNameData, DebugNameData } from 'vs/base/common/observableInternal/debugName'; +import { LazyObservableValue } from 'vs/base/common/observableInternal/lazyObservableValue'; + +export function observableValueOpts( + options: IDebugNameData & { + equalsFn?: EqualityComparer; + lazy?: boolean; + }, + initialValue: T +): ISettableObservable { + if (options.lazy) { + return new LazyObservableValue( + new DebugNameData(options.owner, options.debugName, undefined), + initialValue, + options.equalsFn ?? strictEquals, + ); + } + return new ObservableValue( + new DebugNameData(options.owner, options.debugName, undefined), + initialValue, + options.equalsFn ?? strictEquals, + ); +} diff --git a/node_modules/@xterm/xterm/src/vs/base/common/observableInternal/autorun.ts b/node_modules/@xterm/xterm/src/vs/base/common/observableInternal/autorun.ts new file mode 100644 index 0000000..845e870 --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/common/observableInternal/autorun.ts @@ -0,0 +1,281 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { assertFn } from 'vs/base/common/assert'; +import { DisposableStore, IDisposable, markAsDisposed, toDisposable, trackDisposable } from 'vs/base/common/lifecycle'; +import { IReader, IObservable, IObserver, IChangeContext } from 'vs/base/common/observableInternal/base'; +import { DebugNameData, IDebugNameData } from 'vs/base/common/observableInternal/debugName'; +import { getLogger } from 'vs/base/common/observableInternal/logging'; + +/** + * Runs immediately and whenever a transaction ends and an observed observable changed. + * {@link fn} should start with a JS Doc using `@description` to name the autorun. + */ +export function autorun(fn: (reader: IReader) => void): IDisposable { + return new AutorunObserver( + new DebugNameData(undefined, undefined, fn), + fn, + undefined, + undefined + ); +} + +/** + * Runs immediately and whenever a transaction ends and an observed observable changed. + * {@link fn} should start with a JS Doc using `@description` to name the autorun. + */ +export function autorunOpts(options: IDebugNameData & {}, fn: (reader: IReader) => void): IDisposable { + return new AutorunObserver( + new DebugNameData(options.owner, options.debugName, options.debugReferenceFn ?? fn), + fn, + undefined, + undefined + ); +} + +/** + * Runs immediately and whenever a transaction ends and an observed observable changed. + * {@link fn} should start with a JS Doc using `@description` to name the autorun. + * + * Use `createEmptyChangeSummary` to create a "change summary" that can collect the changes. + * Use `handleChange` to add a reported change to the change summary. + * The run function is given the last change summary. + * The change summary is discarded after the run function was called. + * + * @see autorun + */ +export function autorunHandleChanges( + options: IDebugNameData & { + createEmptyChangeSummary?: () => TChangeSummary; + handleChange: (context: IChangeContext, changeSummary: TChangeSummary) => boolean; + }, + fn: (reader: IReader, changeSummary: TChangeSummary) => void +): IDisposable { + return new AutorunObserver( + new DebugNameData(options.owner, options.debugName, options.debugReferenceFn ?? fn), + fn, + options.createEmptyChangeSummary, + options.handleChange + ); +} + +/** + * @see autorunHandleChanges (but with a disposable store that is cleared before the next run or on dispose) + */ +export function autorunWithStoreHandleChanges( + options: IDebugNameData & { + createEmptyChangeSummary?: () => TChangeSummary; + handleChange: (context: IChangeContext, changeSummary: TChangeSummary) => boolean; + }, + fn: (reader: IReader, changeSummary: TChangeSummary, store: DisposableStore) => void +): IDisposable { + const store = new DisposableStore(); + const disposable = autorunHandleChanges( + { + owner: options.owner, + debugName: options.debugName, + debugReferenceFn: options.debugReferenceFn ?? fn, + createEmptyChangeSummary: options.createEmptyChangeSummary, + handleChange: options.handleChange, + }, + (reader, changeSummary) => { + store.clear(); + fn(reader, changeSummary, store); + } + ); + return toDisposable(() => { + disposable.dispose(); + store.dispose(); + }); +} + +/** + * @see autorun (but with a disposable store that is cleared before the next run or on dispose) + */ +export function autorunWithStore(fn: (reader: IReader, store: DisposableStore) => void): IDisposable { + const store = new DisposableStore(); + const disposable = autorunOpts( + { + owner: undefined, + debugName: undefined, + debugReferenceFn: fn, + }, + reader => { + store.clear(); + fn(reader, store); + } + ); + return toDisposable(() => { + disposable.dispose(); + store.dispose(); + }); +} + +export function autorunDelta( + observable: IObservable, + handler: (args: { lastValue: T | undefined; newValue: T }) => void +): IDisposable { + let _lastValue: T | undefined; + return autorunOpts({ debugReferenceFn: handler }, (reader) => { + const newValue = observable.read(reader); + const lastValue = _lastValue; + _lastValue = newValue; + handler({ lastValue, newValue }); + }); +} + + +const enum AutorunState { + /** + * A dependency could have changed. + * We need to explicitly ask them if at least one dependency changed. + */ + dependenciesMightHaveChanged = 1, + + /** + * A dependency changed and we need to recompute. + */ + stale = 2, + upToDate = 3, +} + +export class AutorunObserver implements IObserver, IReader, IDisposable { + private state = AutorunState.stale; + private updateCount = 0; + private disposed = false; + private dependencies = new Set>(); + private dependenciesToBeRemoved = new Set>(); + private changeSummary: TChangeSummary | undefined; + + public get debugName(): string { + return this._debugNameData.getDebugName(this) ?? '(anonymous)'; + } + + constructor( + public readonly _debugNameData: DebugNameData, + public readonly _runFn: (reader: IReader, changeSummary: TChangeSummary) => void, + private readonly createChangeSummary: (() => TChangeSummary) | undefined, + private readonly _handleChange: ((context: IChangeContext, summary: TChangeSummary) => boolean) | undefined, + ) { + this.changeSummary = this.createChangeSummary?.(); + getLogger()?.handleAutorunCreated(this); + this._runIfNeeded(); + + trackDisposable(this); + } + + public dispose(): void { + this.disposed = true; + for (const o of this.dependencies) { + o.removeObserver(this); + } + this.dependencies.clear(); + + markAsDisposed(this); + } + + private _runIfNeeded() { + if (this.state === AutorunState.upToDate) { + return; + } + + const emptySet = this.dependenciesToBeRemoved; + this.dependenciesToBeRemoved = this.dependencies; + this.dependencies = emptySet; + + this.state = AutorunState.upToDate; + + const isDisposed = this.disposed; + try { + if (!isDisposed) { + getLogger()?.handleAutorunTriggered(this); + const changeSummary = this.changeSummary!; + this.changeSummary = this.createChangeSummary?.(); + this._runFn(this, changeSummary); + } + } finally { + if (!isDisposed) { + getLogger()?.handleAutorunFinished(this); + } + // We don't want our observed observables to think that they are (not even temporarily) not being observed. + // Thus, we only unsubscribe from observables that are definitely not read anymore. + for (const o of this.dependenciesToBeRemoved) { + o.removeObserver(this); + } + this.dependenciesToBeRemoved.clear(); + } + } + + public toString(): string { + return `Autorun<${this.debugName}>`; + } + + // IObserver implementation + public beginUpdate(): void { + if (this.state === AutorunState.upToDate) { + this.state = AutorunState.dependenciesMightHaveChanged; + } + this.updateCount++; + } + + public endUpdate(): void { + if (this.updateCount === 1) { + do { + if (this.state === AutorunState.dependenciesMightHaveChanged) { + this.state = AutorunState.upToDate; + for (const d of this.dependencies) { + d.reportChanges(); + if (this.state as AutorunState === AutorunState.stale) { + // The other dependencies will refresh on demand + break; + } + } + } + + this._runIfNeeded(); + } while (this.state !== AutorunState.upToDate); + } + this.updateCount--; + + assertFn(() => this.updateCount >= 0); + } + + public handlePossibleChange(observable: IObservable): void { + if (this.state === AutorunState.upToDate && this.dependencies.has(observable) && !this.dependenciesToBeRemoved.has(observable)) { + this.state = AutorunState.dependenciesMightHaveChanged; + } + } + + public handleChange(observable: IObservable, change: TChange): void { + if (this.dependencies.has(observable) && !this.dependenciesToBeRemoved.has(observable)) { + const shouldReact = this._handleChange ? this._handleChange({ + changedObservable: observable, + change, + didChange: (o): this is any => o === observable as any, + }, this.changeSummary!) : true; + if (shouldReact) { + this.state = AutorunState.stale; + } + } + } + + // IReader implementation + public readObservable(observable: IObservable): T { + // In case the run action disposes the autorun + if (this.disposed) { + return observable.get(); + } + + observable.addObserver(this); + const value = observable.get(); + this.dependencies.add(observable); + this.dependenciesToBeRemoved.delete(observable); + return value; + } +} + +export namespace autorun { + export const Observer = AutorunObserver; +} diff --git a/node_modules/@xterm/xterm/src/vs/base/common/observableInternal/base.ts b/node_modules/@xterm/xterm/src/vs/base/common/observableInternal/base.ts new file mode 100644 index 0000000..3c63a20 --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/common/observableInternal/base.ts @@ -0,0 +1,489 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { strictEquals, EqualityComparer } from 'vs/base/common/equals'; +import { DisposableStore, IDisposable } from 'vs/base/common/lifecycle'; +import { keepObserved, recomputeInitiallyAndOnChange } from 'vs/base/common/observable'; +import { DebugNameData, DebugOwner, getFunctionName } from 'vs/base/common/observableInternal/debugName'; +import type { derivedOpts } from 'vs/base/common/observableInternal/derived'; +import { getLogger } from 'vs/base/common/observableInternal/logging'; + +/** + * Represents an observable value. + * + * @template T The type of the values the observable can hold. + * @template TChange The type used to describe value changes + * (usually `void` and only used in advanced scenarios). + * While observers can miss temporary values of an observable, + * they will receive all change values (as long as they are subscribed)! + */ +export interface IObservable { + /** + * Returns the current value. + * + * Calls {@link IObserver.handleChange} if the observable notices that the value changed. + * Must not be called from {@link IObserver.handleChange}! + */ + get(): T; + + /** + * Forces the observable to check for changes and report them. + * + * Has the same effect as calling {@link IObservable.get}, but does not force the observable + * to actually construct the value, e.g. if change deltas are used. + * Calls {@link IObserver.handleChange} if the observable notices that the value changed. + * Must not be called from {@link IObserver.handleChange}! + */ + reportChanges(): void; + + /** + * Adds the observer to the set of subscribed observers. + * This method is idempotent. + */ + addObserver(observer: IObserver): void; + + /** + * Removes the observer from the set of subscribed observers. + * This method is idempotent. + */ + removeObserver(observer: IObserver): void; + + /** + * Reads the current value and subscribes the reader to this observable. + * + * Calls {@link IReader.readObservable} if a reader is given, otherwise {@link IObservable.get} + * (see {@link ConvenientObservable.read} for the implementation). + */ + read(reader: IReader | undefined): T; + + /** + * Creates a derived observable that depends on this observable. + * Use the reader to read other observables + * (see {@link ConvenientObservable.map} for the implementation). + */ + map(fn: (value: T, reader: IReader) => TNew): IObservable; + map(owner: object, fn: (value: T, reader: IReader) => TNew): IObservable; + + /** + * Makes sure this value is computed eagerly. + */ + recomputeInitiallyAndOnChange(store: DisposableStore, handleValue?: (value: T) => void): IObservable; + + /** + * Makes sure this value is cached. + */ + keepObserved(store: DisposableStore): IObservable; + + /** + * A human-readable name for debugging purposes. + */ + readonly debugName: string; + + /** + * This property captures the type of the change object. Do not use it at runtime! + */ + readonly TChange: TChange; +} + +export interface IReader { + /** + * Reads the value of an observable and subscribes to it. + */ + readObservable(observable: IObservable): T; +} + +/** + * Represents an observer that can be subscribed to an observable. + * + * If an observer is subscribed to an observable and that observable didn't signal + * a change through one of the observer methods, the observer can assume that the + * observable didn't change. + * If an observable reported a possible change, {@link IObservable.reportChanges} forces + * the observable to report an actual change if there was one. + */ +export interface IObserver { + /** + * Signals that the given observable might have changed and a transaction potentially modifying that observable started. + * Before the given observable can call this method again, is must call {@link IObserver.endUpdate}. + * + * Implementations must not get/read the value of other observables, as they might not have received this event yet! + * The method {@link IObservable.reportChanges} can be used to force the observable to report the changes. + */ + beginUpdate(observable: IObservable): void; + + /** + * Signals that the transaction that potentially modified the given observable ended. + * This is a good place to react to (potential) changes. + */ + endUpdate(observable: IObservable): void; + + /** + * Signals that the given observable might have changed. + * The method {@link IObservable.reportChanges} can be used to force the observable to report the changes. + * + * Implementations must not get/read the value of other observables, as they might not have received this event yet! + * The change should be processed lazily or in {@link IObserver.endUpdate}. + */ + handlePossibleChange(observable: IObservable): void; + + /** + * Signals that the given {@link observable} changed. + * + * Implementations must not get/read the value of other observables, as they might not have received this event yet! + * The change should be processed lazily or in {@link IObserver.endUpdate}. + * + * @param change Indicates how or why the value changed. + */ + handleChange(observable: IObservable, change: TChange): void; +} + +export interface ISettable { + /** + * Sets the value of the observable. + * Use a transaction to batch multiple changes (with a transaction, observers only react at the end of the transaction). + * + * @param transaction When given, value changes are handled on demand or when the transaction ends. + * @param change Describes how or why the value changed. + */ + set(value: T, transaction: ITransaction | undefined, change: TChange): void; +} + +export interface ITransaction { + /** + * Calls {@link Observer.beginUpdate} immediately + * and {@link Observer.endUpdate} when the transaction ends. + */ + updateObserver(observer: IObserver, observable: IObservable): void; +} + +let _recomputeInitiallyAndOnChange: typeof recomputeInitiallyAndOnChange; +export function _setRecomputeInitiallyAndOnChange(recomputeInitiallyAndOnChange: typeof _recomputeInitiallyAndOnChange) { + _recomputeInitiallyAndOnChange = recomputeInitiallyAndOnChange; +} + +let _keepObserved: typeof keepObserved; +export function _setKeepObserved(keepObserved: typeof _keepObserved) { + _keepObserved = keepObserved; +} + + +let _derived: typeof derivedOpts; +/** + * @internal + * This is to allow splitting files. +*/ +export function _setDerivedOpts(derived: typeof _derived) { + _derived = derived; +} + +export abstract class ConvenientObservable implements IObservable { + get TChange(): TChange { return null!; } + + public abstract get(): T; + + public reportChanges(): void { + this.get(); + } + + public abstract addObserver(observer: IObserver): void; + public abstract removeObserver(observer: IObserver): void; + + /** @sealed */ + public read(reader: IReader | undefined): T { + if (reader) { + return reader.readObservable(this); + } else { + return this.get(); + } + } + + /** @sealed */ + public map(fn: (value: T, reader: IReader) => TNew): IObservable; + public map(owner: DebugOwner, fn: (value: T, reader: IReader) => TNew): IObservable; + public map(fnOrOwner: DebugOwner | ((value: T, reader: IReader) => TNew), fnOrUndefined?: (value: T, reader: IReader) => TNew): IObservable { + const owner = fnOrUndefined === undefined ? undefined : fnOrOwner as DebugOwner; + const fn = fnOrUndefined === undefined ? fnOrOwner as (value: T, reader: IReader) => TNew : fnOrUndefined; + + return _derived( + { + owner, + debugName: () => { + const name = getFunctionName(fn); + if (name !== undefined) { + return name; + } + + // regexp to match `x => x.y` or `x => x?.y` where x and y can be arbitrary identifiers (uses backref): + const regexp = /^\s*\(?\s*([a-zA-Z_$][a-zA-Z_$0-9]*)\s*\)?\s*=>\s*\1(?:\??)\.([a-zA-Z_$][a-zA-Z_$0-9]*)\s*$/; + const match = regexp.exec(fn.toString()); + if (match) { + return `${this.debugName}.${match[2]}`; + } + if (!owner) { + return `${this.debugName} (mapped)`; + } + return undefined; + }, + debugReferenceFn: fn, + }, + (reader) => fn(this.read(reader), reader), + ); + } + + public recomputeInitiallyAndOnChange(store: DisposableStore, handleValue?: (value: T) => void): IObservable { + store.add(_recomputeInitiallyAndOnChange!(this, handleValue)); + return this; + } + + /** + * Ensures that this observable is observed. This keeps the cache alive. + * However, in case of deriveds, it does not force eager evaluation (only when the value is read/get). + * Use `recomputeInitiallyAndOnChange` for eager evaluation. + */ + public keepObserved(store: DisposableStore): IObservable { + store.add(_keepObserved!(this)); + return this; + } + + public abstract get debugName(): string; + + protected get debugValue() { + return this.get(); + } +} + +export abstract class BaseObservable extends ConvenientObservable { + protected readonly observers = new Set(); + + public addObserver(observer: IObserver): void { + const len = this.observers.size; + this.observers.add(observer); + if (len === 0) { + this.onFirstObserverAdded(); + } + } + + public removeObserver(observer: IObserver): void { + const deleted = this.observers.delete(observer); + if (deleted && this.observers.size === 0) { + this.onLastObserverRemoved(); + } + } + + protected onFirstObserverAdded(): void { } + protected onLastObserverRemoved(): void { } +} + +/** + * Starts a transaction in which many observables can be changed at once. + * {@link fn} should start with a JS Doc using `@description` to give the transaction a debug name. + * Reaction run on demand or when the transaction ends. + */ + +export function transaction(fn: (tx: ITransaction) => void, getDebugName?: () => string): void { + const tx = new TransactionImpl(fn, getDebugName); + try { + fn(tx); + } finally { + tx.finish(); + } +} + +let _globalTransaction: ITransaction | undefined = undefined; + +export function globalTransaction(fn: (tx: ITransaction) => void) { + if (_globalTransaction) { + fn(_globalTransaction); + } else { + const tx = new TransactionImpl(fn, undefined); + _globalTransaction = tx; + try { + fn(tx); + } finally { + tx.finish(); // During finish, more actions might be added to the transaction. + // Which is why we only clear the global transaction after finish. + _globalTransaction = undefined; + } + } +} + +export async function asyncTransaction(fn: (tx: ITransaction) => Promise, getDebugName?: () => string): Promise { + const tx = new TransactionImpl(fn, getDebugName); + try { + await fn(tx); + } finally { + tx.finish(); + } +} + +/** + * Allows to chain transactions. + */ +export function subtransaction(tx: ITransaction | undefined, fn: (tx: ITransaction) => void, getDebugName?: () => string): void { + if (!tx) { + transaction(fn, getDebugName); + } else { + fn(tx); + } +} + +export class TransactionImpl implements ITransaction { + private updatingObservers: { observer: IObserver; observable: IObservable }[] | null = []; + + constructor(public readonly _fn: Function, private readonly _getDebugName?: () => string) { + getLogger()?.handleBeginTransaction(this); + } + + public getDebugName(): string | undefined { + if (this._getDebugName) { + return this._getDebugName(); + } + return getFunctionName(this._fn); + } + + public updateObserver(observer: IObserver, observable: IObservable): void { + // When this gets called while finish is active, they will still get considered + this.updatingObservers!.push({ observer, observable }); + observer.beginUpdate(observable); + } + + public finish(): void { + const updatingObservers = this.updatingObservers!; + for (let i = 0; i < updatingObservers.length; i++) { + const { observer, observable } = updatingObservers[i]; + observer.endUpdate(observable); + } + // Prevent anyone from updating observers from now on. + this.updatingObservers = null; + getLogger()?.handleEndTransaction(); + } +} + +/** + * A settable observable. + */ +export interface ISettableObservable extends IObservable, ISettable { +} + +/** + * Creates an observable value. + * Observers get informed when the value changes. + * @template TChange An arbitrary type to describe how or why the value changed. Defaults to `void`. + * Observers will receive every single change value. + */ +export function observableValue(name: string, initialValue: T): ISettableObservable; +export function observableValue(owner: object, initialValue: T): ISettableObservable; +export function observableValue(nameOrOwner: string | object, initialValue: T): ISettableObservable { + let debugNameData: DebugNameData; + if (typeof nameOrOwner === 'string') { + debugNameData = new DebugNameData(undefined, nameOrOwner, undefined); + } else { + debugNameData = new DebugNameData(nameOrOwner, undefined, undefined); + } + return new ObservableValue(debugNameData, initialValue, strictEquals); +} + +export class ObservableValue + extends BaseObservable + implements ISettableObservable { + protected _value: T; + + get debugName() { + return this._debugNameData.getDebugName(this) ?? 'ObservableValue'; + } + + constructor( + private readonly _debugNameData: DebugNameData, + initialValue: T, + private readonly _equalityComparator: EqualityComparer, + ) { + super(); + this._value = initialValue; + } + public override get(): T { + return this._value; + } + + public set(value: T, tx: ITransaction | undefined, change: TChange): void { + if (change === undefined && this._equalityComparator(this._value, value)) { + return; + } + + let _tx: TransactionImpl | undefined; + if (!tx) { + tx = _tx = new TransactionImpl(() => { }, () => `Setting ${this.debugName}`); + } + try { + const oldValue = this._value; + this._setValue(value); + getLogger()?.handleObservableChanged(this, { oldValue, newValue: value, change, didChange: true, hadValue: true }); + + for (const observer of this.observers) { + tx.updateObserver(observer, this); + observer.handleChange(this, change); + } + } finally { + if (_tx) { + _tx.finish(); + } + } + } + + override toString(): string { + return `${this.debugName}: ${this._value}`; + } + + protected _setValue(newValue: T): void { + this._value = newValue; + } +} + +/** + * A disposable observable. When disposed, its value is also disposed. + * When a new value is set, the previous value is disposed. + */ +export function disposableObservableValue(nameOrOwner: string | object, initialValue: T): ISettableObservable & IDisposable { + let debugNameData: DebugNameData; + if (typeof nameOrOwner === 'string') { + debugNameData = new DebugNameData(undefined, nameOrOwner, undefined); + } else { + debugNameData = new DebugNameData(nameOrOwner, undefined, undefined); + } + return new DisposableObservableValue(debugNameData, initialValue, strictEquals); +} + +export class DisposableObservableValue extends ObservableValue implements IDisposable { + protected override _setValue(newValue: T): void { + if (this._value === newValue) { + return; + } + if (this._value) { + this._value.dispose(); + } + this._value = newValue; + } + + public dispose(): void { + this._value?.dispose(); + } +} + +export interface IChangeTracker { + /** + * Returns if this change should cause an invalidation. + * Implementations can record changes. + */ + handleChange(context: IChangeContext): boolean; +} + +export interface IChangeContext { + readonly changedObservable: IObservable; + readonly change: unknown; + + /** + * Returns if the given observable caused the change. + */ + didChange(observable: IObservable): this is { change: TChange }; +} diff --git a/node_modules/@xterm/xterm/src/vs/base/common/observableInternal/debugName.ts b/node_modules/@xterm/xterm/src/vs/base/common/observableInternal/debugName.ts new file mode 100644 index 0000000..1ff1f24 --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/common/observableInternal/debugName.ts @@ -0,0 +1,145 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +export interface IDebugNameData { + /** + * The owner object of an observable. + * Used for debugging only, such as computing a name for the observable by iterating over the fields of the owner. + */ + readonly owner?: DebugOwner | undefined; + + /** + * A string or function that returns a string that represents the name of the observable. + * Used for debugging only. + */ + readonly debugName?: DebugNameSource | undefined; + + /** + * A function that points to the defining function of the object. + * Used for debugging only. + */ + readonly debugReferenceFn?: Function | undefined; +} + +export class DebugNameData { + constructor( + public readonly owner: DebugOwner | undefined, + public readonly debugNameSource: DebugNameSource | undefined, + public readonly referenceFn: Function | undefined, + ) { } + + public getDebugName(target: object): string | undefined { + return getDebugName(target, this); + } +} + +/** + * The owning object of an observable. + * Is only used for debugging purposes, such as computing a name for the observable by iterating over the fields of the owner. + */ +export type DebugOwner = object | undefined; +export type DebugNameSource = string | (() => string | undefined); + +const countPerName = new Map(); +const cachedDebugName = new WeakMap(); + +export function getDebugName(target: object, data: DebugNameData): string | undefined { + const cached = cachedDebugName.get(target); + if (cached) { + return cached; + } + + const dbgName = computeDebugName(target, data); + if (dbgName) { + let count = countPerName.get(dbgName) ?? 0; + count++; + countPerName.set(dbgName, count); + const result = count === 1 ? dbgName : `${dbgName}#${count}`; + cachedDebugName.set(target, result); + return result; + } + return undefined; +} + +function computeDebugName(self: object, data: DebugNameData): string | undefined { + const cached = cachedDebugName.get(self); + if (cached) { + return cached; + } + + const ownerStr = data.owner ? formatOwner(data.owner) + `.` : ''; + + let result: string | undefined; + const debugNameSource = data.debugNameSource; + if (debugNameSource !== undefined) { + if (typeof debugNameSource === 'function') { + result = debugNameSource(); + if (result !== undefined) { + return ownerStr + result; + } + } else { + return ownerStr + debugNameSource; + } + } + + const referenceFn = data.referenceFn; + if (referenceFn !== undefined) { + result = getFunctionName(referenceFn); + if (result !== undefined) { + return ownerStr + result; + } + } + + if (data.owner !== undefined) { + const key = findKey(data.owner, self); + if (key !== undefined) { + return ownerStr + key; + } + } + return undefined; +} + +function findKey(obj: object, value: object): string | undefined { + for (const key in obj) { + if ((obj as any)[key] === value) { + return key; + } + } + return undefined; +} + +const countPerClassName = new Map(); +const ownerId = new WeakMap(); + +function formatOwner(owner: object): string { + const id = ownerId.get(owner); + if (id) { + return id; + } + const className = getClassName(owner); + let count = countPerClassName.get(className) ?? 0; + count++; + countPerClassName.set(className, count); + const result = count === 1 ? className : `${className}#${count}`; + ownerId.set(owner, result); + return result; +} + +function getClassName(obj: object): string { + const ctor = obj.constructor; + if (ctor) { + return ctor.name; + } + return 'Object'; +} + +export function getFunctionName(fn: Function): string | undefined { + const fnSrc = fn.toString(); + // Pattern: /** @description ... */ + const regexp = /\/\*\*\s*@description\s*([^*]*)\*\//; + const match = regexp.exec(fnSrc); + const result = match ? match[1] : undefined; + return result?.trim(); +} diff --git a/node_modules/@xterm/xterm/src/vs/base/common/observableInternal/derived.ts b/node_modules/@xterm/xterm/src/vs/base/common/observableInternal/derived.ts new file mode 100644 index 0000000..8de2224 --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/common/observableInternal/derived.ts @@ -0,0 +1,428 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { assertFn } from 'vs/base/common/assert'; +import { EqualityComparer, strictEquals } from 'vs/base/common/equals'; +import { DisposableStore, IDisposable } from 'vs/base/common/lifecycle'; +import { BaseObservable, IChangeContext, IObservable, IObserver, IReader, ISettableObservable, ITransaction, _setDerivedOpts, } from 'vs/base/common/observableInternal/base'; +import { DebugNameData, IDebugNameData, DebugOwner } from 'vs/base/common/observableInternal/debugName'; +import { getLogger } from 'vs/base/common/observableInternal/logging'; + +/** + * Creates an observable that is derived from other observables. + * The value is only recomputed when absolutely needed. + * + * {@link computeFn} should start with a JS Doc using `@description` to name the derived. + */ +export function derived(computeFn: (reader: IReader) => T): IObservable; +export function derived(owner: DebugOwner, computeFn: (reader: IReader) => T): IObservable; +export function derived(computeFnOrOwner: ((reader: IReader) => T) | DebugOwner, computeFn?: ((reader: IReader) => T) | undefined): IObservable { + if (computeFn !== undefined) { + return new Derived( + new DebugNameData(computeFnOrOwner, undefined, computeFn), + computeFn, + undefined, + undefined, + undefined, + strictEquals + ); + } + return new Derived( + new DebugNameData(undefined, undefined, computeFnOrOwner as any), + computeFnOrOwner as any, + undefined, + undefined, + undefined, + strictEquals + ); +} + +export function derivedWithSetter(owner: DebugOwner | undefined, computeFn: (reader: IReader) => T, setter: (value: T, transaction: ITransaction | undefined) => void): ISettableObservable { + return new DerivedWithSetter( + new DebugNameData(owner, undefined, computeFn), + computeFn, + undefined, + undefined, + undefined, + strictEquals, + setter, + ); +} + +export function derivedOpts( + options: IDebugNameData & { + equalsFn?: EqualityComparer; + onLastObserverRemoved?: (() => void); + }, + computeFn: (reader: IReader) => T +): IObservable { + return new Derived( + new DebugNameData(options.owner, options.debugName, options.debugReferenceFn), + computeFn, + undefined, + undefined, + options.onLastObserverRemoved, + options.equalsFn ?? strictEquals + ); +} + +_setDerivedOpts(derivedOpts); + +/** + * Represents an observable that is derived from other observables. + * The value is only recomputed when absolutely needed. + * + * {@link computeFn} should start with a JS Doc using `@description` to name the derived. + * + * Use `createEmptyChangeSummary` to create a "change summary" that can collect the changes. + * Use `handleChange` to add a reported change to the change summary. + * The compute function is given the last change summary. + * The change summary is discarded after the compute function was called. + * + * @see derived + */ +export function derivedHandleChanges( + options: IDebugNameData & { + createEmptyChangeSummary: () => TChangeSummary; + handleChange: (context: IChangeContext, changeSummary: TChangeSummary) => boolean; + equalityComparer?: EqualityComparer; + }, + computeFn: (reader: IReader, changeSummary: TChangeSummary) => T +): IObservable { + return new Derived( + new DebugNameData(options.owner, options.debugName, undefined), + computeFn, + options.createEmptyChangeSummary, + options.handleChange, + undefined, + options.equalityComparer ?? strictEquals + ); +} + +export function derivedWithStore(computeFn: (reader: IReader, store: DisposableStore) => T): IObservable; +export function derivedWithStore(owner: object, computeFn: (reader: IReader, store: DisposableStore) => T): IObservable; +export function derivedWithStore(computeFnOrOwner: ((reader: IReader, store: DisposableStore) => T) | object, computeFnOrUndefined?: ((reader: IReader, store: DisposableStore) => T)): IObservable { + let computeFn: (reader: IReader, store: DisposableStore) => T; + let owner: DebugOwner; + if (computeFnOrUndefined === undefined) { + computeFn = computeFnOrOwner as any; + owner = undefined; + } else { + owner = computeFnOrOwner; + computeFn = computeFnOrUndefined as any; + } + + const store = new DisposableStore(); + return new Derived( + new DebugNameData(owner, undefined, computeFn), + r => { + store.clear(); + return computeFn(r, store); + }, undefined, + undefined, + () => store.dispose(), + strictEquals + ); +} + +export function derivedDisposable(computeFn: (reader: IReader) => T): IObservable; +export function derivedDisposable(owner: DebugOwner, computeFn: (reader: IReader) => T): IObservable; +export function derivedDisposable(computeFnOrOwner: ((reader: IReader) => T) | DebugOwner, computeFnOrUndefined?: ((reader: IReader) => T)): IObservable { + let computeFn: (reader: IReader) => T; + let owner: DebugOwner; + if (computeFnOrUndefined === undefined) { + computeFn = computeFnOrOwner as any; + owner = undefined; + } else { + owner = computeFnOrOwner; + computeFn = computeFnOrUndefined as any; + } + + let store: DisposableStore | undefined = undefined; + return new Derived( + new DebugNameData(owner, undefined, computeFn), + r => { + if (!store) { + store = new DisposableStore(); + } else { + store.clear(); + } + const result = computeFn(r); + if (result) { + store.add(result); + } + return result; + }, undefined, + undefined, + () => { + if (store) { + store.dispose(); + store = undefined; + } + }, + strictEquals + ); +} + +const enum DerivedState { + /** Initial state, no previous value, recomputation needed */ + initial = 0, + + /** + * A dependency could have changed. + * We need to explicitly ask them if at least one dependency changed. + */ + dependenciesMightHaveChanged = 1, + + /** + * A dependency changed and we need to recompute. + * After recomputation, we need to check the previous value to see if we changed as well. + */ + stale = 2, + + /** + * No change reported, our cached value is up to date. + */ + upToDate = 3, +} + +export class Derived extends BaseObservable implements IReader, IObserver { + private state = DerivedState.initial; + private value: T | undefined = undefined; + private updateCount = 0; + private dependencies = new Set>(); + private dependenciesToBeRemoved = new Set>(); + private changeSummary: TChangeSummary | undefined = undefined; + + public override get debugName(): string { + return this._debugNameData.getDebugName(this) ?? '(anonymous)'; + } + + constructor( + public readonly _debugNameData: DebugNameData, + public readonly _computeFn: (reader: IReader, changeSummary: TChangeSummary) => T, + private readonly createChangeSummary: (() => TChangeSummary) | undefined, + private readonly _handleChange: ((context: IChangeContext, summary: TChangeSummary) => boolean) | undefined, + private readonly _handleLastObserverRemoved: (() => void) | undefined = undefined, + private readonly _equalityComparator: EqualityComparer, + ) { + super(); + this.changeSummary = this.createChangeSummary?.(); + getLogger()?.handleDerivedCreated(this); + } + + protected override onLastObserverRemoved(): void { + /** + * We are not tracking changes anymore, thus we have to assume + * that our cache is invalid. + */ + this.state = DerivedState.initial; + this.value = undefined; + for (const d of this.dependencies) { + d.removeObserver(this); + } + this.dependencies.clear(); + + this._handleLastObserverRemoved?.(); + } + + public override get(): T { + if (this.observers.size === 0) { + // Without observers, we don't know when to clean up stuff. + // Thus, we don't cache anything to prevent memory leaks. + const result = this._computeFn(this, this.createChangeSummary?.()!); + // Clear new dependencies + this.onLastObserverRemoved(); + return result; + } else { + do { + // We might not get a notification for a dependency that changed while it is updating, + // thus we also have to ask all our depedencies if they changed in this case. + if (this.state === DerivedState.dependenciesMightHaveChanged) { + for (const d of this.dependencies) { + /** might call {@link handleChange} indirectly, which could make us stale */ + d.reportChanges(); + + if (this.state as DerivedState === DerivedState.stale) { + // The other dependencies will refresh on demand, so early break + break; + } + } + } + + // We called report changes of all dependencies. + // If we are still not stale, we can assume to be up to date again. + if (this.state === DerivedState.dependenciesMightHaveChanged) { + this.state = DerivedState.upToDate; + } + + this._recomputeIfNeeded(); + // In case recomputation changed one of our dependencies, we need to recompute again. + } while (this.state !== DerivedState.upToDate); + return this.value!; + } + } + + private _recomputeIfNeeded() { + if (this.state === DerivedState.upToDate) { + return; + } + const emptySet = this.dependenciesToBeRemoved; + this.dependenciesToBeRemoved = this.dependencies; + this.dependencies = emptySet; + + const hadValue = this.state !== DerivedState.initial; + const oldValue = this.value; + this.state = DerivedState.upToDate; + + const changeSummary = this.changeSummary!; + this.changeSummary = this.createChangeSummary?.(); + try { + /** might call {@link handleChange} indirectly, which could invalidate us */ + this.value = this._computeFn(this, changeSummary); + } finally { + // We don't want our observed observables to think that they are (not even temporarily) not being observed. + // Thus, we only unsubscribe from observables that are definitely not read anymore. + for (const o of this.dependenciesToBeRemoved) { + o.removeObserver(this); + } + this.dependenciesToBeRemoved.clear(); + } + + const didChange = hadValue && !(this._equalityComparator(oldValue!, this.value)); + + getLogger()?.handleDerivedRecomputed(this, { + oldValue, + newValue: this.value, + change: undefined, + didChange, + hadValue, + }); + + if (didChange) { + for (const r of this.observers) { + r.handleChange(this, undefined); + } + } + } + + public override toString(): string { + return `LazyDerived<${this.debugName}>`; + } + + // IObserver Implementation + public beginUpdate(_observable: IObservable): void { + this.updateCount++; + const propagateBeginUpdate = this.updateCount === 1; + if (this.state === DerivedState.upToDate) { + this.state = DerivedState.dependenciesMightHaveChanged; + // If we propagate begin update, that will already signal a possible change. + if (!propagateBeginUpdate) { + for (const r of this.observers) { + r.handlePossibleChange(this); + } + } + } + if (propagateBeginUpdate) { + for (const r of this.observers) { + r.beginUpdate(this); // This signals a possible change + } + } + } + + public endUpdate(_observable: IObservable): void { + this.updateCount--; + if (this.updateCount === 0) { + // End update could change the observer list. + const observers = [...this.observers]; + for (const r of observers) { + r.endUpdate(this); + } + } + assertFn(() => this.updateCount >= 0); + } + + public handlePossibleChange(observable: IObservable): void { + // In all other states, observers already know that we might have changed. + if (this.state === DerivedState.upToDate && this.dependencies.has(observable) && !this.dependenciesToBeRemoved.has(observable)) { + this.state = DerivedState.dependenciesMightHaveChanged; + for (const r of this.observers) { + r.handlePossibleChange(this); + } + } + } + + public handleChange(observable: IObservable, change: TChange): void { + if (this.dependencies.has(observable) && !this.dependenciesToBeRemoved.has(observable)) { + const shouldReact = this._handleChange ? this._handleChange({ + changedObservable: observable, + change, + didChange: (o): this is any => o === observable as any, + }, this.changeSummary!) : true; + const wasUpToDate = this.state === DerivedState.upToDate; + if (shouldReact && (this.state === DerivedState.dependenciesMightHaveChanged || wasUpToDate)) { + this.state = DerivedState.stale; + if (wasUpToDate) { + for (const r of this.observers) { + r.handlePossibleChange(this); + } + } + } + } + } + + // IReader Implementation + public readObservable(observable: IObservable): T { + // Subscribe before getting the value to enable caching + observable.addObserver(this); + /** This might call {@link handleChange} indirectly, which could invalidate us */ + const value = observable.get(); + // Which is why we only add the observable to the dependencies now. + this.dependencies.add(observable); + this.dependenciesToBeRemoved.delete(observable); + return value; + } + + public override addObserver(observer: IObserver): void { + const shouldCallBeginUpdate = !this.observers.has(observer) && this.updateCount > 0; + super.addObserver(observer); + + if (shouldCallBeginUpdate) { + observer.beginUpdate(this); + } + } + + public override removeObserver(observer: IObserver): void { + const shouldCallEndUpdate = this.observers.has(observer) && this.updateCount > 0; + super.removeObserver(observer); + + if (shouldCallEndUpdate) { + // Calling end update after removing the observer makes sure endUpdate cannot be called twice here. + observer.endUpdate(this); + } + } +} + + +export class DerivedWithSetter extends Derived implements ISettableObservable { + constructor( + debugNameData: DebugNameData, + computeFn: (reader: IReader, changeSummary: TChangeSummary) => T, + createChangeSummary: (() => TChangeSummary) | undefined, + handleChange: ((context: IChangeContext, summary: TChangeSummary) => boolean) | undefined, + handleLastObserverRemoved: (() => void) | undefined = undefined, + equalityComparator: EqualityComparer, + public readonly set: (value: T, tx: ITransaction | undefined) => void, + ) { + super( + debugNameData, + computeFn, + createChangeSummary, + handleChange, + handleLastObserverRemoved, + equalityComparator, + ); + } +} diff --git a/node_modules/@xterm/xterm/src/vs/base/common/observableInternal/lazyObservableValue.ts b/node_modules/@xterm/xterm/src/vs/base/common/observableInternal/lazyObservableValue.ts new file mode 100644 index 0000000..1c35f45 --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/common/observableInternal/lazyObservableValue.ts @@ -0,0 +1,146 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { EqualityComparer } from 'vs/base/common/equals'; +import { ISettableObservable, ITransaction } from 'vs/base/common/observable'; +import { BaseObservable, IObserver, TransactionImpl } from 'vs/base/common/observableInternal/base'; +import { DebugNameData } from 'vs/base/common/observableInternal/debugName'; + +/** + * Holds off updating observers until the value is actually read. +*/ +export class LazyObservableValue + extends BaseObservable + implements ISettableObservable { + protected _value: T; + private _isUpToDate = true; + private readonly _deltas: TChange[] = []; + + get debugName() { + return this._debugNameData.getDebugName(this) ?? 'LazyObservableValue'; + } + + constructor( + private readonly _debugNameData: DebugNameData, + initialValue: T, + private readonly _equalityComparator: EqualityComparer, + ) { + super(); + this._value = initialValue; + } + + public override get(): T { + this._update(); + return this._value; + } + + private _update(): void { + if (this._isUpToDate) { + return; + } + this._isUpToDate = true; + + if (this._deltas.length > 0) { + for (const observer of this.observers) { + for (const change of this._deltas) { + observer.handleChange(this, change); + } + } + this._deltas.length = 0; + } else { + for (const observer of this.observers) { + observer.handleChange(this, undefined); + } + } + } + + private _updateCounter = 0; + + private _beginUpdate(): void { + this._updateCounter++; + if (this._updateCounter === 1) { + for (const observer of this.observers) { + observer.beginUpdate(this); + } + } + } + + private _endUpdate(): void { + this._updateCounter--; + if (this._updateCounter === 0) { + this._update(); + + // End update could change the observer list. + const observers = [...this.observers]; + for (const r of observers) { + r.endUpdate(this); + } + } + } + + public override addObserver(observer: IObserver): void { + const shouldCallBeginUpdate = !this.observers.has(observer) && this._updateCounter > 0; + super.addObserver(observer); + + if (shouldCallBeginUpdate) { + observer.beginUpdate(this); + } + } + + public override removeObserver(observer: IObserver): void { + const shouldCallEndUpdate = this.observers.has(observer) && this._updateCounter > 0; + super.removeObserver(observer); + + if (shouldCallEndUpdate) { + // Calling end update after removing the observer makes sure endUpdate cannot be called twice here. + observer.endUpdate(this); + } + } + + public set(value: T, tx: ITransaction | undefined, change: TChange): void { + if (change === undefined && this._equalityComparator(this._value, value)) { + return; + } + + let _tx: TransactionImpl | undefined; + if (!tx) { + tx = _tx = new TransactionImpl(() => { }, () => `Setting ${this.debugName}`); + } + try { + this._isUpToDate = false; + this._setValue(value); + if (change !== undefined) { + this._deltas.push(change); + } + + tx.updateObserver({ + beginUpdate: () => this._beginUpdate(), + endUpdate: () => this._endUpdate(), + handleChange: (observable, change) => { }, + handlePossibleChange: (observable) => { }, + }, this); + + if (this._updateCounter > 1) { + // We already started begin/end update, so we need to manually call handlePossibleChange + for (const observer of this.observers) { + observer.handlePossibleChange(this); + } + } + + } finally { + if (_tx) { + _tx.finish(); + } + } + } + + override toString(): string { + return `${this.debugName}: ${this._value}`; + } + + protected _setValue(newValue: T): void { + this._value = newValue; + } +} diff --git a/node_modules/@xterm/xterm/src/vs/base/common/observableInternal/logging.ts b/node_modules/@xterm/xterm/src/vs/base/common/observableInternal/logging.ts new file mode 100644 index 0000000..5e4712e --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/common/observableInternal/logging.ts @@ -0,0 +1,328 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { AutorunObserver } from 'vs/base/common/observableInternal/autorun'; +import { IObservable, ObservableValue, TransactionImpl } from 'vs/base/common/observableInternal/base'; +import { Derived } from 'vs/base/common/observableInternal/derived'; +import { FromEventObservable } from 'vs/base/common/observableInternal/utils'; + +let globalObservableLogger: IObservableLogger | undefined; + +export function setLogger(logger: IObservableLogger): void { + globalObservableLogger = logger; +} + +export function getLogger(): IObservableLogger | undefined { + return globalObservableLogger; +} + +interface IChangeInformation { + oldValue: unknown; + newValue: unknown; + change: unknown; + didChange: boolean; + hadValue: boolean; +} + +export interface IObservableLogger { + handleObservableChanged(observable: ObservableValue, info: IChangeInformation): void; + handleFromEventObservableTriggered(observable: FromEventObservable, info: IChangeInformation): void; + + handleAutorunCreated(autorun: AutorunObserver): void; + handleAutorunTriggered(autorun: AutorunObserver): void; + handleAutorunFinished(autorun: AutorunObserver): void; + + handleDerivedCreated(observable: Derived): void; + handleDerivedRecomputed(observable: Derived, info: IChangeInformation): void; + + handleBeginTransaction(transaction: TransactionImpl): void; + handleEndTransaction(): void; +} + +export class ConsoleObservableLogger implements IObservableLogger { + private indentation = 0; + + private textToConsoleArgs(text: ConsoleText): unknown[] { + return consoleTextToArgs([ + normalText(repeat('| ', this.indentation)), + text, + ]); + } + + private formatInfo(info: IChangeInformation): ConsoleText[] { + if (!info.hadValue) { + return [ + normalText(` `), + styled(formatValue(info.newValue, 60), { + color: 'green', + }), + normalText(` (initial)`), + ]; + } + return info.didChange + ? [ + normalText(` `), + styled(formatValue(info.oldValue, 70), { + color: 'red', + strikeThrough: true, + }), + normalText(` `), + styled(formatValue(info.newValue, 60), { + color: 'green', + }), + ] + : [normalText(` (unchanged)`)]; + } + + handleObservableChanged(observable: IObservable, info: IChangeInformation): void { + console.log(...this.textToConsoleArgs([ + formatKind('observable value changed'), + styled(observable.debugName, { color: 'BlueViolet' }), + ...this.formatInfo(info), + ])); + } + + private readonly changedObservablesSets = new WeakMap>>(); + + formatChanges(changes: Set>): ConsoleText | undefined { + if (changes.size === 0) { + return undefined; + } + return styled( + ' (changed deps: ' + + [...changes].map((o) => o.debugName).join(', ') + + ')', + { color: 'gray' } + ); + } + + handleDerivedCreated(derived: Derived): void { + const existingHandleChange = derived.handleChange; + this.changedObservablesSets.set(derived, new Set()); + derived.handleChange = (observable, change) => { + this.changedObservablesSets.get(derived)!.add(observable); + return existingHandleChange.apply(derived, [observable, change]); + }; + } + + handleDerivedRecomputed(derived: Derived, info: IChangeInformation): void { + const changedObservables = this.changedObservablesSets.get(derived)!; + console.log(...this.textToConsoleArgs([ + formatKind('derived recomputed'), + styled(derived.debugName, { color: 'BlueViolet' }), + ...this.formatInfo(info), + this.formatChanges(changedObservables), + { data: [{ fn: derived._debugNameData.referenceFn ?? derived._computeFn }] } + ])); + changedObservables.clear(); + } + + handleFromEventObservableTriggered(observable: FromEventObservable, info: IChangeInformation): void { + console.log(...this.textToConsoleArgs([ + formatKind('observable from event triggered'), + styled(observable.debugName, { color: 'BlueViolet' }), + ...this.formatInfo(info), + { data: [{ fn: observable._getValue }] } + ])); + } + + handleAutorunCreated(autorun: AutorunObserver): void { + const existingHandleChange = autorun.handleChange; + this.changedObservablesSets.set(autorun, new Set()); + autorun.handleChange = (observable, change) => { + this.changedObservablesSets.get(autorun)!.add(observable); + return existingHandleChange.apply(autorun, [observable, change]); + }; + } + + handleAutorunTriggered(autorun: AutorunObserver): void { + const changedObservables = this.changedObservablesSets.get(autorun)!; + console.log(...this.textToConsoleArgs([ + formatKind('autorun'), + styled(autorun.debugName, { color: 'BlueViolet' }), + this.formatChanges(changedObservables), + { data: [{ fn: autorun._debugNameData.referenceFn ?? autorun._runFn }] } + ])); + changedObservables.clear(); + this.indentation++; + } + + handleAutorunFinished(autorun: AutorunObserver): void { + this.indentation--; + } + + handleBeginTransaction(transaction: TransactionImpl): void { + let transactionName = transaction.getDebugName(); + if (transactionName === undefined) { + transactionName = ''; + } + console.log(...this.textToConsoleArgs([ + formatKind('transaction'), + styled(transactionName, { color: 'BlueViolet' }), + { data: [{ fn: transaction._fn }] } + ])); + this.indentation++; + } + + handleEndTransaction(): void { + this.indentation--; + } +} + +type ConsoleText = + | (ConsoleText | undefined)[] + | { text: string; style: string; data?: unknown[] } + | { data: unknown[] }; + +function consoleTextToArgs(text: ConsoleText): unknown[] { + const styles = new Array(); + const data: unknown[] = []; + let firstArg = ''; + + function process(t: ConsoleText): void { + if ('length' in t) { + for (const item of t) { + if (item) { + process(item); + } + } + } else if ('text' in t) { + firstArg += `%c${t.text}`; + styles.push(t.style); + if (t.data) { + data.push(...t.data); + } + } else if ('data' in t) { + data.push(...t.data); + } + } + + process(text); + + const result = [firstArg, ...styles]; + result.push(...data); + return result; +} + +function normalText(text: string): ConsoleText { + return styled(text, { color: 'black' }); +} + +function formatKind(kind: string): ConsoleText { + return styled(padStr(`${kind}: `, 10), { color: 'black', bold: true }); +} + +function styled( + text: string, + options: { color: string; strikeThrough?: boolean; bold?: boolean } = { + color: 'black', + } +): ConsoleText { + function objToCss(styleObj: Record): string { + return Object.entries(styleObj).reduce( + (styleString, [propName, propValue]) => { + return `${styleString}${propName}:${propValue};`; + }, + '' + ); + } + + const style: Record = { + color: options.color, + }; + if (options.strikeThrough) { + style['text-decoration'] = 'line-through'; + } + if (options.bold) { + style['font-weight'] = 'bold'; + } + + return { + text, + style: objToCss(style), + }; +} + +function formatValue(value: unknown, availableLen: number): string { + switch (typeof value) { + case 'number': + return '' + value; + case 'string': + if (value.length + 2 <= availableLen) { + return `"${value}"`; + } + return `"${value.substr(0, availableLen - 7)}"+...`; + + case 'boolean': + return value ? 'true' : 'false'; + case 'undefined': + return 'undefined'; + case 'object': + if (value === null) { + return 'null'; + } + if (Array.isArray(value)) { + return formatArray(value, availableLen); + } + return formatObject(value, availableLen); + case 'symbol': + return value.toString(); + case 'function': + return `[[Function${value.name ? ' ' + value.name : ''}]]`; + default: + return '' + value; + } +} + +function formatArray(value: unknown[], availableLen: number): string { + let result = '[ '; + let first = true; + for (const val of value) { + if (!first) { + result += ', '; + } + if (result.length - 5 > availableLen) { + result += '...'; + break; + } + first = false; + result += `${formatValue(val, availableLen - result.length)}`; + } + result += ' ]'; + return result; +} + +function formatObject(value: object, availableLen: number): string { + let result = '{ '; + let first = true; + for (const [key, val] of Object.entries(value)) { + if (!first) { + result += ', '; + } + if (result.length - 5 > availableLen) { + result += '...'; + break; + } + first = false; + result += `${key}: ${formatValue(val, availableLen - result.length)}`; + } + result += ' }'; + return result; +} + +function repeat(str: string, count: number): string { + let result = ''; + for (let i = 1; i <= count; i++) { + result += str; + } + return result; +} + +function padStr(str: string, length: number): string { + while (str.length < length) { + str += ' '; + } + return str; +} diff --git a/node_modules/@xterm/xterm/src/vs/base/common/observableInternal/promise.ts b/node_modules/@xterm/xterm/src/vs/base/common/observableInternal/promise.ts new file mode 100644 index 0000000..80d269c --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/common/observableInternal/promise.ts @@ -0,0 +1,209 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +import { autorun } from 'vs/base/common/observableInternal/autorun'; +import { IObservable, IReader, observableValue, transaction } from './base'; +import { Derived, derived } from 'vs/base/common/observableInternal/derived'; +import { CancellationToken, CancellationTokenSource } from 'vs/base/common/cancellation'; +import { DebugNameData, DebugOwner } from 'vs/base/common/observableInternal/debugName'; +import { strictEquals } from 'vs/base/common/equals'; +import { CancellationError } from 'vs/base/common/errors'; + +export class ObservableLazy { + private readonly _value = observableValue(this, undefined); + + /** + * The cached value. + * Does not force a computation of the value. + */ + public get cachedValue(): IObservable { return this._value; } + + constructor(private readonly _computeValue: () => T) { + } + + /** + * Returns the cached value. + * Computes the value if the value has not been cached yet. + */ + public getValue() { + let v = this._value.get(); + if (!v) { + v = this._computeValue(); + this._value.set(v, undefined); + } + return v; + } +} + +/** + * A promise whose state is observable. + */ +export class ObservablePromise { + public static fromFn(fn: () => Promise): ObservablePromise { + return new ObservablePromise(fn()); + } + + private readonly _value = observableValue | undefined>(this, undefined); + + /** + * The promise that this object wraps. + */ + public readonly promise: Promise; + + /** + * The current state of the promise. + * Is `undefined` if the promise didn't resolve yet. + */ + public readonly promiseResult: IObservable | undefined> = this._value; + + constructor(promise: Promise) { + this.promise = promise.then(value => { + transaction(tx => { + /** @description onPromiseResolved */ + this._value.set(new PromiseResult(value, undefined), tx); + }); + return value; + }, error => { + transaction(tx => { + /** @description onPromiseRejected */ + this._value.set(new PromiseResult(undefined, error), tx); + }); + throw error; + }); + } +} + +export class PromiseResult { + constructor( + /** + * The value of the resolved promise. + * Undefined if the promise rejected. + */ + public readonly data: T | undefined, + + /** + * The error in case of a rejected promise. + * Undefined if the promise resolved. + */ + public readonly error: unknown | undefined, + ) { + } + + /** + * Returns the value if the promise resolved, otherwise throws the error. + */ + public getDataOrThrow(): T { + if (this.error) { + throw this.error; + } + return this.data!; + } +} + +/** + * A lazy promise whose state is observable. + */ +export class ObservableLazyPromise { + private readonly _lazyValue = new ObservableLazy(() => new ObservablePromise(this._computePromise())); + + /** + * Does not enforce evaluation of the promise compute function. + * Is undefined if the promise has not been computed yet. + */ + public readonly cachedPromiseResult = derived(this, reader => this._lazyValue.cachedValue.read(reader)?.promiseResult.read(reader)); + + constructor(private readonly _computePromise: () => Promise) { + } + + public getPromise(): Promise { + return this._lazyValue.getValue().promise; + } +} + +/** + * Resolves the promise when the observables state matches the predicate. + */ +export function waitForState(observable: IObservable): Promise; +export function waitForState(observable: IObservable, predicate: (state: T) => state is TState, isError?: (state: T) => boolean | unknown | undefined, cancellationToken?: CancellationToken): Promise; +export function waitForState(observable: IObservable, predicate: (state: T) => boolean, isError?: (state: T) => boolean | unknown | undefined, cancellationToken?: CancellationToken): Promise; +export function waitForState(observable: IObservable, predicate?: (state: T) => boolean, isError?: (state: T) => boolean | unknown | undefined, cancellationToken?: CancellationToken): Promise { + if (!predicate) { + predicate = state => state !== null && state !== undefined; + } + return new Promise((resolve, reject) => { + let isImmediateRun = true; + let shouldDispose = false; + const stateObs = observable.map(state => { + /** @description waitForState.state */ + return { + isFinished: predicate(state), + error: isError ? isError(state) : false, + state + }; + }); + const d = autorun(reader => { + /** @description waitForState */ + const { isFinished, error, state } = stateObs.read(reader); + if (isFinished || error) { + if (isImmediateRun) { + // The variable `d` is not initialized yet + shouldDispose = true; + } else { + d.dispose(); + } + if (error) { + reject(error === true ? state : error); + } else { + resolve(state); + } + } + }); + if (cancellationToken) { + const dc = cancellationToken.onCancellationRequested(() => { + d.dispose(); + dc.dispose(); + reject(new CancellationError()); + }); + if (cancellationToken.isCancellationRequested) { + d.dispose(); + dc.dispose(); + reject(new CancellationError()); + return; + } + } + isImmediateRun = false; + if (shouldDispose) { + d.dispose(); + } + }); +} + +export function derivedWithCancellationToken(computeFn: (reader: IReader, cancellationToken: CancellationToken) => T): IObservable; +export function derivedWithCancellationToken(owner: object, computeFn: (reader: IReader, cancellationToken: CancellationToken) => T): IObservable; +export function derivedWithCancellationToken(computeFnOrOwner: ((reader: IReader, cancellationToken: CancellationToken) => T) | object, computeFnOrUndefined?: ((reader: IReader, cancellationToken: CancellationToken) => T)): IObservable { + let computeFn: (reader: IReader, store: CancellationToken) => T; + let owner: DebugOwner; + if (computeFnOrUndefined === undefined) { + computeFn = computeFnOrOwner as any; + owner = undefined; + } else { + owner = computeFnOrOwner; + computeFn = computeFnOrUndefined as any; + } + + let cancellationTokenSource: CancellationTokenSource | undefined = undefined; + return new Derived( + new DebugNameData(owner, undefined, computeFn), + r => { + if (cancellationTokenSource) { + cancellationTokenSource.dispose(true); + } + cancellationTokenSource = new CancellationTokenSource(); + return computeFn(r, cancellationTokenSource.token); + }, undefined, + undefined, + () => cancellationTokenSource?.dispose(), + strictEquals, + ); +} diff --git a/node_modules/@xterm/xterm/src/vs/base/common/observableInternal/utils.ts b/node_modules/@xterm/xterm/src/vs/base/common/observableInternal/utils.ts new file mode 100644 index 0000000..1d012de --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/common/observableInternal/utils.ts @@ -0,0 +1,610 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { Event } from 'vs/base/common/event'; +import { DisposableStore, IDisposable, toDisposable } from 'vs/base/common/lifecycle'; +import { autorun, autorunOpts } from 'vs/base/common/observableInternal/autorun'; +import { BaseObservable, ConvenientObservable, IObservable, IObserver, IReader, ITransaction, _setKeepObserved, _setRecomputeInitiallyAndOnChange, observableValue, subtransaction, transaction } from 'vs/base/common/observableInternal/base'; +import { DebugNameData, IDebugNameData, DebugOwner, getDebugName, } from 'vs/base/common/observableInternal/debugName'; +import { derived, derivedOpts } from 'vs/base/common/observableInternal/derived'; +import { getLogger } from 'vs/base/common/observableInternal/logging'; +import { IValueWithChangeEvent } from '../event'; +import { BugIndicatingError } from 'vs/base/common/errors'; +import { EqualityComparer, strictEquals } from 'vs/base/common/equals'; + +/** + * Represents an efficient observable whose value never changes. + */ +export function constObservable(value: T): IObservable { + return new ConstObservable(value); +} + +class ConstObservable extends ConvenientObservable { + constructor(private readonly value: T) { + super(); + } + + public override get debugName(): string { + return this.toString(); + } + + public get(): T { + return this.value; + } + public addObserver(observer: IObserver): void { + // NO OP + } + public removeObserver(observer: IObserver): void { + // NO OP + } + + override toString(): string { + return `Const: ${this.value}`; + } +} + + +export function observableFromPromise(promise: Promise): IObservable<{ value?: T }> { + const observable = observableValue<{ value?: T }>('promiseValue', {}); + promise.then((value) => { + observable.set({ value }, undefined); + }); + return observable; +} + + +export function observableFromEvent( + owner: DebugOwner, + event: Event, + getValue: (args: TArgs | undefined) => T, +): IObservable; +export function observableFromEvent( + event: Event, + getValue: (args: TArgs | undefined) => T, +): IObservable; +export function observableFromEvent(...args: + [owner: DebugOwner, event: Event, getValue: (args: any | undefined) => any] + | [event: Event, getValue: (args: any | undefined) => any] +): IObservable { + let owner; + let event; + let getValue; + if (args.length === 3) { + [owner, event, getValue] = args; + } else { + [event, getValue] = args; + } + return new FromEventObservable( + new DebugNameData(owner, undefined, getValue), + event, + getValue, + () => FromEventObservable.globalTransaction, + strictEquals + ); +} + +export function observableFromEventOpts( + options: IDebugNameData & { + equalsFn?: EqualityComparer; + }, + event: Event, + getValue: (args: TArgs | undefined) => T, +): IObservable { + return new FromEventObservable( + new DebugNameData(options.owner, options.debugName, options.debugReferenceFn ?? getValue), + event, + getValue, () => FromEventObservable.globalTransaction, options.equalsFn ?? strictEquals + ); +} + +export class FromEventObservable extends BaseObservable { + public static globalTransaction: ITransaction | undefined; + + private value: T | undefined; + private hasValue = false; + private subscription: IDisposable | undefined; + + constructor( + private readonly _debugNameData: DebugNameData, + private readonly event: Event, + public readonly _getValue: (args: TArgs | undefined) => T, + private readonly _getTransaction: () => ITransaction | undefined, + private readonly _equalityComparator: EqualityComparer + ) { + super(); + } + + private getDebugName(): string | undefined { + return this._debugNameData.getDebugName(this); + } + + public get debugName(): string { + const name = this.getDebugName(); + return 'From Event' + (name ? `: ${name}` : ''); + } + + protected override onFirstObserverAdded(): void { + this.subscription = this.event(this.handleEvent); + } + + private readonly handleEvent = (args: TArgs | undefined) => { + const newValue = this._getValue(args); + const oldValue = this.value; + + const didChange = !this.hasValue || !(this._equalityComparator(oldValue!, newValue)); + let didRunTransaction = false; + + if (didChange) { + this.value = newValue; + + if (this.hasValue) { + didRunTransaction = true; + subtransaction( + this._getTransaction(), + (tx) => { + getLogger()?.handleFromEventObservableTriggered(this, { oldValue, newValue, change: undefined, didChange, hadValue: this.hasValue }); + + for (const o of this.observers) { + tx.updateObserver(o, this); + o.handleChange(this, undefined); + } + }, + () => { + const name = this.getDebugName(); + return 'Event fired' + (name ? `: ${name}` : ''); + } + ); + } + this.hasValue = true; + } + + if (!didRunTransaction) { + getLogger()?.handleFromEventObservableTriggered(this, { oldValue, newValue, change: undefined, didChange, hadValue: this.hasValue }); + } + }; + + protected override onLastObserverRemoved(): void { + this.subscription!.dispose(); + this.subscription = undefined; + this.hasValue = false; + this.value = undefined; + } + + public get(): T { + if (this.subscription) { + if (!this.hasValue) { + this.handleEvent(undefined); + } + return this.value!; + } else { + // no cache, as there are no subscribers to keep it updated + const value = this._getValue(undefined); + return value; + } + } +} + +export namespace observableFromEvent { + export const Observer = FromEventObservable; + + export function batchEventsGlobally(tx: ITransaction, fn: () => void): void { + let didSet = false; + if (FromEventObservable.globalTransaction === undefined) { + FromEventObservable.globalTransaction = tx; + didSet = true; + } + try { + fn(); + } finally { + if (didSet) { + FromEventObservable.globalTransaction = undefined; + } + } + } +} + +export function observableSignalFromEvent( + debugName: string, + event: Event +): IObservable { + return new FromEventObservableSignal(debugName, event); +} + +class FromEventObservableSignal extends BaseObservable { + private subscription: IDisposable | undefined; + + constructor( + public readonly debugName: string, + private readonly event: Event, + ) { + super(); + } + + protected override onFirstObserverAdded(): void { + this.subscription = this.event(this.handleEvent); + } + + private readonly handleEvent = () => { + transaction( + (tx) => { + for (const o of this.observers) { + tx.updateObserver(o, this); + o.handleChange(this, undefined); + } + }, + () => this.debugName + ); + }; + + protected override onLastObserverRemoved(): void { + this.subscription!.dispose(); + this.subscription = undefined; + } + + public override get(): void { + // NO OP + } +} + +/** + * Creates a signal that can be triggered to invalidate observers. + * Signals don't have a value - when they are triggered they indicate a change. + * However, signals can carry a delta that is passed to observers. + */ +export function observableSignal(debugName: string): IObservableSignal; +export function observableSignal(owner: object): IObservableSignal; +export function observableSignal(debugNameOrOwner: string | object): IObservableSignal { + if (typeof debugNameOrOwner === 'string') { + return new ObservableSignal(debugNameOrOwner); + } else { + return new ObservableSignal(undefined, debugNameOrOwner); + } +} + +export interface IObservableSignal extends IObservable { + trigger(tx: ITransaction | undefined, change: TChange): void; +} + +class ObservableSignal extends BaseObservable implements IObservableSignal { + public get debugName() { + return new DebugNameData(this._owner, this._debugName, undefined).getDebugName(this) ?? 'Observable Signal'; + } + + public override toString(): string { + return this.debugName; + } + + constructor( + private readonly _debugName: string | undefined, + private readonly _owner?: object, + ) { + super(); + } + + public trigger(tx: ITransaction | undefined, change: TChange): void { + if (!tx) { + transaction(tx => { + this.trigger(tx, change); + }, () => `Trigger signal ${this.debugName}`); + return; + } + + for (const o of this.observers) { + tx.updateObserver(o, this); + o.handleChange(this, change); + } + } + + public override get(): void { + // NO OP + } +} + +/** + * @deprecated Use `debouncedObservable2` instead. + */ +export function debouncedObservable(observable: IObservable, debounceMs: number, disposableStore: DisposableStore): IObservable { + const debouncedObservable = observableValue('debounced', undefined); + + let timeout: any = undefined; + + disposableStore.add(autorun(reader => { + /** @description debounce */ + const value = observable.read(reader); + + if (timeout) { + clearTimeout(timeout); + } + timeout = setTimeout(() => { + transaction(tx => { + debouncedObservable.set(value, tx); + }); + }, debounceMs); + + })); + + return debouncedObservable; +} + +/** + * Creates an observable that debounces the input observable. + */ +export function debouncedObservable2(observable: IObservable, debounceMs: number): IObservable { + let hasValue = false; + let lastValue: T | undefined; + + let timeout: any = undefined; + + return observableFromEvent(cb => { + const d = autorun(reader => { + const value = observable.read(reader); + + if (!hasValue) { + hasValue = true; + lastValue = value; + } else { + if (timeout) { + clearTimeout(timeout); + } + timeout = setTimeout(() => { + lastValue = value; + cb(); + }, debounceMs); + } + }); + return { + dispose() { + d.dispose(); + hasValue = false; + lastValue = undefined; + }, + }; + }, () => { + if (hasValue) { + return lastValue!; + } else { + return observable.get(); + } + }); +} + +export function wasEventTriggeredRecently(event: Event, timeoutMs: number, disposableStore: DisposableStore): IObservable { + const observable = observableValue('triggeredRecently', false); + + let timeout: any = undefined; + + disposableStore.add(event(() => { + observable.set(true, undefined); + + if (timeout) { + clearTimeout(timeout); + } + timeout = setTimeout(() => { + observable.set(false, undefined); + }, timeoutMs); + })); + + return observable; +} + +/** + * This makes sure the observable is being observed and keeps its cache alive. + */ +export function keepObserved(observable: IObservable): IDisposable { + const o = new KeepAliveObserver(false, undefined); + observable.addObserver(o); + return toDisposable(() => { + observable.removeObserver(o); + }); +} + +_setKeepObserved(keepObserved); + +/** + * This converts the given observable into an autorun. + */ +export function recomputeInitiallyAndOnChange(observable: IObservable, handleValue?: (value: T) => void): IDisposable { + const o = new KeepAliveObserver(true, handleValue); + observable.addObserver(o); + if (handleValue) { + handleValue(observable.get()); + } else { + observable.reportChanges(); + } + + return toDisposable(() => { + observable.removeObserver(o); + }); +} + +_setRecomputeInitiallyAndOnChange(recomputeInitiallyAndOnChange); + +export class KeepAliveObserver implements IObserver { + private _counter = 0; + + constructor( + private readonly _forceRecompute: boolean, + private readonly _handleValue: ((value: any) => void) | undefined, + ) { } + + beginUpdate(observable: IObservable): void { + this._counter++; + } + + endUpdate(observable: IObservable): void { + this._counter--; + if (this._counter === 0 && this._forceRecompute) { + if (this._handleValue) { + this._handleValue(observable.get()); + } else { + observable.reportChanges(); + } + } + } + + handlePossibleChange(observable: IObservable): void { + // NO OP + } + + handleChange(observable: IObservable, change: TChange): void { + // NO OP + } +} + +export function derivedObservableWithCache(owner: DebugOwner, computeFn: (reader: IReader, lastValue: T | undefined) => T): IObservable { + let lastValue: T | undefined = undefined; + const observable = derivedOpts({ owner, debugReferenceFn: computeFn }, reader => { + lastValue = computeFn(reader, lastValue); + return lastValue; + }); + return observable; +} + +export function derivedObservableWithWritableCache(owner: object, computeFn: (reader: IReader, lastValue: T | undefined) => T): IObservable + & { clearCache(transaction: ITransaction): void; setCache(newValue: T | undefined, tx: ITransaction | undefined): void } { + let lastValue: T | undefined = undefined; + const onChange = observableSignal('derivedObservableWithWritableCache'); + const observable = derived(owner, reader => { + onChange.read(reader); + lastValue = computeFn(reader, lastValue); + return lastValue; + }); + return Object.assign(observable, { + clearCache: (tx: ITransaction) => { + lastValue = undefined; + onChange.trigger(tx); + }, + setCache: (newValue: T | undefined, tx: ITransaction | undefined) => { + lastValue = newValue; + onChange.trigger(tx); + } + }); +} + +/** + * When the items array changes, referential equal items are not mapped again. + */ +export function mapObservableArrayCached(owner: DebugOwner, items: IObservable, map: (input: TIn, store: DisposableStore) => TOut, keySelector?: (input: TIn) => TKey): IObservable { + let m = new ArrayMap(map, keySelector); + const self = derivedOpts({ + debugReferenceFn: map, + owner, + onLastObserverRemoved: () => { + m.dispose(); + m = new ArrayMap(map); + } + }, (reader) => { + m.setItems(items.read(reader)); + return m.getItems(); + }); + return self; +} + +class ArrayMap implements IDisposable { + private readonly _cache = new Map(); + private _items: TOut[] = []; + constructor( + private readonly _map: (input: TIn, store: DisposableStore) => TOut, + private readonly _keySelector?: (input: TIn) => TKey, + ) { + } + + public dispose(): void { + this._cache.forEach(entry => entry.store.dispose()); + this._cache.clear(); + } + + public setItems(items: readonly TIn[]): void { + const newItems: TOut[] = []; + const itemsToRemove = new Set(this._cache.keys()); + + for (const item of items) { + const key = this._keySelector ? this._keySelector(item) : item as unknown as TKey; + + let entry = this._cache.get(key); + if (!entry) { + const store = new DisposableStore(); + const out = this._map(item, store); + entry = { out, store }; + this._cache.set(key, entry); + } else { + itemsToRemove.delete(key); + } + newItems.push(entry.out); + } + + for (const item of itemsToRemove) { + const entry = this._cache.get(item)!; + entry.store.dispose(); + this._cache.delete(item); + } + + this._items = newItems; + } + + public getItems(): TOut[] { + return this._items; + } +} + +export class ValueWithChangeEventFromObservable implements IValueWithChangeEvent { + constructor(public readonly observable: IObservable) { + } + + get onDidChange(): Event { + return Event.fromObservableLight(this.observable); + } + + get value(): T { + return this.observable.get(); + } +} + +export function observableFromValueWithChangeEvent(owner: DebugOwner, value: IValueWithChangeEvent): IObservable { + if (value instanceof ValueWithChangeEventFromObservable) { + return value.observable; + } + return observableFromEvent(owner, value.onDidChange, () => value.value); +} + +/** + * Creates an observable that has the latest changed value of the given observables. + * Initially (and when not observed), it has the value of the last observable. + * When observed and any of the observables change, it has the value of the last changed observable. + * If multiple observables change in the same transaction, the last observable wins. +*/ +export function latestChangedValue[]>(owner: DebugOwner, observables: T): IObservable> { + if (observables.length === 0) { + throw new BugIndicatingError(); + } + + let hasLastChangedValue = false; + let lastChangedValue: any = undefined; + + const result = observableFromEvent(owner, cb => { + const store = new DisposableStore(); + for (const o of observables) { + store.add(autorunOpts({ debugName: () => getDebugName(result, new DebugNameData(owner, undefined, undefined)) + '.updateLastChangedValue' }, reader => { + hasLastChangedValue = true; + lastChangedValue = o.read(reader); + cb(); + })); + } + store.add({ + dispose() { + hasLastChangedValue = false; + lastChangedValue = undefined; + }, + }); + return store; + }, () => { + if (hasLastChangedValue) { + return lastChangedValue; + } else { + return observables[observables.length - 1].get(); + } + }); + return result; +} diff --git a/node_modules/@xterm/xterm/src/vs/base/common/platform.ts b/node_modules/@xterm/xterm/src/vs/base/common/platform.ts new file mode 100644 index 0000000..d931e64 --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/common/platform.ts @@ -0,0 +1,281 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import * as nls from 'vs/nls'; + +export const LANGUAGE_DEFAULT = 'en'; + +let _isWindows = false; +let _isMacintosh = false; +let _isLinux = false; +let _isLinuxSnap = false; +let _isNative = false; +let _isWeb = false; +let _isElectron = false; +let _isIOS = false; +let _isCI = false; +let _isMobile = false; +let _locale: string | undefined = undefined; +let _language: string = LANGUAGE_DEFAULT; +let _platformLocale: string = LANGUAGE_DEFAULT; +let _translationsConfigFile: string | undefined = undefined; +let _userAgent: string | undefined = undefined; + +export interface IProcessEnvironment { + [key: string]: string | undefined; +} + +/** + * This interface is intentionally not identical to node.js + * process because it also works in sandboxed environments + * where the process object is implemented differently. We + * define the properties here that we need for `platform` + * to work and nothing else. + */ +export interface INodeProcess { + platform: string; + arch: string; + env: IProcessEnvironment; + versions?: { + node?: string; + electron?: string; + chrome?: string; + }; + type?: string; + cwd: () => string; +} + +declare const process: INodeProcess; + +const $globalThis: any = globalThis; + +let nodeProcess: INodeProcess | undefined = undefined; +if (typeof $globalThis.vscode !== 'undefined' && typeof $globalThis.vscode.process !== 'undefined') { + // Native environment (sandboxed) + nodeProcess = $globalThis.vscode.process; +} else if (typeof process !== 'undefined' && typeof process?.versions?.node === 'string') { + // Native environment (non-sandboxed) + nodeProcess = process; +} + +const isElectronProcess = typeof nodeProcess?.versions?.electron === 'string'; +const isElectronRenderer = isElectronProcess && nodeProcess?.type === 'renderer'; + +interface INavigator { + userAgent: string; + maxTouchPoints?: number; + language: string; +} +declare const navigator: INavigator; + +// Native environment +if (typeof nodeProcess === 'object') { + _isWindows = (nodeProcess.platform === 'win32'); + _isMacintosh = (nodeProcess.platform === 'darwin'); + _isLinux = (nodeProcess.platform === 'linux'); + _isLinuxSnap = _isLinux && !!nodeProcess.env['SNAP'] && !!nodeProcess.env['SNAP_REVISION']; + _isElectron = isElectronProcess; + _isCI = !!nodeProcess.env['CI'] || !!nodeProcess.env['BUILD_ARTIFACTSTAGINGDIRECTORY']; + _locale = LANGUAGE_DEFAULT; + _language = LANGUAGE_DEFAULT; + const rawNlsConfig = nodeProcess.env['VSCODE_NLS_CONFIG']; + if (rawNlsConfig) { + try { + const nlsConfig: nls.INLSConfiguration = JSON.parse(rawNlsConfig); + _locale = nlsConfig.userLocale; + _platformLocale = nlsConfig.osLocale; + _language = nlsConfig.resolvedLanguage || LANGUAGE_DEFAULT; + _translationsConfigFile = nlsConfig.languagePack?.translationsConfigFile; + } catch (e) { + } + } + _isNative = true; +} + +// Web environment +else if (typeof navigator === 'object' && !isElectronRenderer) { + _userAgent = navigator.userAgent; + _isWindows = _userAgent.indexOf('Windows') >= 0; + _isMacintosh = _userAgent.indexOf('Macintosh') >= 0; + _isIOS = (_userAgent.indexOf('Macintosh') >= 0 || _userAgent.indexOf('iPad') >= 0 || _userAgent.indexOf('iPhone') >= 0) && !!navigator.maxTouchPoints && navigator.maxTouchPoints > 0; + _isLinux = _userAgent.indexOf('Linux') >= 0; + _isMobile = _userAgent?.indexOf('Mobi') >= 0; + _isWeb = true; + // VSCODE_GLOBALS: NLS + _language = globalThis._VSCODE_NLS_LANGUAGE || LANGUAGE_DEFAULT; + _locale = navigator.language.toLowerCase(); + _platformLocale = _locale; +} + +// Unknown environment +else { + console.error('Unable to resolve platform.'); +} + +export const enum Platform { + Web, + Mac, + Linux, + Windows +} +export type PlatformName = 'Web' | 'Windows' | 'Mac' | 'Linux'; + +export function PlatformToString(platform: Platform): PlatformName { + switch (platform) { + case Platform.Web: return 'Web'; + case Platform.Mac: return 'Mac'; + case Platform.Linux: return 'Linux'; + case Platform.Windows: return 'Windows'; + } +} + +let _platform: Platform = Platform.Web; +if (_isMacintosh) { + _platform = Platform.Mac; +} else if (_isWindows) { + _platform = Platform.Windows; +} else if (_isLinux) { + _platform = Platform.Linux; +} + +export const isWindows = _isWindows; +export const isMacintosh = _isMacintosh; +export const isLinux = _isLinux; +export const isLinuxSnap = _isLinuxSnap; +export const isNative = _isNative; +export const isElectron = _isElectron; +export const isWeb = _isWeb; +export const isWebWorker = (_isWeb && typeof $globalThis.importScripts === 'function'); +export const webWorkerOrigin = isWebWorker ? $globalThis.origin : undefined; +export const isIOS = _isIOS; +export const isMobile = _isMobile; +/** + * Whether we run inside a CI environment, such as + * GH actions or Azure Pipelines. + */ +export const isCI = _isCI; +export const platform = _platform; +export const userAgent = _userAgent; + +/** + * The language used for the user interface. The format of + * the string is all lower case (e.g. zh-tw for Traditional + * Chinese or de for German) + */ +export const language = _language; + +export namespace Language { + + export function value(): string { + return language; + } + + export function isDefaultVariant(): boolean { + if (language.length === 2) { + return language === 'en'; + } else if (language.length >= 3) { + return language[0] === 'e' && language[1] === 'n' && language[2] === '-'; + } else { + return false; + } + } + + export function isDefault(): boolean { + return language === 'en'; + } +} + +/** + * Desktop: The OS locale or the locale specified by --locale or `argv.json`. + * Web: matches `platformLocale`. + * + * The UI is not necessarily shown in the provided locale. + */ +export const locale = _locale; + +/** + * This will always be set to the OS/browser's locale regardless of + * what was specified otherwise. The format of the string is all + * lower case (e.g. zh-tw for Traditional Chinese). The UI is not + * necessarily shown in the provided locale. + */ +export const platformLocale = _platformLocale; + +/** + * The translations that are available through language packs. + */ +export const translationsConfigFile = _translationsConfigFile; + +export const setTimeout0IsFaster = (typeof $globalThis.postMessage === 'function' && !$globalThis.importScripts); + +/** + * See https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#:~:text=than%204%2C%20then-,set%20timeout%20to%204,-. + * + * Works similarly to `setTimeout(0)` but doesn't suffer from the 4ms artificial delay + * that browsers set when the nesting level is > 5. + */ +export const setTimeout0 = (() => { + if (setTimeout0IsFaster) { + interface IQueueElement { + id: number; + callback: () => void; + } + const pending: IQueueElement[] = []; + + $globalThis.addEventListener('message', (e: any) => { + if (e.data && e.data.vscodeScheduleAsyncWork) { + for (let i = 0, len = pending.length; i < len; i++) { + const candidate = pending[i]; + if (candidate.id === e.data.vscodeScheduleAsyncWork) { + pending.splice(i, 1); + candidate.callback(); + return; + } + } + } + }); + let lastId = 0; + return (callback: () => void) => { + const myId = ++lastId; + pending.push({ + id: myId, + callback: callback + }); + $globalThis.postMessage({ vscodeScheduleAsyncWork: myId }, '*'); + }; + } + return (callback: () => void) => setTimeout(callback); +})(); + +export const enum OperatingSystem { + Windows = 1, + Macintosh = 2, + Linux = 3 +} +export const OS = (_isMacintosh || _isIOS ? OperatingSystem.Macintosh : (_isWindows ? OperatingSystem.Windows : OperatingSystem.Linux)); + +let _isLittleEndian = true; +let _isLittleEndianComputed = false; +export function isLittleEndian(): boolean { + if (!_isLittleEndianComputed) { + _isLittleEndianComputed = true; + const test = new Uint8Array(2); + test[0] = 1; + test[1] = 2; + const view = new Uint16Array(test.buffer); + _isLittleEndian = (view[0] === (2 << 8) + 1); + } + return _isLittleEndian; +} + +export const isChrome = !!(userAgent && userAgent.indexOf('Chrome') >= 0); +export const isFirefox = !!(userAgent && userAgent.indexOf('Firefox') >= 0); +export const isSafari = !!(!isChrome && (userAgent && userAgent.indexOf('Safari') >= 0)); +export const isEdge = !!(userAgent && userAgent.indexOf('Edg/') >= 0); +export const isAndroid = !!(userAgent && userAgent.indexOf('Android') >= 0); + +export function isBigSurOrNewer(osVersion: string): boolean { + return parseFloat(osVersion) >= 20; +} diff --git a/node_modules/@xterm/xterm/src/vs/base/common/scrollable.ts b/node_modules/@xterm/xterm/src/vs/base/common/scrollable.ts new file mode 100644 index 0000000..4d1360c --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/common/scrollable.ts @@ -0,0 +1,522 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { Emitter, Event } from 'vs/base/common/event'; +import { Disposable, IDisposable } from 'vs/base/common/lifecycle'; + +export const enum ScrollbarVisibility { + Auto = 1, + Hidden = 2, + Visible = 3 +} + +export interface ScrollEvent { + inSmoothScrolling: boolean; + + oldWidth: number; + oldScrollWidth: number; + oldScrollLeft: number; + + width: number; + scrollWidth: number; + scrollLeft: number; + + oldHeight: number; + oldScrollHeight: number; + oldScrollTop: number; + + height: number; + scrollHeight: number; + scrollTop: number; + + widthChanged: boolean; + scrollWidthChanged: boolean; + scrollLeftChanged: boolean; + + heightChanged: boolean; + scrollHeightChanged: boolean; + scrollTopChanged: boolean; +} + +export class ScrollState implements IScrollDimensions, IScrollPosition { + _scrollStateBrand: void = undefined; + + public readonly rawScrollLeft: number; + public readonly rawScrollTop: number; + + public readonly width: number; + public readonly scrollWidth: number; + public readonly scrollLeft: number; + public readonly height: number; + public readonly scrollHeight: number; + public readonly scrollTop: number; + + constructor( + private readonly _forceIntegerValues: boolean, + width: number, + scrollWidth: number, + scrollLeft: number, + height: number, + scrollHeight: number, + scrollTop: number + ) { + if (this._forceIntegerValues) { + width = width | 0; + scrollWidth = scrollWidth | 0; + scrollLeft = scrollLeft | 0; + height = height | 0; + scrollHeight = scrollHeight | 0; + scrollTop = scrollTop | 0; + } + + this.rawScrollLeft = scrollLeft; // before validation + this.rawScrollTop = scrollTop; // before validation + + if (width < 0) { + width = 0; + } + if (scrollLeft + width > scrollWidth) { + scrollLeft = scrollWidth - width; + } + if (scrollLeft < 0) { + scrollLeft = 0; + } + + if (height < 0) { + height = 0; + } + if (scrollTop + height > scrollHeight) { + scrollTop = scrollHeight - height; + } + if (scrollTop < 0) { + scrollTop = 0; + } + + this.width = width; + this.scrollWidth = scrollWidth; + this.scrollLeft = scrollLeft; + this.height = height; + this.scrollHeight = scrollHeight; + this.scrollTop = scrollTop; + } + + public equals(other: ScrollState): boolean { + return ( + this.rawScrollLeft === other.rawScrollLeft + && this.rawScrollTop === other.rawScrollTop + && this.width === other.width + && this.scrollWidth === other.scrollWidth + && this.scrollLeft === other.scrollLeft + && this.height === other.height + && this.scrollHeight === other.scrollHeight + && this.scrollTop === other.scrollTop + ); + } + + public withScrollDimensions(update: INewScrollDimensions, useRawScrollPositions: boolean): ScrollState { + return new ScrollState( + this._forceIntegerValues, + (typeof update.width !== 'undefined' ? update.width : this.width), + (typeof update.scrollWidth !== 'undefined' ? update.scrollWidth : this.scrollWidth), + useRawScrollPositions ? this.rawScrollLeft : this.scrollLeft, + (typeof update.height !== 'undefined' ? update.height : this.height), + (typeof update.scrollHeight !== 'undefined' ? update.scrollHeight : this.scrollHeight), + useRawScrollPositions ? this.rawScrollTop : this.scrollTop + ); + } + + public withScrollPosition(update: INewScrollPosition): ScrollState { + return new ScrollState( + this._forceIntegerValues, + this.width, + this.scrollWidth, + (typeof update.scrollLeft !== 'undefined' ? update.scrollLeft : this.rawScrollLeft), + this.height, + this.scrollHeight, + (typeof update.scrollTop !== 'undefined' ? update.scrollTop : this.rawScrollTop) + ); + } + + public createScrollEvent(previous: ScrollState, inSmoothScrolling: boolean): ScrollEvent { + const widthChanged = (this.width !== previous.width); + const scrollWidthChanged = (this.scrollWidth !== previous.scrollWidth); + const scrollLeftChanged = (this.scrollLeft !== previous.scrollLeft); + + const heightChanged = (this.height !== previous.height); + const scrollHeightChanged = (this.scrollHeight !== previous.scrollHeight); + const scrollTopChanged = (this.scrollTop !== previous.scrollTop); + + return { + inSmoothScrolling: inSmoothScrolling, + oldWidth: previous.width, + oldScrollWidth: previous.scrollWidth, + oldScrollLeft: previous.scrollLeft, + + width: this.width, + scrollWidth: this.scrollWidth, + scrollLeft: this.scrollLeft, + + oldHeight: previous.height, + oldScrollHeight: previous.scrollHeight, + oldScrollTop: previous.scrollTop, + + height: this.height, + scrollHeight: this.scrollHeight, + scrollTop: this.scrollTop, + + widthChanged: widthChanged, + scrollWidthChanged: scrollWidthChanged, + scrollLeftChanged: scrollLeftChanged, + + heightChanged: heightChanged, + scrollHeightChanged: scrollHeightChanged, + scrollTopChanged: scrollTopChanged, + }; + } + +} + +export interface IScrollDimensions { + readonly width: number; + readonly scrollWidth: number; + readonly height: number; + readonly scrollHeight: number; +} +export interface INewScrollDimensions { + width?: number; + scrollWidth?: number; + height?: number; + scrollHeight?: number; +} + +export interface IScrollPosition { + readonly scrollLeft: number; + readonly scrollTop: number; +} +export interface ISmoothScrollPosition { + readonly scrollLeft: number; + readonly scrollTop: number; + + readonly width: number; + readonly height: number; +} +export interface INewScrollPosition { + scrollLeft?: number; + scrollTop?: number; +} + +export interface IScrollableOptions { + /** + * Define if the scroll values should always be integers. + */ + forceIntegerValues: boolean; + /** + * Set the duration (ms) used for smooth scroll animations. + */ + smoothScrollDuration: number; + /** + * A function to schedule an update at the next frame (used for smooth scroll animations). + */ + scheduleAtNextAnimationFrame: (callback: () => void) => IDisposable; +} + +export class Scrollable extends Disposable { + + _scrollableBrand: void = undefined; + + private _smoothScrollDuration: number; + private readonly _scheduleAtNextAnimationFrame: (callback: () => void) => IDisposable; + private _state: ScrollState; + private _smoothScrolling: SmoothScrollingOperation | null; + + private _onScroll = this._register(new Emitter()); + public readonly onScroll: Event = this._onScroll.event; + + constructor(options: IScrollableOptions) { + super(); + + this._smoothScrollDuration = options.smoothScrollDuration; + this._scheduleAtNextAnimationFrame = options.scheduleAtNextAnimationFrame; + this._state = new ScrollState(options.forceIntegerValues, 0, 0, 0, 0, 0, 0); + this._smoothScrolling = null; + } + + public override dispose(): void { + if (this._smoothScrolling) { + this._smoothScrolling.dispose(); + this._smoothScrolling = null; + } + super.dispose(); + } + + public setSmoothScrollDuration(smoothScrollDuration: number): void { + this._smoothScrollDuration = smoothScrollDuration; + } + + public validateScrollPosition(scrollPosition: INewScrollPosition): IScrollPosition { + return this._state.withScrollPosition(scrollPosition); + } + + public getScrollDimensions(): IScrollDimensions { + return this._state; + } + + public setScrollDimensions(dimensions: INewScrollDimensions, useRawScrollPositions: boolean): void { + const newState = this._state.withScrollDimensions(dimensions, useRawScrollPositions); + this._setState(newState, Boolean(this._smoothScrolling)); + + // Validate outstanding animated scroll position target + this._smoothScrolling?.acceptScrollDimensions(this._state); + } + + /** + * Returns the final scroll position that the instance will have once the smooth scroll animation concludes. + * If no scroll animation is occurring, it will return the current scroll position instead. + */ + public getFutureScrollPosition(): IScrollPosition { + if (this._smoothScrolling) { + return this._smoothScrolling.to; + } + return this._state; + } + + /** + * Returns the current scroll position. + * Note: This result might be an intermediate scroll position, as there might be an ongoing smooth scroll animation. + */ + public getCurrentScrollPosition(): IScrollPosition { + return this._state; + } + + public setScrollPositionNow(update: INewScrollPosition): void { + // no smooth scrolling requested + const newState = this._state.withScrollPosition(update); + + // Terminate any outstanding smooth scrolling + if (this._smoothScrolling) { + this._smoothScrolling.dispose(); + this._smoothScrolling = null; + } + + this._setState(newState, false); + } + + public setScrollPositionSmooth(update: INewScrollPosition, reuseAnimation?: boolean): void { + if (this._smoothScrollDuration === 0) { + // Smooth scrolling not supported. + return this.setScrollPositionNow(update); + } + + if (this._smoothScrolling) { + // Combine our pending scrollLeft/scrollTop with incoming scrollLeft/scrollTop + update = { + scrollLeft: (typeof update.scrollLeft === 'undefined' ? this._smoothScrolling.to.scrollLeft : update.scrollLeft), + scrollTop: (typeof update.scrollTop === 'undefined' ? this._smoothScrolling.to.scrollTop : update.scrollTop) + }; + + // Validate `update` + const validTarget = this._state.withScrollPosition(update); + + if (this._smoothScrolling.to.scrollLeft === validTarget.scrollLeft && this._smoothScrolling.to.scrollTop === validTarget.scrollTop) { + // No need to interrupt or extend the current animation since we're going to the same place + return; + } + let newSmoothScrolling: SmoothScrollingOperation; + if (reuseAnimation) { + newSmoothScrolling = new SmoothScrollingOperation(this._smoothScrolling.from, validTarget, this._smoothScrolling.startTime, this._smoothScrolling.duration); + } else { + newSmoothScrolling = this._smoothScrolling.combine(this._state, validTarget, this._smoothScrollDuration); + } + this._smoothScrolling.dispose(); + this._smoothScrolling = newSmoothScrolling; + } else { + // Validate `update` + const validTarget = this._state.withScrollPosition(update); + + this._smoothScrolling = SmoothScrollingOperation.start(this._state, validTarget, this._smoothScrollDuration); + } + + // Begin smooth scrolling animation + this._smoothScrolling.animationFrameDisposable = this._scheduleAtNextAnimationFrame(() => { + if (!this._smoothScrolling) { + return; + } + this._smoothScrolling.animationFrameDisposable = null; + this._performSmoothScrolling(); + }); + } + + public hasPendingScrollAnimation(): boolean { + return Boolean(this._smoothScrolling); + } + + private _performSmoothScrolling(): void { + if (!this._smoothScrolling) { + return; + } + const update = this._smoothScrolling.tick(); + const newState = this._state.withScrollPosition(update); + + this._setState(newState, true); + + if (!this._smoothScrolling) { + // Looks like someone canceled the smooth scrolling + // from the scroll event handler + return; + } + + if (update.isDone) { + this._smoothScrolling.dispose(); + this._smoothScrolling = null; + return; + } + + // Continue smooth scrolling animation + this._smoothScrolling.animationFrameDisposable = this._scheduleAtNextAnimationFrame(() => { + if (!this._smoothScrolling) { + return; + } + this._smoothScrolling.animationFrameDisposable = null; + this._performSmoothScrolling(); + }); + } + + private _setState(newState: ScrollState, inSmoothScrolling: boolean): void { + const oldState = this._state; + if (oldState.equals(newState)) { + // no change + return; + } + this._state = newState; + this._onScroll.fire(this._state.createScrollEvent(oldState, inSmoothScrolling)); + } +} + +export class SmoothScrollingUpdate { + + public readonly scrollLeft: number; + public readonly scrollTop: number; + public readonly isDone: boolean; + + constructor(scrollLeft: number, scrollTop: number, isDone: boolean) { + this.scrollLeft = scrollLeft; + this.scrollTop = scrollTop; + this.isDone = isDone; + } + +} + +interface IAnimation { + (completion: number): number; +} + +function createEaseOutCubic(from: number, to: number): IAnimation { + const delta = to - from; + return function (completion: number): number { + return from + delta * easeOutCubic(completion); + }; +} + +function createComposed(a: IAnimation, b: IAnimation, cut: number): IAnimation { + return function (completion: number): number { + if (completion < cut) { + return a(completion / cut); + } + return b((completion - cut) / (1 - cut)); + }; +} + +export class SmoothScrollingOperation { + + public readonly from: ISmoothScrollPosition; + public to: ISmoothScrollPosition; + public readonly duration: number; + public readonly startTime: number; + public animationFrameDisposable: IDisposable | null; + + private scrollLeft!: IAnimation; + private scrollTop!: IAnimation; + + constructor(from: ISmoothScrollPosition, to: ISmoothScrollPosition, startTime: number, duration: number) { + this.from = from; + this.to = to; + this.duration = duration; + this.startTime = startTime; + + this.animationFrameDisposable = null; + + this._initAnimations(); + } + + private _initAnimations(): void { + this.scrollLeft = this._initAnimation(this.from.scrollLeft, this.to.scrollLeft, this.to.width); + this.scrollTop = this._initAnimation(this.from.scrollTop, this.to.scrollTop, this.to.height); + } + + private _initAnimation(from: number, to: number, viewportSize: number): IAnimation { + const delta = Math.abs(from - to); + if (delta > 2.5 * viewportSize) { + let stop1: number, stop2: number; + if (from < to) { + // scroll to 75% of the viewportSize + stop1 = from + 0.75 * viewportSize; + stop2 = to - 0.75 * viewportSize; + } else { + stop1 = from - 0.75 * viewportSize; + stop2 = to + 0.75 * viewportSize; + } + return createComposed(createEaseOutCubic(from, stop1), createEaseOutCubic(stop2, to), 0.33); + } + return createEaseOutCubic(from, to); + } + + public dispose(): void { + if (this.animationFrameDisposable !== null) { + this.animationFrameDisposable.dispose(); + this.animationFrameDisposable = null; + } + } + + public acceptScrollDimensions(state: ScrollState): void { + this.to = state.withScrollPosition(this.to); + this._initAnimations(); + } + + public tick(): SmoothScrollingUpdate { + return this._tick(Date.now()); + } + + protected _tick(now: number): SmoothScrollingUpdate { + const completion = (now - this.startTime) / this.duration; + + if (completion < 1) { + const newScrollLeft = this.scrollLeft(completion); + const newScrollTop = this.scrollTop(completion); + return new SmoothScrollingUpdate(newScrollLeft, newScrollTop, false); + } + + return new SmoothScrollingUpdate(this.to.scrollLeft, this.to.scrollTop, true); + } + + public combine(from: ISmoothScrollPosition, to: ISmoothScrollPosition, duration: number): SmoothScrollingOperation { + return SmoothScrollingOperation.start(from, to, duration); + } + + public static start(from: ISmoothScrollPosition, to: ISmoothScrollPosition, duration: number): SmoothScrollingOperation { + // +10 / -10 : pretend the animation already started for a quicker response to a scroll request + duration = duration + 10; + const startTime = Date.now() - 10; + + return new SmoothScrollingOperation(from, to, startTime, duration); + } +} + +function easeInCubic(t: number) { + return Math.pow(t, 3); +} + +function easeOutCubic(t: number) { + return 1 - easeInCubic(1 - t); +} diff --git a/node_modules/@xterm/xterm/src/vs/base/common/sequence.ts b/node_modules/@xterm/xterm/src/vs/base/common/sequence.ts new file mode 100644 index 0000000..b68bc7c --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/common/sequence.ts @@ -0,0 +1,34 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { Emitter, Event } from 'vs/base/common/event'; + +export interface ISplice { + readonly start: number; + readonly deleteCount: number; + readonly toInsert: readonly T[]; +} + +export interface ISpliceable { + splice(start: number, deleteCount: number, toInsert: readonly T[]): void; +} + +export interface ISequence { + readonly elements: T[]; + readonly onDidSplice: Event>; +} + +export class Sequence implements ISequence, ISpliceable { + + readonly elements: T[] = []; + + private readonly _onDidSplice = new Emitter>(); + readonly onDidSplice: Event> = this._onDidSplice.event; + + splice(start: number, deleteCount: number, toInsert: readonly T[] = []): void { + this.elements.splice(start, deleteCount, ...toInsert); + this._onDidSplice.fire({ start, deleteCount, toInsert }); + } +} diff --git a/node_modules/@xterm/xterm/src/vs/base/common/stopwatch.ts b/node_modules/@xterm/xterm/src/vs/base/common/stopwatch.ts new file mode 100644 index 0000000..e32c0dd --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/common/stopwatch.ts @@ -0,0 +1,43 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +// fake definition so that the valid layers check won't trip on this +declare const globalThis: { performance?: { now(): number } }; + +const hasPerformanceNow = (globalThis.performance && typeof globalThis.performance.now === 'function'); + +export class StopWatch { + + private _startTime: number; + private _stopTime: number; + + private readonly _now: () => number; + + public static create(highResolution?: boolean): StopWatch { + return new StopWatch(highResolution); + } + + constructor(highResolution?: boolean) { + this._now = hasPerformanceNow && highResolution === false ? Date.now : globalThis.performance!.now.bind(globalThis.performance); + this._startTime = this._now(); + this._stopTime = -1; + } + + public stop(): void { + this._stopTime = this._now(); + } + + public reset(): void { + this._startTime = this._now(); + this._stopTime = -1; + } + + public elapsed(): number { + if (this._stopTime !== -1) { + return this._stopTime - this._startTime; + } + return this._now() - this._startTime; + } +} diff --git a/node_modules/@xterm/xterm/src/vs/base/common/strings.ts b/node_modules/@xterm/xterm/src/vs/base/common/strings.ts new file mode 100644 index 0000000..74b4f00 --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/common/strings.ts @@ -0,0 +1,557 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { CharCode } from 'vs/base/common/charCode'; +import { Constants } from 'vs/base/common/uint'; + +export function isFalsyOrWhitespace(str: string | undefined): boolean { + if (!str || typeof str !== 'string') { + return true; + } + return str.trim().length === 0; +} + +const _formatRegexp = /{(\d+)}/g; + +/** + * Helper to produce a string with a variable number of arguments. Insert variable segments + * into the string using the {n} notation where N is the index of the argument following the string. + * @param value string to which formatting is applied + * @param args replacements for {n}-entries + */ +export function format(value: string, ...args: any[]): string { + if (args.length === 0) { + return value; + } + return value.replace(_formatRegexp, function (match, group) { + const idx = parseInt(group, 10); + return isNaN(idx) || idx < 0 || idx >= args.length ? + match : + args[idx]; + }); +} + +const _format2Regexp = /{([^}]+)}/g; + +/** + * Helper to create a string from a template and a string record. + * Similar to `format` but with objects instead of positional arguments. + */ +export function format2(template: string, values: Record): string { + if (Object.keys(values).length === 0) { + return template; + } + return template.replace(_format2Regexp, (match, group) => (values[group] ?? match) as string); +} + +/** + * Encodes the given value so that it can be used as literal value in html attributes. + * + * In other words, computes `$val`, such that `attr` in `
` has the runtime value `value`. + * This prevents XSS injection. + */ +export function htmlAttributeEncodeValue(value: string): string { + return value.replace(/[<>"'&]/g, ch => { + switch (ch) { + case '<': return '<'; + case '>': return '>'; + case '"': return '"'; + case '\'': return '''; + case '&': return '&'; + } + return ch; + }); +} + +/** + * Converts HTML characters inside the string to use entities instead. Makes the string safe from + * being used e.g. in HTMLElement.innerHTML. + */ +export function escape(html: string): string { + return html.replace(/[<>&]/g, function (match) { + switch (match) { + case '<': return '<'; + case '>': return '>'; + case '&': return '&'; + default: return match; + } + }); +} + +/** + * Escapes regular expression characters in a given string + */ +export function escapeRegExpCharacters(value: string): string { + return value.replace(/[\\\{\}\*\+\?\|\^\$\.\[\]\(\)]/g, '\\$&'); +} + +/** + * Counts how often `substr` occurs inside `value`. + */ +export function count(value: string, substr: string): number { + let result = 0; + let index = value.indexOf(substr); + while (index !== -1) { + result++; + index = value.indexOf(substr, index + substr.length); + } + return result; +} + +export function truncate(value: string, maxLength: number, suffix = '…'): string { + if (value.length <= maxLength) { + return value; + } + + return `${value.substr(0, maxLength)}${suffix}`; +} + +export function truncateMiddle(value: string, maxLength: number, suffix = '…'): string { + if (value.length <= maxLength) { + return value; + } + + const prefixLength = Math.ceil(maxLength / 2) - suffix.length / 2; + const suffixLength = Math.floor(maxLength / 2) - suffix.length / 2; + + return `${value.substr(0, prefixLength)}${suffix}${value.substr(value.length - suffixLength)}`; +} + +/** + * Removes all occurrences of needle from the beginning and end of haystack. + * @param haystack string to trim + * @param needle the thing to trim (default is a blank) + */ +export function trim(haystack: string, needle: string = ' '): string { + const trimmed = ltrim(haystack, needle); + return rtrim(trimmed, needle); +} + +/** + * Removes all occurrences of needle from the beginning of haystack. + * @param haystack string to trim + * @param needle the thing to trim + */ +export function ltrim(haystack: string, needle: string): string { + if (!haystack || !needle) { + return haystack; + } + + const needleLen = needle.length; + if (needleLen === 0 || haystack.length === 0) { + return haystack; + } + + let offset = 0; + + while (haystack.indexOf(needle, offset) === offset) { + offset = offset + needleLen; + } + return haystack.substring(offset); +} + +/** + * Removes all occurrences of needle from the end of haystack. + * @param haystack string to trim + * @param needle the thing to trim + */ +export function rtrim(haystack: string, needle: string): string { + if (!haystack || !needle) { + return haystack; + } + + const needleLen = needle.length, + haystackLen = haystack.length; + + if (needleLen === 0 || haystackLen === 0) { + return haystack; + } + + let offset = haystackLen, + idx = -1; + + while (true) { + idx = haystack.lastIndexOf(needle, offset - 1); + if (idx === -1 || idx + needleLen !== offset) { + break; + } + if (idx === 0) { + return ''; + } + offset = idx; + } + + return haystack.substring(0, offset); +} + +export function convertSimple2RegExpPattern(pattern: string): string { + return pattern.replace(/[\-\\\{\}\+\?\|\^\$\.\,\[\]\(\)\#\s]/g, '\\$&').replace(/[\*]/g, '.*'); +} + +export function stripWildcards(pattern: string): string { + return pattern.replace(/\*/g, ''); +} + +export interface RegExpOptions { + matchCase?: boolean; + wholeWord?: boolean; + multiline?: boolean; + global?: boolean; + unicode?: boolean; +} + +export function createRegExp(searchString: string, isRegex: boolean, options: RegExpOptions = {}): RegExp { + if (!searchString) { + throw new Error('Cannot create regex from empty string'); + } + if (!isRegex) { + searchString = escapeRegExpCharacters(searchString); + } + if (options.wholeWord) { + if (!/\B/.test(searchString.charAt(0))) { + searchString = '\\b' + searchString; + } + if (!/\B/.test(searchString.charAt(searchString.length - 1))) { + searchString = searchString + '\\b'; + } + } + let modifiers = ''; + if (options.global) { + modifiers += 'g'; + } + if (!options.matchCase) { + modifiers += 'i'; + } + if (options.multiline) { + modifiers += 'm'; + } + if (options.unicode) { + modifiers += 'u'; + } + + return new RegExp(searchString, modifiers); +} + +export function regExpLeadsToEndlessLoop(regexp: RegExp): boolean { + // Exit early if it's one of these special cases which are meant to match + // against an empty string + if (regexp.source === '^' || regexp.source === '^$' || regexp.source === '$' || regexp.source === '^\\s*$') { + return false; + } + + // We check against an empty string. If the regular expression doesn't advance + // (e.g. ends in an endless loop) it will match an empty string. + const match = regexp.exec(''); + return !!(match && regexp.lastIndex === 0); +} + +export function splitLines(str: string): string[] { + return str.split(/\r\n|\r|\n/); +} + +export function splitLinesIncludeSeparators(str: string): string[] { + const linesWithSeparators: string[] = []; + const splitLinesAndSeparators = str.split(/(\r\n|\r|\n)/); + for (let i = 0; i < Math.ceil(splitLinesAndSeparators.length / 2); i++) { + linesWithSeparators.push(splitLinesAndSeparators[2 * i] + (splitLinesAndSeparators[2 * i + 1] ?? '')); + } + return linesWithSeparators; +} + +/** + * Returns first index of the string that is not whitespace. + * If string is empty or contains only whitespaces, returns -1 + */ +export function firstNonWhitespaceIndex(str: string): number { + for (let i = 0, len = str.length; i < len; i++) { + const chCode = str.charCodeAt(i); + if (chCode !== CharCode.Space && chCode !== CharCode.Tab) { + return i; + } + } + return -1; +} + +/** + * Returns the leading whitespace of the string. + * If the string contains only whitespaces, returns entire string + */ +export function getLeadingWhitespace(str: string, start: number = 0, end: number = str.length): string { + for (let i = start; i < end; i++) { + const chCode = str.charCodeAt(i); + if (chCode !== CharCode.Space && chCode !== CharCode.Tab) { + return str.substring(start, i); + } + } + return str.substring(start, end); +} + +/** + * Returns last index of the string that is not whitespace. + * If string is empty or contains only whitespaces, returns -1 + */ +export function lastNonWhitespaceIndex(str: string, startIndex: number = str.length - 1): number { + for (let i = startIndex; i >= 0; i--) { + const chCode = str.charCodeAt(i); + if (chCode !== CharCode.Space && chCode !== CharCode.Tab) { + return i; + } + } + return -1; +} + +/** + * Function that works identically to String.prototype.replace, except, the + * replace function is allowed to be async and return a Promise. + */ +export function replaceAsync(str: string, search: RegExp, replacer: (match: string, ...args: any[]) => Promise): Promise { + const parts: (string | Promise)[] = []; + + let last = 0; + for (const match of str.matchAll(search)) { + parts.push(str.slice(last, match.index)); + if (match.index === undefined) { + throw new Error('match.index should be defined'); + } + + last = match.index + match[0].length; + parts.push(replacer(match[0], ...match.slice(1), match.index, str, match.groups)); + } + + parts.push(str.slice(last)); + + return Promise.all(parts).then(p => p.join('')); +} + +export function compare(a: string, b: string): number { + if (a < b) { + return -1; + } else if (a > b) { + return 1; + } else { + return 0; + } +} + +export function compareSubstring(a: string, b: string, aStart: number = 0, aEnd: number = a.length, bStart: number = 0, bEnd: number = b.length): number { + for (; aStart < aEnd && bStart < bEnd; aStart++, bStart++) { + const codeA = a.charCodeAt(aStart); + const codeB = b.charCodeAt(bStart); + if (codeA < codeB) { + return -1; + } else if (codeA > codeB) { + return 1; + } + } + const aLen = aEnd - aStart; + const bLen = bEnd - bStart; + if (aLen < bLen) { + return -1; + } else if (aLen > bLen) { + return 1; + } + return 0; +} + +export function compareIgnoreCase(a: string, b: string): number { + return compareSubstringIgnoreCase(a, b, 0, a.length, 0, b.length); +} + +export function compareSubstringIgnoreCase(a: string, b: string, aStart: number = 0, aEnd: number = a.length, bStart: number = 0, bEnd: number = b.length): number { + + for (; aStart < aEnd && bStart < bEnd; aStart++, bStart++) { + + let codeA = a.charCodeAt(aStart); + let codeB = b.charCodeAt(bStart); + + if (codeA === codeB) { + // equal + continue; + } + + if (codeA >= 128 || codeB >= 128) { + // not ASCII letters -> fallback to lower-casing strings + return compareSubstring(a.toLowerCase(), b.toLowerCase(), aStart, aEnd, bStart, bEnd); + } + + // mapper lower-case ascii letter onto upper-case varinats + // [97-122] (lower ascii) --> [65-90] (upper ascii) + if (isLowerAsciiLetter(codeA)) { + codeA -= 32; + } + if (isLowerAsciiLetter(codeB)) { + codeB -= 32; + } + + // compare both code points + const diff = codeA - codeB; + if (diff === 0) { + continue; + } + + return diff; + } + + const aLen = aEnd - aStart; + const bLen = bEnd - bStart; + + if (aLen < bLen) { + return -1; + } else if (aLen > bLen) { + return 1; + } + + return 0; +} + +export function isAsciiDigit(code: number): boolean { + return code >= CharCode.Digit0 && code <= CharCode.Digit9; +} + +export function isLowerAsciiLetter(code: number): boolean { + return code >= CharCode.a && code <= CharCode.z; +} + +export function isUpperAsciiLetter(code: number): boolean { + return code >= CharCode.A && code <= CharCode.Z; +} + +export function equalsIgnoreCase(a: string, b: string): boolean { + return a.length === b.length && compareSubstringIgnoreCase(a, b) === 0; +} + +export function startsWithIgnoreCase(str: string, candidate: string): boolean { + const candidateLength = candidate.length; + if (candidate.length > str.length) { + return false; + } + + return compareSubstringIgnoreCase(str, candidate, 0, candidateLength) === 0; +} + +/** + * @returns the length of the common prefix of the two strings. + */ +export function commonPrefixLength(a: string, b: string): number { + + const len = Math.min(a.length, b.length); + let i: number; + + for (i = 0; i < len; i++) { + if (a.charCodeAt(i) !== b.charCodeAt(i)) { + return i; + } + } + + return len; +} + +/** + * @returns the length of the common suffix of the two strings. + */ +export function commonSuffixLength(a: string, b: string): number { + + const len = Math.min(a.length, b.length); + let i: number; + + const aLastIndex = a.length - 1; + const bLastIndex = b.length - 1; + + for (i = 0; i < len; i++) { + if (a.charCodeAt(aLastIndex - i) !== b.charCodeAt(bLastIndex - i)) { + return i; + } + } + + return len; +} + +/** + * See http://en.wikipedia.org/wiki/Surrogate_pair + */ +export function isHighSurrogate(charCode: number): boolean { + return (0xD800 <= charCode && charCode <= 0xDBFF); +} + +/** + * See http://en.wikipedia.org/wiki/Surrogate_pair + */ +export function isLowSurrogate(charCode: number): boolean { + return (0xDC00 <= charCode && charCode <= 0xDFFF); +} + +/** + * See http://en.wikipedia.org/wiki/Surrogate_pair + */ +export function computeCodePoint(highSurrogate: number, lowSurrogate: number): number { + return ((highSurrogate - 0xD800) << 10) + (lowSurrogate - 0xDC00) + 0x10000; +} + +/** + * get the code point that begins at offset `offset` + */ +export function getNextCodePoint(str: string, len: number, offset: number): number { + const charCode = str.charCodeAt(offset); + if (isHighSurrogate(charCode) && offset + 1 < len) { + const nextCharCode = str.charCodeAt(offset + 1); + if (isLowSurrogate(nextCharCode)) { + return computeCodePoint(charCode, nextCharCode); + } + } + return charCode; +} + +/** + * get the code point that ends right before offset `offset` + */ +function getPrevCodePoint(str: string, offset: number): number { + const charCode = str.charCodeAt(offset - 1); + if (isLowSurrogate(charCode) && offset > 1) { + const prevCharCode = str.charCodeAt(offset - 2); + if (isHighSurrogate(prevCharCode)) { + return computeCodePoint(prevCharCode, charCode); + } + } + return charCode; +} + +export class CodePointIterator { + + private readonly _str: string; + private readonly _len: number; + private _offset: number; + + public get offset(): number { + return this._offset; + } + + constructor(str: string, offset: number = 0) { + this._str = str; + this._len = str.length; + this._offset = offset; + } + + public setOffset(offset: number): void { + this._offset = offset; + } + + public prevCodePoint(): number { + const codePoint = getPrevCodePoint(this._str, this._offset); + this._offset -= (codePoint >= Constants.UNICODE_SUPPLEMENTARY_PLANE_BEGIN ? 2 : 1); + return codePoint; + } + + public nextCodePoint(): number { + const codePoint = getNextCodePoint(this._str, this._len, this._offset); + this._offset += (codePoint >= Constants.UNICODE_SUPPLEMENTARY_PLANE_BEGIN ? 2 : 1); + return codePoint; + } + + public eol(): boolean { + return (this._offset >= this._len); + } +} + +export const noBreakWhitespace = '\xa0'; diff --git a/node_modules/@xterm/xterm/src/vs/base/common/symbols.ts b/node_modules/@xterm/xterm/src/vs/base/common/symbols.ts new file mode 100644 index 0000000..9aa8e5b --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/common/symbols.ts @@ -0,0 +1,9 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +/** + * Can be passed into the Delayed to defer using a microtask + * */ +export const MicrotaskDelay = Symbol('MicrotaskDelay'); diff --git a/node_modules/@xterm/xterm/src/vs/base/common/uint.ts b/node_modules/@xterm/xterm/src/vs/base/common/uint.ts new file mode 100644 index 0000000..347af57 --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/base/common/uint.ts @@ -0,0 +1,59 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +export const enum Constants { + /** + * MAX SMI (SMall Integer) as defined in v8. + * one bit is lost for boxing/unboxing flag. + * one bit is lost for sign flag. + * See https://thibaultlaurens.github.io/javascript/2013/04/29/how-the-v8-engine-works/#tagged-values + */ + MAX_SAFE_SMALL_INTEGER = 1 << 30, + + /** + * MIN SMI (SMall Integer) as defined in v8. + * one bit is lost for boxing/unboxing flag. + * one bit is lost for sign flag. + * See https://thibaultlaurens.github.io/javascript/2013/04/29/how-the-v8-engine-works/#tagged-values + */ + MIN_SAFE_SMALL_INTEGER = -(1 << 30), + + /** + * Max unsigned integer that fits on 8 bits. + */ + MAX_UINT_8 = 255, // 2^8 - 1 + + /** + * Max unsigned integer that fits on 16 bits. + */ + MAX_UINT_16 = 65535, // 2^16 - 1 + + /** + * Max unsigned integer that fits on 32 bits. + */ + MAX_UINT_32 = 4294967295, // 2^32 - 1 + + UNICODE_SUPPLEMENTARY_PLANE_BEGIN = 0x010000 +} + +export function toUint8(v: number): number { + if (v < 0) { + return 0; + } + if (v > Constants.MAX_UINT_8) { + return Constants.MAX_UINT_8; + } + return v | 0; +} + +export function toUint32(v: number): number { + if (v < 0) { + return 0; + } + if (v > Constants.MAX_UINT_32) { + return Constants.MAX_UINT_32; + } + return v | 0; +} diff --git a/node_modules/@xterm/xterm/src/vs/patches/nls.ts b/node_modules/@xterm/xterm/src/vs/patches/nls.ts new file mode 100644 index 0000000..1661dfb --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/patches/nls.ts @@ -0,0 +1,90 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +export interface ILocalizeInfo { + key: string; + comment: string[]; +} + +export function localize(info: ILocalizeInfo | string, message: string, ...args: (string | number | boolean | undefined | null)[]): string { + return message; +} + +export interface INLSLanguagePackConfiguration { + + /** + * The path to the translations config file that contains pointers to + * all message bundles for `main` and extensions. + */ + readonly translationsConfigFile: string; + + /** + * The path to the file containing the translations for this language + * pack as flat string array. + */ + readonly messagesFile: string; + + /** + * The path to the file that can be used to signal a corrupt language + * pack, for example when reading the `messagesFile` fails. This will + * instruct the application to re-create the cache on next startup. + */ + readonly corruptMarkerFile: string; +} + +export interface INLSConfiguration { + + /** + * Locale as defined in `argv.json` or `app.getLocale()`. + */ + readonly userLocale: string; + + /** + * Locale as defined by the OS (e.g. `app.getPreferredSystemLanguages()`). + */ + readonly osLocale: string; + + /** + * The actual language of the UI that ends up being used considering `userLocale` + * and `osLocale`. + */ + readonly resolvedLanguage: string; + + /** + * Defined if a language pack is used that is not the + * default english language pack. This requires a language + * pack to be installed as extension. + */ + readonly languagePack?: INLSLanguagePackConfiguration; + + /** + * The path to the file containing the default english messages + * as flat string array. The file is only present in built + * versions of the application. + */ + readonly defaultMessagesFile: string; + + /** + * Below properties are deprecated and only there to continue support + * for `vscode-nls` module that depends on them. + * Refs https://github.com/microsoft/vscode-nls/blob/main/src/node/main.ts#L36-L46 + */ + /** @deprecated */ + readonly locale: string; + /** @deprecated */ + readonly availableLanguages: Record; + /** @deprecated */ + readonly _languagePackSupport?: boolean; + /** @deprecated */ + readonly _languagePackId?: string; + /** @deprecated */ + readonly _translationsConfigFile?: string; + /** @deprecated */ + readonly _cacheRoot?: string; + /** @deprecated */ + readonly _resolvedLanguagePackCoreLocation?: string; + /** @deprecated */ + readonly _corruptedFile?: string; +} diff --git a/node_modules/@xterm/xterm/src/vs/typings/base-common.d.ts b/node_modules/@xterm/xterm/src/vs/typings/base-common.d.ts new file mode 100644 index 0000000..4fc7b59 --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/typings/base-common.d.ts @@ -0,0 +1,20 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +// Declare types that we probe for to implement util and/or polyfill functions + +declare global { + + interface IdleDeadline { + readonly didTimeout: boolean; + timeRemaining(): number; + } + + function requestIdleCallback(callback: (args: IdleDeadline) => void, options?: { timeout: number }): number; + function cancelIdleCallback(handle: number): void; + +} + +export { } diff --git a/node_modules/@xterm/xterm/src/vs/typings/require.d.ts b/node_modules/@xterm/xterm/src/vs/typings/require.d.ts new file mode 100644 index 0000000..7934279 --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/typings/require.d.ts @@ -0,0 +1,42 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +declare class LoaderEvent { + readonly type: number; + readonly timestamp: number; + readonly detail: string; +} + +declare const define: { + (moduleName: string, dependencies: string[], callback: (...args: any[]) => any): any; + (moduleName: string, dependencies: string[], definition: any): any; + (moduleName: string, callback: (...args: any[]) => any): any; + (moduleName: string, definition: any): any; + (dependencies: string[], callback: (...args: any[]) => any): any; + (dependencies: string[], definition: any): any; +}; + +interface NodeRequire { + /** + * @deprecated use `FileAccess.asFileUri()` for node.js contexts or `FileAccess.asBrowserUri` for browser contexts. + */ + toUrl(path: string): string; + + /** + * @deprecated MUST not be used anymore + * + * With the move from AMD to ESM we cannot use this anymore. There will be NO MORE node require like this. + */ + __$__nodeRequire(moduleName: string): T; + + (dependencies: string[], callback: (...args: any[]) => any, errorback?: (err: any) => void): any; + config(data: any): any; + onError: Function; + getStats?(): ReadonlyArray; + hasDependencyCycle?(): boolean; + define(amdModuleId: string, dependencies: string[], callback: (...args: any[]) => any): any; +} + +declare var require: NodeRequire; diff --git a/node_modules/@xterm/xterm/src/vs/typings/vscode-globals-nls.d.ts b/node_modules/@xterm/xterm/src/vs/typings/vscode-globals-nls.d.ts new file mode 100644 index 0000000..bc48076 --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/typings/vscode-globals-nls.d.ts @@ -0,0 +1,36 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +// AMD2ESM mirgation relevant + +/** + * NLS Globals: these need to be defined in all contexts that make + * use of our `nls.localize` and `nls.localize2` functions. This includes: + * - Electron main process + * - Electron window (renderer) process + * - Utility Process + * - Node.js + * - Browser + * - Web worker + * + * That is because during build time we strip out all english strings from + * the resulting JS code and replace it with a that is then looked + * up from the `_VSCODE_NLS_MESSAGES` array. + */ +declare global { + /** + * All NLS messages produced by `localize` and `localize2` calls + * under `src/vs` translated to the language as indicated by + * `_VSCODE_NLS_LANGUAGE`. + */ + var _VSCODE_NLS_MESSAGES: string[]; + /** + * The actual language of the NLS messages (e.g. 'en', de' or 'pt-br'). + */ + var _VSCODE_NLS_LANGUAGE: string | undefined; +} + +// fake export to make global work +export { } diff --git a/node_modules/@xterm/xterm/src/vs/typings/vscode-globals-product.d.ts b/node_modules/@xterm/xterm/src/vs/typings/vscode-globals-product.d.ts new file mode 100644 index 0000000..f6aa62b --- /dev/null +++ b/node_modules/@xterm/xterm/src/vs/typings/vscode-globals-product.d.ts @@ -0,0 +1,33 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +// AMD2ESM mirgation relevant + +declare global { + + /** + * Holds the file root for resources. + */ + var _VSCODE_FILE_ROOT: string; + + /** + * CSS loader that's available during development time. + * DO NOT call directly, instead just import css modules, like `import 'some.css'` + */ + var _VSCODE_CSS_LOAD: (module: string) => void; + + /** + * @deprecated You MUST use `IProductService` whenever possible. + */ + var _VSCODE_PRODUCT_JSON: Record; + /** + * @deprecated You MUST use `IProductService` whenever possible. + */ + var _VSCODE_PACKAGE_JSON: Record; + +} + +// fake export to make global work +export { } diff --git a/node_modules/@xterm/xterm/typings/xterm.d.ts b/node_modules/@xterm/xterm/typings/xterm.d.ts new file mode 100644 index 0000000..457f161 --- /dev/null +++ b/node_modules/@xterm/xterm/typings/xterm.d.ts @@ -0,0 +1,1957 @@ +/** + * @license MIT + * + * This contains the type declarations for the xterm.js library. Note that + * some interfaces differ between this file and the actual implementation in + * src/, that's because this file declares the *public* API which is intended + * to be stable and consumed by external programs. + */ + +/// + +declare module '@xterm/xterm' { + /** + * A string or number representing text font weight. + */ + export type FontWeight = 'normal' | 'bold' | '100' | '200' | '300' | '400' | '500' | '600' | '700' | '800' | '900' | number; + + /** + * A string representing log level. + */ + export type LogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'off'; + + /** + * An object containing options for the terminal. + */ + export interface ITerminalOptions { + /** + * Whether to allow the use of proposed API. When false, any usage of APIs + * marked as experimental/proposed will throw an error. The default is + * false. + */ + allowProposedApi?: boolean; + + /** + * Whether background should support non-opaque color. It must be set before + * executing the `Terminal.open()` method and can't be changed later without + * executing it again. Note that enabling this can negatively impact + * performance. + */ + allowTransparency?: boolean; + + /** + * If enabled, alt + click will move the prompt cursor to position + * underneath the mouse. The default is true. + */ + altClickMovesCursor?: boolean; + + /** + * When enabled the cursor will be set to the beginning of the next line + * with every new line. This is equivalent to sending `\r\n` for each `\n`. + * Normally the settings of the underlying PTY (`termios`) deal with the + * translation of `\n` to `\r\n` and this setting should not be used. If you + * deal with data from a non-PTY related source, this settings might be + * useful. + * + * @see https://pubs.opengroup.org/onlinepubs/007904975/basedefs/termios.h.html + */ + convertEol?: boolean; + + /** + * Whether the cursor blinks. + */ + cursorBlink?: boolean; + + /** + * The style of the cursor when the terminal is focused. + */ + cursorStyle?: 'block' | 'underline' | 'bar'; + + /** + * The width of the cursor in CSS pixels when `cursorStyle` is set to 'bar'. + */ + cursorWidth?: number; + + /** + * The style of the cursor when the terminal is not focused. + */ + cursorInactiveStyle?: 'outline' | 'block' | 'bar' | 'underline' | 'none'; + + /** + * Whether to draw custom glyphs for block element and box drawing + * characters instead of using the font. This should typically result in + * better rendering with continuous lines, even when line height and letter + * spacing is used. Note that this doesn't work with the DOM renderer which + * renders all characters using the font. The default is true. + */ + customGlyphs?: boolean; + + /** + * Whether input should be disabled. + */ + disableStdin?: boolean; + + /** + * A {@link Document} to use instead of the one that xterm.js was attached + * to. The purpose of this is to improve support in multi-window + * applications where HTML elements may be references across multiple + * windows which can cause problems with `instanceof`. + * + * The type is `any` because using `Document` can cause TS to have + * performance/compiler problems. + */ + documentOverride?: any | null; + + /** + * Whether to draw bold text in bright colors. The default is true. + */ + drawBoldTextInBrightColors?: boolean; + + /** + * The scroll speed multiplier used for fast scrolling when `Alt` is held. + */ + fastScrollSensitivity?: number; + + /** + * The font size used to render text. + */ + fontSize?: number; + + /** + * The font family used to render text. + */ + fontFamily?: string; + + /** + * The font weight used to render non-bold text. + */ + fontWeight?: FontWeight; + + /** + * The font weight used to render bold text. + */ + fontWeightBold?: FontWeight; + + /** + * Whether to ignore the bracketed paste mode. When true, this will always + * paste without the `\x1b[200~` and `\x1b[201~` sequences, even when the + * shell enables bracketed mode. + */ + ignoreBracketedPasteMode?: boolean; + + /** + * The spacing in whole pixels between characters. + */ + letterSpacing?: number; + + /** + * The line height used to render text. + */ + lineHeight?: number; + + /** + * The handler for OSC 8 hyperlinks. Links will use the `confirm` browser + * API with a strongly worded warning if no link handler is set. + * + * When setting this, consider the security of users opening these links, + * at a minimum there should be a tooltip or a prompt when hovering or + * activating the link respectively. An example of what might be possible is + * a terminal app writing link in the form `javascript:...` that runs some + * javascript, a safe approach to prevent that is to validate the link + * starts with http(s)://. + */ + linkHandler?: ILinkHandler | null; + + /** + * What log level to use, this will log for all levels below and including + * what is set: + * + * 1. trace + * 2. debug + * 3. info (default) + * 4. warn + * 5. error + * 6. off + */ + logLevel?: LogLevel; + + /** + * A logger to use instead of `console`. + */ + logger?: ILogger | null; + + /** + * Whether to treat option as the meta key. + */ + macOptionIsMeta?: boolean; + + /** + * Whether holding a modifier key will force normal selection behavior, + * regardless of whether the terminal is in mouse events mode. This will + * also prevent mouse events from being emitted by the terminal. For + * example, this allows you to use xterm.js' regular selection inside tmux + * with mouse mode enabled. + */ + macOptionClickForcesSelection?: boolean; + + /** + * The minimum contrast ratio for text in the terminal, setting this will + * change the foreground color dynamically depending on whether the contrast + * ratio is met. Example values: + * + * - 1: The default, do nothing. + * - 4.5: Minimum for WCAG AA compliance. + * - 7: Minimum for WCAG AAA compliance. + * - 21: White on black or black on white. + */ + minimumContrastRatio?: number; + + /** + * Whether to reflow the line containing the cursor when the terminal is + * resized. Defaults to false, because shells usually handle this + * themselves. + */ + reflowCursorLine?: boolean; + + /** + * Whether to rescale glyphs horizontally that are a single cell wide but + * have glyphs that would overlap following cell(s). This typically happens + * for ambiguous width characters (eg. the roman numeral characters U+2160+) + * which aren't featured in monospace fonts. This is an important feature + * for achieving GB18030 compliance. + * + * The following glyphs will never be rescaled: + * + * - Emoji glyphs + * - Powerline glyphs + * - Nerd font glyphs + * + * Note that this doesn't work with the DOM renderer. The default is false. + */ + rescaleOverlappingGlyphs?: boolean; + + /** + * Whether to select the word under the cursor on right click, this is + * standard behavior in a lot of macOS applications. + */ + rightClickSelectsWord?: boolean; + + /** + * Whether screen reader support is enabled. When on this will expose + * supporting elements in the DOM to support NVDA on Windows and VoiceOver + * on macOS. + */ + screenReaderMode?: boolean; + + /** + * The amount of scrollback in the terminal. Scrollback is the amount of + * rows that are retained when lines are scrolled beyond the initial + * viewport. Defaults to 1000. + */ + scrollback?: number; + + /** + * If enabled the Erase in Display All (ED2) escape sequence will push + * erased text to scrollback, instead of clearing only the viewport portion. + * This emulates PuTTY's default clear screen behavior. + */ + scrollOnEraseInDisplay?: boolean; + + /** + * Whether to scroll to the bottom whenever there is some user input. The + * default is true. + */ + scrollOnUserInput?: boolean; + + /** + * The scrolling speed multiplier used for adjusting normal scrolling speed. + */ + scrollSensitivity?: number; + + /** + * The duration to smoothly scroll between the origin and the target in + * milliseconds. Set to 0 to disable smooth scrolling and scroll instantly. + */ + smoothScrollDuration?: number; + + /** + * The size of tab stops in the terminal. + */ + tabStopWidth?: number; + + /** + * The color theme of the terminal. + */ + theme?: ITheme; + + /** + * Compatibility information when the pty is known to be hosted on Windows. + * Setting this will turn on certain heuristics/workarounds depending on the + * values: + * + * - `if (backend !== undefined || buildNumber !== undefined)` + * - When increasing the rows in the terminal, the amount increased into + * the scrollback. This is done because ConPTY does not behave like + * expect scrollback to come back into the viewport, instead it makes + * empty rows at of the viewport. Not having this behavior can result in + * missing data as the rows get replaced. + * - `if !(backend === 'conpty' && buildNumber >= 21376)` + * - Reflow is disabled + * - Lines are assumed to be wrapped if the last character of the line is + * not whitespace. + */ + windowsPty?: IWindowsPty; + + /** + * A string containing all characters that are considered word separated by + * the double click to select work logic. + */ + wordSeparator?: string; + + /** + * Enable various window manipulation and report features. + * All features are disabled by default for security reasons. + */ + windowOptions?: IWindowOptions; + + /** + * Controls the visibility and style of the overview ruler which visualizes + * decorations underneath the scroll bar. + */ + overviewRuler?: IOverviewRulerOptions; + } + + /** + * An object containing additional options for the terminal that can only be + * set on start up. + */ + export interface ITerminalInitOnlyOptions { + /** + * The number of columns in the terminal. + */ + cols?: number; + + /** + * The number of rows in the terminal. + */ + rows?: number; + } + + /** + * Contains colors to theme the terminal with. + */ + export interface ITheme { + /** The default foreground color */ + foreground?: string; + /** The default background color */ + background?: string; + /** The cursor color */ + cursor?: string; + /** The accent color of the cursor (fg color for a block cursor) */ + cursorAccent?: string; + /** The selection background color (can be transparent) */ + selectionBackground?: string; + /** The selection foreground color */ + selectionForeground?: string; + /** + * The selection background color when the terminal does not have focus (can + * be transparent) + */ + selectionInactiveBackground?: string; + /** + * The scrollbar slider background color. Defaults to + * {@link ITerminalOptions.foreground foreground} with 20% opacity. + */ + scrollbarSliderBackground?: string; + /** + * The scrollbar slider background color when hovered. Defaults to + * {@link ITerminalOptions.foreground foreground} with 40% opacity. + */ + scrollbarSliderHoverBackground?: string; + /** + * The scrollbar slider background color when clicked. Defaults to + * {@link ITerminalOptions.foreground foreground} with 50% opacity. + */ + scrollbarSliderActiveBackground?: string; + /** + * The border color of the overview ruler. This visually separates the + * terminal from the scroll bar when {@link IOverviewRulerOptions.width} is + * set. When this is not set it defaults to black (`#000000`). + */ + overviewRulerBorder?: string; + /** ANSI black (eg. `\x1b[30m`) */ + black?: string; + /** ANSI red (eg. `\x1b[31m`) */ + red?: string; + /** ANSI green (eg. `\x1b[32m`) */ + green?: string; + /** ANSI yellow (eg. `\x1b[33m`) */ + yellow?: string; + /** ANSI blue (eg. `\x1b[34m`) */ + blue?: string; + /** ANSI magenta (eg. `\x1b[35m`) */ + magenta?: string; + /** ANSI cyan (eg. `\x1b[36m`) */ + cyan?: string; + /** ANSI white (eg. `\x1b[37m`) */ + white?: string; + /** ANSI bright black (eg. `\x1b[1;30m`) */ + brightBlack?: string; + /** ANSI bright red (eg. `\x1b[1;31m`) */ + brightRed?: string; + /** ANSI bright green (eg. `\x1b[1;32m`) */ + brightGreen?: string; + /** ANSI bright yellow (eg. `\x1b[1;33m`) */ + brightYellow?: string; + /** ANSI bright blue (eg. `\x1b[1;34m`) */ + brightBlue?: string; + /** ANSI bright magenta (eg. `\x1b[1;35m`) */ + brightMagenta?: string; + /** ANSI bright cyan (eg. `\x1b[1;36m`) */ + brightCyan?: string; + /** ANSI bright white (eg. `\x1b[1;37m`) */ + brightWhite?: string; + /** ANSI extended colors (16-255) */ + extendedAnsi?: string[]; + } + + /** + * Pty information for Windows. + */ + export interface IWindowsPty { + /** + * What pty emulation backend is being used. + */ + backend?: 'conpty' | 'winpty'; + /** + * The Windows build version (eg. 19045) + */ + buildNumber?: number; + } + + /** + * A replacement logger for `console`. + */ + export interface ILogger { + /** + * Log a trace message, this will only be called if + * {@link ITerminalOptions.logLevel} is set to trace. + */ + trace(message: string, ...args: any[]): void; + /** + * Log a debug message, this will only be called if + * {@link ITerminalOptions.logLevel} is set to debug or below. + */ + debug(message: string, ...args: any[]): void; + /** + * Log a debug message, this will only be called if + * {@link ITerminalOptions.logLevel} is set to info or below. + */ + info(message: string, ...args: any[]): void; + /** + * Log a debug message, this will only be called if + * {@link ITerminalOptions.logLevel} is set to warn or below. + */ + warn(message: string, ...args: any[]): void; + /** + * Log a debug message, this will only be called if + * {@link ITerminalOptions.logLevel} is set to error or below. + */ + error(message: string | Error, ...args: any[]): void; + } + + /** + * An object that can be disposed via a dispose function. + */ + export interface IDisposable { + dispose(): void; + } + + /** + * An event that can be listened to. + * @returns an `IDisposable` to stop listening. + */ + export interface IEvent { + (listener: (arg1: T, arg2: U) => any): IDisposable; + } + + /** + * Represents a specific line in the terminal that is tracked when scrollback + * is trimmed and lines are added or removed. This is a single line that may + * be part of a larger wrapped line. + */ + export interface IMarker extends IDisposableWithEvent { + /** + * A unique identifier for this marker. + */ + readonly id: number; + + /** + * The actual line index in the buffer at this point in time. This is set to + * -1 if the marker has been disposed. + */ + readonly line: number; + } + + /** + * Represents a disposable that tracks is disposed state. + */ + export interface IDisposableWithEvent extends IDisposable { + /** + * Event listener to get notified when this gets disposed. + */ + onDispose: IEvent; + + /** + * Whether this is disposed. + */ + readonly isDisposed: boolean; + } + + /** + * Represents a decoration in the terminal that is associated with a + * particular marker and DOM element. + */ + export interface IDecoration extends IDisposableWithEvent { + /* + * The marker for the decoration in the terminal. + */ + readonly marker: IMarker; + + /** + * An event fired when the decoration + * is rendered, returns the dom element + * associated with the decoration. + */ + readonly onRender: IEvent; + + /** + * The element that the decoration is rendered to. This will be undefined + * until it is rendered for the first time by {@link IDecoration.onRender}. + * that. + */ + element: HTMLElement | undefined; + + /** + * The options for the overview ruler that can be updated. This will only + * take effect when {@link IDecorationOptions.overviewRulerOptions} were + * provided initially. + */ + options: Pick; + } + + + /** + * Overview ruler decoration options + */ + interface IDecorationOverviewRulerOptions { + color: string; + position?: 'left' | 'center' | 'right' | 'full'; + } + + /* + * Options that define the presentation of the decoration. + */ + export interface IDecorationOptions { + /** + * The line in the terminal where + * the decoration will be displayed + */ + readonly marker: IMarker; + + /* + * Where the decoration will be anchored - + * defaults to the left edge + */ + readonly anchor?: 'right' | 'left'; + + /** + * The x position offset relative to the anchor + */ + readonly x?: number; + + + /** + * The width of the decoration in cells, defaults to 1. + */ + readonly width?: number; + + /** + * The height of the decoration in cells, defaults to 1. + */ + readonly height?: number; + + /** + * The background color of the cell(s). When 2 decorations both set the + * foreground color the last registered decoration will be used. Only the + * `#RRGGBB` format is supported. + */ + readonly backgroundColor?: string; + + /** + * The foreground color of the cell(s). When 2 decorations both set the + * foreground color the last registered decoration will be used. Only the + * `#RRGGBB` format is supported. + */ + readonly foregroundColor?: string; + + /** + * What layer to render the decoration at when {@link backgroundColor} or + * {@link foregroundColor} are used. `'bottom'` will render under the + * selection, `'top`' will render above the selection\*. + */ + readonly layer?: 'bottom' | 'top'; + + /** + * When defined, renders the decoration in the overview ruler to the right + * of the terminal. {@link IOverviewRulerOptions.width} must be set in order + * to see the overview ruler. + * @param color The color of the decoration. + * @param position The position of the decoration. + */ + overviewRulerOptions?: IDecorationOverviewRulerOptions; + } + + /** + * The set of localizable strings. + */ + export interface ILocalizableStrings { + /** + * The aria label for the underlying input textarea for the terminal. + */ + promptLabel: string; + + /** + * Announcement for when line reading is suppressed due to too many lines + * being printed to the terminal when `screenReaderMode` is enabled. + */ + tooMuchOutput: string; + } + + export interface IOverviewRulerOptions { + /** + * When defined, renders decorations in the overview ruler to the right of + * the terminal. This must be set in order to see the overview ruler. + * @param color The color of the decoration. + * @param position The position of the decoration. + */ + width?: number; + + /** + * Whether to show the top border of the overview ruler, which uses the + * {@link ITheme.overviewRulerBorder} color. + */ + showTopBorder?: boolean; + + /** + * Whether to show the bottom border of the overview ruler, which uses the + * {@link ITheme.overviewRulerBorder} color. + */ + showBottomBorder?: boolean; + } + + /** + * Enable various window manipulation and report features + * (`CSI Ps ; Ps ; Ps t`). + * + * Most settings have no default implementation, as they heavily rely on + * the embedding environment. + * + * To implement a feature, create a custom CSI hook like this: + * ```ts + * term.parser.addCsiHandler({final: 't'}, params => { + * const ps = params[0]; + * switch (ps) { + * case XY: + * ... // your implementation for option XY + * return true; // signal Ps=XY was handled + * } + * return false; // any Ps that was not handled + * }); + * ``` + * + * Note on security: + * Most features are meant to deal with some information of the host machine + * where the terminal runs on. This is seen as a security risk possibly + * leaking sensitive data of the host to the program in the terminal. + * Therefore all options (even those without a default implementation) are + * guarded by the boolean flag and disabled by default. + */ + export interface IWindowOptions { + /** + * Ps=1 De-iconify window. + * No default implementation. + */ + restoreWin?: boolean; + /** + * Ps=2 Iconify window. + * No default implementation. + */ + minimizeWin?: boolean; + /** + * Ps=3 ; x ; y + * Move window to [x, y]. + * No default implementation. + */ + setWinPosition?: boolean; + /** + * Ps = 4 ; height ; width + * Resize the window to given `height` and `width` in pixels. + * Omitted parameters should reuse the current height or width. + * Zero parameters should use the display's height or width. + * No default implementation. + */ + setWinSizePixels?: boolean; + /** + * Ps=5 Raise the window to the front of the stacking order. + * No default implementation. + */ + raiseWin?: boolean; + /** + * Ps=6 Lower the xterm window to the bottom of the stacking order. + * No default implementation. + */ + lowerWin?: boolean; + /** Ps=7 Refresh the window. */ + refreshWin?: boolean; + /** + * Ps = 8 ; height ; width + * Resize the text area to given height and width in characters. + * Omitted parameters should reuse the current height or width. + * Zero parameters use the display's height or width. + * No default implementation. + */ + setWinSizeChars?: boolean; + /** + * Ps=9 ; 0 Restore maximized window. + * Ps=9 ; 1 Maximize window (i.e., resize to screen size). + * Ps=9 ; 2 Maximize window vertically. + * Ps=9 ; 3 Maximize window horizontally. + * No default implementation. + */ + maximizeWin?: boolean; + /** + * Ps=10 ; 0 Undo full-screen mode. + * Ps=10 ; 1 Change to full-screen. + * Ps=10 ; 2 Toggle full-screen. + * No default implementation. + */ + fullscreenWin?: boolean; + /** Ps=11 Report xterm window state. + * If the xterm window is non-iconified, it returns "CSI 1 t". + * If the xterm window is iconified, it returns "CSI 2 t". + * No default implementation. + */ + getWinState?: boolean; + /** + * Ps=13 Report xterm window position. Result is "CSI 3 ; x ; y t". + * Ps=13 ; 2 Report xterm text-area position. Result is "CSI 3 ; x ; y t". + * No default implementation. + */ + getWinPosition?: boolean; + /** + * Ps=14 Report xterm text area size in pixels. Result is "CSI 4 ; height ; width t". + * Ps=14 ; 2 Report xterm window size in pixels. Result is "CSI 4 ; height ; width t". + * Has a default implementation. + */ + getWinSizePixels?: boolean; + /** + * Ps=15 Report size of the screen in pixels. Result is "CSI 5 ; height ; width t". + * No default implementation. + */ + getScreenSizePixels?: boolean; + /** + * Ps=16 Report xterm character cell size in pixels. Result is "CSI 6 ; height ; width t". + * Has a default implementation. + */ + getCellSizePixels?: boolean; + /** + * Ps=18 Report the size of the text area in characters. Result is "CSI 8 ; height ; width t". + * Has a default implementation. + */ + getWinSizeChars?: boolean; + /** + * Ps=19 Report the size of the screen in characters. Result is "CSI 9 ; height ; width t". + * No default implementation. + */ + getScreenSizeChars?: boolean; + /** + * Ps=20 Report xterm window's icon label. Result is "OSC L label ST". + * No default implementation. + */ + getIconTitle?: boolean; + /** + * Ps=21 Report xterm window's title. Result is "OSC l label ST". + * No default implementation. + */ + getWinTitle?: boolean; + /** + * Ps=22 ; 0 Save xterm icon and window title on stack. + * Ps=22 ; 1 Save xterm icon title on stack. + * Ps=22 ; 2 Save xterm window title on stack. + * All variants have a default implementation. + */ + pushTitle?: boolean; + /** + * Ps=23 ; 0 Restore xterm icon and window title from stack. + * Ps=23 ; 1 Restore xterm icon title from stack. + * Ps=23 ; 2 Restore xterm window title from stack. + * All variants have a default implementation. + */ + popTitle?: boolean; + /** + * Ps>=24 Resize to Ps lines (DECSLPP). + * DECSLPP is not implemented. This settings is also used to + * enable / disable DECCOLM (earlier variant of DECSLPP). + */ + setWinLines?: boolean; + } + + /** + * The class that represents an xterm.js terminal. + */ + export class Terminal implements IDisposable { + /** + * The element containing the terminal. + */ + readonly element: HTMLElement | undefined; + + /** + * The textarea that accepts input for the terminal. + */ + readonly textarea: HTMLTextAreaElement | undefined; + + /** + * The number of rows in the terminal's viewport. Use + * `ITerminalOptions.rows` to set this in the constructor and + * `Terminal.resize` for when the terminal exists. + */ + readonly rows: number; + + /** + * The number of columns in the terminal's viewport. Use + * `ITerminalOptions.cols` to set this in the constructor and + * `Terminal.resize` for when the terminal exists. + */ + readonly cols: number; + + /** + * Access to the terminal's normal and alt buffer. + */ + readonly buffer: IBufferNamespace; + + /** + * (EXPERIMENTAL) Get all markers registered against the buffer. If the alt + * buffer is active this will always return []. + */ + readonly markers: ReadonlyArray; + + /** + * Get the parser interface to register custom escape sequence handlers. + */ + readonly parser: IParser; + + /** + * (EXPERIMENTAL) Get the Unicode handling interface + * to register and switch Unicode version. + */ + readonly unicode: IUnicodeHandling; + + /** + * Gets the terminal modes as set by SM/DECSET. + */ + readonly modes: IModes; + + /** + * Gets or sets the terminal options. This supports setting multiple + * options. + * + * @example Get a single option + * ```ts + * console.log(terminal.options.fontSize); + * ``` + * + * @example Set a single option: + * ```ts + * terminal.options.fontSize = 12; + * ``` + * Note that for options that are object, a new object must be used in order + * to take effect as a reference comparison will be done: + * ```ts + * const newValue = terminal.options.theme; + * newValue.background = '#000000'; + * + * // This won't work + * terminal.options.theme = newValue; + * + * // This will work + * terminal.options.theme = { ...newValue }; + * ``` + * + * @example Set multiple options + * ```ts + * terminal.options = { + * fontSize: 12, + * fontFamily: 'Courier New' + * }; + * ``` + */ + options: ITerminalOptions; + + /** + * Natural language strings that can be localized. + */ + static strings: ILocalizableStrings; + + /** + * Creates a new `Terminal` object. + * + * @param options An object containing a set of options. + */ + constructor(options?: ITerminalOptions & ITerminalInitOnlyOptions); + + /** + * Adds an event listener for when the bell is triggered. + * @returns an `IDisposable` to stop listening. + */ + onBell: IEvent; + + /** + * Adds an event listener for when a binary event fires. This is used to + * enable non UTF-8 conformant binary messages to be sent to the backend. + * Currently this is only used for a certain type of mouse reports that + * happen to be not UTF-8 compatible. + * The event value is a JS string, pass it to the underlying pty as + * binary data, e.g. `pty.write(Buffer.from(data, 'binary'))`. + * @returns an `IDisposable` to stop listening. + */ + onBinary: IEvent; + + /** + * Adds an event listener for the cursor moves. + * @returns an `IDisposable` to stop listening. + */ + onCursorMove: IEvent; + + /** + * Adds an event listener for when a data event fires. This happens for + * example when the user types or pastes into the terminal. The event value + * is whatever `string` results, in a typical setup, this should be passed + * on to the backing pty. + * @returns an `IDisposable` to stop listening. + */ + onData: IEvent; + + /** + * Adds an event listener for when a key is pressed. The event value + * contains the string that will be sent in the data event as well as the + * DOM event that triggered it. + * @returns an `IDisposable` to stop listening. + */ + onKey: IEvent<{ key: string, domEvent: KeyboardEvent }>; + + /** + * Adds an event listener for when a line feed is added. + * @returns an `IDisposable` to stop listening. + */ + onLineFeed: IEvent; + + /** + * Adds an event listener for when rows are rendered. The event value + * contains the start row and end rows of the rendered area (ranges from `0` + * to `Terminal.rows - 1`). + * @returns an `IDisposable` to stop listening. + */ + onRender: IEvent<{ start: number, end: number }>; + + /** + * Adds an event listener for when data has been parsed by the terminal, + * after {@link write} is called. This event is useful to listen for any + * changes in the buffer. + * + * This fires at most once per frame, after data parsing completes. Note + * that this can fire when there are still writes pending if there is a lot + * of data. + */ + onWriteParsed: IEvent; + + /** + * Adds an event listener for when the terminal is resized. The event value + * contains the new size. + * @returns an `IDisposable` to stop listening. + */ + onResize: IEvent<{ cols: number, rows: number }>; + + /** + * Adds an event listener for when a scroll occurs. The event value is the + * new position of the viewport. + * @returns an `IDisposable` to stop listening. + */ + onScroll: IEvent; + + /** + * Adds an event listener for when a selection change occurs. + * @returns an `IDisposable` to stop listening. + */ + onSelectionChange: IEvent; + + /** + * Adds an event listener for when an OSC 0 or OSC 2 title change occurs. + * The event value is the new title. + * @returns an `IDisposable` to stop listening. + */ + onTitleChange: IEvent; + + /** + * Unfocus the terminal. + */ + blur(): void; + + /** + * Focus the terminal. + */ + focus(): void; + + /** + * Input data to application side. The data is treated the same way input + * typed into the terminal would (ie. the {@link onData} event will fire). + * @param data The data to forward to the application. + * @param wasUserInput Whether the input is genuine user input. This is true + * by default and triggers additionalbehavior like focus or selection + * clearing. Set this to false if the data sent should not be treated like + * user input would, for example passing an escape sequence to the + * application. + */ + input(data: string, wasUserInput?: boolean): void; + + /** + * Resizes the terminal. It's best practice to debounce calls to resize, + * this will help ensure that the pty can respond to the resize event + * before another one occurs. + * @param x The number of columns to resize to. + * @param y The number of rows to resize to. + */ + resize(columns: number, rows: number): void; + + /** + * Opens the terminal within an element. This should also be called if the + * xterm.js element ever changes browser window. + * @param parent The element to create the terminal within. This element + * must be visible (have dimensions) when `open` is called as several DOM- + * based measurements need to be performed when this function is called. + */ + open(parent: HTMLElement): void; + + /** + * Attaches a custom key event handler which is run before keys are + * processed, giving consumers of xterm.js ultimate control as to what keys + * should be processed by the terminal and what keys should not. + * @param customKeyEventHandler The custom KeyboardEvent handler to attach. + * This is a function that takes a KeyboardEvent, allowing consumers to stop + * propagation and/or prevent the default action. The function returns + * whether the event should be processed by xterm.js. + * + * @example A custom keymap that overrides the backspace key + * ```ts + * const keymap = [ + * { "key": "Backspace", "shiftKey": false, "mapCode": 8 }, + * { "key": "Backspace", "shiftKey": true, "mapCode": 127 } + * ]; + * term.attachCustomKeyEventHandler(ev => { + * if (ev.type === 'keydown') { + * for (let i in keymap) { + * if (keymap[i].key == ev.key && keymap[i].shiftKey == ev.shiftKey) { + * socket.send(String.fromCharCode(keymap[i].mapCode)); + * return false; + * } + * } + * } + * }); + * ``` + */ + attachCustomKeyEventHandler(customKeyEventHandler: (event: KeyboardEvent) => boolean): void; + + /** + * Attaches a custom wheel event handler which is run before keys are + * processed, giving consumers of xterm.js control over whether to proceed + * or cancel terminal wheel events. + * @param customWheelEventHandler The custom WheelEvent handler to attach. + * This is a function that takes a WheelEvent, allowing consumers to stop + * propagation and/or prevent the default action. The function returns + * whether the event should be processed by xterm.js. + * + * @example A handler that prevents all wheel events while ctrl is held from + * being processed. + * ```ts + * term.attachCustomWheelEventHandler(ev => { + * if (ev.ctrlKey) { + * return false; + * } + * return true; + * }); + * ``` + */ + attachCustomWheelEventHandler(customWheelEventHandler: (event: WheelEvent) => boolean): void; + + /** + * Registers a link provider, allowing a custom parser to be used to match + * and handle links. Multiple link providers can be used, they will be asked + * in the order in which they are registered. + * @param linkProvider The link provider to use to detect links. + */ + registerLinkProvider(linkProvider: ILinkProvider): IDisposable; + + /** + * (EXPERIMENTAL) Registers a character joiner, allowing custom sequences of + * characters to be rendered as a single unit. This is useful in particular + * for rendering ligatures and graphemes, among other things. + * + * Each registered character joiner is called with a string of text + * representing a portion of a line in the terminal that can be rendered as + * a single unit. The joiner must return a sorted array, where each entry is + * itself an array of length two, containing the start (inclusive) and end + * (exclusive) index of a substring of the input that should be rendered as + * a single unit. When multiple joiners are provided, the results of each + * are collected. If there are any overlapping substrings between them, they + * are combined into one larger unit that is drawn together. + * + * All character joiners that are registered get called every time a line is + * rendered in the terminal, so it is essential for the handler function to + * run as quickly as possible to avoid slowdowns when rendering. Similarly, + * joiners should strive to return the smallest possible substrings to + * render together, since they aren't drawn as optimally as individual + * characters. + * + * NOTE: character joiners are only used by the webgl renderer. + * + * @param handler The function that determines character joins. It is called + * with a string of text that is eligible for joining and returns an array + * where each entry is an array containing the start (inclusive) and end + * (exclusive) indexes of ranges that should be rendered as a single unit. + * @returns The ID of the new joiner, this can be used to deregister + */ + registerCharacterJoiner(handler: (text: string) => [number, number][]): number; + + /** + * (EXPERIMENTAL) Deregisters the character joiner if one was registered. + * NOTE: character joiners are only used by the webgl renderer. + * @param joinerId The character joiner's ID (returned after register) + */ + deregisterCharacterJoiner(joinerId: number): void; + + /** + * Adds a marker to the normal buffer and returns it. + * @param cursorYOffset The y position offset of the marker from the cursor. + * @returns The new marker or undefined. + */ + registerMarker(cursorYOffset?: number): IMarker; + + /** + * (EXPERIMENTAL) Adds a decoration to the terminal using + * @param decorationOptions, which takes a marker and an optional anchor, + * width, height, and x offset from the anchor. Returns the decoration or + * undefined if the alt buffer is active or the marker has already been + * disposed of. + * @throws when options include a negative x offset. + */ + registerDecoration(decorationOptions: IDecorationOptions): IDecoration | undefined; + + /** + * Gets whether the terminal has an active selection. + */ + hasSelection(): boolean; + + /** + * Gets the terminal's current selection, this is useful for implementing + * copy behavior outside of xterm.js. + */ + getSelection(): string; + + /** + * Gets the selection position or undefined if there is no selection. + */ + getSelectionPosition(): IBufferRange | undefined; + + /** + * Clears the current terminal selection. + */ + clearSelection(): void; + + /** + * Selects text within the terminal. + * @param column The column the selection starts at. + * @param row The row the selection starts at. + * @param length The length of the selection. + */ + select(column: number, row: number, length: number): void; + + /** + * Selects all text within the terminal. + */ + selectAll(): void; + + /** + * Selects text in the buffer between 2 lines. + * @param start The 0-based line index to select from (inclusive). + * @param end The 0-based line index to select to (inclusive). + */ + selectLines(start: number, end: number): void; + + /* + * Disposes of the terminal, detaching it from the DOM and removing any + * active listeners. Once the terminal is disposed it should not be used + * again. + */ + dispose(): void; + + /** + * Scroll the display of the terminal + * @param amount The number of lines to scroll down (negative scroll up). + */ + scrollLines(amount: number): void; + + /** + * Scroll the display of the terminal by a number of pages. + * @param pageCount The number of pages to scroll (negative scrolls up). + */ + scrollPages(pageCount: number): void; + + /** + * Scrolls the display of the terminal to the top. + */ + scrollToTop(): void; + + /** + * Scrolls the display of the terminal to the bottom. + */ + scrollToBottom(): void; + + /** + * Scrolls to a line within the buffer. + * @param line The 0-based line index to scroll to. + */ + scrollToLine(line: number): void; + + /** + * Clear the entire buffer, making the prompt line the new first line. + */ + clear(): void; + + /** + * Write data to the terminal. + * + * Note that the change will not be reflected in the {@link buffer} + * immediately as the data is processed asynchronously. Provide a + * {@link callback} to know when the data was processed. + * @param data The data to write to the terminal. This can either be raw + * bytes given as Uint8Array from the pty or a string. Raw bytes will always + * be treated as UTF-8 encoded, string data as UTF-16. + * @param callback Optional callback that fires when the data was processed + * by the parser. This callback must be provided and awaited in order for + * {@link buffer} to reflect the change in the write. + */ + write(data: string | Uint8Array, callback?: () => void): void; + + /** + * Writes data to the terminal, followed by a break line character (\n). + * + * Note that the change will not be reflected in the {@link buffer} + * immediately as the data is processed asynchronously. Provide a + * {@link callback} to know when the data was processed. + * @param data The data to write to the terminal. This can either be raw + * bytes given as Uint8Array from the pty or a string. Raw bytes will always + * be treated as UTF-8 encoded, string data as UTF-16. + * @param callback Optional callback that fires when the data was processed + * by the parser. This callback must be provided and awaited in order for + * {@link buffer} to reflect the change in the write. + */ + writeln(data: string | Uint8Array, callback?: () => void): void; + + /** + * Writes text to the terminal, performing the necessary transformations for + * pasted text. + * @param data The text to write to the terminal. + */ + paste(data: string): void; + + /** + * Tells the renderer to refresh terminal content between two rows + * (inclusive) at the next opportunity. + * @param start The row to start from (between 0 and this.rows - 1). + * @param end The row to end at (between start and this.rows - 1). + */ + refresh(start: number, end: number): void; + + /** + * Clears the texture atlas of the webgl renderer if it's active. Doing + * this will force a redraw of all glyphs which can workaround issues + * causing the texture to become corrupt, for example Chromium/Nvidia has an + * issue where the texture gets messed up when resuming the OS from sleep. + */ + clearTextureAtlas(): void; + + /** + * Perform a full reset (RIS, aka '\x1bc'). + */ + reset(): void; + + /** + * Loads an addon into this instance of xterm.js. + * @param addon The addon to load. + */ + loadAddon(addon: ITerminalAddon): void; + } + + /** + * An addon that can provide additional functionality to the terminal. + */ + export interface ITerminalAddon extends IDisposable { + /** + * This is called when the addon is activated. + */ + activate(terminal: Terminal): void; + } + + /** + * An object representing a range within the viewport of the terminal. + */ + export interface IViewportRange { + /** + * The start of the range. + */ + start: IViewportRangePosition; + + /** + * The end of the range. + */ + end: IViewportRangePosition; + } + + /** + * An object representing a cell position within the viewport of the terminal. + */ + interface IViewportRangePosition { + /** + * The x position of the cell. This is a 0-based index that refers to the + * space in between columns, not the column itself. Index 0 refers to the + * left side of the viewport, index `Terminal.cols` refers to the right side + * of the viewport. This can be thought of as how a cursor is positioned in + * a text editor. + */ + x: number; + + /** + * The y position of the cell. This is a 0-based index that refers to a + * specific row. + */ + y: number; + } + + /** + * A link handler for OSC 8 hyperlinks. + */ + interface ILinkHandler { + /** + * Calls when the link is activated. + * @param event The mouse event triggering the callback. + * @param text The text of the link. + * @param range The buffer range of the link. + */ + activate(event: MouseEvent, text: string, range: IBufferRange): void; + + /** + * Called when the mouse hovers the link. To use this to create a DOM-based + * hover tooltip, create the hover element within `Terminal.element` and + * add the `xterm-hover` class to it, that will cause mouse events to not + * fall through and activate other links. + * @param event The mouse event triggering the callback. + * @param text The text of the link. + * @param range The buffer range of the link. + */ + hover?(event: MouseEvent, text: string, range: IBufferRange): void; + + /** + * Called when the mouse leaves the link. + * @param event The mouse event triggering the callback. + * @param text The text of the link. + * @param range The buffer range of the link. + */ + leave?(event: MouseEvent, text: string, range: IBufferRange): void; + + /** + * Whether to receive non-HTTP URLs from LinkProvider. When false, any + * usage of non-HTTP URLs will be ignored. Enabling this option without + * proper protection in `activate` function may cause security issues such + * as XSS. + */ + allowNonHttpProtocols?: boolean; + } + + /** + * A custom link provider. + */ + interface ILinkProvider { + /** + * Provides a link a buffer position + * @param bufferLineNumber The y position of the buffer to check for links + * within. + * @param callback The callback to be fired when ready with the resulting + * link(s) for the line or `undefined`. + */ + provideLinks(bufferLineNumber: number, callback: (links: ILink[] | undefined) => void): void; + } + + /** + * A link within the terminal. + */ + interface ILink { + /** + * The buffer range of the link. + */ + range: IBufferRange; + + /** + * The text of the link. + */ + text: string; + + /** + * What link decorations to show when hovering the link, this property is + * tracked and changes made after the link is provided will trigger changes. + * If not set, all decroations will be enabled. + */ + decorations?: ILinkDecorations; + + /** + * Calls when the link is activated. + * @param event The mouse event triggering the callback. + * @param text The text of the link. + */ + activate(event: MouseEvent, text: string): void; + + /** + * Called when the mouse hovers the link. To use this to create a DOM-based + * hover tooltip, create the hover element within `Terminal.element` and add + * the `xterm-hover` class to it, that will cause mouse events to not fall + * through and activate other links. + * @param event The mouse event triggering the callback. + * @param text The text of the link. + */ + hover?(event: MouseEvent, text: string): void; + + /** + * Called when the mouse leaves the link. + * @param event The mouse event triggering the callback. + * @param text The text of the link. + */ + leave?(event: MouseEvent, text: string): void; + + /** + * Called when the link is released and no longer used by xterm.js. + */ + dispose?(): void; + } + + /** + * A set of decorations that can be applied to links. + */ + interface ILinkDecorations { + /** + * Whether the cursor is set to pointer. + */ + pointerCursor: boolean; + + /** + * Whether the underline is visible + */ + underline: boolean; + } + + /** + * A range within a buffer. + */ + interface IBufferRange { + /** + * The start position of the range. + */ + start: IBufferCellPosition; + + /** + * The end position of the range. + */ + end: IBufferCellPosition; + } + + /** + * A position within a buffer. + */ + interface IBufferCellPosition { + /** + * The x position within the buffer (1-based). + */ + x: number; + + /** + * The y position within the buffer (1-based). + */ + y: number; + } + + /** + * Represents a terminal buffer. + */ + interface IBuffer { + /** + * The type of the buffer. + */ + readonly type: 'normal' | 'alternate'; + + /** + * The y position of the cursor. This ranges between `0` (when the + * cursor is at baseY) and `Terminal.rows - 1` (when the cursor is on the + * last row). + */ + readonly cursorY: number; + + /** + * The x position of the cursor. This ranges between `0` (left side) and + * `Terminal.cols` (after last cell of the row). + */ + readonly cursorX: number; + + /** + * The line within the buffer where the top of the viewport is. + */ + readonly viewportY: number; + + /** + * The line within the buffer where the top of the bottom page is (when + * fully scrolled down). + */ + readonly baseY: number; + + /** + * The amount of lines in the buffer. + */ + readonly length: number; + + /** + * Gets a line from the buffer, or undefined if the line index does not + * exist. + * + * Note that the result of this function should be used immediately after + * calling as when the terminal updates it could lead to unexpected + * behavior. + * + * @param y The line index to get. + */ + getLine(y: number): IBufferLine | undefined; + + /** + * Creates an empty cell object suitable as a cell reference in + * `line.getCell(x, cell)`. Use this to avoid costly recreation of + * cell objects when dealing with tons of cells. + */ + getNullCell(): IBufferCell; + } + + export interface IBufferElementProvider { + /** + * Provides a document fragment or HTMLElement containing the buffer + * elements. + */ + provideBufferElements(): DocumentFragment | HTMLElement; + } + + /** + * Represents the terminal's set of buffers. + */ + interface IBufferNamespace { + /** + * The active buffer, this will either be the normal or alternate buffers. + */ + readonly active: IBuffer; + + /** + * The normal buffer. + */ + readonly normal: IBuffer; + + /** + * The alternate buffer, this becomes the active buffer when an application + * enters this mode via DECSET (`CSI ? 4 7 h`) + */ + readonly alternate: IBuffer; + + /** + * Adds an event listener for when the active buffer changes. + * @returns an `IDisposable` to stop listening. + */ + onBufferChange: IEvent; + } + + /** + * Represents a line in the terminal's buffer. + */ + interface IBufferLine { + /** + * Whether the line is wrapped from the previous line. + */ + readonly isWrapped: boolean; + + /** + * The length of the line, all call to getCell beyond the length will result + * in `undefined`. Note that this may exceed columns as the line array may + * not be trimmed after a resize, compare against {@link Terminal.cols} to + * get the actual maximum length of a line. + */ + readonly length: number; + + /** + * Gets a cell from the line, or undefined if the line index does not exist. + * + * Note that the result of this function should be used immediately after + * calling as when the terminal updates it could lead to unexpected + * behavior. + * + * @param x The character index to get. + * @param cell Optional cell object to load data into for performance + * reasons. This is mainly useful when every cell in the buffer is being + * looped over to avoid creating new objects for every cell. + */ + getCell(x: number, cell?: IBufferCell): IBufferCell | undefined; + + /** + * Gets the line as a string. Note that this is gets only the string for the + * line, not taking isWrapped into account. + * + * @param trimRight Whether to trim any whitespace at the right of the line. + * @param startColumn The column to start from (inclusive). + * @param endColumn The column to end at (exclusive). + */ + translateToString(trimRight?: boolean, startColumn?: number, endColumn?: number): string; + } + + /** + * Represents a single cell in the terminal's buffer. + */ + interface IBufferCell { + /** + * The width of the character. Some examples: + * + * - `1` for most cells. + * - `2` for wide character like CJK glyphs. + * - `0` for cells immediately following cells with a width of `2`. + */ + getWidth(): number; + + /** + * The character(s) within the cell. Examples of what this can contain: + * + * - A normal width character + * - A wide character (eg. CJK) + * - An emoji + */ + getChars(): string; + + /** + * Gets the UTF32 codepoint of single characters, if content is a combined + * string it returns the codepoint of the last character in the string. + */ + getCode(): number; + + /** + * Gets the number representation of the foreground color mode, this can be + * used to perform quick comparisons of 2 cells to see if they're the same. + * Use `isFgRGB`, `isFgPalette` and `isFgDefault` to check what color mode + * a cell is. + */ + getFgColorMode(): number; + + /** + * Gets the number representation of the background color mode, this can be + * used to perform quick comparisons of 2 cells to see if they're the same. + * Use `isBgRGB`, `isBgPalette` and `isBgDefault` to check what color mode + * a cell is. + */ + getBgColorMode(): number; + + /** + * Gets a cell's foreground color number, this differs depending on what the + * color mode of the cell is: + * + * - Default: This should be 0, representing the default foreground color + * (CSI 39 m). + * - Palette: This is a number from 0 to 255 of ANSI colors (CSI 3(0-7) m, + * CSI 9(0-7) m, CSI 38 ; 5 ; 0-255 m). + * - RGB: A hex value representing a 'true color': 0xRRGGBB. + * (CSI 3 8 ; 2 ; Pi ; Pr ; Pg ; Pb) + */ + getFgColor(): number; + + /** + * Gets a cell's background color number, this differs depending on what the + * color mode of the cell is: + * + * - Default: This should be 0, representing the default background color + * (CSI 49 m). + * - Palette: This is a number from 0 to 255 of ANSI colors + * (CSI 4(0-7) m, CSI 10(0-7) m, CSI 48 ; 5 ; 0-255 m). + * - RGB: A hex value representing a 'true color': 0xRRGGBB + * (CSI 4 8 ; 2 ; Pi ; Pr ; Pg ; Pb) + */ + getBgColor(): number; + + /** Whether the cell has the bold attribute (CSI 1 m). */ + isBold(): number; + /** Whether the cell has the italic attribute (CSI 3 m). */ + isItalic(): number; + /** Whether the cell has the dim attribute (CSI 2 m). */ + isDim(): number; + /** Whether the cell has the underline attribute (CSI 4 m). */ + isUnderline(): number; + /** Whether the cell has the blink attribute (CSI 5 m). */ + isBlink(): number; + /** Whether the cell has the inverse attribute (CSI 7 m). */ + isInverse(): number; + /** Whether the cell has the invisible attribute (CSI 8 m). */ + isInvisible(): number; + /** Whether the cell has the strikethrough attribute (CSI 9 m). */ + isStrikethrough(): number; + /** Whether the cell has the overline attribute (CSI 53 m). */ + isOverline(): number; + + /** Whether the cell is using the RGB foreground color mode. */ + isFgRGB(): boolean; + /** Whether the cell is using the RGB background color mode. */ + isBgRGB(): boolean; + /** Whether the cell is using the palette foreground color mode. */ + isFgPalette(): boolean; + /** Whether the cell is using the palette background color mode. */ + isBgPalette(): boolean; + /** Whether the cell is using the default foreground color mode. */ + isFgDefault(): boolean; + /** Whether the cell is using the default background color mode. */ + isBgDefault(): boolean; + + /** Whether the cell has the default attribute (no color or style). */ + isAttributeDefault(): boolean; + } + + /** + * Data type to register a CSI, DCS or ESC callback in the parser + * in the form: + * ESC I..I F + * CSI Prefix P..P I..I F + * DCS Prefix P..P I..I F data_bytes ST + * + * with these rules/restrictions: + * - prefix can only be used with CSI and DCS + * - only one leading prefix byte is recognized by the parser + * before any other parameter bytes (P..P) + * - intermediate bytes are recognized up to 2 + * + * For custom sequences make sure to read ECMA-48 and the resources at + * vt100.net to not clash with existing sequences or reserved address space. + * General recommendations: + * - use private address space (see ECMA-48) + * - use max one intermediate byte (technically not limited by the spec, + * in practice there are no sequences with more than one intermediate byte, + * thus parsers might get confused with more intermediates) + * - test against other common emulators to check whether they escape/ignore + * the sequence correctly + * + * Notes: OSC command registration is handled differently (see addOscHandler) + * APC, PM or SOS is currently not supported. + */ + export interface IFunctionIdentifier { + /** + * Optional prefix byte, must be in range \x3c .. \x3f. + * Usable in CSI and DCS. + */ + prefix?: string; + /** + * Optional intermediate bytes, must be in range \x20 .. \x2f. + * Usable in CSI, DCS and ESC. + */ + intermediates?: string; + /** + * Final byte, must be in range \x40 .. \x7e for CSI and DCS, + * \x30 .. \x7e for ESC. + */ + final: string; + } + + /** + * Allows hooking into the parser for custom handling of escape sequences. + * + * Note on sync vs. async handlers: + * xterm.js implements all parser actions with synchronous handlers. + * In general custom handlers should also operate in sync mode wherever + * possible to keep the parser fast. + * Still the exposed interfaces allow to register async handlers by returning + * a `Promise`. Here the parser will pause input processing until + * the promise got resolved or rejected (in-band blocking). This "full stop" + * on the input chain allows to implement backpressure from a certain async + * action while the terminal state will not progress any further from input. + * It does not mean that the terminal state will not change at all in between, + * as user actions like resize or reset are still processed immediately. + * It is an error to assume a stable terminal state while giving back control + * in between, e.g. by multiple chained `then` calls. + * Downside of an async handler is a rather bad throughput performance, + * thus use async handlers only as a last resort or for actions that have + * to rely on async interfaces itself. + */ + export interface IParser { + /** + * Adds a handler for CSI escape sequences. + * @param id Specifies the function identifier under which the callback gets + * registered, e.g. {final: 'm'} for SGR. + * @param callback The function to handle the sequence. The callback is + * called with the numerical params. If the sequence has subparams the array + * will contain subarrays with their numercial values. Return `true` if the + * sequence was handled, `false` if the parser should try a previous + * handler. The most recently added handler is tried first. + * @returns An IDisposable you can call to remove this handler. + */ + registerCsiHandler(id: IFunctionIdentifier, callback: (params: (number | number[])[]) => boolean | Promise): IDisposable; + + /** + * Adds a handler for DCS escape sequences. + * @param id Specifies the function identifier under which the callback gets + * registered, e.g. {intermediates: '$' final: 'q'} for DECRQSS. + * @param callback The function to handle the sequence. Note that the + * function will only be called once if the sequence finished sucessfully. + * There is currently no way to intercept smaller data chunks, data chunks + * will be stored up until the sequence is finished. Since DCS sequences are + * not limited by the amount of data this might impose a problem for big + * payloads. Currently xterm.js limits DCS payload to 10 MB which should + * give enough room for most use cases. The function gets the payload and + * numerical parameters as arguments. Return `true` if the sequence was + * handled, `false` if the parser should try a previous handler. The most + * recently added handler is tried first. + * @returns An IDisposable you can call to remove this handler. + */ + registerDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: (number | number[])[]) => boolean | Promise): IDisposable; + + /** + * Adds a handler for ESC escape sequences. + * @param id Specifies the function identifier under which the callback gets + * registered, e.g. {intermediates: '%' final: 'G'} for default charset + * selection. + * @param callback The function to handle the sequence. + * Return `true` if the sequence was handled, `false` if the parser should + * try a previous handler. The most recently added handler is tried first. + * @returns An IDisposable you can call to remove this handler. + */ + registerEscHandler(id: IFunctionIdentifier, handler: () => boolean | Promise): IDisposable; + + /** + * Adds a handler for OSC escape sequences. + * @param ident The number (first parameter) of the sequence. + * @param callback The function to handle the sequence. Note that the + * function will only be called once if the sequence finished sucessfully. + * There is currently no way to intercept smaller data chunks, data chunks + * will be stored up until the sequence is finished. Since OSC sequences are + * not limited by the amount of data this might impose a problem for big + * payloads. Currently xterm.js limits OSC payload to 10 MB which should + * give enough room for most use cases. The callback is called with OSC data + * string. Return `true` if the sequence was handled, `false` if the parser + * should try a previous handler. The most recently added handler is tried + * first. + * @returns An IDisposable you can call to remove this handler. + */ + registerOscHandler(ident: number, callback: (data: string) => boolean | Promise): IDisposable; + } + + /** + * (EXPERIMENTAL) Unicode version provider. + * Used to register custom Unicode versions with `Terminal.unicode.register`. + */ + export interface IUnicodeVersionProvider { + /** + * String indicating the Unicode version provided. + */ + readonly version: string; + + /** + * Unicode version dependent wcwidth implementation. + */ + wcwidth(codepoint: number): 0 | 1 | 2; + charProperties(codepoint: number, preceding: number): number; + } + + /** + * (EXPERIMENTAL) Unicode handling interface. + */ + export interface IUnicodeHandling { + /** + * Register a custom Unicode version provider. + */ + register(provider: IUnicodeVersionProvider): void; + + /** + * Registered Unicode versions. + */ + readonly versions: ReadonlyArray; + + /** + * Getter/setter for active Unicode version. + */ + activeVersion: string; + } + + /** + * Terminal modes as set by SM/DECSET. + */ + export interface IModes { + /** + * Application Cursor Keys (DECCKM): `CSI ? 1 h` + */ + readonly applicationCursorKeysMode: boolean; + /** + * Application Keypad Mode (DECNKM): `CSI ? 6 6 h` + */ + readonly applicationKeypadMode: boolean; + /** + * Bracketed Paste Mode: `CSI ? 2 0 0 4 h` + */ + readonly bracketedPasteMode: boolean; + /** + * Insert Mode (IRM): `CSI 4 h` + */ + readonly insertMode: boolean; + /** + * Mouse Tracking, this can be one of the following: + * - none: This is the default value and can be reset with DECRST + * - x10: Send Mouse X & Y on button press `CSI ? 9 h` + * - vt200: Send Mouse X & Y on button press and release `CSI ? 1 0 0 0 h` + * - drag: Use Cell Motion Mouse Tracking `CSI ? 1 0 0 2 h` + * - any: Use All Motion Mouse Tracking `CSI ? 1 0 0 3 h` + */ + readonly mouseTrackingMode: 'none' | 'x10' | 'vt200' | 'drag' | 'any'; + /** + * Origin Mode (DECOM): `CSI ? 6 h` + */ + readonly originMode: boolean; + /** + * Reverse-wraparound Mode: `CSI ? 4 5 h` + */ + readonly reverseWraparoundMode: boolean; + /** + * Send FocusIn/FocusOut events: `CSI ? 1 0 0 4 h` + */ + readonly sendFocusMode: boolean; + /** + * Synchronized Output Mode: `CSI ? 2 0 2 6 h` + * + * When enabled, output is buffered and only rendered when the mode is + * disabled, allowing for atomic screen updates without tearing. + */ + readonly synchronizedOutputMode: boolean; + /** + * Auto-Wrap Mode (DECAWM): `CSI ? 7 h` + */ + readonly wraparoundMode: boolean; + } +} diff --git a/package-lock.json b/package-lock.json index a41f802..ebbaf5c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,6 +9,8 @@ "version": "0.1.0", "dependencies": { "@tauri-apps/api": "^2.1.1", + "@xterm/addon-fit": "^0.11.0", + "@xterm/xterm": "^6.0.0", "react": "^18.3.1", "react-dom": "^18.3.1" }, @@ -1471,6 +1473,21 @@ "vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0" } }, + "node_modules/@xterm/addon-fit": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/@xterm/addon-fit/-/addon-fit-0.11.0.tgz", + "integrity": "sha512-jYcgT6xtVYhnhgxh3QgYDnnNMYTcf8ElbxxFzX0IZo+vabQqSPAjC3c1wJrKB5E19VwQei89QCiZZP86DCPF7g==", + "license": "MIT" + }, + "node_modules/@xterm/xterm": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/@xterm/xterm/-/xterm-6.0.0.tgz", + "integrity": "sha512-TQwDdQGtwwDt+2cgKDLn0IRaSxYu1tSUjgKarSDkUM0ZNiSRXFpjxEsvc/Zgc5kq5omJ+V0a8/kIM2WD3sMOYg==", + "license": "MIT", + "workspaces": [ + "addons/*" + ] + }, "node_modules/baseline-browser-mapping": { "version": "2.10.29", "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.10.29.tgz", diff --git a/package.json b/package.json index f874d8f..8aa9a3a 100644 --- a/package.json +++ b/package.json @@ -11,6 +11,8 @@ }, "dependencies": { "@tauri-apps/api": "^2.1.1", + "@xterm/addon-fit": "^0.11.0", + "@xterm/xterm": "^6.0.0", "react": "^18.3.1", "react-dom": "^18.3.1" }, diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 0f5d361..d312f1a 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -79,12 +79,15 @@ checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c" name = "app" version = "0.1.0" dependencies = [ + "base64 0.22.1", "log", + "portable-pty", "serde", "serde_json", "tauri", "tauri-build", "tauri-plugin-log", + "uuid", ] [[package]] @@ -753,6 +756,12 @@ dependencies = [ "tendril", ] +[[package]] +name = "downcast-rs" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2" + [[package]] name = "dpi" version = "0.1.2" @@ -815,7 +824,7 @@ dependencies = [ "rustc_version", "toml 1.1.2+spec-1.1.0", "vswhom", - "winreg", + "winreg 0.55.0", ] [[package]] @@ -881,10 +890,21 @@ version = "0.3.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "38e2275cc4e4fc009b0669731a1e5ab7ebf11f469eaede2bab9309a5b4d6057f" dependencies = [ - "memoffset", + "memoffset 0.9.1", "rustc_version", ] +[[package]] +name = "filedescriptor" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e40758ed24c9b2eeb76c35fb0aebc66c626084edd827e07e1552279814c6682d" +dependencies = [ + "libc", + "thiserror 1.0.69", + "winapi", +] + [[package]] name = "find-msvc-tools" version = "0.1.9" @@ -1640,6 +1660,15 @@ dependencies = [ "cfb", ] +[[package]] +name = "ioctl-rs" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7970510895cee30b3e9128319f2cefd4bde883a39f38baa279567ba3a7eb97d" +dependencies = [ + "libc", +] + [[package]] name = "ipnet" version = "2.12.0" @@ -1764,6 +1793,12 @@ dependencies = [ "unicode-segmentation", ] +[[package]] +name = "lazy_static" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" + [[package]] name = "leb128fmt" version = "0.1.0" @@ -1869,6 +1904,15 @@ version = "2.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" +[[package]] +name = "memoffset" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5aa361d4faea93603064a027415f07bd8e1d5c88c9fbf68bf56a285428fd79ce" +dependencies = [ + "autocfg", +] + [[package]] name = "memoffset" version = "0.9.1" @@ -1956,6 +2000,20 @@ version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" +[[package]] +name = "nix" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f346ff70e7dbfd675fe90590b92d59ef2de15a8779ae305ebcbfd3f0caf59be4" +dependencies = [ + "autocfg", + "bitflags 1.3.2", + "cfg-if", + "libc", + "memoffset 0.6.5", + "pin-utils", +] + [[package]] name = "num-conv" version = "0.2.1" @@ -2322,6 +2380,12 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +[[package]] +name = "pin-utils" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" + [[package]] name = "pkg-config" version = "0.3.33" @@ -2367,6 +2431,27 @@ dependencies = [ "miniz_oxide", ] +[[package]] +name = "portable-pty" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "806ee80c2a03dbe1a9fb9534f8d19e4c0546b790cde8fd1fea9d6390644cb0be" +dependencies = [ + "anyhow", + "bitflags 1.3.2", + "downcast-rs", + "filedescriptor", + "lazy_static", + "libc", + "log", + "nix", + "serial", + "shared_library", + "shell-words", + "winapi", + "winreg 0.10.1", +] + [[package]] name = "potential_utf" version = "0.1.5" @@ -2968,6 +3053,48 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "serial" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1237a96570fc377c13baa1b88c7589ab66edced652e43ffb17088f003db3e86" +dependencies = [ + "serial-core", + "serial-unix", + "serial-windows", +] + +[[package]] +name = "serial-core" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f46209b345401737ae2125fe5b19a77acce90cd53e1658cda928e4fe9a64581" +dependencies = [ + "libc", +] + +[[package]] +name = "serial-unix" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f03fbca4c9d866e24a459cbca71283f545a37f8e3e002ad8c70593871453cab7" +dependencies = [ + "ioctl-rs", + "libc", + "serial-core", + "termios", +] + +[[package]] +name = "serial-windows" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15c6d3b776267a75d31bbdfd5d36c0ca051251caafc285827052bc53bcdc8162" +dependencies = [ + "libc", + "serial-core", +] + [[package]] name = "serialize-to-javascript" version = "0.1.2" @@ -3010,6 +3137,22 @@ dependencies = [ "digest", ] +[[package]] +name = "shared_library" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a9e7e0f2bfae24d8a5b5a66c5b257a83c7412304311512a0c054cd5e619da11" +dependencies = [ + "lazy_static", + "libc", +] + +[[package]] +name = "shell-words" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc6fe69c597f9c37bfeeeeeb33da3530379845f10be461a66d16d03eca2ded77" + [[package]] name = "shlex" version = "1.3.0" @@ -3530,6 +3673,15 @@ dependencies = [ "utf-8", ] +[[package]] +name = "termios" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5d9cf598a6d7ce700a4e6a9199da127e6819a61e64b68609683cc9a01b5683a" +dependencies = [ + "libc", +] + [[package]] name = "thiserror" version = "1.0.69" @@ -4653,6 +4805,15 @@ dependencies = [ "memchr", ] +[[package]] +name = "winreg" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80d0f4e272c85def139476380b12f9ac60926689dd2e01d4923222f40580869d" +dependencies = [ + "winapi", +] + [[package]] name = "winreg" version = "0.55.0" diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 5ad23a2..cd7f776 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -23,3 +23,6 @@ serde = { version = "1.0", features = ["derive"] } log = "0.4" tauri = { version = "2.11.1" } tauri-plugin-log = "2" +portable-pty = "0.8" +uuid = { version = "1", features = ["v4"] } +base64 = "0.22" diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 9c3118c..0ffe21b 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1,16 +1,27 @@ +mod pty; + +use pty::{pty_kill, pty_resize, pty_spawn, pty_write, PtyState}; + #[cfg_attr(mobile, tauri::mobile_entry_point)] pub fn run() { - tauri::Builder::default() - .setup(|app| { - if cfg!(debug_assertions) { - app.handle().plugin( - tauri_plugin_log::Builder::default() - .level(log::LevelFilter::Info) - .build(), - )?; - } - Ok(()) - }) - .run(tauri::generate_context!()) - .expect("error while running tauri application"); + tauri::Builder::default() + .manage(PtyState::default()) + .setup(|app| { + if cfg!(debug_assertions) { + app.handle().plugin( + tauri_plugin_log::Builder::default() + .level(log::LevelFilter::Info) + .build(), + )?; + } + Ok(()) + }) + .invoke_handler(tauri::generate_handler![ + pty_spawn, + pty_write, + pty_resize, + pty_kill, + ]) + .run(tauri::generate_context!()) + .expect("error while running tauri application"); } diff --git a/src-tauri/src/pty.rs b/src-tauri/src/pty.rs new file mode 100644 index 0000000..c5cb1f4 --- /dev/null +++ b/src-tauri/src/pty.rs @@ -0,0 +1,164 @@ +use base64::{engine::general_purpose::STANDARD as B64, Engine as _}; +use portable_pty::{native_pty_system, CommandBuilder, MasterPty, PtySize}; +use serde::{Deserialize, Serialize}; +use std::collections::HashMap; +use std::io::{Read, Write}; +use std::sync::Mutex; +use tauri::{AppHandle, Emitter, State}; +use uuid::Uuid; + +pub struct PtyHandle { + master: Box, + writer: Box, +} + +#[derive(Default)] +pub struct PtyState { + handles: Mutex>, +} + +#[derive(Deserialize)] +pub struct SpawnOpts { + pub cols: u16, + pub rows: u16, + pub shell: Option, + pub cwd: Option, +} + +#[derive(Serialize, Clone)] +struct DataPayload { + id: String, + data: String, +} + +#[derive(Serialize, Clone)] +struct ExitPayload { + id: String, + status: Option, +} + +#[tauri::command] +pub async fn pty_spawn( + app: AppHandle, + state: State<'_, PtyState>, + opts: SpawnOpts, +) -> Result { + let id = Uuid::new_v4().to_string(); + + let pty_system = native_pty_system(); + let pair = pty_system + .openpty(PtySize { + rows: opts.rows.max(1), + cols: opts.cols.max(1), + pixel_width: 0, + pixel_height: 0, + }) + .map_err(|e| e.to_string())?; + + let shell = opts + .shell + .or_else(|| std::env::var("SHELL").ok()) + .unwrap_or_else(|| "/bin/bash".into()); + + let mut cmd = CommandBuilder::new(&shell); + if let Some(cwd) = opts.cwd { + cmd.cwd(cwd); + } else if let Ok(home) = std::env::var("HOME") { + cmd.cwd(home); + } + cmd.env("TERM", "xterm-256color"); + cmd.env("COLORTERM", "truecolor"); + + let mut child = pair + .slave + .spawn_command(cmd) + .map_err(|e| e.to_string())?; + drop(pair.slave); + + let reader = pair + .master + .try_clone_reader() + .map_err(|e| e.to_string())?; + let writer = pair + .master + .take_writer() + .map_err(|e| e.to_string())?; + + let app_for_thread = app.clone(); + let id_for_thread = id.clone(); + std::thread::spawn(move || { + let mut reader = reader; + let mut buf = vec![0u8; 4096]; + loop { + match reader.read(&mut buf) { + Ok(0) => break, + Ok(n) => { + let payload = DataPayload { + id: id_for_thread.clone(), + data: B64.encode(&buf[..n]), + }; + let _ = app_for_thread.emit("pty:data", payload); + } + Err(_) => break, + } + } + let status = child.wait().ok().map(|s| s.exit_code() as i32); + let _ = app_for_thread.emit( + "pty:exit", + ExitPayload { + id: id_for_thread, + status, + }, + ); + }); + + state + .handles + .lock() + .unwrap() + .insert(id.clone(), PtyHandle { master: pair.master, writer }); + + Ok(id) +} + +#[tauri::command] +pub fn pty_write( + state: State<'_, PtyState>, + id: String, + data: String, +) -> Result<(), String> { + let bytes = B64.decode(&data).map_err(|e| e.to_string())?; + let mut handles = state.handles.lock().unwrap(); + let handle = handles.get_mut(&id).ok_or("pty not found")?; + handle.writer.write_all(&bytes).map_err(|e| e.to_string())?; + handle.writer.flush().map_err(|e| e.to_string())?; + Ok(()) +} + +#[tauri::command] +pub fn pty_resize( + state: State<'_, PtyState>, + id: String, + cols: u16, + rows: u16, +) -> Result<(), String> { + let handles = state.handles.lock().unwrap(); + let handle = handles.get(&id).ok_or("pty not found")?; + handle + .master + .resize(PtySize { + cols: cols.max(1), + rows: rows.max(1), + pixel_width: 0, + pixel_height: 0, + }) + .map_err(|e| e.to_string())?; + Ok(()) +} + +#[tauri::command] +pub fn pty_kill(state: State<'_, PtyState>, id: String) -> Result<(), String> { + // Dropping the handle closes the master fd; child receives SIGHUP and exits. + state.handles.lock().unwrap().remove(&id); + Ok(()) +} diff --git a/src/App.tsx b/src/App.tsx index a037173..24d8619 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -7,20 +7,14 @@ const initialCards: Card[] = [ kind: "note", x: 200, y: 200, - width: 320, - height: 180, - z: 0, - text: "Welcome to Infinite.\n\nPan: middle-drag or space+drag.\nZoom: Ctrl+wheel.", - }, - { - id: "todo", - kind: "note", - x: 600, - y: 320, - width: 260, - height: 140, - z: 0, - text: "Next: terminal cards, then X11 embedding.", + width: 340, + height: 200, + z: 1, + text: + "Welcome to Infinite.\n\n" + + "Pan: middle-drag or Space + drag\n" + + "Zoom: Ctrl + scroll\n\n" + + "Use the toolbar to add notes and terminals.", }, ]; diff --git a/src/canvas/Canvas.tsx b/src/canvas/Canvas.tsx index 2cb442a..721bf45 100644 --- a/src/canvas/Canvas.tsx +++ b/src/canvas/Canvas.tsx @@ -2,6 +2,7 @@ import { useEffect, useRef, useState, useCallback } from "react"; import type { Card, Viewport } from "./types"; import { ViewportContext } from "./viewport"; import { NoteCardView } from "./cards/NoteCardView"; +import { TerminalCardView } from "./cards/TerminalCardView"; import "./canvas.css"; const MIN_SCALE = 0.1; @@ -20,6 +21,9 @@ export function Canvas({ initialCards }: CanvasProps) { const panState = useRef<{ startX: number; startY: number; vpX: number; vpY: number } | null>( null, ); + const maxZRef = useRef( + initialCards.reduce((m, c) => Math.max(m, c.z), 0), + ); useEffect(() => { const onKeyDown = (e: KeyboardEvent) => { @@ -36,23 +40,17 @@ export function Canvas({ initialCards }: CanvasProps) { }; }, []); - // Suppress WebKit/GTK middle-click defaults (autoscroll on some platforms, - // paste primary selection on Linux). Must be a native listener — React's - // synthetic onPointerDown.preventDefault doesn't reliably stop these. useEffect(() => { const el = containerRef.current; if (!el) return; const stopMiddle = (e: MouseEvent) => { if (e.button === 1) e.preventDefault(); }; - const stopAux = (e: MouseEvent) => { - if (e.button === 1) e.preventDefault(); - }; el.addEventListener("mousedown", stopMiddle); - el.addEventListener("auxclick", stopAux); + el.addEventListener("auxclick", stopMiddle); return () => { el.removeEventListener("mousedown", stopMiddle); - el.removeEventListener("auxclick", stopAux); + el.removeEventListener("auxclick", stopMiddle); }; }, []); @@ -74,8 +72,6 @@ export function Canvas({ initialCards }: CanvasProps) { const isPan = e.button === 1 || (e.button === 0 && spaceHeld); if (!isPan) return; e.preventDefault(); - // Capture on the container, not e.target — survives card re-renders and - // avoids odd behavior when the click lands on a textarea or child element. containerRef.current?.setPointerCapture(e.pointerId); panState.current = { startX: e.clientX, startY: e.clientY, vpX: vp.x, vpY: vp.y }; }; @@ -93,7 +89,7 @@ export function Canvas({ initialCards }: CanvasProps) { try { containerRef.current?.releasePointerCapture(e.pointerId); } catch { - // capture may already be released if pointercancel fired + // already released } panState.current = null; } @@ -103,6 +99,41 @@ export function Canvas({ initialCards }: CanvasProps) { setCards((cs) => cs.map((c) => (c.id === id ? ({ ...c, ...patch } as Card) : c))); }; + const addCardAtCenter = (build: (id: string, x: number, y: number, z: number) => Card) => { + const w = window.innerWidth / 2; + const h = window.innerHeight / 2; + const cx = (w - vp.x) / vp.scale; + const cy = (h - vp.y) / vp.scale; + const id = crypto.randomUUID(); + maxZRef.current += 1; + const card = build(id, cx, cy, maxZRef.current); + setCards((cs) => [...cs, card]); + }; + + const addNote = () => + addCardAtCenter((id, cx, cy, z) => ({ + id, + kind: "note", + x: cx - 160, + y: cy - 90, + width: 320, + height: 180, + z, + text: "", + })); + + const addTerminal = () => + addCardAtCenter((id, cx, cy, z) => ({ + id, + kind: "terminal", + x: cx - 280, + y: cy - 180, + width: 560, + height: 360, + z, + ptyId: "", + })); + return (
updateCard(c.id, p)} />; } + if (c.kind === "terminal") { + return updateCard(c.id, p)} />; + } return null; })} +
+ + +
x {vp.x.toFixed(0)} y {vp.y.toFixed(0)} diff --git a/src/canvas/canvas.css b/src/canvas/canvas.css index 8e65fea..95d30b8 100644 --- a/src/canvas/canvas.css +++ b/src/canvas/canvas.css @@ -78,3 +78,43 @@ font-size: 1em; padding: 0.77em; } + +.terminal-body { + background: #1d1d23; + padding: calc(4px * var(--scale, 1)); + height: 100%; +} + +.terminal-body .xterm, +.terminal-body .xterm-viewport, +.terminal-body .xterm-screen { + height: 100% !important; + width: 100% !important; +} + +.toolbar { + position: fixed; + top: 12px; + left: 12px; + display: flex; + gap: 6px; + padding: 6px; + background: rgba(0, 0, 0, 0.5); + border-radius: 8px; + z-index: 1000; +} + +.toolbar button { + background: var(--card-bg); + color: var(--text); + border: 1px solid var(--card-border); + border-radius: 5px; + padding: 6px 10px; + font-size: 12px; + cursor: pointer; + font-family: inherit; +} + +.toolbar button:hover { + border-color: var(--accent); +} diff --git a/src/canvas/cards/NoteCardView.tsx b/src/canvas/cards/NoteCardView.tsx index 3e89d71..74c05b1 100644 --- a/src/canvas/cards/NoteCardView.tsx +++ b/src/canvas/cards/NoteCardView.tsx @@ -1,6 +1,6 @@ -import { useRef } from "react"; import type { NoteCard } from "../types"; import { useViewport } from "../viewport"; +import { useDragHandle } from "../useDragHandle"; interface Props { card: NoteCard; @@ -11,63 +11,24 @@ const BODY_FONT_BASE = 13; export function NoteCardView({ card, onUpdate }: Props) { const vp = useViewport(); - const dragState = useRef<{ startX: number; startY: number; cardX: number; cardY: number } | null>( - null, - ); - - const onHeaderPointerDown = (e: React.PointerEvent) => { - if (e.button !== 0) return; - e.stopPropagation(); - (e.target as Element).setPointerCapture(e.pointerId); - dragState.current = { startX: e.clientX, startY: e.clientY, cardX: card.x, cardY: card.y }; - }; - - const onHeaderPointerMove = (e: React.PointerEvent) => { - const ds = dragState.current; - if (!ds) return; - const dx = (e.clientX - ds.startX) / vp.scale; - const dy = (e.clientY - ds.startY) / vp.scale; - onUpdate({ x: ds.cardX + dx, y: ds.cardY + dy }); - }; - - const onHeaderPointerUp = (e: React.PointerEvent) => { - if (dragState.current) { - try { - (e.target as Element).releasePointerCapture(e.pointerId); - } catch { - // already released - } - dragState.current = null; - } - }; - - const screenLeft = vp.x + card.x * vp.scale; - const screenTop = vp.y + card.y * vp.scale; - const screenW = card.width * vp.scale; - const screenH = card.height * vp.scale; + const drag = useDragHandle(card, (p) => onUpdate(p)); return (
-
+
note
diff --git a/src/canvas/cards/TerminalCardView.tsx b/src/canvas/cards/TerminalCardView.tsx new file mode 100644 index 0000000..cb6d648 --- /dev/null +++ b/src/canvas/cards/TerminalCardView.tsx @@ -0,0 +1,130 @@ +import { useEffect, useRef, useState } from "react"; +import { Terminal } from "@xterm/xterm"; +import { FitAddon } from "@xterm/addon-fit"; +import "@xterm/xterm/css/xterm.css"; +import type { TerminalCard } from "../types"; +import { useViewport } from "../viewport"; +import { useDragHandle } from "../useDragHandle"; +import { pty, base64ToBytes, stringToBase64 } from "../../ipc"; + +const BASE_FONT_SIZE = 13; + +interface Props { + card: TerminalCard; + onUpdate: (patch: Partial) => void; +} + +export function TerminalCardView({ card, onUpdate }: Props) { + const vp = useViewport(); + const drag = useDragHandle(card, (p) => onUpdate(p)); + const containerRef = useRef(null); + const termRef = useRef(null); + const fitRef = useRef(null); + const ptyIdRef = useRef(card.ptyId); + const [ready, setReady] = useState(false); + + useEffect(() => { + let unlistenData: (() => void) | undefined; + let unlistenExit: (() => void) | undefined; + let disposed = false; + + const term = new Terminal({ + fontSize: BASE_FONT_SIZE * vp.scale, + fontFamily: 'Menlo, "Cascadia Code", Consolas, monospace', + theme: { + background: "#1d1d23", + foreground: "#e8e8ec", + cursor: "#e8e8ec", + }, + cursorBlink: true, + allowProposedApi: true, + }); + const fit = new FitAddon(); + term.loadAddon(fit); + term.open(containerRef.current!); + fit.fit(); + termRef.current = term; + fitRef.current = fit; + + (async () => { + let id = ptyIdRef.current; + if (!id) { + id = await pty.spawn({ cols: term.cols, rows: term.rows }); + if (disposed) { + await pty.kill(id); + return; + } + ptyIdRef.current = id; + onUpdate({ ptyId: id }); + } + + unlistenData = await pty.onData((e) => { + if (e.id !== id) return; + term.write(base64ToBytes(e.data)); + }); + unlistenExit = await pty.onExit((e) => { + if (e.id !== id) return; + term.write("\r\n\x1b[2m[process exited]\x1b[0m\r\n"); + }); + + term.onData((data) => { + pty.write(id!, stringToBase64(data)).catch((err) => console.error("pty_write", err)); + }); + term.onResize(({ cols, rows }) => { + pty.resize(id!, cols, rows).catch(() => {}); + }); + + setReady(true); + })(); + + return () => { + disposed = true; + unlistenData?.(); + unlistenExit?.(); + term.dispose(); + }; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + + // Update xterm font size when canvas zoom changes so text stays crisp. + useEffect(() => { + if (!ready) return; + const term = termRef.current; + const fit = fitRef.current; + if (!term || !fit) return; + term.options.fontSize = BASE_FONT_SIZE * vp.scale; + fit.fit(); + }, [vp.scale, ready]); + + // Refit on card resize. + useEffect(() => { + if (!ready) return; + fitRef.current?.fit(); + }, [card.width, card.height, ready]); + + return ( +
+
+ terminal +
+
e.stopPropagation()} + onWheel={(e) => e.stopPropagation()} + /> +
+ ); +} diff --git a/src/canvas/useDragHandle.ts b/src/canvas/useDragHandle.ts new file mode 100644 index 0000000..32d6a94 --- /dev/null +++ b/src/canvas/useDragHandle.ts @@ -0,0 +1,47 @@ +import { useRef } from "react"; +import { useViewport } from "./viewport"; + +interface Pos { + x: number; + y: number; +} + +export function useDragHandle(card: Pos, onUpdate: (p: Pos) => void) { + const vp = useViewport(); + const dragRef = useRef<{ startX: number; startY: number; cardX: number; cardY: number } | null>( + null, + ); + + const onPointerDown = (e: React.PointerEvent) => { + if (e.button !== 0) return; + e.stopPropagation(); + (e.target as Element).setPointerCapture(e.pointerId); + dragRef.current = { startX: e.clientX, startY: e.clientY, cardX: card.x, cardY: card.y }; + }; + + const onPointerMove = (e: React.PointerEvent) => { + const d = dragRef.current; + if (!d) return; + const dx = (e.clientX - d.startX) / vp.scale; + const dy = (e.clientY - d.startY) / vp.scale; + onUpdate({ x: d.cardX + dx, y: d.cardY + dy }); + }; + + const onPointerUp = (e: React.PointerEvent) => { + if (dragRef.current) { + try { + (e.target as Element).releasePointerCapture(e.pointerId); + } catch { + // already released + } + dragRef.current = null; + } + }; + + return { + onPointerDown, + onPointerMove, + onPointerUp, + onPointerCancel: onPointerUp, + }; +} diff --git a/src/ipc.ts b/src/ipc.ts new file mode 100644 index 0000000..0fc5dcf --- /dev/null +++ b/src/ipc.ts @@ -0,0 +1,50 @@ +import { invoke } from "@tauri-apps/api/core"; +import { listen, type UnlistenFn } from "@tauri-apps/api/event"; + +export interface PtySpawnOpts { + cols: number; + rows: number; + shell?: string; + cwd?: string; +} + +export interface PtyDataEvent { + id: string; + data: string; +} + +export interface PtyExitEvent { + id: string; + status: number | null; +} + +export const pty = { + spawn: (opts: PtySpawnOpts) => invoke("pty_spawn", { opts }), + write: (id: string, dataBase64: string) => + invoke("pty_write", { id, data: dataBase64 }), + resize: (id: string, cols: number, rows: number) => + invoke("pty_resize", { id, cols, rows }), + kill: (id: string) => invoke("pty_kill", { id }), + + onData: (handler: (e: PtyDataEvent) => void): Promise => + listen("pty:data", (e) => handler(e.payload)), + onExit: (handler: (e: PtyExitEvent) => void): Promise => + listen("pty:exit", (e) => handler(e.payload)), +}; + +export function bytesToBase64(bytes: Uint8Array): string { + let bin = ""; + for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]); + return btoa(bin); +} + +export function base64ToBytes(b64: string): Uint8Array { + const bin = atob(b64); + const out = new Uint8Array(bin.length); + for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); + return out; +} + +export function stringToBase64(s: string): string { + return bytesToBase64(new TextEncoder().encode(s)); +}