=r)return this._interim=s,i;var a;56320<=(a=e.charCodeAt(o))&&a<=57343?t[i++]=1024*(s-55296)+a-56320+65536:(t[i++]=s,t[i++]=a)}else t[i++]=s}return i},e}();t.StringToUtf32=i;var n=function(){function e(){this.interim=new Uint8Array(3)}return e.prototype.clear=function(){this.interim.fill(0)},e.prototype.decode=function(e,t){var r=e.length;if(!r)return 0;var i,n,o,s,a=0,c=0,l=0;if(this.interim[0]){var h=!1,u=this.interim[0];u&=192==(224&u)?31:224==(240&u)?15:7;for(var f=0,_=void 0;(_=63&this.interim[++f])&&f<4;)u<<=6,u|=_;for(var d=192==(224&this.interim[0])?2:224==(240&this.interim[0])?3:4,p=d-f;l=r)return 0;if(128!=(192&(_=e[l++]))){l--,h=!0;break}this.interim[f++]=_,u<<=6,u|=63&_}h||(2===d?u<128?l--:t[a++]=u:3===d?u<2048||u>=55296&&u<=57343||(t[a++]=u):u<65536||u>1114111||(t[a++]=u)),this.interim.fill(0)}for(var v=r-4,g=l;g=r)return this.interim[0]=i,a;if(128!=(192&(n=e[g++]))){g--;continue}if((c=(31&i)<<6|63&n)<128){g--;continue}t[a++]=c}else if(224==(240&i)){if(g>=r)return this.interim[0]=i,a;if(128!=(192&(n=e[g++]))){g--;continue}if(g>=r)return this.interim[0]=i,this.interim[1]=n,a;if(128!=(192&(o=e[g++]))){g--;continue}if((c=(15&i)<<12|(63&n)<<6|63&o)<2048||c>=55296&&c<=57343)continue;t[a++]=c}else if(240==(248&i)){if(g>=r)return this.interim[0]=i,a;if(128!=(192&(n=e[g++]))){g--;continue}if(g>=r)return this.interim[0]=i,this.interim[1]=n,a;if(128!=(192&(o=e[g++]))){g--;continue}if(g>=r)return this.interim[0]=i,this.interim[1]=n,this.interim[2]=o,a;if(128!=(192&(s=e[g++]))){g--;continue}if((c=(7&i)<<18|(63&n)<<12|(63&o)<<6|63&s)<65536||c>1114111)continue;t[a++]=c}}return a},e}();t.Utf8ToUtf32=n},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CHAR_ATLAS_CELL_SPACING=t.DIM_OPACITY=t.INVERTED_DEFAULT_COLOR=void 0,t.INVERTED_DEFAULT_COLOR=257,t.DIM_OPACITY=.5,t.CHAR_ATLAS_CELL_SPACING=1},function(e,t,r){"use strict";var i,n,o,s;function a(e){var t=e.toString(16);return t.length<2?"0"+t:t}function c(e,t){return e>>0}}(i=t.channels||(t.channels={})),(n=t.color||(t.color={})).blend=function(e,t){var r=(255&t.rgba)/255;if(1===r)return{css:t.css,rgba:t.rgba};var n=t.rgba>>24&255,o=t.rgba>>16&255,s=t.rgba>>8&255,a=e.rgba>>24&255,c=e.rgba>>16&255,l=e.rgba>>8&255,h=a+Math.round((n-a)*r),u=c+Math.round((o-c)*r),f=l+Math.round((s-l)*r);return{css:i.toCss(h,u,f),rgba:i.toRgba(h,u,f)}},n.isOpaque=function(e){return 255==(255&e.rgba)},n.ensureContrastRatio=function(e,t,r){var i=s.ensureContrastRatio(e.rgba,t.rgba,r);if(i)return s.toColor(i>>24&255,i>>16&255,i>>8&255)},n.opaque=function(e){var t=(255|e.rgba)>>>0,r=s.toChannels(t),n=r[0],o=r[1],a=r[2];return{css:i.toCss(n,o,a),rgba:t}},n.opacity=function(e,t){var r=Math.round(255*t),n=s.toChannels(e.rgba),o=n[0],a=n[1],c=n[2];return{css:i.toCss(o,a,c,r),rgba:i.toRgba(o,a,c,r)}},(t.css||(t.css={})).toColor=function(e){switch(e.length){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}}throw new Error("css.toColor: Unsupported css format")},function(e){function t(e,t,r){var i=e/255,n=t/255,o=r/255;return.2126*(i<=.03928?i/12.92:Math.pow((i+.055)/1.055,2.4))+.7152*(n<=.03928?n/12.92:Math.pow((n+.055)/1.055,2.4))+.0722*(o<=.03928?o/12.92:Math.pow((o+.055)/1.055,2.4))}e.relativeLuminance=function(e){return t(e>>16&255,e>>8&255,255&e)},e.relativeLuminance2=t}(o=t.rgb||(t.rgb={})),function(e){function t(e,t,r){for(var i=e>>24&255,n=e>>16&255,s=e>>8&255,a=t>>24&255,l=t>>16&255,h=t>>8&255,u=c(o.relativeLuminance2(a,h,l),o.relativeLuminance2(i,n,s));u0||l>0||h>0);)a-=Math.max(0,Math.ceil(.1*a)),l-=Math.max(0,Math.ceil(.1*l)),h-=Math.max(0,Math.ceil(.1*h)),u=c(o.relativeLuminance2(a,h,l),o.relativeLuminance2(i,n,s));return(a<<24|l<<16|h<<8|255)>>>0}function r(e,t,r){for(var i=e>>24&255,n=e>>16&255,s=e>>8&255,a=t>>24&255,l=t>>16&255,h=t>>8&255,u=c(o.relativeLuminance2(a,h,l),o.relativeLuminance2(i,n,s));u>>0}e.ensureContrastRatio=function(e,i,n){var s=o.relativeLuminance(e>>8),a=o.relativeLuminance(i>>8);if(c(s,a)>24&255,e>>16&255,e>>8&255,255&e]},e.toColor=function(e,t,r){return{css:i.toCss(e,t,r),rgba:i.toRgba(e,t,r)}}}(s=t.rgba||(t.rgba={})),t.toPaddedHex=a,t.contrastRatio=c},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isLinux=t.isWindows=t.isIphone=t.isIpad=t.isMac=t.isSafari=t.isFirefox=void 0;var i="undefined"==typeof navigator,n=i?"node":navigator.userAgent,o=i?"node":navigator.platform;function s(e,t){return e.indexOf(t)>=0}t.isFirefox=!!~n.indexOf("Firefox"),t.isSafari=/^((?!chrome|android).)*safari/i.test(n),t.isMac=s(["Macintosh","MacIntel","MacPPC","Mac68K"],o),t.isIpad="iPad"===o,t.isIphone="iPhone"===o,t.isWindows=s(["Windows","Win16","Win32","WinCE"],o),t.isLinux=o.indexOf("Linux")>=0},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),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=""}(t.C0||(t.C0={})),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=""}(t.C1||(t.C1={}))},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BaseRenderLayer=void 0;var i=r(3),n=r(9),o=r(25),s=r(6),a=r(28),c=r(10),l=r(17),h=function(){function e(e,t,r,i,n,o,s,a){this._container=e,this._alpha=i,this._colors=n,this._rendererId=o,this._bufferService=s,this._optionsService=a,this._scaledCharWidth=0,this._scaledCharHeight=0,this._scaledCellWidth=0,this._scaledCellHeight=0,this._scaledCharLeft=0,this._scaledCharTop=0,this._currentGlyphIdentifier={chars:"",code:0,bg:0,fg:0,bold:!1,dim:!1,italic:!1},this._canvas=document.createElement("canvas"),this._canvas.classList.add("xterm-"+t+"-layer"),this._canvas.style.zIndex=r.toString(),this._initCanvas(),this._container.appendChild(this._canvas)}return e.prototype.dispose=function(){var e;l.removeElementFromParent(this._canvas),null===(e=this._charAtlas)||void 0===e||e.dispose()},e.prototype._initCanvas=function(){this._ctx=a.throwIfFalsy(this._canvas.getContext("2d",{alpha:this._alpha})),this._alpha||this._clearAll()},e.prototype.onOptionsChanged=function(){},e.prototype.onBlur=function(){},e.prototype.onFocus=function(){},e.prototype.onCursorMove=function(){},e.prototype.onGridChanged=function(e,t){},e.prototype.onSelectionChanged=function(e,t,r){void 0===r&&(r=!1)},e.prototype.setColors=function(e){this._refreshCharAtlas(e)},e.prototype._setTransparency=function(e){if(e!==this._alpha){var t=this._canvas;this._alpha=e,this._canvas=this._canvas.cloneNode(),this._initCanvas(),this._container.replaceChild(this._canvas,t),this._refreshCharAtlas(this._colors),this.onGridChanged(0,this._bufferService.rows-1)}},e.prototype._refreshCharAtlas=function(e){this._scaledCharWidth<=0&&this._scaledCharHeight<=0||(this._charAtlas=o.acquireCharAtlas(this._optionsService.options,this._rendererId,e,this._scaledCharWidth,this._scaledCharHeight),this._charAtlas.warmUp())},e.prototype.resize=function(e){this._scaledCellWidth=e.scaledCellWidth,this._scaledCellHeight=e.scaledCellHeight,this._scaledCharWidth=e.scaledCharWidth,this._scaledCharHeight=e.scaledCharHeight,this._scaledCharLeft=e.scaledCharLeft,this._scaledCharTop=e.scaledCharTop,this._canvas.width=e.scaledCanvasWidth,this._canvas.height=e.scaledCanvasHeight,this._canvas.style.width=e.canvasWidth+"px",this._canvas.style.height=e.canvasHeight+"px",this._alpha||this._clearAll(),this._refreshCharAtlas(this._colors)},e.prototype._fillCells=function(e,t,r,i){this._ctx.fillRect(e*this._scaledCellWidth,t*this._scaledCellHeight,r*this._scaledCellWidth,i*this._scaledCellHeight)},e.prototype._fillBottomLineAtCells=function(e,t,r){void 0===r&&(r=1),this._ctx.fillRect(e*this._scaledCellWidth,(t+1)*this._scaledCellHeight-window.devicePixelRatio-1,r*this._scaledCellWidth,window.devicePixelRatio)},e.prototype._fillLeftLineAtCell=function(e,t,r){this._ctx.fillRect(e*this._scaledCellWidth,t*this._scaledCellHeight,window.devicePixelRatio*r,this._scaledCellHeight)},e.prototype._strokeRectAtCell=function(e,t,r,i){this._ctx.lineWidth=window.devicePixelRatio,this._ctx.strokeRect(e*this._scaledCellWidth+window.devicePixelRatio/2,t*this._scaledCellHeight+window.devicePixelRatio/2,r*this._scaledCellWidth-window.devicePixelRatio,i*this._scaledCellHeight-window.devicePixelRatio)},e.prototype._clearAll=function(){this._alpha?this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height):(this._ctx.fillStyle=this._colors.background.css,this._ctx.fillRect(0,0,this._canvas.width,this._canvas.height))},e.prototype._clearCells=function(e,t,r,i){this._alpha?this._ctx.clearRect(e*this._scaledCellWidth,t*this._scaledCellHeight,r*this._scaledCellWidth,i*this._scaledCellHeight):(this._ctx.fillStyle=this._colors.background.css,this._ctx.fillRect(e*this._scaledCellWidth,t*this._scaledCellHeight,r*this._scaledCellWidth,i*this._scaledCellHeight))},e.prototype._fillCharTrueColor=function(e,t,r){this._ctx.font=this._getFont(!1,!1),this._ctx.textBaseline="middle",this._clipRow(r),this._ctx.fillText(e.getChars(),t*this._scaledCellWidth+this._scaledCharLeft,r*this._scaledCellHeight+this._scaledCharTop+this._scaledCharHeight/2)},e.prototype._drawChars=function(e,t,r){var o,s,a=this._getContrastColor(e);a||e.isFgRGB()||e.isBgRGB()?this._drawUncachedChars(e,t,r,a):(e.isInverse()?(o=e.isBgDefault()?n.INVERTED_DEFAULT_COLOR:e.getBgColor(),s=e.isFgDefault()?n.INVERTED_DEFAULT_COLOR:e.getFgColor()):(s=e.isBgDefault()?i.DEFAULT_COLOR:e.getBgColor(),o=e.isFgDefault()?i.DEFAULT_COLOR:e.getFgColor()),o+=this._optionsService.options.drawBoldTextInBrightColors&&e.isBold()&&o<8?8:0,this._currentGlyphIdentifier.chars=e.getChars()||i.WHITESPACE_CELL_CHAR,this._currentGlyphIdentifier.code=e.getCode()||i.WHITESPACE_CELL_CODE,this._currentGlyphIdentifier.bg=s,this._currentGlyphIdentifier.fg=o,this._currentGlyphIdentifier.bold=!!e.isBold(),this._currentGlyphIdentifier.dim=!!e.isDim(),this._currentGlyphIdentifier.italic=!!e.isItalic(),this._charAtlas&&this._charAtlas.draw(this._ctx,this._currentGlyphIdentifier,t*this._scaledCellWidth+this._scaledCharLeft,r*this._scaledCellHeight+this._scaledCharTop)||this._drawUncachedChars(e,t,r))},e.prototype._drawUncachedChars=function(e,t,r,i){if(this._ctx.save(),this._ctx.font=this._getFont(!!e.isBold(),!!e.isItalic()),this._ctx.textBaseline="middle",e.isInverse())if(i)this._ctx.fillStyle=i.css;else if(e.isBgDefault())this._ctx.fillStyle=c.color.opaque(this._colors.background).css;else if(e.isBgRGB())this._ctx.fillStyle="rgb("+s.AttributeData.toColorRGB(e.getBgColor()).join(",")+")";else{var o=e.getBgColor();this._optionsService.options.drawBoldTextInBrightColors&&e.isBold()&&o<8&&(o+=8),this._ctx.fillStyle=this._colors.ansi[o].css}else if(i)this._ctx.fillStyle=i.css;else if(e.isFgDefault())this._ctx.fillStyle=this._colors.foreground.css;else if(e.isFgRGB())this._ctx.fillStyle="rgb("+s.AttributeData.toColorRGB(e.getFgColor()).join(",")+")";else{var a=e.getFgColor();this._optionsService.options.drawBoldTextInBrightColors&&e.isBold()&&a<8&&(a+=8),this._ctx.fillStyle=this._colors.ansi[a].css}this._clipRow(r),e.isDim()&&(this._ctx.globalAlpha=n.DIM_OPACITY),this._ctx.fillText(e.getChars(),t*this._scaledCellWidth+this._scaledCharLeft,r*this._scaledCellHeight+this._scaledCharTop+this._scaledCharHeight/2),this._ctx.restore()},e.prototype._clipRow=function(e){this._ctx.beginPath(),this._ctx.rect(0,e*this._scaledCellHeight,this._bufferService.cols*this._scaledCellWidth,this._scaledCellHeight),this._ctx.clip()},e.prototype._getFont=function(e,t){return(t?"italic":"")+" "+(e?this._optionsService.options.fontWeightBold:this._optionsService.options.fontWeight)+" "+this._optionsService.options.fontSize*window.devicePixelRatio+"px "+this._optionsService.options.fontFamily},e.prototype._getContrastColor=function(e){if(1!==this._optionsService.options.minimumContrastRatio){var t=this._colors.contrastCache.getColor(e.bg,e.fg);if(void 0!==t)return t||void 0;var r=e.getFgColor(),i=e.getFgColorMode(),n=e.getBgColor(),o=e.getBgColorMode(),s=!!e.isInverse(),a=!!e.isInverse();if(s){var l=r;r=n,n=l;var h=i;i=o,o=h}var u=this._resolveBackgroundRgba(o,n,s),f=this._resolveForegroundRgba(i,r,s,a),_=c.rgba.ensureContrastRatio(u,f,this._optionsService.options.minimumContrastRatio);if(_){var d={css:c.channels.toCss(_>>24&255,_>>16&255,_>>8&255),rgba:_};return this._colors.contrastCache.setColor(e.bg,e.fg,d),d}this._colors.contrastCache.setColor(e.bg,e.fg,null)}},e.prototype._resolveBackgroundRgba=function(e,t,r){switch(e){case 16777216:case 33554432:return this._colors.ansi[t].rgba;case 50331648:return t<<8;case 0:default:return r?this._colors.foreground.rgba:this._colors.background.rgba}},e.prototype._resolveForegroundRgba=function(e,t,r,i){switch(e){case 16777216:case 33554432:return this._optionsService.options.drawBoldTextInBrightColors&&i&&t<8&&(t+=8),this._colors.ansi[t].rgba;case 50331648:return t<<8;case 0:default:return r?this._colors.background.rgba:this._colors.foreground.rgba}},e}();t.BaseRenderLayer=h},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createDecorator=t.getServiceDependencies=t.serviceRegistry=void 0;function i(e,t,r){t.di$target===t?t.di$dependencies.push({id:e,index:r}):(t.di$dependencies=[{id:e,index:r}],t.di$target=t)}t.serviceRegistry=new Map,t.getServiceDependencies=function(e){return e.di$dependencies||[]},t.createDecorator=function(e){if(t.serviceRegistry.has(e))return t.serviceRegistry.get(e);var r=function(e,t,n){if(3!==arguments.length)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");i(r,e,n)};return r.toString=function(){return e},t.serviceRegistry.set(e,r),r}},function(e,t,r){"use strict";function i(e,t,r,i){if(void 0===r&&(r=0),void 0===i&&(i=e.length),r>=e.length)return e;r=(e.length+r)%e.length,i=i>=e.length?e.length:(e.length+i)%e.length;for(var n=r;n>22,2097152&t?this._combined[e].charCodeAt(this._combined[e].length-1):r]},e.prototype.set=function(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},e.prototype.getWidth=function(e){return this._data[3*e+0]>>22},e.prototype.hasWidth=function(e){return 12582912&this._data[3*e+0]},e.prototype.getFg=function(e){return this._data[3*e+1]},e.prototype.getBg=function(e){return this._data[3*e+2]},e.prototype.hasContent=function(e){return 4194303&this._data[3*e+0]},e.prototype.getCodePoint=function(e){var t=this._data[3*e+0];return 2097152&t?this._combined[e].charCodeAt(this._combined[e].length-1):2097151&t},e.prototype.isCombined=function(e){return 2097152&this._data[3*e+0]},e.prototype.getString=function(e){var t=this._data[3*e+0];return 2097152&t?this._combined[e]:2097151&t?i.stringFromCodePoint(2097151&t):""},e.prototype.loadCell=function(e,t){var r=3*e;return t.content=this._data[r+0],t.fg=this._data[r+1],t.bg=this._data[r+2],2097152&t.content&&(t.combinedData=this._combined[e]),268435456&t.bg&&(t.extended=this._extendedAttrs[e]),t},e.prototype.setCell=function(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},e.prototype.setCellFromCodePoint=function(e,t,r,i,n,o){268435456&n&&(this._extendedAttrs[e]=o),this._data[3*e+0]=t|r<<22,this._data[3*e+1]=i,this._data[3*e+2]=n},e.prototype.addCodepointToCell=function(e,t){var r=this._data[3*e+0];2097152&r?this._combined[e]+=i.stringFromCodePoint(t):(2097151&r?(this._combined[e]=i.stringFromCodePoint(2097151&r)+i.stringFromCodePoint(t),r&=-2097152,r|=2097152):r=t|1<<22,this._data[3*e+0]=r)},e.prototype.insertCells=function(e,t,r,i){if((e%=this.length)&&2===this.getWidth(e-1)&&this.setCellFromCodePoint(e-1,0,1,(null==i?void 0:i.fg)||0,(null==i?void 0:i.bg)||0,(null==i?void 0:i.extended)||new s.ExtendedAttrs),t=0;--a)this.setCell(e+t+a,this.loadCell(e+a,n));for(a=0;athis.length){var r=new Uint32Array(3*e);this.length&&(3*e=e&&delete this._combined[o]}}else this._data=new Uint32Array(0),this._combined={};this.length=e}},e.prototype.fill=function(e){this._combined={},this._extendedAttrs={};for(var t=0;t=0;--e)if(4194303&this._data[3*e+0])return e+(this._data[3*e+0]>>22);return 0},e.prototype.copyCellsFrom=function(e,t,r,i,n){var o=e._data;if(n)for(var s=i-1;s>=0;s--)for(var a=0;a<3;a++)this._data[3*(r+s)+a]=o[3*(t+s)+a];else for(s=0;s=t&&(this._combined[l-t+r]=e._combined[l])}},e.prototype.translateToString=function(e,t,r){void 0===e&&(e=!1),void 0===t&&(t=0),void 0===r&&(r=this.length),e&&(r=Math.min(r,this.getTrimmedLength()));for(var o="";t>22||1}return o},e}();t.BufferLine=a},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.removeElementFromParent=void 0,t.removeElementFromParent=function(){for(var e,t=[],r=0;r24)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}!function(e){e[e.GET_WIN_SIZE_PIXELS=0]="GET_WIN_SIZE_PIXELS",e[e.GET_CELL_SIZE_PIXELS=1]="GET_CELL_SIZE_PIXELS"}(o=t.WindowsOptionsReportType||(t.WindowsOptionsReportType={}));var m=function(){function e(e,t,r,i){this._bufferService=e,this._coreService=t,this._logService=r,this._optionsService=i,this._data=new Uint32Array(0)}return e.prototype.hook=function(e){this._data=new Uint32Array(0)},e.prototype.put=function(e,t,r){this._data=h.concat(this._data,e.subarray(t,r))},e.prototype.unhook=function(e){if(e){var t=u.utf32ToString(this._data);switch(this._data=new Uint32Array(0),t){case'"q':return this._coreService.triggerDataEvent(s.C0.ESC+'P1$r0"q'+s.C0.ESC+"\\");case'"p':return this._coreService.triggerDataEvent(s.C0.ESC+'P1$r61;1"p'+s.C0.ESC+"\\");case"r":var r=this._bufferService.buffer.scrollTop+1+";"+(this._bufferService.buffer.scrollBottom+1)+"r";return this._coreService.triggerDataEvent(s.C0.ESC+"P1$r"+r+s.C0.ESC+"\\");case"m":return this._coreService.triggerDataEvent(s.C0.ESC+"P1$r0m"+s.C0.ESC+"\\");case" q":var i={block:2,underline:4,bar:6}[this._optionsService.options.cursorStyle];return i-=this._optionsService.options.cursorBlink?1:0,this._coreService.triggerDataEvent(s.C0.ESC+"P1$r"+i+" q"+s.C0.ESC+"\\");default:this._logService.debug("Unknown DCS $q %s",t),this._coreService.triggerDataEvent(s.C0.ESC+"P0$r"+s.C0.ESC+"\\")}}else this._data=new Uint32Array(0)},e}(),C=function(e){function t(t,r,i,n,o,l,h,d,v){void 0===v&&(v=new c.EscapeSequenceParser);var y=e.call(this)||this;y._bufferService=t,y._charsetService=r,y._coreService=i,y._dirtyRowService=n,y._logService=o,y._optionsService=l,y._coreMouseService=h,y._unicodeService=d,y._parser=v,y._parseBuffer=new Uint32Array(4096),y._stringDecoder=new u.StringToUtf32,y._utf8Decoder=new u.Utf8ToUtf32,y._workCell=new p.CellData,y._windowTitle="",y._iconName="",y._windowTitleStack=[],y._iconNameStack=[],y._curAttrData=f.DEFAULT_ATTR_DATA.clone(),y._eraseAttrDataInternal=f.DEFAULT_ATTR_DATA.clone(),y._onRequestBell=new _.EventEmitter,y._onRequestRefreshRows=new _.EventEmitter,y._onRequestReset=new _.EventEmitter,y._onRequestScroll=new _.EventEmitter,y._onRequestSyncScrollBar=new _.EventEmitter,y._onRequestWindowsOptionsReport=new _.EventEmitter,y._onA11yChar=new _.EventEmitter,y._onA11yTab=new _.EventEmitter,y._onCursorMove=new _.EventEmitter,y._onLineFeed=new _.EventEmitter,y._onScroll=new _.EventEmitter,y._onTitleChange=new _.EventEmitter,y.register(y._parser),y._parser.setCsiHandlerFallback((function(e,t){y._logService.debug("Unknown CSI code: ",{identifier:y._parser.identToString(e),params:t.toArray()})})),y._parser.setEscHandlerFallback((function(e){y._logService.debug("Unknown ESC code: ",{identifier:y._parser.identToString(e)})})),y._parser.setExecuteHandlerFallback((function(e){y._logService.debug("Unknown EXECUTE code: ",{code:e})})),y._parser.setOscHandlerFallback((function(e,t,r){y._logService.debug("Unknown OSC code: ",{identifier:e,action:t,data:r})})),y._parser.setDcsHandlerFallback((function(e,t,r){"HOOK"===t&&(r=r.toArray()),y._logService.debug("Unknown DCS code: ",{identifier:y._parser.identToString(e),action:t,payload:r})})),y._parser.setPrintHandler((function(e,t,r){return y.print(e,t,r)})),y._parser.setCsiHandler({final:"@"},(function(e){return y.insertChars(e)})),y._parser.setCsiHandler({intermediates:" ",final:"@"},(function(e){return y.scrollLeft(e)})),y._parser.setCsiHandler({final:"A"},(function(e){return y.cursorUp(e)})),y._parser.setCsiHandler({intermediates:" ",final:"A"},(function(e){return y.scrollRight(e)})),y._parser.setCsiHandler({final:"B"},(function(e){return y.cursorDown(e)})),y._parser.setCsiHandler({final:"C"},(function(e){return y.cursorForward(e)})),y._parser.setCsiHandler({final:"D"},(function(e){return y.cursorBackward(e)})),y._parser.setCsiHandler({final:"E"},(function(e){return y.cursorNextLine(e)})),y._parser.setCsiHandler({final:"F"},(function(e){return y.cursorPrecedingLine(e)})),y._parser.setCsiHandler({final:"G"},(function(e){return y.cursorCharAbsolute(e)})),y._parser.setCsiHandler({final:"H"},(function(e){return y.cursorPosition(e)})),y._parser.setCsiHandler({final:"I"},(function(e){return y.cursorForwardTab(e)})),y._parser.setCsiHandler({final:"J"},(function(e){return y.eraseInDisplay(e)})),y._parser.setCsiHandler({prefix:"?",final:"J"},(function(e){return y.eraseInDisplay(e)})),y._parser.setCsiHandler({final:"K"},(function(e){return y.eraseInLine(e)})),y._parser.setCsiHandler({prefix:"?",final:"K"},(function(e){return y.eraseInLine(e)})),y._parser.setCsiHandler({final:"L"},(function(e){return y.insertLines(e)})),y._parser.setCsiHandler({final:"M"},(function(e){return y.deleteLines(e)})),y._parser.setCsiHandler({final:"P"},(function(e){return y.deleteChars(e)})),y._parser.setCsiHandler({final:"S"},(function(e){return y.scrollUp(e)})),y._parser.setCsiHandler({final:"T"},(function(e){return y.scrollDown(e)})),y._parser.setCsiHandler({final:"X"},(function(e){return y.eraseChars(e)})),y._parser.setCsiHandler({final:"Z"},(function(e){return y.cursorBackwardTab(e)})),y._parser.setCsiHandler({final:"`"},(function(e){return y.charPosAbsolute(e)})),y._parser.setCsiHandler({final:"a"},(function(e){return y.hPositionRelative(e)})),y._parser.setCsiHandler({final:"b"},(function(e){return y.repeatPrecedingCharacter(e)})),y._parser.setCsiHandler({final:"c"},(function(e){return y.sendDeviceAttributesPrimary(e)})),y._parser.setCsiHandler({prefix:">",final:"c"},(function(e){return y.sendDeviceAttributesSecondary(e)})),y._parser.setCsiHandler({final:"d"},(function(e){return y.linePosAbsolute(e)})),y._parser.setCsiHandler({final:"e"},(function(e){return y.vPositionRelative(e)})),y._parser.setCsiHandler({final:"f"},(function(e){return y.hVPosition(e)})),y._parser.setCsiHandler({final:"g"},(function(e){return y.tabClear(e)})),y._parser.setCsiHandler({final:"h"},(function(e){return y.setMode(e)})),y._parser.setCsiHandler({prefix:"?",final:"h"},(function(e){return y.setModePrivate(e)})),y._parser.setCsiHandler({final:"l"},(function(e){return y.resetMode(e)})),y._parser.setCsiHandler({prefix:"?",final:"l"},(function(e){return y.resetModePrivate(e)})),y._parser.setCsiHandler({final:"m"},(function(e){return y.charAttributes(e)})),y._parser.setCsiHandler({final:"n"},(function(e){return y.deviceStatus(e)})),y._parser.setCsiHandler({prefix:"?",final:"n"},(function(e){return y.deviceStatusPrivate(e)})),y._parser.setCsiHandler({intermediates:"!",final:"p"},(function(e){return y.softReset(e)})),y._parser.setCsiHandler({intermediates:" ",final:"q"},(function(e){return y.setCursorStyle(e)})),y._parser.setCsiHandler({final:"r"},(function(e){return y.setScrollRegion(e)})),y._parser.setCsiHandler({final:"s"},(function(e){return y.saveCursor(e)})),y._parser.setCsiHandler({final:"t"},(function(e){return y.windowOptions(e)})),y._parser.setCsiHandler({final:"u"},(function(e){return y.restoreCursor(e)})),y._parser.setCsiHandler({intermediates:"'",final:"}"},(function(e){return y.insertColumns(e)})),y._parser.setCsiHandler({intermediates:"'",final:"~"},(function(e){return y.deleteColumns(e)})),y._parser.setExecuteHandler(s.C0.BEL,(function(){return y.bell()})),y._parser.setExecuteHandler(s.C0.LF,(function(){return y.lineFeed()})),y._parser.setExecuteHandler(s.C0.VT,(function(){return y.lineFeed()})),y._parser.setExecuteHandler(s.C0.FF,(function(){return y.lineFeed()})),y._parser.setExecuteHandler(s.C0.CR,(function(){return y.carriageReturn()})),y._parser.setExecuteHandler(s.C0.BS,(function(){return y.backspace()})),y._parser.setExecuteHandler(s.C0.HT,(function(){return y.tab()})),y._parser.setExecuteHandler(s.C0.SO,(function(){return y.shiftOut()})),y._parser.setExecuteHandler(s.C0.SI,(function(){return y.shiftIn()})),y._parser.setExecuteHandler(s.C1.IND,(function(){return y.index()})),y._parser.setExecuteHandler(s.C1.NEL,(function(){return y.nextLine()})),y._parser.setExecuteHandler(s.C1.HTS,(function(){return y.tabSet()})),y._parser.setOscHandler(0,new g.OscHandler((function(e){y.setTitle(e),y.setIconName(e)}))),y._parser.setOscHandler(1,new g.OscHandler((function(e){return y.setIconName(e)}))),y._parser.setOscHandler(2,new g.OscHandler((function(e){return y.setTitle(e)}))),y._parser.setEscHandler({final:"7"},(function(){return y.saveCursor()})),y._parser.setEscHandler({final:"8"},(function(){return y.restoreCursor()})),y._parser.setEscHandler({final:"D"},(function(){return y.index()})),y._parser.setEscHandler({final:"E"},(function(){return y.nextLine()})),y._parser.setEscHandler({final:"H"},(function(){return y.tabSet()})),y._parser.setEscHandler({final:"M"},(function(){return y.reverseIndex()})),y._parser.setEscHandler({final:"="},(function(){return y.keypadApplicationMode()})),y._parser.setEscHandler({final:">"},(function(){return y.keypadNumericMode()})),y._parser.setEscHandler({final:"c"},(function(){return y.fullReset()})),y._parser.setEscHandler({final:"n"},(function(){return y.setgLevel(2)})),y._parser.setEscHandler({final:"o"},(function(){return y.setgLevel(3)})),y._parser.setEscHandler({final:"|"},(function(){return y.setgLevel(3)})),y._parser.setEscHandler({final:"}"},(function(){return y.setgLevel(2)})),y._parser.setEscHandler({final:"~"},(function(){return y.setgLevel(1)})),y._parser.setEscHandler({intermediates:"%",final:"@"},(function(){return y.selectDefaultCharset()})),y._parser.setEscHandler({intermediates:"%",final:"G"},(function(){return y.selectDefaultCharset()}));var b=function(e){S._parser.setEscHandler({intermediates:"(",final:e},(function(){return y.selectCharset("("+e)})),S._parser.setEscHandler({intermediates:")",final:e},(function(){return y.selectCharset(")"+e)})),S._parser.setEscHandler({intermediates:"*",final:e},(function(){return y.selectCharset("*"+e)})),S._parser.setEscHandler({intermediates:"+",final:e},(function(){return y.selectCharset("+"+e)})),S._parser.setEscHandler({intermediates:"-",final:e},(function(){return y.selectCharset("-"+e)})),S._parser.setEscHandler({intermediates:".",final:e},(function(){return y.selectCharset("."+e)})),S._parser.setEscHandler({intermediates:"/",final:e},(function(){return y.selectCharset("/"+e)}))},S=this;for(var C in a.CHARSETS)b(C);return y._parser.setEscHandler({intermediates:"#",final:"8"},(function(){return y.screenAlignmentPattern()})),y._parser.setErrorHandler((function(e){return y._logService.error("Parsing error: ",e),e})),y._parser.setDcsHandler({intermediates:"$",final:"q"},new m(y._bufferService,y._coreService,y._logService,y._optionsService)),y}return n(t,e),Object.defineProperty(t.prototype,"onRequestBell",{get:function(){return this._onRequestBell.event},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"onRequestRefreshRows",{get:function(){return this._onRequestRefreshRows.event},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"onRequestReset",{get:function(){return this._onRequestReset.event},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"onRequestScroll",{get:function(){return this._onRequestScroll.event},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"onRequestSyncScrollBar",{get:function(){return this._onRequestSyncScrollBar.event},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"onRequestWindowsOptionsReport",{get:function(){return this._onRequestWindowsOptionsReport.event},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"onA11yChar",{get:function(){return this._onA11yChar.event},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"onA11yTab",{get:function(){return this._onA11yTab.event},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"onCursorMove",{get:function(){return this._onCursorMove.event},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"onLineFeed",{get:function(){return this._onLineFeed.event},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"onScroll",{get:function(){return this._onScroll.event},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"onTitleChange",{get:function(){return this._onTitleChange.event},enumerable:!1,configurable:!0}),t.prototype.dispose=function(){e.prototype.dispose.call(this)},t.prototype.parse=function(e){var t=this._bufferService.buffer,r=t.x,i=t.y;if(this._logService.debug("parsing data",e),this._parseBuffer.length131072)for(var n=0;n0&&2===_.getWidth(o.x-1)&&_.setCellFromCodePoint(o.x-1,0,1,f.fg,f.bg,f.extended);for(var p=t;p=c)if(l){for(;o.x=this._bufferService.rows&&(o.y=this._bufferService.rows-1),o.lines.get(o.ybase+o.y).isWrapped=!0),_=o.lines.get(o.ybase+o.y)}else if(o.x=c-1,2===n)continue;if(h&&(_.insertCells(o.x,n,o.getNullCell(f),f),2===_.getWidth(c-1)&&_.setCellFromCodePoint(c-1,d.NULL_CELL_CODE,d.NULL_CELL_WIDTH,f.fg,f.bg,f.extended)),_.setCellFromCodePoint(o.x++,i,n,f.fg,f.bg,f.extended),n>0)for(;--n;)_.setCellFromCodePoint(o.x++,0,0,f.fg,f.bg,f.extended)}else _.getWidth(o.x-1)?_.addCodepointToCell(o.x-1,i):_.addCodepointToCell(o.x-2,i)}r-t>0&&(_.loadCell(o.x-1,this._workCell),2===this._workCell.getWidth()||this._workCell.getCode()>65535?this._parser.precedingCodepoint=0:this._workCell.isCombined()?this._parser.precedingCodepoint=this._workCell.getChars().charCodeAt(0):this._parser.precedingCodepoint=this._workCell.content),o.x0&&0===_.getWidth(o.x)&&!_.hasContent(o.x)&&_.setCellFromCodePoint(o.x,0,1,f.fg,f.bg,f.extended),this._dirtyRowService.markDirty(o.y)},t.prototype.addCsiHandler=function(e,t){var r=this;return"t"!==e.final||e.prefix||e.intermediates?this._parser.addCsiHandler(e,t):this._parser.addCsiHandler(e,(function(e){return!S(e.params[0],r._optionsService.options.windowOptions)||t(e)}))},t.prototype.addDcsHandler=function(e,t){return this._parser.addDcsHandler(e,new y.DcsHandler(t))},t.prototype.addEscHandler=function(e,t){return this._parser.addEscHandler(e,t)},t.prototype.addOscHandler=function(e,t){return this._parser.addOscHandler(e,new g.OscHandler(t))},t.prototype.bell=function(){this._onRequestBell.fire()},t.prototype.lineFeed=function(){var e=this._bufferService.buffer;this._dirtyRowService.markDirty(e.y),this._optionsService.options.convertEol&&(e.x=0),e.y++,e.y===e.scrollBottom+1?(e.y--,this._onRequestScroll.fire(this._eraseAttrData())):e.y>=this._bufferService.rows&&(e.y=this._bufferService.rows-1),e.x>=this._bufferService.cols&&e.x--,this._dirtyRowService.markDirty(e.y),this._onLineFeed.fire()},t.prototype.carriageReturn=function(){this._bufferService.buffer.x=0},t.prototype.backspace=function(){var e,t=this._bufferService.buffer;if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),void(t.x>0&&t.x--);if(this._restrictCursor(this._bufferService.cols),t.x>0)t.x--;else if(0===t.x&&t.y>t.scrollTop&&t.y<=t.scrollBottom&&(null===(e=t.lines.get(t.ybase+t.y))||void 0===e?void 0:e.isWrapped)){t.lines.get(t.ybase+t.y).isWrapped=!1,t.y--,t.x=this._bufferService.cols-1;var r=t.lines.get(t.ybase+t.y);r.hasWidth(t.x)&&!r.hasContent(t.x)&&t.x--}this._restrictCursor()},t.prototype.tab=function(){if(!(this._bufferService.buffer.x>=this._bufferService.cols)){var e=this._bufferService.buffer.x;this._bufferService.buffer.x=this._bufferService.buffer.nextStop(),this._optionsService.options.screenReaderMode&&this._onA11yTab.fire(this._bufferService.buffer.x-e)}},t.prototype.shiftOut=function(){this._charsetService.setgLevel(1)},t.prototype.shiftIn=function(){this._charsetService.setgLevel(0)},t.prototype._restrictCursor=function(e){void 0===e&&(e=this._bufferService.cols-1),this._bufferService.buffer.x=Math.min(e,Math.max(0,this._bufferService.buffer.x)),this._bufferService.buffer.y=this._coreService.decPrivateModes.origin?Math.min(this._bufferService.buffer.scrollBottom,Math.max(this._bufferService.buffer.scrollTop,this._bufferService.buffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._bufferService.buffer.y)),this._dirtyRowService.markDirty(this._bufferService.buffer.y)},t.prototype._setCursor=function(e,t){this._dirtyRowService.markDirty(this._bufferService.buffer.y),this._coreService.decPrivateModes.origin?(this._bufferService.buffer.x=e,this._bufferService.buffer.y=this._bufferService.buffer.scrollTop+t):(this._bufferService.buffer.x=e,this._bufferService.buffer.y=t),this._restrictCursor(),this._dirtyRowService.markDirty(this._bufferService.buffer.y)},t.prototype._moveCursor=function(e,t){this._restrictCursor(),this._setCursor(this._bufferService.buffer.x+e,this._bufferService.buffer.y+t)},t.prototype.cursorUp=function(e){var t=this._bufferService.buffer.y-this._bufferService.buffer.scrollTop;t>=0?this._moveCursor(0,-Math.min(t,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1))},t.prototype.cursorDown=function(e){var t=this._bufferService.buffer.scrollBottom-this._bufferService.buffer.y;t>=0?this._moveCursor(0,Math.min(t,e.params[0]||1)):this._moveCursor(0,e.params[0]||1)},t.prototype.cursorForward=function(e){this._moveCursor(e.params[0]||1,0)},t.prototype.cursorBackward=function(e){this._moveCursor(-(e.params[0]||1),0)},t.prototype.cursorNextLine=function(e){this.cursorDown(e),this._bufferService.buffer.x=0},t.prototype.cursorPrecedingLine=function(e){this.cursorUp(e),this._bufferService.buffer.x=0},t.prototype.cursorCharAbsolute=function(e){this._setCursor((e.params[0]||1)-1,this._bufferService.buffer.y)},t.prototype.cursorPosition=function(e){this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1)},t.prototype.charPosAbsolute=function(e){this._setCursor((e.params[0]||1)-1,this._bufferService.buffer.y)},t.prototype.hPositionRelative=function(e){this._moveCursor(e.params[0]||1,0)},t.prototype.linePosAbsolute=function(e){this._setCursor(this._bufferService.buffer.x,(e.params[0]||1)-1)},t.prototype.vPositionRelative=function(e){this._moveCursor(0,e.params[0]||1)},t.prototype.hVPosition=function(e){this.cursorPosition(e)},t.prototype.tabClear=function(e){var t=e.params[0];0===t?delete this._bufferService.buffer.tabs[this._bufferService.buffer.x]:3===t&&(this._bufferService.buffer.tabs={})},t.prototype.cursorForwardTab=function(e){if(!(this._bufferService.buffer.x>=this._bufferService.cols))for(var t=e.params[0]||1;t--;)this._bufferService.buffer.x=this._bufferService.buffer.nextStop()},t.prototype.cursorBackwardTab=function(e){if(!(this._bufferService.buffer.x>=this._bufferService.cols))for(var t=e.params[0]||1,r=this._bufferService.buffer;t--;)r.x=r.prevStop()},t.prototype._eraseInBufferLine=function(e,t,r,i){void 0===i&&(i=!1);var n=this._bufferService.buffer.lines.get(this._bufferService.buffer.ybase+e);n.replaceCells(t,r,this._bufferService.buffer.getNullCell(this._eraseAttrData()),this._eraseAttrData()),i&&(n.isWrapped=!1)},t.prototype._resetBufferLine=function(e){var t=this._bufferService.buffer.lines.get(this._bufferService.buffer.ybase+e);t.fill(this._bufferService.buffer.getNullCell(this._eraseAttrData())),t.isWrapped=!1},t.prototype.eraseInDisplay=function(e){var t;switch(this._restrictCursor(),e.params[0]){case 0:for(t=this._bufferService.buffer.y,this._dirtyRowService.markDirty(t),this._eraseInBufferLine(t++,this._bufferService.buffer.x,this._bufferService.cols,0===this._bufferService.buffer.x);t=this._bufferService.cols&&(this._bufferService.buffer.lines.get(t+1).isWrapped=!1);t--;)this._resetBufferLine(t);this._dirtyRowService.markDirty(0);break;case 2:for(t=this._bufferService.rows,this._dirtyRowService.markDirty(t-1);t--;)this._resetBufferLine(t);this._dirtyRowService.markDirty(0);break;case 3:var r=this._bufferService.buffer.lines.length-this._bufferService.rows;r>0&&(this._bufferService.buffer.lines.trimStart(r),this._bufferService.buffer.ybase=Math.max(this._bufferService.buffer.ybase-r,0),this._bufferService.buffer.ydisp=Math.max(this._bufferService.buffer.ydisp-r,0),this._onScroll.fire(0))}},t.prototype.eraseInLine=function(e){switch(this._restrictCursor(),e.params[0]){case 0:this._eraseInBufferLine(this._bufferService.buffer.y,this._bufferService.buffer.x,this._bufferService.cols);break;case 1:this._eraseInBufferLine(this._bufferService.buffer.y,0,this._bufferService.buffer.x+1);break;case 2:this._eraseInBufferLine(this._bufferService.buffer.y,0,this._bufferService.cols)}this._dirtyRowService.markDirty(this._bufferService.buffer.y)},t.prototype.insertLines=function(e){this._restrictCursor();var t=e.params[0]||1,r=this._bufferService.buffer;if(!(r.y>r.scrollBottom||r.yr.scrollBottom||r.yt.scrollBottom||t.yt.scrollBottom||t.yt.scrollBottom||t.yt.scrollBottom||t.y0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(s.C0.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(s.C0.ESC+"[?6c"))},t.prototype.sendDeviceAttributesSecondary=function(e){e.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(s.C0.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(s.C0.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(e.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(s.C0.ESC+"[>83;40003;0c"))},t.prototype._is=function(e){return 0===(this._optionsService.options.termName+"").indexOf(e)},t.prototype.setMode=function(e){for(var t=0;t=2||2===i[1]&&o+n>=5)break;i[1]&&(n=1)}while(++o+t5)&&(e=1),t.extended.underlineStyle=e,t.fg|=268435456,0===e&&(t.fg&=-268435457),t.updateExtended()},t.prototype.charAttributes=function(e){if(1===e.length&&0===e.params[0])return this._curAttrData.fg=f.DEFAULT_ATTR_DATA.fg,void(this._curAttrData.bg=f.DEFAULT_ATTR_DATA.bg);for(var t,r=e.length,i=this._curAttrData,n=0;n=30&&t<=37?(i.fg&=-50331904,i.fg|=16777216|t-30):t>=40&&t<=47?(i.bg&=-50331904,i.bg|=16777216|t-40):t>=90&&t<=97?(i.fg&=-50331904,i.fg|=16777224|t-90):t>=100&&t<=107?(i.bg&=-50331904,i.bg|=16777224|t-100):0===t?(i.fg=f.DEFAULT_ATTR_DATA.fg,i.bg=f.DEFAULT_ATTR_DATA.bg):1===t?i.fg|=134217728:3===t?i.bg|=67108864:4===t?(i.fg|=268435456,this._processUnderline(e.hasSubParams(n)?e.getSubParams(n)[0]:1,i)):5===t?i.fg|=536870912:7===t?i.fg|=67108864:8===t?i.fg|=1073741824:2===t?i.bg|=134217728:21===t?this._processUnderline(2,i):22===t?(i.fg&=-134217729,i.bg&=-134217729):23===t?i.bg&=-67108865:24===t?i.fg&=-268435457:25===t?i.fg&=-536870913:27===t?i.fg&=-67108865:28===t?i.fg&=-1073741825:39===t?(i.fg&=-67108864,i.fg|=16777215&f.DEFAULT_ATTR_DATA.fg):49===t?(i.bg&=-67108864,i.bg|=16777215&f.DEFAULT_ATTR_DATA.bg):38===t||48===t||58===t?n+=this._extractColor(e,n,i):59===t?(i.extended=i.extended.clone(),i.extended.underlineColor=-1,i.updateExtended()):100===t?(i.fg&=-67108864,i.fg|=16777215&f.DEFAULT_ATTR_DATA.fg,i.bg&=-67108864,i.bg|=16777215&f.DEFAULT_ATTR_DATA.bg):this._logService.debug("Unknown SGR attribute: %d.",t)},t.prototype.deviceStatus=function(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(s.C0.ESC+"[0n");break;case 6:var t=this._bufferService.buffer.y+1,r=this._bufferService.buffer.x+1;this._coreService.triggerDataEvent(s.C0.ESC+"["+t+";"+r+"R")}},t.prototype.deviceStatusPrivate=function(e){switch(e.params[0]){case 6:var t=this._bufferService.buffer.y+1,r=this._bufferService.buffer.x+1;this._coreService.triggerDataEvent(s.C0.ESC+"[?"+t+";"+r+"R")}},t.prototype.softReset=function(e){this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._bufferService.buffer.scrollTop=0,this._bufferService.buffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=f.DEFAULT_ATTR_DATA.clone(),this._coreService.reset(),this._charsetService.reset(),this._bufferService.buffer.savedX=0,this._bufferService.buffer.savedY=this._bufferService.buffer.ybase,this._bufferService.buffer.savedCurAttrData.fg=this._curAttrData.fg,this._bufferService.buffer.savedCurAttrData.bg=this._curAttrData.bg,this._bufferService.buffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1},t.prototype.setCursorStyle=function(e){var t=e.params[0]||1;switch(t){case 1:case 2:this._optionsService.options.cursorStyle="block";break;case 3:case 4:this._optionsService.options.cursorStyle="underline";break;case 5:case 6:this._optionsService.options.cursorStyle="bar"}var r=t%2==1;this._optionsService.options.cursorBlink=r},t.prototype.setScrollRegion=function(e){var t,r=e.params[0]||1;(e.length<2||(t=e.params[1])>this._bufferService.rows||0===t)&&(t=this._bufferService.rows),t>r&&(this._bufferService.buffer.scrollTop=r-1,this._bufferService.buffer.scrollBottom=t-1,this._setCursor(0,0))},t.prototype.windowOptions=function(e){if(S(e.params[0],this._optionsService.options.windowOptions)){var t=e.length>1?e.params[1]:0;switch(e.params[0]){case 14:2!==t&&this._onRequestWindowsOptionsReport.fire(o.GET_WIN_SIZE_PIXELS);break;case 16:this._onRequestWindowsOptionsReport.fire(o.GET_CELL_SIZE_PIXELS);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(s.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())}}},t.prototype.saveCursor=function(e){this._bufferService.buffer.savedX=this._bufferService.buffer.x,this._bufferService.buffer.savedY=this._bufferService.buffer.ybase+this._bufferService.buffer.y,this._bufferService.buffer.savedCurAttrData.fg=this._curAttrData.fg,this._bufferService.buffer.savedCurAttrData.bg=this._curAttrData.bg,this._bufferService.buffer.savedCharset=this._charsetService.charset},t.prototype.restoreCursor=function(e){this._bufferService.buffer.x=this._bufferService.buffer.savedX||0,this._bufferService.buffer.y=Math.max(this._bufferService.buffer.savedY-this._bufferService.buffer.ybase,0),this._curAttrData.fg=this._bufferService.buffer.savedCurAttrData.fg,this._curAttrData.bg=this._bufferService.buffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._bufferService.buffer.savedCharset&&(this._charsetService.charset=this._bufferService.buffer.savedCharset),this._restrictCursor()},t.prototype.setTitle=function(e){this._windowTitle=e,this._onTitleChange.fire(e)},t.prototype.setIconName=function(e){this._iconName=e},t.prototype.nextLine=function(){this._bufferService.buffer.x=0,this.index()},t.prototype.keypadApplicationMode=function(){this._logService.debug("Serial port requested application keypad."),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire()},t.prototype.keypadNumericMode=function(){this._logService.debug("Switching back to normal keypad."),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire()},t.prototype.selectDefaultCharset=function(){this._charsetService.setgLevel(0),this._charsetService.setgCharset(0,a.DEFAULT_CHARSET)},t.prototype.selectCharset=function(e){2===e.length?"/"!==e[0]&&this._charsetService.setgCharset(b[e[0]],a.CHARSETS[e[1]]||a.DEFAULT_CHARSET):this.selectDefaultCharset()},t.prototype.index=function(){this._restrictCursor();var e=this._bufferService.buffer;this._bufferService.buffer.y++,e.y===e.scrollBottom+1?(e.y--,this._onRequestScroll.fire(this._eraseAttrData())):e.y>=this._bufferService.rows&&(e.y=this._bufferService.rows-1),this._restrictCursor()},t.prototype.tabSet=function(){this._bufferService.buffer.tabs[this._bufferService.buffer.x]=!0},t.prototype.reverseIndex=function(){this._restrictCursor();var e=this._bufferService.buffer;if(e.y===e.scrollTop){var t=e.scrollBottom-e.scrollTop;e.lines.shiftElements(e.ybase+e.y,t,1),e.lines.set(e.ybase+e.y,e.getBlankLine(this._eraseAttrData())),this._dirtyRowService.markRangeDirty(e.scrollTop,e.scrollBottom)}else e.y--,this._restrictCursor()},t.prototype.fullReset=function(){this._parser.reset(),this._onRequestReset.fire()},t.prototype.reset=function(){this._curAttrData=f.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=f.DEFAULT_ATTR_DATA.clone()},t.prototype._eraseAttrData=function(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=67108863&this._curAttrData.bg,this._eraseAttrDataInternal},t.prototype.setgLevel=function(e){this._charsetService.setgLevel(e)},t.prototype.screenAlignmentPattern=function(){var e=new p.CellData;e.content=1<<22|"E".charCodeAt(0),e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg;var t=this._bufferService.buffer;this._setCursor(0,0);for(var r=0;r256)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}return e.fromArray=function(t){var r=new e;if(!t.length)return r;for(var i=t[0]instanceof Array?1:0;i>8,i=255&this._subParamsIdx[t];i-r>0&&e.push(Array.prototype.slice.call(this._subParams,r,i))}return e},e.prototype.reset=function(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1},e.prototype.addParam=function(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>2147483647?2147483647:e}},e.prototype.addSubParam=function(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>2147483647?2147483647:e,this._subParamsIdx[this.length-1]++}},e.prototype.hasSubParams=function(e){return(255&this._subParamsIdx[e])-(this._subParamsIdx[e]>>8)>0},e.prototype.getSubParams=function(e){var t=this._subParamsIdx[e]>>8,r=255&this._subParamsIdx[e];return r-t>0?this._subParams.subarray(t,r):null},e.prototype.getSubParamsAll=function(){for(var e={},t=0;t>8,i=255&this._subParamsIdx[t];i-r>0&&(e[t]=this._subParams.slice(r,i))}return e},e.prototype.addDigit=function(e){var t;if(!(this._rejectDigits||!(t=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)){var r=this._digitIsSub?this._subParams:this.params,i=r[t-1];r[t-1]=~i?Math.min(10*i+e,2147483647):e}},e}();t.Params=i},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OscHandler=t.OscParser=void 0;var i=r(23),n=r(8),o=function(){function e(){this._state=0,this._id=-1,this._handlers=Object.create(null),this._handlerFb=function(){}}return e.prototype.addHandler=function(e,t){void 0===this._handlers[e]&&(this._handlers[e]=[]);var r=this._handlers[e];return r.push(t),{dispose:function(){var e=r.indexOf(t);-1!==e&&r.splice(e,1)}}},e.prototype.setHandler=function(e,t){this._handlers[e]=[t]},e.prototype.clearHandler=function(e){this._handlers[e]&&delete this._handlers[e]},e.prototype.setHandlerFallback=function(e){this._handlerFb=e},e.prototype.dispose=function(){this._handlers=Object.create(null),this._handlerFb=function(){}},e.prototype.reset=function(){2===this._state&&this.end(!1),this._id=-1,this._state=0},e.prototype._start=function(){var e=this._handlers[this._id];if(e)for(var t=e.length-1;t>=0;t--)e[t].start();else this._handlerFb(this._id,"START")},e.prototype._put=function(e,t,r){var i=this._handlers[this._id];if(i)for(var o=i.length-1;o>=0;o--)i[o].put(e,t,r);else this._handlerFb(this._id,"PUT",n.utf32ToString(e,t,r))},e.prototype._end=function(e){var t=this._handlers[this._id];if(t){for(var r=t.length-1;r>=0&&!1===t[r].end(e);r--);for(r--;r>=0;r--)t[r].end(!1)}else this._handlerFb(this._id,"END",e)},e.prototype.start=function(){this.reset(),this._id=-1,this._state=1},e.prototype.put=function(e,t,r){if(3!==this._state){if(1===this._state)for(;t0&&this._put(e,t,r)}},e.prototype.end=function(e){0!==this._state&&(3!==this._state&&(1===this._state&&this._start(),this._end(e)),this._id=-1,this._state=0)},e}();t.OscParser=o;var s=function(){function e(e){this._handler=e,this._data="",this._hitLimit=!1}return e.prototype.start=function(){this._data="",this._hitLimit=!1},e.prototype.put=function(e,t,r){this._hitLimit||(this._data+=n.utf32ToString(e,t,r),this._data.length>i.PAYLOAD_LIMIT&&(this._data="",this._hitLimit=!0))},e.prototype.end=function(e){var t;return this._hitLimit?t=!1:e&&(t=this._handler(this._data)),this._data="",this._hitLimit=!1,t},e}();t.OscHandler=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PAYLOAD_LIMIT=void 0,t.PAYLOAD_LIMIT=1e7},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DcsHandler=t.DcsParser=void 0;var i=r(8),n=r(21),o=r(23),s=[],a=function(){function e(){this._handlers=Object.create(null),this._active=s,this._ident=0,this._handlerFb=function(){}}return e.prototype.dispose=function(){this._handlers=Object.create(null),this._handlerFb=function(){}},e.prototype.addHandler=function(e,t){void 0===this._handlers[e]&&(this._handlers[e]=[]);var r=this._handlers[e];return r.push(t),{dispose:function(){var e=r.indexOf(t);-1!==e&&r.splice(e,1)}}},e.prototype.setHandler=function(e,t){this._handlers[e]=[t]},e.prototype.clearHandler=function(e){this._handlers[e]&&delete this._handlers[e]},e.prototype.setHandlerFallback=function(e){this._handlerFb=e},e.prototype.reset=function(){this._active.length&&this.unhook(!1),this._active=s,this._ident=0},e.prototype.hook=function(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||s,this._active.length)for(var r=this._active.length-1;r>=0;r--)this._active[r].hook(t);else this._handlerFb(this._ident,"HOOK",t)},e.prototype.put=function(e,t,r){if(this._active.length)for(var n=this._active.length-1;n>=0;n--)this._active[n].put(e,t,r);else this._handlerFb(this._ident,"PUT",i.utf32ToString(e,t,r))},e.prototype.unhook=function(e){if(this._active.length){for(var t=this._active.length-1;t>=0&&!1===this._active[t].unhook(e);t--);for(t--;t>=0;t--)this._active[t].unhook(!1)}else this._handlerFb(this._ident,"UNHOOK",e);this._active=s,this._ident=0},e}();t.DcsParser=a;var c=function(){function e(e){this._handler=e,this._data="",this._hitLimit=!1}return e.prototype.hook=function(e){this._params=e.clone(),this._data="",this._hitLimit=!1},e.prototype.put=function(e,t,r){this._hitLimit||(this._data+=i.utf32ToString(e,t,r),this._data.length>o.PAYLOAD_LIMIT&&(this._data="",this._hitLimit=!0))},e.prototype.unhook=function(e){var t;return this._hitLimit?t=!1:e&&(t=this._handler(this._data,this._params||new n.Params)),this._params=void 0,this._data="",this._hitLimit=!1,t},e}();t.DcsHandler=c},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.removeTerminalFromCache=t.acquireCharAtlas=void 0;var i=r(26),n=r(43),o=[];t.acquireCharAtlas=function(e,t,r,s,a){for(var c=i.generateConfig(s,a,e,r),l=0;l=0){if(i.configEquals(u.config,c))return u.atlas;1===u.ownedBy.length?(u.atlas.dispose(),o.splice(l,1)):u.ownedBy.splice(h,1);break}}for(l=0;l1)for(var u=this._getJoinedRanges(i,a,o,t,n),f=0;f1)for(u=this._getJoinedRanges(i,a,o,t,n),f=0;f=this._line.length))return t?(this._line.loadCell(e,t),t):this._line.loadCell(e,new i.CellData)},e.prototype.translateToString=function(e,t,r){return this._line.translateToString(e,t,r)},e}(),f=function(){function e(e){this._core=e}return e.prototype.registerCsiHandler=function(e,t){return this._core.addCsiHandler(e,(function(e){return t(e.toArray())}))},e.prototype.addCsiHandler=function(e,t){return this.registerCsiHandler(e,t)},e.prototype.registerDcsHandler=function(e,t){return this._core.addDcsHandler(e,(function(e,r){return t(e,r.toArray())}))},e.prototype.addDcsHandler=function(e,t){return this.registerDcsHandler(e,t)},e.prototype.registerEscHandler=function(e,t){return this._core.addEscHandler(e,t)},e.prototype.addEscHandler=function(e,t){return this.registerEscHandler(e,t)},e.prototype.registerOscHandler=function(e,t){return this._core.addOscHandler(e,t)},e.prototype.addOscHandler=function(e,t){return this.registerOscHandler(e,t)},e}(),_=function(){function e(e){this._core=e}return e.prototype.register=function(e){this._core.unicodeService.register(e)},Object.defineProperty(e.prototype,"versions",{get:function(){return this._core.unicodeService.versions},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"activeVersion",{get:function(){return this._core.unicodeService.activeVersion},set:function(e){this._core.unicodeService.activeVersion=e},enumerable:!1,configurable:!0}),e}()},function(e,t,r){"use strict";var i,n=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0}),t.Terminal=void 0;var o=r(36),s=r(37),a=r(38),c=r(12),l=r(19),h=r(40),u=r(50),f=r(51),_=r(11),d=r(7),p=r(18),v=r(54),g=r(55),y=r(56),b=r(57),S=r(59),m=r(0),C=r(16),w=r(27),E=r(60),L=r(5),A=r(61),R=r(62),k=r(63),x=r(64),D=r(65),T="undefined"!=typeof window?window.document:null,O=function(e){function t(t){void 0===t&&(t={});var r=e.call(this,t)||this;return r.browser=_,r._keyDownHandled=!1,r._onCursorMove=new m.EventEmitter,r._onKey=new m.EventEmitter,r._onRender=new m.EventEmitter,r._onSelectionChange=new m.EventEmitter,r._onTitleChange=new m.EventEmitter,r._onFocus=new m.EventEmitter,r._onBlur=new m.EventEmitter,r._onA11yCharEmitter=new m.EventEmitter,r._onA11yTabEmitter=new m.EventEmitter,r._setup(),r.linkifier=r._instantiationService.createInstance(u.Linkifier),r.linkifier2=r.register(r._instantiationService.createInstance(k.Linkifier2)),r.register(r._inputHandler.onRequestBell((function(){return r.bell()}))),r.register(r._inputHandler.onRequestRefreshRows((function(e,t){return r.refresh(e,t)}))),r.register(r._inputHandler.onRequestReset((function(){return r.reset()}))),r.register(r._inputHandler.onRequestScroll((function(e,t){return r.scroll(e,t||void 0)}))),r.register(r._inputHandler.onRequestWindowsOptionsReport((function(e){return r._reportWindowsOptions(e)}))),r.register(m.forwardEvent(r._inputHandler.onCursorMove,r._onCursorMove)),r.register(m.forwardEvent(r._inputHandler.onTitleChange,r._onTitleChange)),r.register(m.forwardEvent(r._inputHandler.onA11yChar,r._onA11yCharEmitter)),r.register(m.forwardEvent(r._inputHandler.onA11yTab,r._onA11yTabEmitter)),r.register(r._bufferService.onResize((function(e){return r._afterResize(e.cols,e.rows)}))),r}return n(t,e),Object.defineProperty(t.prototype,"options",{get:function(){return this.optionsService.options},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"onCursorMove",{get:function(){return this._onCursorMove.event},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"onKey",{get:function(){return this._onKey.event},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"onRender",{get:function(){return this._onRender.event},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"onSelectionChange",{get:function(){return this._onSelectionChange.event},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"onTitleChange",{get:function(){return this._onTitleChange.event},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"onFocus",{get:function(){return this._onFocus.event},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"onBlur",{get:function(){return this._onBlur.event},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"onA11yChar",{get:function(){return this._onA11yCharEmitter.event},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"onA11yTab",{get:function(){return this._onA11yTabEmitter.event},enumerable:!1,configurable:!0}),t.prototype.dispose=function(){var t,r,i;this._isDisposed||(e.prototype.dispose.call(this),null===(t=this._renderService)||void 0===t||t.dispose(),this._customKeyEventHandler=void 0,this.write=function(){},null===(i=null===(r=this.element)||void 0===r?void 0:r.parentNode)||void 0===i||i.removeChild(this.element))},t.prototype._setup=function(){e.prototype._setup.call(this),this._customKeyEventHandler=void 0},Object.defineProperty(t.prototype,"buffer",{get:function(){return this.buffers.active},enumerable:!1,configurable:!0}),t.prototype.focus=function(){this.textarea&&this.textarea.focus({preventScroll:!0})},t.prototype._updateOptions=function(t){var r,i,n,o;switch(e.prototype._updateOptions.call(this,t),t){case"fontFamily":case"fontSize":null===(r=this._renderService)||void 0===r||r.clear(),null===(i=this._charSizeService)||void 0===i||i.measure();break;case"cursorBlink":case"cursorStyle":this.refresh(this.buffer.y,this.buffer.y);break;case"drawBoldTextInBrightColors":case"letterSpacing":case"lineHeight":case"fontWeight":case"fontWeightBold":case"minimumContrastRatio":this._renderService&&(this._renderService.clear(),this._renderService.onResize(this.cols,this.rows),this.refresh(0,this.rows-1));break;case"rendererType":this._renderService&&(this._renderService.setRenderer(this._createRenderer()),this._renderService.onResize(this.cols,this.rows));break;case"scrollback":null===(n=this.viewport)||void 0===n||n.syncScrollArea();break;case"screenReaderMode":this.optionsService.options.screenReaderMode?!this._accessibilityManager&&this._renderService&&(this._accessibilityManager=new y.AccessibilityManager(this,this._renderService)):(null===(o=this._accessibilityManager)||void 0===o||o.dispose(),this._accessibilityManager=void 0);break;case"tabStopWidth":this.buffers.setupTabStops();break;case"theme":this._setTheme(this.optionsService.options.theme)}},t.prototype._onTextAreaFocus=function(e){this._coreService.decPrivateModes.sendFocus&&this._coreService.triggerDataEvent(c.C0.ESC+"[I"),this.updateCursorStyle(e),this.element.classList.add("focus"),this._showCursor(),this._onFocus.fire()},t.prototype.blur=function(){var e;return null===(e=this.textarea)||void 0===e?void 0:e.blur()},t.prototype._onTextAreaBlur=function(){this.textarea.value="",this.refresh(this.buffer.y,this.buffer.y),this._coreService.decPrivateModes.sendFocus&&this._coreService.triggerDataEvent(c.C0.ESC+"[O"),this.element.classList.remove("focus"),this._onBlur.fire()},t.prototype._syncTextArea=function(){if(this.textarea&&this.buffer.isCursorInViewport&&!this._compositionHelper.isComposing){var e=Math.ceil(this._charSizeService.height*this.optionsService.options.lineHeight),t=this._bufferService.buffer.y*e,r=this._bufferService.buffer.x*this._charSizeService.width;this.textarea.style.left=r+"px",this.textarea.style.top=t+"px",this.textarea.style.width=this._charSizeService.width+"px",this.textarea.style.height=e+"px",this.textarea.style.lineHeight=e+"px",this.textarea.style.zIndex="-5"}},t.prototype._initGlobal=function(){var e=this;this._bindKeys(),this.register(d.addDisposableDomListener(this.element,"copy",(function(t){e.hasSelection()&&a.copyHandler(t,e._selectionService)})));var t=function(t){return a.handlePasteEvent(t,e.textarea,e._coreService)};this.register(d.addDisposableDomListener(this.textarea,"paste",t)),this.register(d.addDisposableDomListener(this.element,"paste",t)),_.isFirefox?this.register(d.addDisposableDomListener(this.element,"mousedown",(function(t){2===t.button&&a.rightClickHandler(t,e.textarea,e.screenElement,e._selectionService,e.options.rightClickSelectsWord)}))):this.register(d.addDisposableDomListener(this.element,"contextmenu",(function(t){a.rightClickHandler(t,e.textarea,e.screenElement,e._selectionService,e.options.rightClickSelectsWord)}))),_.isLinux&&this.register(d.addDisposableDomListener(this.element,"auxclick",(function(t){1===t.button&&a.moveTextAreaUnderMouseCursor(t,e.textarea,e.screenElement)})))},t.prototype._bindKeys=function(){var e=this;this.register(d.addDisposableDomListener(this.textarea,"keyup",(function(t){return e._keyUp(t)}),!0)),this.register(d.addDisposableDomListener(this.textarea,"keydown",(function(t){return e._keyDown(t)}),!0)),this.register(d.addDisposableDomListener(this.textarea,"keypress",(function(t){return e._keyPress(t)}),!0)),this.register(d.addDisposableDomListener(this.textarea,"compositionstart",(function(){return e._compositionHelper.compositionstart()}))),this.register(d.addDisposableDomListener(this.textarea,"compositionupdate",(function(t){return e._compositionHelper.compositionupdate(t)}))),this.register(d.addDisposableDomListener(this.textarea,"compositionend",(function(){return e._compositionHelper.compositionend()}))),this.register(this.onRender((function(){return e._compositionHelper.updateCompositionElements()}))),this.register(this.onRender((function(t){return e._queueLinkification(t.start,t.end)})))},t.prototype.open=function(e){var t=this;if(!e)throw new Error("Terminal requires a parent element.");T.body.contains(e)||this._logService.debug("Terminal.open was called on an element that was not attached to the DOM"),this._document=e.ownerDocument,this.element=this._document.createElement("div"),this.element.dir="ltr",this.element.classList.add("terminal"),this.element.classList.add("xterm"),this.element.setAttribute("tabindex","0"),e.appendChild(this.element);var r=T.createDocumentFragment();this._viewportElement=T.createElement("div"),this._viewportElement.classList.add("xterm-viewport"),r.appendChild(this._viewportElement),this._viewportScrollArea=T.createElement("div"),this._viewportScrollArea.classList.add("xterm-scroll-area"),this._viewportElement.appendChild(this._viewportScrollArea),this.screenElement=T.createElement("div"),this.screenElement.classList.add("xterm-screen"),this._helperContainer=T.createElement("div"),this._helperContainer.classList.add("xterm-helpers"),this.screenElement.appendChild(this._helperContainer),r.appendChild(this.screenElement),this.textarea=T.createElement("textarea"),this.textarea.classList.add("xterm-helper-textarea"),this.textarea.setAttribute("aria-label",p.promptLabel),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(d.addDisposableDomListener(this.textarea,"focus",(function(e){return t._onTextAreaFocus(e)}))),this.register(d.addDisposableDomListener(this.textarea,"blur",(function(){return t._onTextAreaBlur()}))),this._helperContainer.appendChild(this.textarea);var i=this._instantiationService.createInstance(x.CoreBrowserService,this.textarea);this._instantiationService.setService(L.ICoreBrowserService,i),this._charSizeService=this._instantiationService.createInstance(A.CharSizeService,this._document,this._helperContainer),this._instantiationService.setService(L.ICharSizeService,this._charSizeService),this._compositionView=T.createElement("div"),this._compositionView.classList.add("composition-view"),this._compositionHelper=this._instantiationService.createInstance(o.CompositionHelper,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this.element.appendChild(r),this._theme=this.options.theme||this._theme,this._colorManager=new w.ColorManager(T,this.options.allowTransparency),this.register(this.optionsService.onOptionChange((function(e){return t._colorManager.onOptionsChange(e)}))),this._colorManager.setTheme(this._theme);var n=this._createRenderer();this._renderService=this.register(this._instantiationService.createInstance(E.RenderService,n,this.rows,this.screenElement)),this._instantiationService.setService(L.IRenderService,this._renderService),this.register(this._renderService.onRenderedBufferChange((function(e){return t._onRender.fire(e)}))),this.onResize((function(e){return t._renderService.resize(e.cols,e.rows)})),this._soundService=this._instantiationService.createInstance(v.SoundService),this._instantiationService.setService(L.ISoundService,this._soundService),this._mouseService=this._instantiationService.createInstance(R.MouseService),this._instantiationService.setService(L.IMouseService,this._mouseService),this.viewport=this._instantiationService.createInstance(s.Viewport,(function(e,r){return t.scrollLines(e,r)}),this._viewportElement,this._viewportScrollArea),this.viewport.onThemeChange(this._colorManager.colors),this.register(this._inputHandler.onRequestSyncScrollBar((function(){return t.viewport.syncScrollArea()}))),this.register(this.viewport),this.register(this.onCursorMove((function(){t._renderService.onCursorMove(),t._syncTextArea()}))),this.register(this.onResize((function(){return t._renderService.onResize(t.cols,t.rows)}))),this.register(this.onBlur((function(){return t._renderService.onBlur()}))),this.register(this.onFocus((function(){return t._renderService.onFocus()}))),this.register(this._renderService.onDimensionsChange((function(){return t.viewport.syncScrollArea()}))),this._selectionService=this.register(this._instantiationService.createInstance(f.SelectionService,this.element,this.screenElement)),this._instantiationService.setService(L.ISelectionService,this._selectionService),this.register(this._selectionService.onRequestScrollLines((function(e){return t.scrollLines(e.amount,e.suppressScrollEvent)}))),this.register(this._selectionService.onSelectionChange((function(){return t._onSelectionChange.fire()}))),this.register(this._selectionService.onRequestRedraw((function(e){return t._renderService.onSelectionChanged(e.start,e.end,e.columnSelectMode)}))),this.register(this._selectionService.onLinuxMouseSelection((function(e){t.textarea.value=e,t.textarea.focus(),t.textarea.select()}))),this.register(this.onScroll((function(){t.viewport.syncScrollArea(),t._selectionService.refresh()}))),this.register(d.addDisposableDomListener(this._viewportElement,"scroll",(function(){return t._selectionService.refresh()}))),this._mouseZoneManager=this._instantiationService.createInstance(g.MouseZoneManager,this.element,this.screenElement),this.register(this._mouseZoneManager),this.register(this.onScroll((function(){return t._mouseZoneManager.clearAll()}))),this.linkifier.attachToDom(this.element,this._mouseZoneManager),this.linkifier2.attachToDom(this.element,this._mouseService,this._renderService),this.register(d.addDisposableDomListener(this.element,"mousedown",(function(e){return t._selectionService.onMouseDown(e)}))),this._coreMouseService.areMouseEventsActive?(this._selectionService.disable(),this.element.classList.add("enable-mouse-events")):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager=new y.AccessibilityManager(this,this._renderService)),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()},t.prototype._createRenderer=function(){switch(this.options.rendererType){case"canvas":return this._instantiationService.createInstance(h.Renderer,this._colorManager.colors,this.screenElement,this.linkifier,this.linkifier2);case"dom":return this._instantiationService.createInstance(b.DomRenderer,this._colorManager.colors,this.element,this.screenElement,this._viewportElement,this.linkifier,this.linkifier2);default:throw new Error('Unrecognized rendererType "'+this.options.rendererType+'"')}},t.prototype._setTheme=function(e){var t,r,i;this._theme=e,null===(t=this._colorManager)||void 0===t||t.setTheme(e),null===(r=this._renderService)||void 0===r||r.setColors(this._colorManager.colors),null===(i=this.viewport)||void 0===i||i.onThemeChange(this._colorManager.colors)},t.prototype.bindMouse=function(){var e=this,t=this,r=this.element;function i(e){var r,i,n=t._mouseService.getRawByteCoords(e,t.screenElement,t.cols,t.rows);if(!n)return!1;switch(e.overrideType||e.type){case"mousemove":i=32,void 0===e.buttons?(r=3,void 0!==e.button&&(r=e.button<3?e.button:3)):r=1&e.buttons?0:4&e.buttons?1:2&e.buttons?2:3;break;case"mouseup":i=0,r=e.button<3?e.button:3;break;case"mousedown":i=1,r=e.button<3?e.button:3;break;case"wheel":0!==e.deltaY&&(i=e.deltaY<0?0:1),r=4;break;default:return!1}return!(void 0===i||void 0===r||r>4)&&t._coreMouseService.triggerMouseEvent({col:n.x-33,row:n.y-33,button:r,action:i,ctrl:e.ctrlKey,alt:e.altKey,shift:e.shiftKey})}var n={mouseup:null,wheel:null,mousedrag:null,mousemove:null},o=function(t){return i(t),t.buttons||(e._document.removeEventListener("mouseup",n.mouseup),n.mousedrag&&e._document.removeEventListener("mousemove",n.mousedrag)),e.cancel(t)},s=function(t){return i(t),t.preventDefault(),e.cancel(t)},a=function(e){e.buttons&&i(e)},l=function(e){e.buttons||i(e)};this.register(this._coreMouseService.onProtocolChange((function(t){t?("debug"===e.optionsService.options.logLevel&&e._logService.debug("Binding to mouse events:",e._coreMouseService.explainEvents(t)),e.element.classList.add("enable-mouse-events"),e._selectionService.disable()):(e._logService.debug("Unbinding from mouse events."),e.element.classList.remove("enable-mouse-events"),e._selectionService.enable()),8&t?n.mousemove||(r.addEventListener("mousemove",l),n.mousemove=l):(r.removeEventListener("mousemove",n.mousemove),n.mousemove=null),16&t?n.wheel||(r.addEventListener("wheel",s,{passive:!1}),n.wheel=s):(r.removeEventListener("wheel",n.wheel),n.wheel=null),2&t?n.mouseup||(n.mouseup=o):(e._document.removeEventListener("mouseup",n.mouseup),n.mouseup=null),4&t?n.mousedrag||(n.mousedrag=a):(e._document.removeEventListener("mousemove",n.mousedrag),n.mousedrag=null)}))),this._coreMouseService.activeProtocol=this._coreMouseService.activeProtocol,this.register(d.addDisposableDomListener(r,"mousedown",(function(t){if(t.preventDefault(),e.focus(),e._coreMouseService.areMouseEventsActive&&!e._selectionService.shouldForceSelection(t))return i(t),n.mouseup&&e._document.addEventListener("mouseup",n.mouseup),n.mousedrag&&e._document.addEventListener("mousemove",n.mousedrag),e.cancel(t)}))),this.register(d.addDisposableDomListener(r,"wheel",(function(t){if(n.wheel);else if(!e.buffer.hasScrollback){var r=e.viewport.getLinesScrolled(t);if(0===r)return;for(var i=c.C0.ESC+(e._coreService.decPrivateModes.applicationCursorKeys?"O":"[")+(t.deltaY<0?"A":"B"),o="",s=0;s47)},t.prototype._keyUp=function(e){this._customKeyEventHandler&&!1===this._customKeyEventHandler(e)||(function(e){return 16===e.keyCode||17===e.keyCode||18===e.keyCode}(e)||this.focus(),this.updateCursorStyle(e))},t.prototype._keyPress=function(e){var t;if(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),!0)},t.prototype.bell=function(){this._soundBell()&&this._soundService.playBellSound()},t.prototype.resize=function(t,r){t!==this.cols||r!==this.rows?e.prototype.resize.call(this,t,r):this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure()},t.prototype._afterResize=function(e,t){var r,i;null===(r=this._charSizeService)||void 0===r||r.measure(),null===(i=this.viewport)||void 0===i||i.syncScrollArea(!0)},t.prototype.clear=function(){if(0!==this.buffer.ybase||0!==this.buffer.y){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(var e=1;e=0;a--)(n=e[a])&&(s=(o<3?n(s):o>3?n(t,r,s):n(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},n=this&&this.__param||function(e,t){return function(r,i){t(r,i,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.CompositionHelper=void 0;var o=r(5),s=r(1),a=function(){function e(e,t,r,i,n,o){this._textarea=e,this._compositionView=t,this._bufferService=r,this._optionsService=i,this._charSizeService=n,this._coreService=o,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0}}return Object.defineProperty(e.prototype,"isComposing",{get:function(){return this._isComposing},enumerable:!1,configurable:!0}),e.prototype.compositionstart=function(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent="",this._compositionView.classList.add("active")},e.prototype.compositionupdate=function(e){var t=this;this._compositionView.textContent=e.data,this.updateCompositionElements(),setTimeout((function(){t._compositionPosition.end=t._textarea.value.length}),0)},e.prototype.compositionend=function(){this._finalizeComposition(!0)},e.prototype.keydown=function(e){if(this._isComposing||this._isSendingComposition){if(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)},e.prototype._finalizeComposition=function(e){var t=this;if(this._compositionView.classList.remove("active"),this._isComposing=!1,e){var r={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout((function(){if(t._isSendingComposition){t._isSendingComposition=!1;var e=void 0;e=t._isComposing?t._textarea.value.substring(r.start,r.end):t._textarea.value.substring(r.start),t._coreService.triggerDataEvent(e,!0)}}),0)}else{this._isSendingComposition=!1;var i=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(i,!0)}},e.prototype._handleAnyTextareaChanges=function(){var e=this,t=this._textarea.value;setTimeout((function(){if(!e._isComposing){var r=e._textarea.value.replace(t,"");r.length>0&&e._coreService.triggerDataEvent(r,!0)}}),0)},e.prototype.updateCompositionElements=function(e){var t=this;if(this._isComposing){if(this._bufferService.buffer.isCursorInViewport){var r=Math.ceil(this._charSizeService.height*this._optionsService.options.lineHeight),i=this._bufferService.buffer.y*r,n=this._bufferService.buffer.x*this._charSizeService.width;this._compositionView.style.left=n+"px",this._compositionView.style.top=i+"px",this._compositionView.style.height=r+"px",this._compositionView.style.lineHeight=r+"px",this._compositionView.style.fontFamily=this._optionsService.options.fontFamily,this._compositionView.style.fontSize=this._optionsService.options.fontSize+"px";var o=this._compositionView.getBoundingClientRect();this._textarea.style.left=n+"px",this._textarea.style.top=i+"px",this._textarea.style.width=o.width+"px",this._textarea.style.height=o.height+"px",this._textarea.style.lineHeight=o.height+"px"}e||setTimeout((function(){return t.updateCompositionElements(!0)}),0)}},e=i([n(2,s.IBufferService),n(3,s.IOptionsService),n(4,o.ICharSizeService),n(5,s.ICoreService)],e)}();t.CompositionHelper=a},function(e,t,r){"use strict";var i,n=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}),o=this&&this.__decorate||function(e,t,r,i){var n,o=arguments.length,s=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,r):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,r,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(o<3?n(s):o>3?n(t,r,s):n(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},s=this&&this.__param||function(e,t){return function(r,i){t(r,i,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.Viewport=void 0;var a=r(2),c=r(7),l=r(5),h=r(1),u=function(e){function t(t,r,i,n,o,s,a){var l=e.call(this)||this;return l._scrollLines=t,l._viewportElement=r,l._scrollArea=i,l._bufferService=n,l._optionsService=o,l._charSizeService=s,l._renderService=a,l.scrollBarWidth=0,l._currentRowHeight=0,l._lastRecordedBufferLength=0,l._lastRecordedViewportHeight=0,l._lastRecordedBufferHeight=0,l._lastTouchY=0,l._lastScrollTop=0,l._wheelPartialScroll=0,l._refreshAnimationFrame=null,l._ignoreNextScrollEvent=!1,l.scrollBarWidth=l._viewportElement.offsetWidth-l._scrollArea.offsetWidth||15,l.register(c.addDisposableDomListener(l._viewportElement,"scroll",l._onScroll.bind(l))),setTimeout((function(){return l.syncScrollArea()}),0),l}return n(t,e),t.prototype.onThemeChange=function(e){this._viewportElement.style.backgroundColor=e.background.css},t.prototype._refresh=function(e){var t=this;if(e)return this._innerRefresh(),void(null!==this._refreshAnimationFrame&&cancelAnimationFrame(this._refreshAnimationFrame));null===this._refreshAnimationFrame&&(this._refreshAnimationFrame=requestAnimationFrame((function(){return t._innerRefresh()})))},t.prototype._innerRefresh=function(){if(this._charSizeService.height>0){this._currentRowHeight=this._renderService.dimensions.scaledCellHeight/window.devicePixelRatio,this._lastRecordedViewportHeight=this._viewportElement.offsetHeight;var e=Math.round(this._currentRowHeight*this._lastRecordedBufferLength)+(this._lastRecordedViewportHeight-this._renderService.dimensions.canvasHeight);this._lastRecordedBufferHeight!==e&&(this._lastRecordedBufferHeight=e,this._scrollArea.style.height=this._lastRecordedBufferHeight+"px")}var t=this._bufferService.buffer.ydisp*this._currentRowHeight;this._viewportElement.scrollTop!==t&&(this._ignoreNextScrollEvent=!0,this._viewportElement.scrollTop=t),this._refreshAnimationFrame=null},t.prototype.syncScrollArea=function(e){if(void 0===e&&(e=!1),this._lastRecordedBufferLength!==this._bufferService.buffer.lines.length)return this._lastRecordedBufferLength=this._bufferService.buffer.lines.length,void this._refresh(e);if(this._lastRecordedViewportHeight===this._renderService.dimensions.canvasHeight){var t=this._bufferService.buffer.ydisp*this._currentRowHeight;this._lastScrollTop===t&&this._lastScrollTop===this._viewportElement.scrollTop&&this._renderService.dimensions.scaledCellHeight/window.devicePixelRatio===this._currentRowHeight||this._refresh(e)}else this._refresh(e)},t.prototype._onScroll=function(e){if(this._lastScrollTop=this._viewportElement.scrollTop,this._viewportElement.offsetParent)if(this._ignoreNextScrollEvent)this._ignoreNextScrollEvent=!1;else{var t=Math.round(this._lastScrollTop/this._currentRowHeight)-this._bufferService.buffer.ydisp;this._scrollLines(t,!0)}},t.prototype._bubbleScroll=function(e,t){var r=this._viewportElement.scrollTop+this._lastRecordedViewportHeight;return!(t<0&&0!==this._viewportElement.scrollTop||t>0&&r0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(t*=this._bufferService.rows),t},t.prototype._applyScrollModifier=function(e,t){var r=this._optionsService.options.fastScrollModifier;return"alt"===r&&t.altKey||"ctrl"===r&&t.ctrlKey||"shift"===r&&t.shiftKey?e*this._optionsService.options.fastScrollSensitivity*this._optionsService.options.scrollSensitivity:e*this._optionsService.options.scrollSensitivity},t.prototype.onTouchStart=function(e){this._lastTouchY=e.touches[0].pageY},t.prototype.onTouchMove=function(e){var t=this._lastTouchY-e.touches[0].pageY;return this._lastTouchY=e.touches[0].pageY,0!==t&&(this._viewportElement.scrollTop+=t,this._bubbleScroll(e,t))},t=o([s(3,h.IBufferService),s(4,h.IOptionsService),s(5,l.ICharSizeService),s(6,l.IRenderService)],t)}(a.Disposable);t.Viewport=u},function(e,t,r){"use strict";function i(e){return e.replace(/\r?\n/g,"\r")}function n(e,t){return t?"[200~"+e+"[201~":e}function o(e,t,r){e=n(e=i(e),r.decPrivateModes.bracketedPasteMode),r.triggerDataEvent(e,!0),t.value=""}function s(e,t,r){var i=r.getBoundingClientRect(),n=e.clientX-i.left-10,o=e.clientY-i.top-10;t.style.width="20px",t.style.height="20px",t.style.left=n+"px",t.style.top=o+"px",t.style.zIndex="1000",t.focus()}Object.defineProperty(t,"__esModule",{value:!0}),t.rightClickHandler=t.moveTextAreaUnderMouseCursor=t.paste=t.handlePasteEvent=t.copyHandler=t.bracketTextForPaste=t.prepareTextForTerminal=void 0,t.prepareTextForTerminal=i,t.bracketTextForPaste=n,t.copyHandler=function(e,t){e.clipboardData&&e.clipboardData.setData("text/plain",t.selectionText),e.preventDefault()},t.handlePasteEvent=function(e,t,r){e.stopPropagation(),e.clipboardData&&o(e.clipboardData.getData("text/plain"),t,r)},t.paste=o,t.moveTextAreaUnderMouseCursor=s,t.rightClickHandler=function(e,t,r,i,n){s(e,t,r),n&&!i.isClickInSelection(e)&&i.selectWordAtCursor(e),t.value=i.selectionText,t.select()}},function(e,t,r){"use strict";var i,n=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0}),t.EscapeSequenceParser=t.VT500_TRANSITION_TABLE=t.TransitionTable=void 0;var o=r(2),s=r(15),a=r(21),c=r(22),l=r(24),h=function(){function e(e){this.table=new Uint8Array(e)}return e.prototype.setDefault=function(e,t){s.fill(this.table,e<<4|t)},e.prototype.add=function(e,t,r,i){this.table[t<<8|e]=r<<4|i},e.prototype.addMany=function(e,t,r,i){for(var n=0;n1)throw new Error("only one byte as prefix supported");if((r=e.prefix.charCodeAt(0))&&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(var i=0;in||n>47)throw new Error("intermediate must be in range 0x20 .. 0x2f");r<<=8,r|=n}}if(1!==e.final.length)throw new Error("final must be a single byte");var o=e.final.charCodeAt(0);if(t[0]>o||o>t[1])throw new Error("final must be in range "+t[0]+" .. "+t[1]);return r<<=8,r|=o},r.prototype.identToString=function(e){for(var t=[];e;)t.push(String.fromCharCode(255&e)),e>>=8;return t.reverse().join("")},r.prototype.dispose=function(){this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null),this._oscParser.dispose(),this._dcsParser.dispose()},r.prototype.setPrintHandler=function(e){this._printHandler=e},r.prototype.clearPrintHandler=function(){this._printHandler=this._printHandlerFb},r.prototype.addEscHandler=function(e,t){var r=this._identifier(e,[48,126]);void 0===this._escHandlers[r]&&(this._escHandlers[r]=[]);var i=this._escHandlers[r];return i.push(t),{dispose:function(){var e=i.indexOf(t);-1!==e&&i.splice(e,1)}}},r.prototype.setEscHandler=function(e,t){this._escHandlers[this._identifier(e,[48,126])]=[t]},r.prototype.clearEscHandler=function(e){this._escHandlers[this._identifier(e,[48,126])]&&delete this._escHandlers[this._identifier(e,[48,126])]},r.prototype.setEscHandlerFallback=function(e){this._escHandlerFb=e},r.prototype.setExecuteHandler=function(e,t){this._executeHandlers[e.charCodeAt(0)]=t},r.prototype.clearExecuteHandler=function(e){this._executeHandlers[e.charCodeAt(0)]&&delete this._executeHandlers[e.charCodeAt(0)]},r.prototype.setExecuteHandlerFallback=function(e){this._executeHandlerFb=e},r.prototype.addCsiHandler=function(e,t){var r=this._identifier(e);void 0===this._csiHandlers[r]&&(this._csiHandlers[r]=[]);var i=this._csiHandlers[r];return i.push(t),{dispose:function(){var e=i.indexOf(t);-1!==e&&i.splice(e,1)}}},r.prototype.setCsiHandler=function(e,t){this._csiHandlers[this._identifier(e)]=[t]},r.prototype.clearCsiHandler=function(e){this._csiHandlers[this._identifier(e)]&&delete this._csiHandlers[this._identifier(e)]},r.prototype.setCsiHandlerFallback=function(e){this._csiHandlerFb=e},r.prototype.addDcsHandler=function(e,t){return this._dcsParser.addHandler(this._identifier(e),t)},r.prototype.setDcsHandler=function(e,t){this._dcsParser.setHandler(this._identifier(e),t)},r.prototype.clearDcsHandler=function(e){this._dcsParser.clearHandler(this._identifier(e))},r.prototype.setDcsHandlerFallback=function(e){this._dcsParser.setHandlerFallback(e)},r.prototype.addOscHandler=function(e,t){return this._oscParser.addHandler(e,t)},r.prototype.setOscHandler=function(e,t){this._oscParser.setHandler(e,t)},r.prototype.clearOscHandler=function(e){this._oscParser.clearHandler(e)},r.prototype.setOscHandlerFallback=function(e){this._oscParser.setHandlerFallback(e)},r.prototype.setErrorHandler=function(e){this._errorHandler=e},r.prototype.clearErrorHandler=function(){this._errorHandler=this._errorHandlerFb},r.prototype.reset=function(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingCodepoint=0},r.prototype.parse=function(e,t){for(var r=0,i=0,n=this.currentState,o=this._oscParser,s=this._dcsParser,a=this._collect,c=this._params,l=this._transitions.table,h=0;h>4){case 2:for(var u=h+1;;++u){if(u>=t||(r=e[u])<32||r>126&&r<160){this._printHandler(e,h,u),h=u-1;break}if(++u>=t||(r=e[u])<32||r>126&&r<160){this._printHandler(e,h,u),h=u-1;break}if(++u>=t||(r=e[u])<32||r>126&&r<160){this._printHandler(e,h,u),h=u-1;break}if(++u>=t||(r=e[u])<32||r>126&&r<160){this._printHandler(e,h,u),h=u-1;break}}break;case 3:this._executeHandlers[r]?this._executeHandlers[r]():this._executeHandlerFb(r),this.precedingCodepoint=0;break;case 0:break;case 1:if(this._errorHandler({position:h,code:r,currentState:n,collect:a,params:c,abort:!1}).abort)return;break;case 7:for(var f=this._csiHandlers[a<<8|r],_=f?f.length-1:-1;_>=0&&!1===f[_](c);_--);_<0&&this._csiHandlerFb(a<<8|r,c),this.precedingCodepoint=0;break;case 8:do{switch(r){case 59:c.addParam(0);break;case 58:c.addSubParam(-1);break;default:c.addDigit(r-48)}}while(++h47&&r<60);h--;break;case 9:a<<=8,a|=r;break;case 10:for(var d=this._escHandlers[a<<8|r],p=d?d.length-1:-1;p>=0&&!1===d[p]();p--);p<0&&this._escHandlerFb(a<<8|r),this.precedingCodepoint=0;break;case 11:c.reset(),c.addParam(0),a=0;break;case 12:s.hook(a<<8|r,c);break;case 13:for(var v=h+1;;++v)if(v>=t||24===(r=e[v])||26===r||27===r||r>127&&r<160){s.put(e,h,v),h=v-1;break}break;case 14:s.unhook(24!==r&&26!==r),27===r&&(i|=1),c.reset(),c.addParam(0),a=0,this.precedingCodepoint=0;break;case 4:o.start();break;case 5:for(var g=h+1;;g++)if(g>=t||(r=e[g])<32||r>127&&r<=159){o.put(e,h,g),h=g-1;break}break;case 6:o.end(24!==r&&26!==r),27===r&&(i|=1),c.reset(),c.addParam(0),a=0,this.precedingCodepoint=0}n=15&i}this._collect=a,this.currentState=n},r}(o.Disposable);t.EscapeSequenceParser=u},function(e,t,r){"use strict";var i,n=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}),o=this&&this.__decorate||function(e,t,r,i){var n,o=arguments.length,s=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,r):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,r,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(o<3?n(s):o>3?n(t,r,s):n(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},s=this&&this.__param||function(e,t){return function(r,i){t(r,i,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.Renderer=void 0;var a=r(41),c=r(47),l=r(48),h=r(49),u=r(29),f=r(2),_=r(5),d=r(1),p=r(25),v=r(0),g=1,y=function(e){function t(t,r,i,n,o,s,f,_,d){var p=e.call(this)||this;p._colors=t,p._screenElement=r,p._bufferService=o,p._charSizeService=s,p._optionsService=f,p._id=g++,p._onRequestRedraw=new v.EventEmitter;var y=p._optionsService.options.allowTransparency;return p._characterJoinerRegistry=new u.CharacterJoinerRegistry(p._bufferService),p._renderLayers=[new a.TextRenderLayer(p._screenElement,0,p._colors,p._characterJoinerRegistry,y,p._id,p._bufferService,f),new c.SelectionRenderLayer(p._screenElement,1,p._colors,p._id,p._bufferService,f),new h.LinkRenderLayer(p._screenElement,2,p._colors,p._id,i,n,p._bufferService,f),new l.CursorRenderLayer(p._screenElement,3,p._colors,p._id,p._onRequestRedraw,p._bufferService,f,_,d)],p.dimensions={scaledCharWidth:0,scaledCharHeight:0,scaledCellWidth:0,scaledCellHeight:0,scaledCharLeft:0,scaledCharTop:0,scaledCanvasWidth:0,scaledCanvasHeight:0,canvasWidth:0,canvasHeight:0,actualCellWidth:0,actualCellHeight:0},p._devicePixelRatio=window.devicePixelRatio,p._updateDimensions(),p.onOptionsChanged(),p}return n(t,e),Object.defineProperty(t.prototype,"onRequestRedraw",{get:function(){return this._onRequestRedraw.event},enumerable:!1,configurable:!0}),t.prototype.dispose=function(){for(var t=0,r=this._renderLayers;t0&&h===a[0][0]){f=!0;var d=a.shift();u=new l.JoinedCellData(this._workCell,s.translateToString(!0,d[0],d[1]),d[1]-d[0]),_=d[1]-1}!f&&this._isOverlapping(u)&&_this._characterWidth;return this._ctx.restore(),this._characterOverlapCache[t]=r,r},t}(s.BaseRenderLayer);t.TextRenderLayer=u},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.GridCache=void 0;var i=function(){function e(){this.cache=[]}return e.prototype.resize=function(e,t){for(var r=0;r>>24,n=t.rgba>>>16&255,o=t.rgba>>>8&255,s=0;s=this.capacity)r=this._head,this._unlinkNode(r),delete this._map[r.key],r.key=e,r.value=t,this._map[e]=r;else{var i=this._nodePool;i.length>0?((r=i.pop()).key=e,r.value=t):r={prev:null,next:null,key:e,value:t},this._map[e]=r,this.size++}this._appendNode(r)},e}();t.LRUMap=i},function(e,t,r){"use strict";var i,n=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0}),t.SelectionRenderLayer=void 0;var o=function(e){function t(t,r,i,n,o,s){var a=e.call(this,t,"selection",r,!0,i,n,o,s)||this;return a._clearState(),a}return n(t,e),t.prototype._clearState=function(){this._state={start:void 0,end:void 0,columnSelectMode:void 0,ydisp:void 0}},t.prototype.resize=function(t){e.prototype.resize.call(this,t),this._clearState()},t.prototype.reset=function(){this._state.start&&this._state.end&&(this._clearState(),this._clearAll())},t.prototype.onSelectionChanged=function(e,t,r){if(this._didStateChange(e,t,r,this._bufferService.buffer.ydisp))if(this._clearAll(),e&&t){var i=e[1]-this._bufferService.buffer.ydisp,n=t[1]-this._bufferService.buffer.ydisp,o=Math.max(i,0),s=Math.min(n,this._bufferService.rows-1);if(!(o>=this._bufferService.rows||s<0)){if(this._ctx.fillStyle=this._colors.selectionTransparent.css,r){var a=e[0],c=t[0]-a,l=s-o+1;this._fillCells(a,o,c,l)}else{a=i===o?e[0]:0;var h=o===s?t[0]:this._bufferService.cols;this._fillCells(a,o,h-a,1);var u=Math.max(s-o-1,0);if(this._fillCells(0,o+1,this._bufferService.cols,u),o!==s){var f=n===s?t[0]:this._bufferService.cols;this._fillCells(0,s,f,1)}}this._state.start=[e[0],e[1]],this._state.end=[t[0],t[1]],this._state.columnSelectMode=r,this._state.ydisp=this._bufferService.buffer.ydisp}}else this._clearState()},t.prototype._didStateChange=function(e,t,r,i){return!this._areCoordinatesEqual(e,this._state.start)||!this._areCoordinatesEqual(t,this._state.end)||r!==this._state.columnSelectMode||i!==this._state.ydisp},t.prototype._areCoordinatesEqual=function(e,t){return!(!e||!t)&&(e[0]===t[0]&&e[1]===t[1])},t}(r(13).BaseRenderLayer);t.SelectionRenderLayer=o},function(e,t,r){"use strict";var i,n=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0}),t.CursorRenderLayer=void 0;var o=r(13),s=r(4),a=function(e){function t(t,r,i,n,o,a,c,l,h){var u=e.call(this,t,"cursor",r,!0,i,n,a,c)||this;return u._onRequestRedraw=o,u._coreService=l,u._coreBrowserService=h,u._cell=new s.CellData,u._state={x:0,y:0,isFocused:!1,style:"",width:0},u._cursorRenderers={bar:u._renderBarCursor.bind(u),block:u._renderBlockCursor.bind(u),underline:u._renderUnderlineCursor.bind(u)},u}return n(t,e),t.prototype.resize=function(t){e.prototype.resize.call(this,t),this._state={x:0,y:0,isFocused:!1,style:"",width:0}},t.prototype.reset=function(){this._clearCursor(),this._cursorBlinkStateManager&&(this._cursorBlinkStateManager.dispose(),this._cursorBlinkStateManager=void 0,this.onOptionsChanged())},t.prototype.onBlur=function(){this._cursorBlinkStateManager&&this._cursorBlinkStateManager.pause(),this._onRequestRedraw.fire({start:this._bufferService.buffer.y,end:this._bufferService.buffer.y})},t.prototype.onFocus=function(){this._cursorBlinkStateManager?this._cursorBlinkStateManager.resume():this._onRequestRedraw.fire({start:this._bufferService.buffer.y,end:this._bufferService.buffer.y})},t.prototype.onOptionsChanged=function(){var e,t=this;this._optionsService.options.cursorBlink?this._cursorBlinkStateManager||(this._cursorBlinkStateManager=new c(this._coreBrowserService.isFocused,(function(){t._render(!0)}))):(null===(e=this._cursorBlinkStateManager)||void 0===e||e.dispose(),this._cursorBlinkStateManager=void 0),this._onRequestRedraw.fire({start:this._bufferService.buffer.y,end:this._bufferService.buffer.y})},t.prototype.onCursorMove=function(){this._cursorBlinkStateManager&&this._cursorBlinkStateManager.restartBlinkAnimation()},t.prototype.onGridChanged=function(e,t){!this._cursorBlinkStateManager||this._cursorBlinkStateManager.isPaused?this._render(!1):this._cursorBlinkStateManager.restartBlinkAnimation()},t.prototype._render=function(e){if(this._coreService.isCursorInitialized&&!this._coreService.isCursorHidden){var t=this._bufferService.buffer.ybase+this._bufferService.buffer.y,r=t-this._bufferService.buffer.ydisp;if(r<0||r>=this._bufferService.rows)this._clearCursor();else{var i=Math.min(this._bufferService.buffer.x,this._bufferService.cols-1);if(this._bufferService.buffer.lines.get(t).loadCell(i,this._cell),void 0!==this._cell.content){if(!this._coreBrowserService.isFocused){this._clearCursor(),this._ctx.save(),this._ctx.fillStyle=this._colors.cursor.css;var n=this._optionsService.options.cursorStyle;return n&&"block"!==n?this._cursorRenderers[n](i,r,this._cell):this._renderBlurCursor(i,r,this._cell),this._ctx.restore(),this._state.x=i,this._state.y=r,this._state.isFocused=!1,this._state.style=n,void(this._state.width=this._cell.getWidth())}if(!this._cursorBlinkStateManager||this._cursorBlinkStateManager.isCursorVisible){if(this._state){if(this._state.x===i&&this._state.y===r&&this._state.isFocused===this._coreBrowserService.isFocused&&this._state.style===this._optionsService.options.cursorStyle&&this._state.width===this._cell.getWidth())return;this._clearCursor()}this._ctx.save(),this._cursorRenderers[this._optionsService.options.cursorStyle||"block"](i,r,this._cell),this._ctx.restore(),this._state.x=i,this._state.y=r,this._state.isFocused=!1,this._state.style=this._optionsService.options.cursorStyle,this._state.width=this._cell.getWidth()}else this._clearCursor()}}}else this._clearCursor()},t.prototype._clearCursor=function(){this._state&&(this._clearCells(this._state.x,this._state.y,this._state.width,1),this._state={x:0,y:0,isFocused:!1,style:"",width:0})},t.prototype._renderBarCursor=function(e,t,r){this._ctx.save(),this._ctx.fillStyle=this._colors.cursor.css,this._fillLeftLineAtCell(e,t,this._optionsService.options.cursorWidth),this._ctx.restore()},t.prototype._renderBlockCursor=function(e,t,r){this._ctx.save(),this._ctx.fillStyle=this._colors.cursor.css,this._fillCells(e,t,r.getWidth(),1),this._ctx.fillStyle=this._colors.cursorAccent.css,this._fillCharTrueColor(r,e,t),this._ctx.restore()},t.prototype._renderUnderlineCursor=function(e,t,r){this._ctx.save(),this._ctx.fillStyle=this._colors.cursor.css,this._fillBottomLineAtCells(e,t),this._ctx.restore()},t.prototype._renderBlurCursor=function(e,t,r){this._ctx.save(),this._ctx.strokeStyle=this._colors.cursor.css,this._strokeRectAtCell(e,t,r.getWidth(),1),this._ctx.restore()},t}(o.BaseRenderLayer);t.CursorRenderLayer=a;var c=function(){function e(e,t){this._renderCallback=t,this.isCursorVisible=!0,e&&this._restartInterval()}return Object.defineProperty(e.prototype,"isPaused",{get:function(){return!(this._blinkStartTimeout||this._blinkInterval)},enumerable:!1,configurable:!0}),e.prototype.dispose=function(){this._blinkInterval&&(window.clearInterval(this._blinkInterval),this._blinkInterval=void 0),this._blinkStartTimeout&&(window.clearTimeout(this._blinkStartTimeout),this._blinkStartTimeout=void 0),this._animationFrame&&(window.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0)},e.prototype.restartBlinkAnimation=function(){var e=this;this.isPaused||(this._animationTimeRestarted=Date.now(),this.isCursorVisible=!0,this._animationFrame||(this._animationFrame=window.requestAnimationFrame((function(){e._renderCallback(),e._animationFrame=void 0}))))},e.prototype._restartInterval=function(e){var t=this;void 0===e&&(e=600),this._blinkInterval&&window.clearInterval(this._blinkInterval),this._blinkStartTimeout=window.setTimeout((function(){if(t._animationTimeRestarted){var e=600-(Date.now()-t._animationTimeRestarted);if(t._animationTimeRestarted=void 0,e>0)return void t._restartInterval(e)}t.isCursorVisible=!1,t._animationFrame=window.requestAnimationFrame((function(){t._renderCallback(),t._animationFrame=void 0})),t._blinkInterval=window.setInterval((function(){if(t._animationTimeRestarted){var e=600-(Date.now()-t._animationTimeRestarted);return t._animationTimeRestarted=void 0,void t._restartInterval(e)}t.isCursorVisible=!t.isCursorVisible,t._animationFrame=window.requestAnimationFrame((function(){t._renderCallback(),t._animationFrame=void 0}))}),600)}),e)},e.prototype.pause=function(){this.isCursorVisible=!0,this._blinkInterval&&(window.clearInterval(this._blinkInterval),this._blinkInterval=void 0),this._blinkStartTimeout&&(window.clearTimeout(this._blinkStartTimeout),this._blinkStartTimeout=void 0),this._animationFrame&&(window.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0)},e.prototype.resume=function(){this.pause(),this._animationTimeRestarted=void 0,this._restartInterval(),this.restartBlinkAnimation()},e}()},function(e,t,r){"use strict";var i,n=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0}),t.LinkRenderLayer=void 0;var o=r(13),s=r(9),a=r(26),c=function(e){function t(t,r,i,n,o,s,a,c){var l=e.call(this,t,"link",r,!0,i,n,a,c)||this;return o.onShowLinkUnderline((function(e){return l._onShowLinkUnderline(e)})),o.onHideLinkUnderline((function(e){return l._onHideLinkUnderline(e)})),s.onShowLinkUnderline((function(e){return l._onShowLinkUnderline(e)})),s.onHideLinkUnderline((function(e){return l._onHideLinkUnderline(e)})),l}return n(t,e),t.prototype.resize=function(t){e.prototype.resize.call(this,t),this._state=void 0},t.prototype.reset=function(){this._clearCurrentLink()},t.prototype._clearCurrentLink=function(){if(this._state){this._clearCells(this._state.x1,this._state.y1,this._state.cols-this._state.x1,1);var e=this._state.y2-this._state.y1-1;e>0&&this._clearCells(0,this._state.y1+1,this._state.cols,e),this._clearCells(0,this._state.y2,this._state.x2,1),this._state=void 0}},t.prototype._onShowLinkUnderline=function(e){if(e.fg===s.INVERTED_DEFAULT_COLOR?this._ctx.fillStyle=this._colors.background.css:e.fg&&a.is256Color(e.fg)?this._ctx.fillStyle=this._colors.ansi[e.fg].css:this._ctx.fillStyle=this._colors.foreground.css,e.y1===e.y2)this._fillBottomLineAtCells(e.x1,e.y1,e.x2-e.x1);else{this._fillBottomLineAtCells(e.x1,e.y1,e.cols-e.x1);for(var t=e.y1+1;t=0;a--)(n=e[a])&&(s=(o<3?n(s):o>3?n(t,r,s):n(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},n=this&&this.__param||function(e,t){return function(r,i){t(r,i,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.MouseZone=t.Linkifier=void 0;var o=r(0),s=r(1),a=function(){function e(e,t,r){this._bufferService=e,this._logService=t,this._unicodeService=r,this._linkMatchers=[],this._nextLinkMatcherId=0,this._onShowLinkUnderline=new o.EventEmitter,this._onHideLinkUnderline=new o.EventEmitter,this._onLinkTooltip=new o.EventEmitter,this._rowsToLinkify={start:void 0,end:void 0}}return Object.defineProperty(e.prototype,"onShowLinkUnderline",{get:function(){return this._onShowLinkUnderline.event},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onHideLinkUnderline",{get:function(){return this._onHideLinkUnderline.event},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onLinkTooltip",{get:function(){return this._onLinkTooltip.event},enumerable:!1,configurable:!0}),e.prototype.attachToDom=function(e,t){this._element=e,this._mouseZoneManager=t},e.prototype.linkifyRows=function(t,r){var i=this;this._mouseZoneManager&&(void 0===this._rowsToLinkify.start||void 0===this._rowsToLinkify.end?(this._rowsToLinkify.start=t,this._rowsToLinkify.end=r):(this._rowsToLinkify.start=Math.min(this._rowsToLinkify.start,t),this._rowsToLinkify.end=Math.max(this._rowsToLinkify.end,r)),this._mouseZoneManager.clearAll(t,r),this._rowsTimeoutId&&clearTimeout(this._rowsTimeoutId),this._rowsTimeoutId=setTimeout((function(){return i._linkifyRows()}),e._timeBeforeLatency))},e.prototype._linkifyRows=function(){this._rowsTimeoutId=void 0;var e=this._bufferService.buffer;if(void 0!==this._rowsToLinkify.start&&void 0!==this._rowsToLinkify.end){var t=e.ydisp+this._rowsToLinkify.start;if(!(t>=e.lines.length)){for(var r=e.ydisp+Math.min(this._rowsToLinkify.end,this._bufferService.rows)+1,i=Math.ceil(2e3/this._bufferService.cols),n=this._bufferService.buffer.iterator(!1,t,r,i,i);n.hasNext();)for(var o=n.next(),s=0;s=0;t--)if(e.priority<=this._linkMatchers[t].priority)return void this._linkMatchers.splice(t+1,0,e);this._linkMatchers.splice(0,0,e)}else this._linkMatchers.push(e)},e.prototype.deregisterLinkMatcher=function(e){for(var t=0;t>9&511:void 0;r.validationCallback?r.validationCallback(a,(function(e){n._rowsTimeoutId||e&&n._addLink(l[1],l[0]-n._bufferService.buffer.ydisp,a,r,f)})):c._addLink(l[1],l[0]-c._bufferService.buffer.ydisp,a,r,f)},c=this;null!==(i=o.exec(t));){if("break"===a())break}},e.prototype._addLink=function(e,t,r,i,n){var o=this;if(this._mouseZoneManager&&this._element){var s=this._unicodeService.getStringCellWidth(r),a=e%this._bufferService.cols,l=t+Math.floor(e/this._bufferService.cols),h=(a+s)%this._bufferService.cols,u=l+Math.floor((a+s)/this._bufferService.cols);0===h&&(h=this._bufferService.cols,u--),this._mouseZoneManager.add(new c(a+1,l+1,h+1,u+1,(function(e){if(i.handler)return i.handler(e,r);var t=window.open();t?(t.opener=null,t.location.href=r):console.warn("Opening link blocked as opener could not be cleared")}),(function(){o._onShowLinkUnderline.fire(o._createLinkHoverEvent(a,l,h,u,n)),o._element.classList.add("xterm-cursor-pointer")}),(function(e){o._onLinkTooltip.fire(o._createLinkHoverEvent(a,l,h,u,n)),i.hoverTooltipCallback&&i.hoverTooltipCallback(e,r,{start:{x:a,y:l},end:{x:h,y:u}})}),(function(){o._onHideLinkUnderline.fire(o._createLinkHoverEvent(a,l,h,u,n)),o._element.classList.remove("xterm-cursor-pointer"),i.hoverLeaveCallback&&i.hoverLeaveCallback()}),(function(e){return!i.willLinkActivate||i.willLinkActivate(e,r)})))}},e.prototype._createLinkHoverEvent=function(e,t,r,i,n){return{x1:e,y1:t,x2:r,y2:i,cols:this._bufferService.cols,fg:n}},e._timeBeforeLatency=200,e=i([n(0,s.IBufferService),n(1,s.ILogService),n(2,s.IUnicodeService)],e)}();t.Linkifier=a;var c=function(e,t,r,i,n,o,s,a,c){this.x1=e,this.y1=t,this.x2=r,this.y2=i,this.clickCallback=n,this.hoverCallback=o,this.tooltipCallback=s,this.leaveCallback=a,this.willLinkActivate=c};t.MouseZone=c},function(e,t,r){"use strict";var i,n=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}),o=this&&this.__decorate||function(e,t,r,i){var n,o=arguments.length,s=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,r):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,r,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(o<3?n(s):o>3?n(t,r,s):n(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},s=this&&this.__param||function(e,t){return function(r,i){t(r,i,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.SelectionService=void 0;var a=r(11),c=r(52),l=r(4),h=r(0),u=r(5),f=r(1),_=r(30),d=r(53),p=r(2),v=String.fromCharCode(160),g=new RegExp(v,"g"),y=function(e){function t(t,r,i,n,o,s,a){var u=e.call(this)||this;return u._element=t,u._screenElement=r,u._bufferService=i,u._coreService=n,u._mouseService=o,u._optionsService=s,u._renderService=a,u._dragScrollAmount=0,u._enabled=!0,u._workCell=new l.CellData,u._mouseDownTimeStamp=0,u._onLinuxMouseSelection=u.register(new h.EventEmitter),u._onRedrawRequest=u.register(new h.EventEmitter),u._onSelectionChange=u.register(new h.EventEmitter),u._onRequestScrollLines=u.register(new h.EventEmitter),u._mouseMoveListener=function(e){return u._onMouseMove(e)},u._mouseUpListener=function(e){return u._onMouseUp(e)},u._coreService.onUserInput((function(){u.hasSelection&&u.clearSelection()})),u._trimListener=u._bufferService.buffer.lines.onTrim((function(e){return u._onTrim(e)})),u.register(u._bufferService.buffers.onBufferActivate((function(e){return u._onBufferActivate(e)}))),u.enable(),u._model=new c.SelectionModel(u._bufferService),u._activeSelectionMode=0,u}return n(t,e),Object.defineProperty(t.prototype,"onLinuxMouseSelection",{get:function(){return this._onLinuxMouseSelection.event},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"onRequestRedraw",{get:function(){return this._onRedrawRequest.event},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"onSelectionChange",{get:function(){return this._onSelectionChange.event},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"onRequestScrollLines",{get:function(){return this._onRequestScrollLines.event},enumerable:!1,configurable:!0}),t.prototype.dispose=function(){this._removeMouseDownListeners()},t.prototype.reset=function(){this.clearSelection()},t.prototype.disable=function(){this.clearSelection(),this._enabled=!1},t.prototype.enable=function(){this._enabled=!0},Object.defineProperty(t.prototype,"selectionStart",{get:function(){return this._model.finalSelectionStart},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"selectionEnd",{get:function(){return this._model.finalSelectionEnd},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"hasSelection",{get:function(){var e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;return!(!e||!t)&&(e[0]!==t[0]||e[1]!==t[1])},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"selectionText",{get:function(){var e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;if(!e||!t)return"";var r=this._bufferService.buffer,i=[];if(3===this._activeSelectionMode){if(e[0]===t[0])return"";for(var n=e[1];n<=t[1];n++){var o=r.translateBufferLineToString(n,!0,e[0],t[0]);i.push(o)}}else{var s=e[1]===t[1]?t[0]:void 0;i.push(r.translateBufferLineToString(e[1],!0,e[0],s));for(n=e[1]+1;n<=t[1]-1;n++){var c=r.lines.get(n);o=r.translateBufferLineToString(n,!0);c&&c.isWrapped?i[i.length-1]+=o:i.push(o)}if(e[1]!==t[1]){c=r.lines.get(t[1]),o=r.translateBufferLineToString(t[1],!0,0,t[0]);c&&c.isWrapped?i[i.length-1]+=o:i.push(o)}}return i.map((function(e){return e.replace(g," ")})).join(a.isWindows?"\r\n":"\n")},enumerable:!1,configurable:!0}),t.prototype.clearSelection=function(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()},t.prototype.refresh=function(e){var t=this;(this._refreshAnimationFrame||(this._refreshAnimationFrame=window.requestAnimationFrame((function(){return t._refresh()}))),a.isLinux&&e)&&(this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText))},t.prototype._refresh=function(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:3===this._activeSelectionMode})},t.prototype.isClickInSelection=function(e){var t=this._getMouseBufferCoords(e),r=this._model.finalSelectionStart,i=this._model.finalSelectionEnd;return!!(r&&i&&t)&&this._areCoordsInSelection(t,r,i)},t.prototype._areCoordsInSelection=function(e,t,r){return e[1]>t[1]&&e[1]=t[0]&&e[0]=t[0]},t.prototype.selectWordAtCursor=function(e){var t=this._getMouseBufferCoords(e);t&&(this._selectWordAt(t,!1),this._model.selectionEnd=void 0,this.refresh(!0))},t.prototype.selectAll=function(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()},t.prototype.selectLines=function(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()},t.prototype._onTrim=function(e){this._model.onTrim(e)&&this.refresh()},t.prototype._getMouseBufferCoords=function(e){var 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},t.prototype._getMouseEventScrollAmount=function(e){var t=_.getCoordsRelativeToElement(e,this._screenElement)[1],r=this._renderService.dimensions.canvasHeight;return t>=0&&t<=r?0:(t>r&&(t-=r),t=Math.min(Math.max(t,-50),50),(t/=50)/Math.abs(t)+Math.round(14*t))},t.prototype.shouldForceSelection=function(e){return a.isMac?e.altKey&&this._optionsService.options.macOptionClickForcesSelection:e.shiftKey},t.prototype.onMouseDown=function(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._onIncrementalClick(e):1===e.detail?this._onSingleClick(e):2===e.detail?this._onDoubleClick(e):3===e.detail&&this._onTripleClick(e),this._addMouseDownListeners(),this.refresh(!0)}},t.prototype._addMouseDownListeners=function(){var e=this;this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener("mouseup",this._mouseUpListener)),this._dragScrollIntervalTimer=window.setInterval((function(){return e._dragScroll()}),50)},t.prototype._removeMouseDownListeners=function(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener("mouseup",this._mouseUpListener)),clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0},t.prototype._onIncrementalClick=function(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))},t.prototype._onSingleClick=function(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){this._model.selectionEnd=void 0;var 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]++}},t.prototype._onDoubleClick=function(e){var t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=1,this._selectWordAt(t,!0))},t.prototype._onTripleClick=function(e){var t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))},t.prototype.shouldColumnSelect=function(e){return e.altKey&&!(a.isMac&&this._optionsService.options.macOptionClickForcesSelection)},t.prototype._onMouseMove=function(e){if(e.stopImmediatePropagation(),this._model.selectionStart){var t=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),this._model.selectionEnd){2===this._activeSelectionMode?this._model.selectionEnd[1]0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));var r=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()}},t.prototype._onMouseUp=function(e){var t=e.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&t<500&&e.altKey){if(this._bufferService.buffer.ybase===this._bufferService.buffer.ydisp){var r=this._mouseService.getCoords(e,this._element,this._bufferService.cols,this._bufferService.rows,!1);if(r&&void 0!==r[0]&&void 0!==r[1]){var i=d.moveToCellSequence(r[0]-1,r[1]-1,this._bufferService,this._coreService.decPrivateModes.applicationCursorKeys);this._coreService.triggerDataEvent(i,!0)}}}else this.hasSelection&&this._onSelectionChange.fire()},t.prototype._onBufferActivate=function(e){var t=this;this.clearSelection(),this._trimListener.dispose(),this._trimListener=e.activeBuffer.lines.onTrim((function(e){return t._onTrim(e)}))},t.prototype._convertViewportColToCharacterIndex=function(e,t){for(var r=t[0],i=0;t[0]>=i;i++){var n=e.loadCell(i,this._workCell).getChars().length;0===this._workCell.getWidth()?r--:n>1&&t[0]!==i&&(r+=n-1)}return r},t.prototype.setSelection=function(e,t,r){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,t],this._model.selectionStartLength=r,this.refresh()},t.prototype._getWordAt=function(e,t,r,i){if(void 0===r&&(r=!0),void 0===i&&(i=!0),!(e[0]>=this._bufferService.cols)){var n=this._bufferService.buffer,o=n.lines.get(e[1]);if(o){var s=n.translateBufferLineToString(e[1],!1),a=this._convertViewportColToCharacterIndex(o,e),c=a,l=e[0]-a,h=0,u=0,f=0,_=0;if(" "===s.charAt(a)){for(;a>0&&" "===s.charAt(a-1);)a--;for(;c1&&(_+=v-1,c+=v-1);d>0&&a>0&&!this._isCharWordSeparator(o.loadCell(d-1,this._workCell));){o.loadCell(d-1,this._workCell);var g=this._workCell.getChars().length;0===this._workCell.getWidth()?(h++,d--):g>1&&(f+=g-1,a-=g-1),a--,d--}for(;p1&&(_+=y-1,c+=y-1),c++,p++}}c++;var b=a+l-h+f,S=Math.min(this._bufferService.cols,c-a+h+u-f-_);if(t||""!==s.slice(a,c).trim()){if(r&&0===b&&32!==o.getCodePoint(0)){var m=n.lines.get(e[1]-1);if(m&&o.isWrapped&&32!==m.getCodePoint(this._bufferService.cols-1)){var C=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(C){var w=this._bufferService.cols-C.start;b-=w,S+=w}}}if(i&&b+S===this._bufferService.cols&&32!==o.getCodePoint(this._bufferService.cols-1)){var E=n.lines.get(e[1]+1);if(E&&E.isWrapped&&32!==E.getCodePoint(0)){var L=this._getWordAt([0,e[1]+1],!1,!1,!0);L&&(S+=L.length)}}return{start:b,length:S}}}}},t.prototype._selectWordAt=function(e,t){var r=this._getWordAt(e,t);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}},t.prototype._selectToWordAt=function(e){var t=this._getWordAt(e,!0);if(t){for(var r=e[1];t.start<0;)t.start+=this._bufferService.cols,r--;if(!this._model.areSelectionValuesReversed())for(;t.start+t.length>this._bufferService.cols;)t.length-=this._bufferService.cols,r++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?t.start:t.start+t.length,r]}},t.prototype._isCharWordSeparator=function(e){return 0!==e.getWidth()&&this._optionsService.options.wordSeparator.indexOf(e.getChars())>=0},t.prototype._selectLineAt=function(e){var t=this._bufferService.buffer.getWrappedRangeForLine(e);this._model.selectionStart=[0,t.first],this._model.selectionEnd=[this._bufferService.cols,t.last],this._model.selectionStartLength=0},t=o([s(2,f.IBufferService),s(3,f.ICoreService),s(4,u.IMouseService),s(5,f.IOptionsService),s(6,u.IRenderService)],t)}(p.Disposable);t.SelectionService=y},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SelectionModel=void 0;var i=function(){function e(e){this._bufferService=e,this.isSelectAllActive=!1,this.selectionStartLength=0}return e.prototype.clearSelection=function(){this.selectionStart=void 0,this.selectionEnd=void 0,this.isSelectAllActive=!1,this.selectionStartLength=0},Object.defineProperty(e.prototype,"finalSelectionStart",{get:function(){return this.isSelectAllActive?[0,0]:this.selectionEnd&&this.selectionStart&&this.areSelectionValuesReversed()?this.selectionEnd:this.selectionStart},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"finalSelectionEnd",{get:function(){if(this.isSelectAllActive)return[this._bufferService.cols,this._bufferService.buffer.ybase+this._bufferService.rows-1];if(this.selectionStart){if(!this.selectionEnd||this.areSelectionValuesReversed()){var e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[e,this.selectionStart[1]]}return this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]?[Math.max(this.selectionStart[0]+this.selectionStartLength,this.selectionEnd[0]),this.selectionEnd[1]]:this.selectionEnd}},enumerable:!1,configurable:!0}),e.prototype.areSelectionValuesReversed=function(){var e=this.selectionStart,t=this.selectionEnd;return!(!e||!t)&&(e[1]>t[1]||e[1]===t[1]&&e[0]>t[0])},e.prototype.onTrim=function(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)},e}();t.SelectionModel=i},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.moveToCellSequence=void 0;var i=r(12);function n(e,t,r,i){var n=e-o(r,e),a=t-o(r,t);return l(Math.abs(n-a)-function(e,t,r){for(var i=0,n=e-o(r,e),a=t-o(r,t),c=0;c=0&&tt?"A":"B"}function a(e,t,r,i,n,o){for(var s=e,a=t,c="";s!==r||a!==i;)s+=n?1:-1,n&&s>o.cols-1?(c+=o.buffer.translateBufferLineToString(a,!1,e,s),s=0,e=0,a++):!n&&s<0&&(c+=o.buffer.translateBufferLineToString(a,!1,0,e+1),e=s=o.cols-1,a--);return c+o.buffer.translateBufferLineToString(a,!1,e,s)}function c(e,t){var r=t?"O":"[";return i.C0.ESC+r+e}function l(e,t){e=Math.floor(e);for(var r="",i=0;i0?i-o(s,i):t;var f=i,_=function(e,t,r,i,s,a){var c;c=n(r,i,s,a).length>0?i-o(s,i):t;if(e=r&&ce?"D":"C",l(Math.abs(h-e),c(s,i));s=u>t?"D":"C";var f=Math.abs(u-t);return l(function(e,t){return t.cols-e}(u>t?e:h,r)+(f-1)*r.cols+1+((u>t?h:e)-1),c(s,i))}},function(e,t,r){"use strict";var i=this&&this.__decorate||function(e,t,r,i){var n,o=arguments.length,s=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,r):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,r,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(o<3?n(s):o>3?n(t,r,s):n(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},n=this&&this.__param||function(e,t){return function(r,i){t(r,i,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.SoundService=void 0;var o=r(1),s=function(){function e(e){this._optionsService=e}return Object.defineProperty(e,"audioContext",{get:function(){if(!e._audioContext){var t=window.AudioContext||window.webkitAudioContext;if(!t)return console.warn("Web Audio API is not supported by this browser. Consider upgrading to the latest version"),null;e._audioContext=new t}return e._audioContext},enumerable:!1,configurable:!0}),e.prototype.playBellSound=function(){var t=e.audioContext;if(t){var r=t.createBufferSource();t.decodeAudioData(this._base64ToArrayBuffer(this._removeMimeType(this._optionsService.options.bellSound)),(function(e){r.buffer=e,r.connect(t.destination),r.start(0)}))}},e.prototype._base64ToArrayBuffer=function(e){for(var t=window.atob(e),r=t.length,i=new Uint8Array(r),n=0;n=0;a--)(n=e[a])&&(s=(o<3?n(s):o>3?n(t,r,s):n(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},s=this&&this.__param||function(e,t){return function(r,i){t(r,i,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.MouseZoneManager=void 0;var a=r(2),c=r(7),l=r(5),h=r(1),u=function(e){function t(t,r,i,n,o,s){var a=e.call(this)||this;return a._element=t,a._screenElement=r,a._bufferService=i,a._mouseService=n,a._selectionService=o,a._optionsService=s,a._zones=[],a._areZonesActive=!1,a._lastHoverCoords=[void 0,void 0],a._initialSelectionLength=0,a.register(c.addDisposableDomListener(a._element,"mousedown",(function(e){return a._onMouseDown(e)}))),a._mouseMoveListener=function(e){return a._onMouseMove(e)},a._mouseLeaveListener=function(e){return a._onMouseLeave(e)},a._clickListener=function(e){return a._onClick(e)},a}return n(t,e),t.prototype.dispose=function(){e.prototype.dispose.call(this),this._deactivate()},t.prototype.add=function(e){this._zones.push(e),1===this._zones.length&&this._activate()},t.prototype.clearAll=function(e,t){if(0!==this._zones.length){e&&t||(e=0,t=this._bufferService.rows-1);for(var r=0;re&&i.y1<=t+1||i.y2>e&&i.y2<=t+1||i.y1t+1)&&(this._currentZone&&this._currentZone===i&&(this._currentZone.leaveCallback(),this._currentZone=void 0),this._zones.splice(r--,1))}0===this._zones.length&&this._deactivate()}},t.prototype._activate=function(){this._areZonesActive||(this._areZonesActive=!0,this._element.addEventListener("mousemove",this._mouseMoveListener),this._element.addEventListener("mouseleave",this._mouseLeaveListener),this._element.addEventListener("click",this._clickListener))},t.prototype._deactivate=function(){this._areZonesActive&&(this._areZonesActive=!1,this._element.removeEventListener("mousemove",this._mouseMoveListener),this._element.removeEventListener("mouseleave",this._mouseLeaveListener),this._element.removeEventListener("click",this._clickListener))},t.prototype._onMouseMove=function(e){this._lastHoverCoords[0]===e.pageX&&this._lastHoverCoords[1]===e.pageY||(this._onHover(e),this._lastHoverCoords=[e.pageX,e.pageY])},t.prototype._onHover=function(e){var t=this,r=this._findZoneEventAt(e);r!==this._currentZone&&(this._currentZone&&(this._currentZone.leaveCallback(),this._currentZone=void 0,this._tooltipTimeout&&clearTimeout(this._tooltipTimeout)),r&&(this._currentZone=r,r.hoverCallback&&r.hoverCallback(e),this._tooltipTimeout=window.setTimeout((function(){return t._onTooltip(e)}),this._optionsService.options.linkTooltipHoverDuration)))},t.prototype._onTooltip=function(e){this._tooltipTimeout=void 0;var t=this._findZoneEventAt(e);t&&t.tooltipCallback&&t.tooltipCallback(e)},t.prototype._onMouseDown=function(e){if(this._initialSelectionLength=this._getSelectionLength(),this._areZonesActive){var t=this._findZoneEventAt(e);(null==t?void 0:t.willLinkActivate(e))&&(e.preventDefault(),e.stopImmediatePropagation())}},t.prototype._onMouseLeave=function(e){this._currentZone&&(this._currentZone.leaveCallback(),this._currentZone=void 0,this._tooltipTimeout&&clearTimeout(this._tooltipTimeout))},t.prototype._onClick=function(e){var t=this._findZoneEventAt(e),r=this._getSelectionLength();t&&r===this._initialSelectionLength&&(t.clickCallback(e),e.preventDefault(),e.stopImmediatePropagation())},t.prototype._getSelectionLength=function(){var e=this._selectionService.selectionText;return e?e.length:0},t.prototype._findZoneEventAt=function(e){var t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows);if(t)for(var r=t[0],i=t[1],n=0;n=o.x1&&r=o.x1||i===o.y2&&ro.y1&&ie;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()},t.prototype._createAccessibilityTreeNode=function(){var e=document.createElement("div");return e.setAttribute("role","listitem"),e.tabIndex=-1,this._refreshRowDimensions(e),e},t.prototype._onTab=function(e){for(var t=0;t0)this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e);else this._charsToAnnounce+=e;"\n"===e&&(this._liveRegionLineCount++,21===this._liveRegionLineCount&&(this._liveRegion.textContent+=o.tooMuchOutput)),s.isMac&&this._liveRegion.textContent&&this._liveRegion.textContent.length>0&&!this._liveRegion.parentNode&&setTimeout((function(){t._accessibilityTreeRoot.appendChild(t._liveRegion)}),0)}},t.prototype._clearLiveRegion=function(){this._liveRegion.textContent="",this._liveRegionLineCount=0,s.isMac&&u.removeElementFromParent(this._liveRegion)},t.prototype._onKey=function(e){this._clearLiveRegion(),this._charsToConsume.push(e)},t.prototype._refreshRows=function(e,t){this._renderRowsDebouncer.refresh(e,t,this._terminal.rows)},t.prototype._renderRows=function(e,t){for(var r=this._terminal.buffer,i=r.lines.length.toString(),n=e;n<=t;n++){var o=r.translateBufferLineToString(r.ydisp+n,!0),s=(r.ydisp+n+1).toString(),a=this._rowElements[n];a&&(0===o.length?a.innerHTML=" ":a.textContent=o,a.setAttribute("aria-posinset",s),a.setAttribute("aria-setsize",i))}this._announceCharacters()},t.prototype._refreshRowsDimensions=function(){if(this._renderService.dimensions.actualCellHeight){this._rowElements.length!==this._terminal.rows&&this._onResize(this._terminal.rows);for(var e=0;e=0;a--)(n=e[a])&&(s=(o<3?n(s):o>3?n(t,r,s):n(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},s=this&&this.__param||function(e,t){return function(r,i){t(r,i,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.DomRenderer=void 0;var a=r(58),c=r(9),l=r(2),h=r(5),u=r(1),f=r(0),_=r(10),d=r(17),p=1,v=function(e){function t(t,r,i,n,o,s,c,l,h){var u=e.call(this)||this;return u._colors=t,u._element=r,u._screenElement=i,u._viewportElement=n,u._linkifier=o,u._linkifier2=s,u._charSizeService=c,u._optionsService=l,u._bufferService=h,u._terminalClass=p++,u._rowElements=[],u._rowContainer=document.createElement("div"),u._rowContainer.classList.add("xterm-rows"),u._rowContainer.style.lineHeight="normal",u._rowContainer.setAttribute("aria-hidden","true"),u._refreshRowElements(u._bufferService.cols,u._bufferService.rows),u._selectionContainer=document.createElement("div"),u._selectionContainer.classList.add("xterm-selection"),u._selectionContainer.setAttribute("aria-hidden","true"),u.dimensions={scaledCharWidth:0,scaledCharHeight:0,scaledCellWidth:0,scaledCellHeight:0,scaledCharLeft:0,scaledCharTop:0,scaledCanvasWidth:0,scaledCanvasHeight:0,canvasWidth:0,canvasHeight:0,actualCellWidth:0,actualCellHeight:0},u._updateDimensions(),u._injectCss(),u._rowFactory=new a.DomRendererRowFactory(document,u._optionsService,u._colors),u._element.classList.add("xterm-dom-renderer-owner-"+u._terminalClass),u._screenElement.appendChild(u._rowContainer),u._screenElement.appendChild(u._selectionContainer),u._linkifier.onShowLinkUnderline((function(e){return u._onLinkHover(e)})),u._linkifier.onHideLinkUnderline((function(e){return u._onLinkLeave(e)})),u._linkifier2.onShowLinkUnderline((function(e){return u._onLinkHover(e)})),u._linkifier2.onHideLinkUnderline((function(e){return u._onLinkLeave(e)})),u}return n(t,e),Object.defineProperty(t.prototype,"onRequestRedraw",{get:function(){return(new f.EventEmitter).event},enumerable:!1,configurable:!0}),t.prototype.dispose=function(){this._element.classList.remove("xterm-dom-renderer-owner-"+this._terminalClass),d.removeElementFromParent(this._rowContainer,this._selectionContainer,this._themeStyleElement,this._dimensionsStyleElement),e.prototype.dispose.call(this)},t.prototype._updateDimensions=function(){this.dimensions.scaledCharWidth=this._charSizeService.width*window.devicePixelRatio,this.dimensions.scaledCharHeight=Math.ceil(this._charSizeService.height*window.devicePixelRatio),this.dimensions.scaledCellWidth=this.dimensions.scaledCharWidth+Math.round(this._optionsService.options.letterSpacing),this.dimensions.scaledCellHeight=Math.floor(this.dimensions.scaledCharHeight*this._optionsService.options.lineHeight),this.dimensions.scaledCharLeft=0,this.dimensions.scaledCharTop=0,this.dimensions.scaledCanvasWidth=this.dimensions.scaledCellWidth*this._bufferService.cols,this.dimensions.scaledCanvasHeight=this.dimensions.scaledCellHeight*this._bufferService.rows,this.dimensions.canvasWidth=Math.round(this.dimensions.scaledCanvasWidth/window.devicePixelRatio),this.dimensions.canvasHeight=Math.round(this.dimensions.scaledCanvasHeight/window.devicePixelRatio),this.dimensions.actualCellWidth=this.dimensions.canvasWidth/this._bufferService.cols,this.dimensions.actualCellHeight=this.dimensions.canvasHeight/this._bufferService.rows;for(var e=0,t=this._rowElements;et;)this._rowContainer.removeChild(this._rowElements.pop())},t.prototype.onResize=function(e,t){this._refreshRowElements(e,t),this._updateDimensions()},t.prototype.onCharSizeChanged=function(){this._updateDimensions()},t.prototype.onBlur=function(){this._rowContainer.classList.remove("xterm-focus")},t.prototype.onFocus=function(){this._rowContainer.classList.add("xterm-focus")},t.prototype.onSelectionChanged=function(e,t,r){for(;this._selectionContainer.children.length;)this._selectionContainer.removeChild(this._selectionContainer.children[0]);if(e&&t){var i=e[1]-this._bufferService.buffer.ydisp,n=t[1]-this._bufferService.buffer.ydisp,o=Math.max(i,0),s=Math.min(n,this._bufferService.rows-1);if(!(o>=this._bufferService.rows||s<0)){var a=document.createDocumentFragment();if(r)a.appendChild(this._createSelectionElement(o,e[0],t[0],s-o+1));else{var c=i===o?e[0]:0,l=o===s?t[0]:this._bufferService.cols;a.appendChild(this._createSelectionElement(o,c,l));var h=s-o-1;if(a.appendChild(this._createSelectionElement(o+1,0,this._bufferService.cols,h)),o!==s){var u=n===s?t[0]:this._bufferService.cols;a.appendChild(this._createSelectionElement(s,0,u))}}this._selectionContainer.appendChild(a)}}},t.prototype._createSelectionElement=function(e,t,r,i){void 0===i&&(i=1);var n=document.createElement("div");return n.style.height=i*this.dimensions.actualCellHeight+"px",n.style.top=e*this.dimensions.actualCellHeight+"px",n.style.left=t*this.dimensions.actualCellWidth+"px",n.style.width=this.dimensions.actualCellWidth*(r-t)+"px",n},t.prototype.onCursorMove=function(){},t.prototype.onOptionsChanged=function(){this._updateDimensions(),this._injectCss()},t.prototype.clear=function(){for(var e=0,t=this._rowElements;e=n&&(e=0,r++)}},t=o([s(6,h.ICharSizeService),s(7,u.IOptionsService),s(8,u.IBufferService)],t)}(l.Disposable);t.DomRenderer=v},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DomRendererRowFactory=t.CURSOR_STYLE_UNDERLINE_CLASS=t.CURSOR_STYLE_BAR_CLASS=t.CURSOR_STYLE_BLOCK_CLASS=t.CURSOR_BLINK_CLASS=t.CURSOR_CLASS=t.UNDERLINE_CLASS=t.ITALIC_CLASS=t.DIM_CLASS=t.BOLD_CLASS=void 0;var i=r(9),n=r(3),o=r(4),s=r(10);t.BOLD_CLASS="xterm-bold",t.DIM_CLASS="xterm-dim",t.ITALIC_CLASS="xterm-italic",t.UNDERLINE_CLASS="xterm-underline",t.CURSOR_CLASS="xterm-cursor",t.CURSOR_BLINK_CLASS="xterm-cursor-blink",t.CURSOR_STYLE_BLOCK_CLASS="xterm-cursor-block",t.CURSOR_STYLE_BAR_CLASS="xterm-cursor-bar",t.CURSOR_STYLE_UNDERLINE_CLASS="xterm-cursor-underline";var a=function(){function e(e,t,r){this._document=e,this._optionsService=t,this._colors=r,this._workCell=new o.CellData}return e.prototype.setColors=function(e){this._colors=e},e.prototype.createRow=function(e,r,o,a,l,h,u){for(var f=this._document.createDocumentFragment(),_=0,d=Math.min(e.length,u)-1;d>=0;d--)if(e.loadCell(d,this._workCell).getCode()!==n.NULL_CELL_CODE||r&&d===a){_=d+1;break}for(d=0;d<_;d++){e.loadCell(d,this._workCell);var p=this._workCell.getWidth();if(0!==p){var v=this._document.createElement("span");if(p>1&&(v.style.width=h*p+"px"),r&&d===a)switch(v.classList.add(t.CURSOR_CLASS),l&&v.classList.add(t.CURSOR_BLINK_CLASS),o){case"bar":v.classList.add(t.CURSOR_STYLE_BAR_CLASS);break;case"underline":v.classList.add(t.CURSOR_STYLE_UNDERLINE_CLASS);break;default:v.classList.add(t.CURSOR_STYLE_BLOCK_CLASS)}this._workCell.isBold()&&v.classList.add(t.BOLD_CLASS),this._workCell.isItalic()&&v.classList.add(t.ITALIC_CLASS),this._workCell.isDim()&&v.classList.add(t.DIM_CLASS),this._workCell.isUnderline()&&v.classList.add(t.UNDERLINE_CLASS),this._workCell.isInvisible()?v.textContent=n.WHITESPACE_CELL_CHAR:v.textContent=this._workCell.getChars()||n.WHITESPACE_CELL_CHAR;var g=this._workCell.getFgColor(),y=this._workCell.getFgColorMode(),b=this._workCell.getBgColor(),S=this._workCell.getBgColorMode(),m=!!this._workCell.isInverse();if(m){var C=g;g=b,b=C;var w=y;y=S,S=w}switch(y){case 16777216:case 33554432:this._workCell.isBold()&&g<8&&this._optionsService.options.drawBoldTextInBrightColors&&(g+=8),this._applyMinimumContrast(v,this._colors.background,this._colors.ansi[g])||v.classList.add("xterm-fg-"+g);break;case 50331648:var E=s.rgba.toColor(g>>16&255,g>>8&255,255&g);this._applyMinimumContrast(v,this._colors.background,E)||this._addStyle(v,"color:#"+c(g.toString(16),"0",6));break;case 0:default:this._applyMinimumContrast(v,this._colors.background,this._colors.foreground)||m&&v.classList.add("xterm-fg-"+i.INVERTED_DEFAULT_COLOR)}switch(S){case 16777216:case 33554432:v.classList.add("xterm-bg-"+b);break;case 50331648:this._addStyle(v,"background-color:#"+c(b.toString(16),"0",6));break;case 0:default:m&&v.classList.add("xterm-bg-"+i.INVERTED_DEFAULT_COLOR)}f.appendChild(v)}}return f},e.prototype._applyMinimumContrast=function(e,t,r){if(1===this._optionsService.options.minimumContrastRatio)return!1;var i=this._colors.contrastCache.getColor(this._workCell.bg,this._workCell.fg);return void 0===i&&(i=s.color.ensureContrastRatio(t,r,this._optionsService.options.minimumContrastRatio),this._colors.contrastCache.setColor(this._workCell.bg,this._workCell.fg,null!=i?i:null)),!!i&&(this._addStyle(e,"color:"+i.css),!0)},e.prototype._addStyle=function(e,t){e.setAttribute("style",""+(e.getAttribute("style")||"")+t+";")},e}();function c(e,t,r){for(;e.length"],191:["/","?"],192:["`","~"],219:["[","{"],220:["\\","|"],221:["]","}"],222:["'",'"']};t.evaluateKeyboardEvent=function(e,t,r,o){var s={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?s.key=t?i.C0.ESC+"OA":i.C0.ESC+"[A":"UIKeyInputLeftArrow"===e.key?s.key=t?i.C0.ESC+"OD":i.C0.ESC+"[D":"UIKeyInputRightArrow"===e.key?s.key=t?i.C0.ESC+"OC":i.C0.ESC+"[C":"UIKeyInputDownArrow"===e.key&&(s.key=t?i.C0.ESC+"OB":i.C0.ESC+"[B");break;case 8:if(e.shiftKey){s.key=i.C0.BS;break}if(e.altKey){s.key=i.C0.ESC+i.C0.DEL;break}s.key=i.C0.DEL;break;case 9:if(e.shiftKey){s.key=i.C0.ESC+"[Z";break}s.key=i.C0.HT,s.cancel=!0;break;case 13:s.key=e.altKey?i.C0.ESC+i.C0.CR:i.C0.CR,s.cancel=!0;break;case 27:s.key=i.C0.ESC,e.altKey&&(s.key=i.C0.ESC+i.C0.ESC),s.cancel=!0;break;case 37:if(e.metaKey)break;a?(s.key=i.C0.ESC+"[1;"+(a+1)+"D",s.key===i.C0.ESC+"[1;3D"&&(s.key=i.C0.ESC+(r?"b":"[1;5D"))):s.key=t?i.C0.ESC+"OD":i.C0.ESC+"[D";break;case 39:if(e.metaKey)break;a?(s.key=i.C0.ESC+"[1;"+(a+1)+"C",s.key===i.C0.ESC+"[1;3C"&&(s.key=i.C0.ESC+(r?"f":"[1;5C"))):s.key=t?i.C0.ESC+"OC":i.C0.ESC+"[C";break;case 38:if(e.metaKey)break;a?(s.key=i.C0.ESC+"[1;"+(a+1)+"A",r||s.key!==i.C0.ESC+"[1;3A"||(s.key=i.C0.ESC+"[1;5A")):s.key=t?i.C0.ESC+"OA":i.C0.ESC+"[A";break;case 40:if(e.metaKey)break;a?(s.key=i.C0.ESC+"[1;"+(a+1)+"B",r||s.key!==i.C0.ESC+"[1;3B"||(s.key=i.C0.ESC+"[1;5B")):s.key=t?i.C0.ESC+"OB":i.C0.ESC+"[B";break;case 45:e.shiftKey||e.ctrlKey||(s.key=i.C0.ESC+"[2~");break;case 46:s.key=a?i.C0.ESC+"[3;"+(a+1)+"~":i.C0.ESC+"[3~";break;case 36:s.key=a?i.C0.ESC+"[1;"+(a+1)+"H":t?i.C0.ESC+"OH":i.C0.ESC+"[H";break;case 35:s.key=a?i.C0.ESC+"[1;"+(a+1)+"F":t?i.C0.ESC+"OF":i.C0.ESC+"[F";break;case 33:e.shiftKey?s.type=2:s.key=i.C0.ESC+"[5~";break;case 34:e.shiftKey?s.type=3:s.key=i.C0.ESC+"[6~";break;case 112:s.key=a?i.C0.ESC+"[1;"+(a+1)+"P":i.C0.ESC+"OP";break;case 113:s.key=a?i.C0.ESC+"[1;"+(a+1)+"Q":i.C0.ESC+"OQ";break;case 114:s.key=a?i.C0.ESC+"[1;"+(a+1)+"R":i.C0.ESC+"OR";break;case 115:s.key=a?i.C0.ESC+"[1;"+(a+1)+"S":i.C0.ESC+"OS";break;case 116:s.key=a?i.C0.ESC+"[15;"+(a+1)+"~":i.C0.ESC+"[15~";break;case 117:s.key=a?i.C0.ESC+"[17;"+(a+1)+"~":i.C0.ESC+"[17~";break;case 118:s.key=a?i.C0.ESC+"[18;"+(a+1)+"~":i.C0.ESC+"[18~";break;case 119:s.key=a?i.C0.ESC+"[19;"+(a+1)+"~":i.C0.ESC+"[19~";break;case 120:s.key=a?i.C0.ESC+"[20;"+(a+1)+"~":i.C0.ESC+"[20~";break;case 121:s.key=a?i.C0.ESC+"[21;"+(a+1)+"~":i.C0.ESC+"[21~";break;case 122:s.key=a?i.C0.ESC+"[23;"+(a+1)+"~":i.C0.ESC+"[23~";break;case 123:s.key=a?i.C0.ESC+"[24;"+(a+1)+"~":i.C0.ESC+"[24~";break;default:if(!e.ctrlKey||e.shiftKey||e.altKey||e.metaKey)if(r&&!o||!e.altKey||e.metaKey)r&&!e.altKey&&!e.ctrlKey&&e.metaKey?65===e.keyCode&&(s.type=1):e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.keyCode>=48&&1===e.key.length?s.key=e.key:e.key&&e.ctrlKey&&"_"===e.key&&(s.key=i.C0.US);else{var c=n[e.keyCode],l=c&&c[e.shiftKey?1:0];if(l)s.key=i.C0.ESC+l;else if(e.keyCode>=65&&e.keyCode<=90){var h=e.ctrlKey?e.keyCode-64:e.keyCode+32;s.key=i.C0.ESC+String.fromCharCode(h)}}else e.keyCode>=65&&e.keyCode<=90?s.key=String.fromCharCode(e.keyCode-64):32===e.keyCode?s.key=i.C0.NUL:e.keyCode>=51&&e.keyCode<=55?s.key=String.fromCharCode(e.keyCode-51+27):56===e.keyCode?s.key=i.C0.DEL:219===e.keyCode?s.key=i.C0.ESC:220===e.keyCode?s.key=i.C0.FS:221===e.keyCode&&(s.key=i.C0.GS)}return s}},function(e,t,r){"use strict";var i,n=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}),o=this&&this.__decorate||function(e,t,r,i){var n,o=arguments.length,s=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,r):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,r,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(o<3?n(s):o>3?n(t,r,s):n(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},s=this&&this.__param||function(e,t){return function(r,i){t(r,i,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.RenderService=void 0;var a=r(31),c=r(0),l=r(2),h=r(32),u=r(7),f=r(1),_=r(5),d=function(e){function t(t,r,i,n,o,s){var l=e.call(this)||this;if(l._renderer=t,l._rowCount=r,l._isPaused=!1,l._needsFullRefresh=!1,l._isNextRenderRedrawOnly=!0,l._needsSelectionRefresh=!1,l._canvasWidth=0,l._canvasHeight=0,l._selectionState={start:void 0,end:void 0,columnSelectMode:!1},l._onDimensionsChange=new c.EventEmitter,l._onRender=new c.EventEmitter,l._onRefreshRequest=new c.EventEmitter,l.register({dispose:function(){return l._renderer.dispose()}}),l._renderDebouncer=new a.RenderDebouncer((function(e,t){return l._renderRows(e,t)})),l.register(l._renderDebouncer),l._screenDprMonitor=new h.ScreenDprMonitor,l._screenDprMonitor.setListener((function(){return l.onDevicePixelRatioChange()})),l.register(l._screenDprMonitor),l.register(s.onResize((function(e){return l._fullRefresh()}))),l.register(n.onOptionChange((function(){return l._renderer.onOptionsChanged()}))),l.register(o.onCharSizeChange((function(){return l.onCharSizeChanged()}))),l._renderer.onRequestRedraw((function(e){return l.refreshRows(e.start,e.end,!0)})),l.register(u.addDisposableDomListener(window,"resize",(function(){return l.onDevicePixelRatioChange()}))),"IntersectionObserver"in window){var f=new IntersectionObserver((function(e){return l._onIntersectionChange(e[e.length-1])}),{threshold:0});f.observe(i),l.register({dispose:function(){return f.disconnect()}})}return l}return n(t,e),Object.defineProperty(t.prototype,"onDimensionsChange",{get:function(){return this._onDimensionsChange.event},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"onRenderedBufferChange",{get:function(){return this._onRender.event},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"onRefreshRequest",{get:function(){return this._onRefreshRequest.event},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"dimensions",{get:function(){return this._renderer.dimensions},enumerable:!1,configurable:!0}),t.prototype._onIntersectionChange=function(e){this._isPaused=0===e.intersectionRatio,!this._isPaused&&this._needsFullRefresh&&(this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)},t.prototype.refreshRows=function(e,t,r){void 0===r&&(r=!1),this._isPaused?this._needsFullRefresh=!0:(r||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(e,t,this._rowCount))},t.prototype._renderRows=function(e,t){this._renderer.renderRows(e,t),this._needsSelectionRefresh&&(this._renderer.onSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),this._needsSelectionRefresh=!1),this._isNextRenderRedrawOnly||this._onRender.fire({start:e,end:t}),this._isNextRenderRedrawOnly=!0},t.prototype.resize=function(e,t){this._rowCount=t,this._fireOnCanvasResize()},t.prototype.changeOptions=function(){this._renderer.onOptionsChanged(),this.refreshRows(0,this._rowCount-1),this._fireOnCanvasResize()},t.prototype._fireOnCanvasResize=function(){this._renderer.dimensions.canvasWidth===this._canvasWidth&&this._renderer.dimensions.canvasHeight===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.dimensions)},t.prototype.dispose=function(){e.prototype.dispose.call(this)},t.prototype.setRenderer=function(e){var t=this;this._renderer.dispose(),this._renderer=e,this._renderer.onRequestRedraw((function(e){return t.refreshRows(e.start,e.end,!0)})),this._needsSelectionRefresh=!0,this._fullRefresh()},t.prototype._fullRefresh=function(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)},t.prototype.setColors=function(e){this._renderer.setColors(e),this._fullRefresh()},t.prototype.onDevicePixelRatioChange=function(){this._renderer.onDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1)},t.prototype.onResize=function(e,t){this._renderer.onResize(e,t),this._fullRefresh()},t.prototype.onCharSizeChanged=function(){this._renderer.onCharSizeChanged()},t.prototype.onBlur=function(){this._renderer.onBlur()},t.prototype.onFocus=function(){this._renderer.onFocus()},t.prototype.onSelectionChanged=function(e,t,r){this._selectionState.start=e,this._selectionState.end=t,this._selectionState.columnSelectMode=r,this._renderer.onSelectionChanged(e,t,r)},t.prototype.onCursorMove=function(){this._renderer.onCursorMove()},t.prototype.clear=function(){this._renderer.clear()},t.prototype.registerCharacterJoiner=function(e){return this._renderer.registerCharacterJoiner(e)},t.prototype.deregisterCharacterJoiner=function(e){return this._renderer.deregisterCharacterJoiner(e)},t=o([s(3,f.IOptionsService),s(4,_.ICharSizeService),s(5,f.IBufferService)],t)}(l.Disposable);t.RenderService=d},function(e,t,r){"use strict";var i=this&&this.__decorate||function(e,t,r,i){var n,o=arguments.length,s=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,r):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,r,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(o<3?n(s):o>3?n(t,r,s):n(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},n=this&&this.__param||function(e,t){return function(r,i){t(r,i,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.CharSizeService=void 0;var o=r(1),s=r(0),a=function(){function e(e,t,r){this._optionsService=r,this.width=0,this.height=0,this._onCharSizeChange=new s.EventEmitter,this._measureStrategy=new c(e,t,this._optionsService)}return Object.defineProperty(e.prototype,"hasValidSize",{get:function(){return this.width>0&&this.height>0},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onCharSizeChange",{get:function(){return this._onCharSizeChange.event},enumerable:!1,configurable:!0}),e.prototype.measure=function(){var e=this._measureStrategy.measure();e.width===this.width&&e.height===this.height||(this.width=e.width,this.height=e.height,this._onCharSizeChange.fire())},e=i([n(2,o.IOptionsService)],e)}();t.CharSizeService=a;var c=function(){function e(e,t,r){this._document=e,this._parentElement=t,this._optionsService=r,this._result={width:0,height:0},this._measureElement=this._document.createElement("span"),this._measureElement.classList.add("xterm-char-measure-element"),this._measureElement.textContent="W",this._measureElement.setAttribute("aria-hidden","true"),this._parentElement.appendChild(this._measureElement)}return e.prototype.measure=function(){this._measureElement.style.fontFamily=this._optionsService.options.fontFamily,this._measureElement.style.fontSize=this._optionsService.options.fontSize+"px";var e=this._measureElement.getBoundingClientRect();return 0!==e.width&&0!==e.height&&(this._result.width=e.width,this._result.height=Math.ceil(e.height)),this._result},e}()},function(e,t,r){"use strict";var i=this&&this.__decorate||function(e,t,r,i){var n,o=arguments.length,s=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,r):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,r,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(o<3?n(s):o>3?n(t,r,s):n(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},n=this&&this.__param||function(e,t){return function(r,i){t(r,i,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.MouseService=void 0;var o=r(5),s=r(30),a=function(){function e(e,t){this._renderService=e,this._charSizeService=t}return e.prototype.getCoords=function(e,t,r,i,n){return s.getCoords(e,t,r,i,this._charSizeService.hasValidSize,this._renderService.dimensions.actualCellWidth,this._renderService.dimensions.actualCellHeight,n)},e.prototype.getRawByteCoords=function(e,t,r,i){var n=this.getCoords(e,t,r,i);return s.getRawByteCoords(n)},e=i([n(0,o.IRenderService),n(1,o.ICharSizeService)],e)}();t.MouseService=a},function(e,t,r){"use strict";var i,n=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}),o=this&&this.__decorate||function(e,t,r,i){var n,o=arguments.length,s=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,r):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,r,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(o<3?n(s):o>3?n(t,r,s):n(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},s=this&&this.__param||function(e,t){return function(r,i){t(r,i,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.Linkifier2=void 0;var a=r(1),c=r(0),l=r(2),h=r(7),u=function(e){function t(t){var r=e.call(this)||this;return r._bufferService=t,r._linkProviders=[],r._linkCacheDisposables=[],r._isMouseOut=!0,r._activeLine=-1,r._onShowLinkUnderline=r.register(new c.EventEmitter),r._onHideLinkUnderline=r.register(new c.EventEmitter),r.register(l.getDisposeArrayDisposable(r._linkCacheDisposables)),r}return n(t,e),Object.defineProperty(t.prototype,"onShowLinkUnderline",{get:function(){return this._onShowLinkUnderline.event},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"onHideLinkUnderline",{get:function(){return this._onHideLinkUnderline.event},enumerable:!1,configurable:!0}),t.prototype.registerLinkProvider=function(e){var t=this;return this._linkProviders.push(e),{dispose:function(){var r=t._linkProviders.indexOf(e);-1!==r&&t._linkProviders.splice(r,1)}}},t.prototype.attachToDom=function(e,t,r){var i=this;this._element=e,this._mouseService=t,this._renderService=r,this.register(h.addDisposableDomListener(this._element,"mouseleave",(function(){i._isMouseOut=!0,i._clearCurrentLink()}))),this.register(h.addDisposableDomListener(this._element,"mousemove",this._onMouseMove.bind(this))),this.register(h.addDisposableDomListener(this._element,"click",this._onClick.bind(this)))},t.prototype._onMouseMove=function(e){if(this._lastMouseEvent=e,this._element&&this._mouseService){var t=this._positionFromMouseEvent(e,this._element,this._mouseService);if(t){this._isMouseOut=!1;for(var r=e.composedPath(),i=0;ie?this._bufferService.cols:s.link.range.end.x,l=a;l<=c;l++){if(r.has(l)){n.splice(o--,1);break}r.add(l)}}},t.prototype._checkLinkProviderResult=function(e,t,r){var i,n=this;if(!this._activeProviderReplies)return r;for(var o=this._activeProviderReplies.get(e),s=!1,a=0;a=e&&this._currentLink.link.range.end.y<=t)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,l.disposeArray(this._linkCacheDisposables))},t.prototype._handleNewLink=function(e){var t=this;if(this._element&&this._lastMouseEvent&&this._mouseService){var r=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);r&&this._linkAtPosition(e.link,r)&&(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:function(){var e,r;return null===(r=null===(e=t._currentLink)||void 0===e?void 0:e.state)||void 0===r?void 0:r.decorations.pointerCursor},set:function(e){var r,i;(null===(r=t._currentLink)||void 0===r?void 0:r.state)&&t._currentLink.state.decorations.pointerCursor!==e&&(t._currentLink.state.decorations.pointerCursor=e,t._currentLink.state.isHovered&&(null===(i=t._element)||void 0===i||i.classList.toggle("xterm-cursor-pointer",e)))}},underline:{get:function(){var e,r;return null===(r=null===(e=t._currentLink)||void 0===e?void 0:e.state)||void 0===r?void 0:r.decorations.underline},set:function(r){var i,n,o;(null===(i=t._currentLink)||void 0===i?void 0:i.state)&&(null===(o=null===(n=t._currentLink)||void 0===n?void 0:n.state)||void 0===o?void 0:o.decorations.underline)!==r&&(t._currentLink.state.decorations.underline=r,t._currentLink.state.isHovered&&t._fireUnderlineEvent(e.link,r))}}}),this._renderService&&this._linkCacheDisposables.push(this._renderService.onRenderedBufferChange((function(e){var r=0===e.start?0:e.start+1+t._bufferService.buffer.ydisp;t._clearCurrentLink(r,e.end+1+t._bufferService.buffer.ydisp)}))))}},t.prototype._linkHover=function(e,t,r){var i;(null===(i=this._currentLink)||void 0===i?void 0:i.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(r,t.text)},t.prototype._fireUnderlineEvent=function(e,t){var r=e.range,i=this._bufferService.buffer.ydisp,n=this._createLinkUnderlineEvent(r.start.x-1,r.start.y-i-1,r.end.x,r.end.y-i-1,void 0);(t?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(n)},t.prototype._linkLeave=function(e,t,r){var i;(null===(i=this._currentLink)||void 0===i?void 0:i.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(r,t.text)},t.prototype._linkAtPosition=function(e,t){var r=e.range.start.y===e.range.end.y,i=e.range.start.yt.y;return(r&&e.range.start.x<=t.x&&e.range.end.x>=t.x||i&&e.range.end.x>=t.x||n&&e.range.start.x<=t.x||i&&n)&&e.range.start.y<=t.y&&e.range.end.y>=t.y},t.prototype._positionFromMouseEvent=function(e,t,r){var i=r.getCoords(e,t,this._bufferService.cols,this._bufferService.rows);if(i)return{x:i[0],y:i[1]+this._bufferService.buffer.ydisp}},t.prototype._createLinkUnderlineEvent=function(e,t,r,i,n){return{x1:e,y1:t,x2:r,y2:i,cols:this._bufferService.cols,fg:n}},t=o([s(0,a.IBufferService)],t)}(l.Disposable);t.Linkifier2=u},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CoreBrowserService=void 0;var i=function(){function e(e){this._textarea=e}return Object.defineProperty(e.prototype,"isFocused",{get:function(){return document.activeElement===this._textarea&&document.hasFocus()},enumerable:!1,configurable:!0}),e}();t.CoreBrowserService=i},function(e,t,r){"use strict";var i,n=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0}),t.CoreTerminal=void 0;var o=r(2),s=r(1),a=r(66),c=r(67),l=r(68),h=r(74),u=r(75),f=r(0),_=r(76),d=r(77),p=r(78),v=r(80),g=r(81),y=r(19),b=r(82),S=function(e){function t(t){var r=e.call(this)||this;return r._onBinary=new f.EventEmitter,r._onData=new f.EventEmitter,r._onLineFeed=new f.EventEmitter,r._onResize=new f.EventEmitter,r._onScroll=new f.EventEmitter,r._instantiationService=new a.InstantiationService,r.optionsService=new h.OptionsService(t),r._instantiationService.setService(s.IOptionsService,r.optionsService),r._bufferService=r.register(r._instantiationService.createInstance(l.BufferService)),r._instantiationService.setService(s.IBufferService,r._bufferService),r._logService=r._instantiationService.createInstance(c.LogService),r._instantiationService.setService(s.ILogService,r._logService),r._coreService=r.register(r._instantiationService.createInstance(u.CoreService,(function(){return r.scrollToBottom()}))),r._instantiationService.setService(s.ICoreService,r._coreService),r._coreMouseService=r._instantiationService.createInstance(_.CoreMouseService),r._instantiationService.setService(s.ICoreMouseService,r._coreMouseService),r._dirtyRowService=r._instantiationService.createInstance(d.DirtyRowService),r._instantiationService.setService(s.IDirtyRowService,r._dirtyRowService),r.unicodeService=r._instantiationService.createInstance(p.UnicodeService),r._instantiationService.setService(s.IUnicodeService,r.unicodeService),r._charsetService=r._instantiationService.createInstance(v.CharsetService),r._instantiationService.setService(s.ICharsetService,r._charsetService),r._inputHandler=new y.InputHandler(r._bufferService,r._charsetService,r._coreService,r._dirtyRowService,r._logService,r.optionsService,r._coreMouseService,r.unicodeService),r.register(f.forwardEvent(r._inputHandler.onLineFeed,r._onLineFeed)),r.register(r._inputHandler),r.register(f.forwardEvent(r._bufferService.onResize,r._onResize)),r.register(f.forwardEvent(r._coreService.onData,r._onData)),r.register(f.forwardEvent(r._coreService.onBinary,r._onBinary)),r.register(r.optionsService.onOptionChange((function(e){return r._updateOptions(e)}))),r._writeBuffer=new b.WriteBuffer((function(e){return r._inputHandler.parse(e)})),r}return n(t,e),Object.defineProperty(t.prototype,"onBinary",{get:function(){return this._onBinary.event},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"onData",{get:function(){return this._onData.event},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"onLineFeed",{get:function(){return this._onLineFeed.event},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"onResize",{get:function(){return this._onResize.event},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"onScroll",{get:function(){return this._onScroll.event},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"cols",{get:function(){return this._bufferService.cols},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"rows",{get:function(){return this._bufferService.rows},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"buffers",{get:function(){return this._bufferService.buffers},enumerable:!1,configurable:!0}),t.prototype.dispose=function(){var t;this._isDisposed||(e.prototype.dispose.call(this),null===(t=this._windowsMode)||void 0===t||t.dispose(),this._windowsMode=void 0)},t.prototype.write=function(e,t){this._writeBuffer.write(e,t)},t.prototype.writeSync=function(e){this._writeBuffer.writeSync(e)},t.prototype.resize=function(e,t){isNaN(e)||isNaN(t)||(e=Math.max(e,l.MINIMUM_COLS),t=Math.max(t,l.MINIMUM_ROWS),this._bufferService.resize(e,t))},t.prototype.scroll=function(e,t){void 0===t&&(t=!1);var r,i=this._bufferService.buffer;(r=this._cachedBlankLine)&&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;var n=i.ybase+i.scrollTop,o=i.ybase+i.scrollBottom;if(0===i.scrollTop){var s=i.lines.isFull;o===i.lines.length-1?s?i.lines.recycle().copyFrom(r):i.lines.push(r.clone()):i.lines.splice(o+1,0,r.clone()),s?this._bufferService.isUserScrolling&&(i.ydisp=Math.max(i.ydisp-1,0)):(i.ybase++,this._bufferService.isUserScrolling||i.ydisp++)}else{var a=o-n+1;i.lines.shiftElements(n+1,a-1,-1),i.lines.set(o,r.clone())}this._bufferService.isUserScrolling||(i.ydisp=i.ybase),this._dirtyRowService.markRangeDirty(i.scrollTop,i.scrollBottom),this._onScroll.fire(i.ydisp)},t.prototype.scrollLines=function(e,t){var r=this._bufferService.buffer;if(e<0){if(0===r.ydisp)return;this._bufferService.isUserScrolling=!0}else e+r.ydisp>=r.ybase&&(this._bufferService.isUserScrolling=!1);var i=r.ydisp;r.ydisp=Math.max(Math.min(r.ydisp+e,r.ybase),0),i!==r.ydisp&&(t||this._onScroll.fire(r.ydisp))},t.prototype.scrollPages=function(e){this.scrollLines(e*(this.rows-1))},t.prototype.scrollToTop=function(){this.scrollLines(-this._bufferService.buffer.ydisp)},t.prototype.scrollToBottom=function(){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)},t.prototype.scrollToLine=function(e){var t=e-this._bufferService.buffer.ydisp;0!==t&&this.scrollLines(t)},t.prototype.addEscHandler=function(e,t){return this._inputHandler.addEscHandler(e,t)},t.prototype.addDcsHandler=function(e,t){return this._inputHandler.addDcsHandler(e,t)},t.prototype.addCsiHandler=function(e,t){return this._inputHandler.addCsiHandler(e,t)},t.prototype.addOscHandler=function(e,t){return this._inputHandler.addOscHandler(e,t)},t.prototype._setup=function(){this.optionsService.options.windowsMode&&this._enableWindowsMode()},t.prototype.reset=function(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this._coreService.reset(),this._coreMouseService.reset()},t.prototype._updateOptions=function(e){var t;switch(e){case"scrollback":this.buffers.resize(this.cols,this.rows);break;case"windowsMode":this.optionsService.options.windowsMode?this._enableWindowsMode():(null===(t=this._windowsMode)||void 0===t||t.dispose(),this._windowsMode=void 0)}},t.prototype._enableWindowsMode=function(){var e=this;if(!this._windowsMode){var t=[];t.push(this.onLineFeed(g.updateWindowsModeWrappedState.bind(null,this._bufferService))),t.push(this.addCsiHandler({final:"H"},(function(){return g.updateWindowsModeWrappedState(e._bufferService),!1}))),this._windowsMode={dispose:function(){for(var e=0,r=t;e0?n[0].index:t.length;if(t.length!==u)throw new Error("[createInstance] First service dependency of "+e.name+" at position "+(u+1)+" conflicts with "+t.length+" static arguments");return new(e.bind.apply(e,i([void 0],i(t,s))))},e}();t.InstantiationService=a},function(e,t,r){"use strict";var i=this&&this.__decorate||function(e,t,r,i){var n,o=arguments.length,s=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,r):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,r,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(o<3?n(s):o>3?n(t,r,s):n(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},n=this&&this.__param||function(e,t){return function(r,i){t(r,i,e)}},o=this&&this.__spreadArrays||function(){for(var e=0,t=0,r=arguments.length;t=0;a--)(n=e[a])&&(s=(o<3?n(s):o>3?n(t,r,s):n(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},s=this&&this.__param||function(e,t){return function(r,i){t(r,i,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.BufferService=t.MINIMUM_ROWS=t.MINIMUM_COLS=void 0;var a=r(1),c=r(69),l=r(0),h=r(2);t.MINIMUM_COLS=2,t.MINIMUM_ROWS=1;var u=function(e){function r(r){var i=e.call(this)||this;return i._optionsService=r,i.isUserScrolling=!1,i._onResize=new l.EventEmitter,i.cols=Math.max(r.options.cols,t.MINIMUM_COLS),i.rows=Math.max(r.options.rows,t.MINIMUM_ROWS),i.buffers=new c.BufferSet(r,i),i}return n(r,e),Object.defineProperty(r.prototype,"onResize",{get:function(){return this._onResize.event},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"buffer",{get:function(){return this.buffers.active},enumerable:!1,configurable:!0}),r.prototype.dispose=function(){e.prototype.dispose.call(this),this.buffers.dispose()},r.prototype.resize=function(e,t){this.cols=e,this.rows=t,this.buffers.resize(e,t),this.buffers.setupTabStops(this.cols),this._onResize.fire({cols:e,rows:t})},r.prototype.reset=function(){this.buffers.dispose(),this.buffers=new c.BufferSet(this._optionsService,this),this.isUserScrolling=!1},r=o([s(0,a.IOptionsService)],r)}(h.Disposable);t.BufferService=u},function(e,t,r){"use strict";var i,n=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0}),t.BufferSet=void 0;var o=r(70),s=r(0),a=function(e){function t(t,r){var i=e.call(this)||this;return i._onBufferActivate=i.register(new s.EventEmitter),i._normal=new o.Buffer(!0,t,r),i._normal.fillViewportRows(),i._alt=new o.Buffer(!1,t,r),i._activeBuffer=i._normal,i.setupTabStops(),i}return n(t,e),Object.defineProperty(t.prototype,"onBufferActivate",{get:function(){return this._onBufferActivate.event},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"alt",{get:function(){return this._alt},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"active",{get:function(){return this._activeBuffer},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"normal",{get:function(){return this._normal},enumerable:!1,configurable:!0}),t.prototype.activateNormalBuffer=function(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))},t.prototype.activateAltBuffer=function(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}))},t.prototype.resize=function(e,t){this._normal.resize(e,t),this._alt.resize(e,t)},t.prototype.setupTabStops=function(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)},t}(r(2).Disposable);t.BufferSet=a},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BufferStringIterator=t.Buffer=t.MAX_BUFFER_SIZE=void 0;var i=r(71),n=r(16),o=r(4),s=r(3),a=r(72),c=r(73),l=r(20),h=r(6);t.MAX_BUFFER_SIZE=4294967295;var u=function(){function e(e,t,r){this._hasScrollback=e,this._optionsService=t,this._bufferService=r,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.savedY=0,this.savedX=0,this.savedCurAttrData=n.DEFAULT_ATTR_DATA.clone(),this.savedCharset=l.DEFAULT_CHARSET,this.markers=[],this._nullCell=o.CellData.fromCharData([0,s.NULL_CELL_CHAR,s.NULL_CELL_WIDTH,s.NULL_CELL_CODE]),this._whitespaceCell=o.CellData.fromCharData([0,s.WHITESPACE_CELL_CHAR,s.WHITESPACE_CELL_WIDTH,s.WHITESPACE_CELL_CODE]),this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new i.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}return e.prototype.getNullCell=function(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 h.ExtendedAttrs),this._nullCell},e.prototype.getWhitespaceCell=function(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 h.ExtendedAttrs),this._whitespaceCell},e.prototype.getBlankLine=function(e,t){return new n.BufferLine(this._bufferService.cols,this.getNullCell(e),t)},Object.defineProperty(e.prototype,"hasScrollback",{get:function(){return this._hasScrollback&&this.lines.maxLength>this._rows},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isCursorInViewport",{get:function(){var e=this.ybase+this.y-this.ydisp;return e>=0&&et.MAX_BUFFER_SIZE?t.MAX_BUFFER_SIZE:r},e.prototype.fillViewportRows=function(e){if(0===this.lines.length){void 0===e&&(e=n.DEFAULT_ATTR_DATA);for(var t=this._rows;t--;)this.lines.push(this.getBlankLine(e))}},e.prototype.clear=function(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new i.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()},e.prototype.resize=function(e,t){var r=this.getNullCell(n.DEFAULT_ATTR_DATA),i=this._getCorrectBufferLength(t);if(i>this.lines.maxLength&&(this.lines.maxLength=i),this.lines.length>0){if(this._cols0&&this.lines.length<=this.ybase+this.y+s+1?(this.ybase--,s++,this.ydisp>0&&this.ydisp--):this.lines.push(new n.BufferLine(e,r)));else for(a=this._rows;a>t;a--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(i0&&(this.lines.trimStart(c),this.ybase=Math.max(this.ybase-c,0),this.ydisp=Math.max(this.ydisp-c,0),this.savedY=Math.max(this.savedY-c,0)),this.lines.maxLength=i}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),s&&(this.y+=s),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(o=0;othis._cols?this._reflowLarger(e,t):this._reflowSmaller(e,t))},e.prototype._reflowLarger=function(e,t){var r=a.reflowLargerGetLinesToRemove(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(n.DEFAULT_ATTR_DATA));if(r.length>0){var i=a.reflowLargerCreateNewLayout(this.lines,r);a.reflowLargerApplyNewLayout(this.lines,i.layout),this._reflowLargerAdjustViewport(e,t,i.countRemoved)}},e.prototype._reflowLargerAdjustViewport=function(e,t,r){for(var i=this.getNullCell(n.DEFAULT_ATTR_DATA),o=r;o-- >0;)0===this.ybase?(this.y>0&&this.y--,this.lines.length=0;s--){var c=this.lines.get(s);if(!(!c||!c.isWrapped&&c.getTrimmedLength()<=e)){for(var l=[c];c.isWrapped&&s>0;)c=this.lines.get(--s),l.unshift(c);var h=this.ybase+this.y;if(!(h>=s&&h0&&(i.push({start:s+l.length+o,newLines:p}),o+=p.length),l.push.apply(l,p);var y=f.length-1,b=f[y];0===b&&(b=f[--y]);for(var S=l.length-_-1,m=u;S>=0;){var C=Math.min(m,b);if(l[y].copyCellsFrom(l[S],m-C,b-C,C,!0),0===(b-=C)&&(b=f[--y]),0===(m-=C)){S--;var w=Math.max(S,0);m=a.getWrappedLineTrimmedLength(l,w,this._cols)}}for(v=0;v0;)0===this.ybase?this.y0){var L=[],A=[];for(v=0;v=0;v--)if(D&&D.start>k+T){for(var O=D.newLines.length-1;O>=0;O--)this.lines.set(v--,D.newLines[O]);v++,L.push({index:k+1,amount:D.newLines.length}),T+=D.newLines.length,D=i[++x]}else this.lines.set(v,A[k--]);var M=0;for(v=L.length-1;v>=0;v--)L[v].index+=M,this.lines.onInsertEmitter.fire(L[v]),M+=L[v].amount;var P=Math.max(0,R+o-this.lines.maxLength);P>0&&this.lines.onTrimEmitter.fire(P)}},e.prototype.stringIndexToBufferIndex=function(e,t,r){for(void 0===r&&(r=!1);t;){var i=this.lines.get(e);if(!i)return[-1,-1];for(var n=r?i.getTrimmedLength():i.length,o=0;o0&&this.lines.get(t).isWrapped;)t--;for(;r+10;);return e>=this._cols?this._cols-1:e<0?0:e},e.prototype.nextStop=function(e){for(null==e&&(e=this.x);!this.tabs[++e]&&e=this._cols?this._cols-1:e<0?0:e},e.prototype.addMarker=function(e){var t=this,r=new c.Marker(e);return this.markers.push(r),r.register(this.lines.onTrim((function(e){r.line-=e,r.line<0&&r.dispose()}))),r.register(this.lines.onInsert((function(e){r.line>=e.index&&(r.line+=e.amount)}))),r.register(this.lines.onDelete((function(e){r.line>=e.index&&r.linee.index&&(r.line-=e.amount)}))),r.register(r.onDispose((function(){return t._removeMarker(r)}))),r},e.prototype._removeMarker=function(e){this.markers.splice(this.markers.indexOf(e),1)},e.prototype.iterator=function(e,t,r,i,n){return new f(this,e,t,r,i,n)},e}();t.Buffer=u;var f=function(){function e(e,t,r,i,n,o){void 0===r&&(r=0),void 0===i&&(i=e.lines.length),void 0===n&&(n=0),void 0===o&&(o=0),this._buffer=e,this._trimRight=t,this._startIndex=r,this._endIndex=i,this._startOverscan=n,this._endOverscan=o,this._startIndex<0&&(this._startIndex=0),this._endIndex>this._buffer.lines.length&&(this._endIndex=this._buffer.lines.length),this._current=this._startIndex}return e.prototype.hasNext=function(){return this._currentthis._endIndex+this._endOverscan&&(e.last=this._endIndex+this._endOverscan),e.first=Math.max(e.first,0),e.last=Math.min(e.last,this._buffer.lines.length);for(var t="",r=e.first;r<=e.last;++r)t+=this._buffer.translateBufferLineToString(r,this._trimRight);return this._current=e.last+1,{range:e,content:t}},e}();t.BufferStringIterator=f},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CircularList=void 0;var i=r(0),n=function(){function e(e){this._maxLength=e,this.onDeleteEmitter=new i.EventEmitter,this.onInsertEmitter=new i.EventEmitter,this.onTrimEmitter=new i.EventEmitter,this._array=new Array(this._maxLength),this._startIndex=0,this._length=0}return Object.defineProperty(e.prototype,"onDelete",{get:function(){return this.onDeleteEmitter.event},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onInsert",{get:function(){return this.onInsertEmitter.event},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onTrim",{get:function(){return this.onTrimEmitter.event},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"maxLength",{get:function(){return this._maxLength},set:function(e){if(this._maxLength!==e){for(var t=new Array(e),r=0;rthis._length)for(var t=this._length;t=e;n--)this._array[this._getCyclicIndex(n+r.length)]=this._array[this._getCyclicIndex(n)];for(n=0;nthis._maxLength){var o=this._length+r.length-this._maxLength;this._startIndex+=o,this._length=this._maxLength,this.onTrimEmitter.fire(o)}else this._length+=r.length},e.prototype.trimStart=function(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)},e.prototype.shiftElements=function(e,t,r){if(!(t<=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(var i=t-1;i>=0;i--)this.set(e+i+r,this.get(e+i));var n=e+t+r-this._length;if(n>0)for(this._length+=n;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(i=0;i=a&&n0&&(S>u||0===h[S].getTrimmedLength());S--)b++;b>0&&(s.push(a+h.length-b),s.push(b)),a+=h.length-1}}}return s},t.reflowLargerCreateNewLayout=function(e,t){for(var r=[],i=0,n=t[i],o=0,s=0;sl&&(s-=l,a++);var h=2===e[a].getWidth(s-1);h&&s--;var u=h?r-1:r;n.push(u),c+=u}return n},t.getWrappedLineTrimmedLength=i},function(e,t,r){"use strict";var i,n=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0}),t.Marker=void 0;var o=r(0),s=function(e){function t(r){var i=e.call(this)||this;return i.line=r,i._id=t._nextId++,i.isDisposed=!1,i._onDispose=new o.EventEmitter,i}return n(t,e),Object.defineProperty(t.prototype,"id",{get:function(){return this._id},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"onDispose",{get:function(){return this._onDispose.event},enumerable:!1,configurable:!0}),t.prototype.dispose=function(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire())},t._nextId=1,t}(r(2).Disposable);t.Marker=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionsService=t.DEFAULT_OPTIONS=t.DEFAULT_BELL_SOUND=void 0;var i=r(0),n=r(11),o=r(33);t.DEFAULT_BELL_SOUND="data:audio/mp3;base64,SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4LjMyLjEwNAAAAAAAAAAAAAAA//tQxAADB8AhSmxhIIEVCSiJrDCQBTcu3UrAIwUdkRgQbFAZC1CQEwTJ9mjRvBA4UOLD8nKVOWfh+UlK3z/177OXrfOdKl7pyn3Xf//WreyTRUoAWgBgkOAGbZHBgG1OF6zM82DWbZaUmMBptgQhGjsyYqc9ae9XFz280948NMBWInljyzsNRFLPWdnZGWrddDsjK1unuSrVN9jJsK8KuQtQCtMBjCEtImISdNKJOopIpBFpNSMbIHCSRpRR5iakjTiyzLhchUUBwCgyKiweBv/7UsQbg8isVNoMPMjAAAA0gAAABEVFGmgqK////9bP/6XCykxBTUUzLjEwMKqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq",t.DEFAULT_OPTIONS=Object.freeze({cols:80,rows:24,cursorBlink:!1,cursorStyle:"block",cursorWidth:1,bellSound:t.DEFAULT_BELL_SOUND,bellStyle:"none",drawBoldTextInBrightColors:!0,fastScrollModifier:"alt",fastScrollSensitivity:5,fontFamily:"courier-new, courier, monospace",fontSize:15,fontWeight:"normal",fontWeightBold:"bold",lineHeight:1,linkTooltipHoverDuration:500,letterSpacing:0,logLevel:"info",scrollback:1e3,scrollSensitivity:1,screenReaderMode:!1,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!0,allowTransparency:!1,tabStopWidth:8,theme:{},rightClickSelectsWord:n.isMac,rendererType:"canvas",windowOptions:{},windowsMode:!1,wordSeparator:" ()[]{}',\"`",convertEol:!1,termName:"xterm",cancelEvents:!1});var s=["cols","rows"],a=function(){function e(e){this._onOptionChange=new i.EventEmitter,this.options=o.clone(t.DEFAULT_OPTIONS);for(var r=0,n=Object.keys(e);r=0;a--)(n=e[a])&&(s=(o<3?n(s):o>3?n(t,r,s):n(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},s=this&&this.__param||function(e,t){return function(r,i){t(r,i,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.CoreService=void 0;var a=r(1),c=r(0),l=r(33),h=r(2),u=Object.freeze({insertMode:!1}),f=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,origin:!1,reverseWraparound:!1,sendFocus:!1,wraparound:!0}),_=function(e){function t(t,r,i,n){var o=e.call(this)||this;return o._bufferService=r,o._logService=i,o._optionsService=n,o.isCursorInitialized=!1,o.isCursorHidden=!1,o._onData=o.register(new c.EventEmitter),o._onUserInput=o.register(new c.EventEmitter),o._onBinary=o.register(new c.EventEmitter),o._scrollToBottom=t,o.register({dispose:function(){return o._scrollToBottom=void 0}}),o.modes=l.clone(u),o.decPrivateModes=l.clone(f),o}return n(t,e),Object.defineProperty(t.prototype,"onData",{get:function(){return this._onData.event},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"onUserInput",{get:function(){return this._onUserInput.event},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"onBinary",{get:function(){return this._onBinary.event},enumerable:!1,configurable:!0}),t.prototype.reset=function(){this.modes=l.clone(u),this.decPrivateModes=l.clone(f)},t.prototype.triggerDataEvent=function(e,t){if(void 0===t&&(t=!1),!this._optionsService.options.disableStdin){var r=this._bufferService.buffer;r.ybase!==r.ydisp&&this._scrollToBottom(),t&&this._onUserInput.fire(),this._logService.debug('sending data "'+e+'"',(function(){return e.split("").map((function(e){return e.charCodeAt(0)}))})),this._onData.fire(e)}},t.prototype.triggerBinaryEvent=function(e){this._optionsService.options.disableStdin||(this._logService.debug('sending binary "'+e+'"',(function(){return e.split("").map((function(e){return e.charCodeAt(0)}))})),this._onBinary.fire(e))},t=o([s(1,a.IBufferService),s(2,a.ILogService),s(3,a.IOptionsService)],t)}(h.Disposable);t.CoreService=_},function(e,t,r){"use strict";var i=this&&this.__decorate||function(e,t,r,i){var n,o=arguments.length,s=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,r):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,r,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(o<3?n(s):o>3?n(t,r,s):n(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},n=this&&this.__param||function(e,t){return function(r,i){t(r,i,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.CoreMouseService=void 0;var o=r(1),s=r(0),a={NONE:{events:0,restrict:function(){return!1}},X10:{events:1,restrict:function(e){return 4!==e.button&&1===e.action&&(e.ctrl=!1,e.alt=!1,e.shift=!1,!0)}},VT200:{events:19,restrict:function(e){return 32!==e.action}},DRAG:{events:23,restrict:function(e){return 32!==e.action||3!==e.button}},ANY:{events:31,restrict:function(e){return!0}}};function c(e,t){var r=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return 4===e.button?(r|=64,r|=e.action):(r|=3&e.button,4&e.button&&(r|=64),8&e.button&&(r|=128),32===e.action?r|=32:0!==e.action||t||(r|=3)),r}var l=String.fromCharCode,h={DEFAULT:function(e){var t=[c(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?"":"[M"+l(t[0])+l(t[1])+l(t[2])},SGR:function(e){var t=0===e.action&&4!==e.button?"m":"M";return"[<"+c(e,!0)+";"+e.col+";"+e.row+t}},u=function(){function e(e,t){this._bufferService=e,this._coreService=t,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._onProtocolChange=new s.EventEmitter,this._lastEvent=null;for(var r=0,i=Object.keys(a);r=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._compareEvents(this._lastEvent,e))return!1;if(!this._protocols[this._activeProtocol].restrict(e))return!1;var t=this._encodings[this._activeEncoding](e);return t&&("DEFAULT"===this._activeEncoding?this._coreService.triggerBinaryEvent(t):this._coreService.triggerDataEvent(t,!0)),this._lastEvent=e,!0},e.prototype.explainEvents=function(e){return{down:!!(1&e),up:!!(2&e),drag:!!(4&e),move:!!(8&e),wheel:!!(16&e)}},e.prototype._compareEvents=function(e,t){return e.col===t.col&&(e.row===t.row&&(e.button===t.button&&(e.action===t.action&&(e.ctrl===t.ctrl&&(e.alt===t.alt&&e.shift===t.shift)))))},e=i([n(0,o.IBufferService),n(1,o.ICoreService)],e)}();t.CoreMouseService=u},function(e,t,r){"use strict";var i=this&&this.__decorate||function(e,t,r,i){var n,o=arguments.length,s=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,r):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,r,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(o<3?n(s):o>3?n(t,r,s):n(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},n=this&&this.__param||function(e,t){return function(r,i){t(r,i,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.DirtyRowService=void 0;var o=r(1),s=function(){function e(e){this._bufferService=e,this.clearRange()}return Object.defineProperty(e.prototype,"start",{get:function(){return this._start},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"end",{get:function(){return this._end},enumerable:!1,configurable:!0}),e.prototype.clearRange=function(){this._start=this._bufferService.buffer.y,this._end=this._bufferService.buffer.y},e.prototype.markDirty=function(e){ethis._end&&(this._end=e)},e.prototype.markRangeDirty=function(e,t){if(e>t){var r=e;e=t,t=r}ethis._end&&(this._end=t)},e.prototype.markAllDirty=function(){this.markRangeDirty(0,this._bufferService.rows-1)},e=i([n(0,o.IBufferService)],e)}();t.DirtyRowService=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UnicodeService=void 0;var i=r(0),n=r(79),o=function(){function e(){this._providers=Object.create(null),this._active="",this._onChange=new i.EventEmitter;var e=new n.UnicodeV6;this.register(e),this._active=e.version,this._activeProvider=e}return Object.defineProperty(e.prototype,"onChange",{get:function(){return this._onChange.event},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"versions",{get:function(){return Object.keys(this._providers)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"activeVersion",{get:function(){return this._active},set:function(e){if(!this._providers[e])throw new Error('unknown Unicode version "'+e+'"');this._active=e,this._activeProvider=this._providers[e],this._onChange.fire(e)},enumerable:!1,configurable:!0}),e.prototype.register=function(e){this._providers[e.version]=e},e.prototype.wcwidth=function(e){return this._activeProvider.wcwidth(e)},e.prototype.getStringCellWidth=function(e){for(var t=0,r=e.length,i=0;i=r)return t+this.wcwidth(n);var o=e.charCodeAt(i);56320<=o&&o<=57343?n=1024*(n-55296)+o-56320+65536:t+=this.wcwidth(o)}t+=this.wcwidth(n)}return t},e}();t.UnicodeService=o},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UnicodeV6=void 0;var i,n=r(15),o=[[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]],s=[[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]];var a=function(){function e(){if(this.version="6",!i){i=new Uint8Array(65536),n.fill(i,1),i[0]=0,n.fill(i,0,1,32),n.fill(i,0,127,160),n.fill(i,2,4352,4448),i[9001]=2,i[9002]=2,n.fill(i,2,11904,42192),i[12351]=1,n.fill(i,2,44032,55204),n.fill(i,2,63744,64256),n.fill(i,2,65040,65050),n.fill(i,2,65072,65136),n.fill(i,2,65280,65377),n.fill(i,2,65504,65511);for(var e=0;et[n][1])return!1;for(;n>=i;)if(e>t[r=i+n>>1][1])i=r+1;else{if(!(e=131072&&e<=196605||e>=196608&&e<=262141?2:1},e}();t.UnicodeV6=a},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CharsetService=void 0;var i=function(){function e(){this.glevel=0,this._charsets=[]}return e.prototype.reset=function(){this.charset=void 0,this._charsets=[],this.glevel=0},e.prototype.setgLevel=function(e){this.glevel=e,this.charset=this._charsets[e]},e.prototype.setgCharset=function(e,t){this._charsets[e]=t,this.glevel===e&&(this.charset=t)},e}();t.CharsetService=i},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.updateWindowsModeWrappedState=void 0;var i=r(3);t.updateWindowsModeWrappedState=function(e){var t=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1),r=null==t?void 0:t.get(e.cols-1),n=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);n&&r&&(n.isWrapped=r[i.CHAR_DATA_CODE_INDEX]!==i.NULL_CELL_CODE&&r[i.CHAR_DATA_CODE_INDEX]!==i.WHITESPACE_CELL_CODE)}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WriteBuffer=void 0;var i=function(){function e(e){this._action=e,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0}return e.prototype.writeSync=function(e){if(this._writeBuffer.length){for(var t=this._bufferOffset;t5e7)throw new Error("write data discarded, use flow control to avoid losing data");this._writeBuffer.length||(this._bufferOffset=0,setTimeout((function(){return r._innerWrite()}))),this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t)},e.prototype._innerWrite=function(){for(var e=this,t=Date.now();this._writeBuffer.length>this._bufferOffset;){var r=this._writeBuffer[this._bufferOffset],i=this._callbacks[this._bufferOffset];if(this._bufferOffset++,this._action(r),this._pendingData-=r.length,i&&i(),Date.now()-t>=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((function(){return e._innerWrite()}),0)):(this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0)},e}();t.WriteBuffer=i},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AddonManager=void 0;var i=function(){function e(){this._addons=[]}return e.prototype.dispose=function(){for(var e=this._addons.length-1;e>=0;e--)this._addons[e].instance.dispose()},e.prototype.loadAddon=function(e,t){var r=this,i={instance:t,dispose:t.dispose,isDisposed:!1};this._addons.push(i),t.dispose=function(){return r._wrappedAddonDispose(i)},t.activate(e)},e.prototype._wrappedAddonDispose=function(e){if(!e.isDisposed){for(var t=-1,r=0;rr.cols;)p-=r.cols,h++;var v={start:{x:l+1,y:d+1},end:{x:p,y:h}};c.push({range:v,text:f,activate:i})}return c},e._translateBufferLineToStringWithWrap=function(e,t,n){var r,i,o="";do{if(!(s=n.buffer.active.getLine(e)))break;s.isWrapped&&e--,i=s.isWrapped}while(i);var a=e;do{var s,u=n.buffer.active.getLine(e+1);if(r=!!u&&u.isWrapped,!(s=n.buffer.active.getLine(e)))break;o+=s.translateToString(!r&&t).substring(0,n.cols),e++}while(r);return[o,a]},e}();t.LinkComputer=i}])}));
\ No newline at end of file
diff --git a/BTPanel/static/language/English/log.json b/BTPanel/static/language/English/log.json
index 64295eb2..bb65b1c6 100644
--- a/BTPanel/static/language/English/log.json
+++ b/BTPanel/static/language/English/log.json
@@ -146,6 +146,14 @@
"GET_INFO": "Get Info",
"NGINX_LOAD_ERR": "Nginx load status acquisition failed:{1}",
"GET_DATA_ERR": "Data acquisition failed!",
- "PHP_LOAD_ERR": "PHP load status acquisition failed: {1}"
-
+ "PHP_LOAD_ERR": "PHP load status acquisition failed: {1}",
+ "MODIFY_SSH_INFO": "Modify the SSH information of HOST: {1}",
+ "ADD_SSH_INFO": "Add the SSH information of HOST: {1}",
+ "DEL_SSH_INFO": "Delete the SSH information of HOST: {1}",
+ "TYPE_TERMINAL": "aaPanel terminal",
+ "ADD_COMMAND_COMMAND": "Add common commands [{1}]",
+ "EDIT_COMMAND_COMMAND": "Modify common commands [{1}]",
+ "DEL_COMMAND_COMMAND": "Delete common commands [{1}]",
+ "OPEN_FILE": "Open File",
+ "TASK_QUEUE": "Task queue"
}
diff --git a/BTPanel/static/language/English/public.json b/BTPanel/static/language/English/public.json
index 53e158bb..985034fc 100644
--- a/BTPanel/static/language/English/public.json
+++ b/BTPanel/static/language/English/public.json
@@ -187,7 +187,7 @@
"DATABASE_NAME_EXISTS":"Database exists!",
"DATABASE_NAME_LEN":"Database name cannot be more than 16 characters!",
"DATABASE_ERR_CONNECT":"ERROR to connect database, pls check database status!",
- "DATABASE_ERR_PASS":"Database password is incorrect!",
+ "DATABASE_ERR_PASS":"Mysql root or user password is incorrect, please try to reset!",
"DATABASE_ERR_NOT_EXISTS":"Database user does NOT exist!",
"DATABASE_USER_NAME_ERR": "Database username is illegal!",
"DATABASE_ERR_MYSQLDB":"MySQLdb component is missing! Please enter SSH and run the command: pip install mysql-python",
@@ -383,6 +383,7 @@
"CHANVE_FAIL": "Failed to change",
"DB_NOT_EXIST": "Database does NOT exist!",
"DOWNLOAD_FILE": "Download file",
+ "DOWNLOAD_FILE1": "Download file {1}",
"FILE_NAME_SPECIAL_CHARACTRES": "File names can NOT contain special characters!",
"DIR_NAME_SPECIAL_CHARACTRES": "Directory names cannot contain special characters!",
"RENAME_SUCCESS": "Successfully renamed!",
@@ -959,5 +960,29 @@
"PHPMYADMIN_SSL_ERR2": "Did not detect the port that nginx phpmyadmin listens, please confirm whether the file has been manually modified.",
"PHPMYADMIN_SSL_ERR3": "Did not detect the port that apache phpmyadmin listens, please confirm whether the file has been manually modified.",
"PHPMYADMIN_SSL_ERR4": "The panel certificate does not exist. Please apply for the panel certificate and try again.",
- "PHPMYADMIN_SSL_ERR5": "Open successfully, please manually release phpmyadmin ssl port"
+ "PHPMYADMIN_SSL_ERR5": "Open successfully, please manually release phpmyadmin ssl port",
+ "CONCTION_FAILURE": "Connection failure!",
+ "SSH_LOGIN_INFO_ERR": "Password or private key cannot both be empty: {1}:{2}",
+ "SSH_LOGIN_ERR": "Unable to complete the automatic authentication, please add 127.0.0.1 to the server list and set the authentication method to [password authentication]",
+ "SSH_LOGIN_ERR1": "Account or Password incorrect: {1}",
+ "SSH_LOGIN_ERR2": "Unsupported authentication type: {1}",
+ "SSH_LOGIN_ERR3": "The target server actively refused the connection",
+ "SSH_LOGIN_ERR4": "The protocol header response timed out, and the network quality with the target server was too bad: {1}",
+ "SSH_LOGIN_ERR5": "The SSH protocol handshake timed out, and the network quality with the target server is too bad",
+ "SSH_LOGIN_ERR6": "unknown error: {1}",
+ "SSH_LOGIN": "Successfully logged in to the SSH server [{1}:{2}]",
+ "LOGIN_SUCCESS2": "Login success\n",
+ "CONNECTION_SUCCEEDED": "connection succeeded",
+ "RECONNECT_SSH": "The connection is disconnected, press enter to try to reconnect!",
+ "SSH_LOGIN_ERR7": "The specified SSH information does not exist!",
+ "SSH_LOGIN_ERR8": "The specified host address has been added to other SSH information!",
+ "SSH_LOGIN_ERR9": "Please pass in the [sort_list] field",
+ "COMMAND_NAME_EXIST": "The specified command name already exists",
+ "COMMAND_NOTEXIST": "The specified command does not exist",
+ "AUTH_FAILED": "10 consecutive authentication failures are prohibited for 1 hour",
+ "AUTH_FAILED1": "20 consecutive verification failures, prohibited for 1 hour",
+ "UNBOUND_DEVICE": "Unbound device",
+ "KEY_ERR": "Key verification failed",
+ "FORM_DATA_ERR": "No form_data data found",
+ "WRONG_RESPONSE": "Wrong response: {1}"
}
diff --git a/BTPanel/static/language/English/template.json b/BTPanel/static/language/English/template.json
index 5c3a363d..877b49c0 100644
--- a/BTPanel/static/language/English/template.json
+++ b/BTPanel/static/language/English/template.json
@@ -52,10 +52,10 @@
"H1":"Dashboard",
"H2":"Site Manager",
"SEARCH":"Site search",
- "PS":"Permission will be allocated to www user when a site is created with aaPanel",
+ "PS":"After the website is created, the file owner will be set to [www], You can add your backup plan in ",
"BTN1":"Add site",
- "BTN2":"Set default page",
- "BTN3":"Default domain",
+ "BTN2":"Default page",
+ "BTN3":"Default WebSite",
"BTN4":"Delete",
"BTN5":"Category manager",
"TH1":"Domain",
@@ -142,9 +142,9 @@
"CT11":"Bind BT account",
"CT12":"Panel template",
"CY1":"Take alias for aaPanel",
- "CY2":"Suggested range of port: 8888 - 65535",
+ "CY2":"Suggested port: 8888-65535",
"CY3":"Binding a access domain to the Panel Warning:If a domain is bound to Panel, you'll have to access panel with Domain ONLY!",
- "CY4":"Set authorized access IP, split multiple IP with (,) Warning:If authorized IP is set, ONLY the PC with authorized IP can access the panel!",
+ "CY4":"Split multiple IP with (,) Warning:If authorized IP is set, ONLY the PC with authorized IP can access the panel!",
"CY5":"New created site will be saved to subdirectory by default!",
"CY6":"Directory of site and database backup!",
"CY7":"Defualt IP is Internet IP. If you need use local virtual machine to test, please input Intranet IP of virtual machine!",
diff --git a/BTPanel/templates/default/database.html b/BTPanel/templates/default/database.html
index 2754d742..a2b77497 100644
--- a/BTPanel/templates/default/database.html
+++ b/BTPanel/templates/default/database.html
@@ -22,7 +22,7 @@
{{data['lan']['BTN1']}}
{{data['lan']['BTN2']}}
{{data['lan']['BTN3']}}
- Adminer
+
{{data['lan']['BTN4']}}
{{data['lan']['RECYCLE_BIN']}}
diff --git a/BTPanel/templates/default/site.html b/BTPanel/templates/default/site.html
index 2100667b..3efe809a 100644
--- a/BTPanel/templates/default/site.html
+++ b/BTPanel/templates/default/site.html
@@ -17,7 +17,7 @@
-
{{data['lan']['PS']}}After the site is successfully established, please[Cron] Add scheduled backup tasks to the page!
+
{{data['lan']['PS']}}[Cron]
{{data['lan']['BTN1']}}
{{data['lan']['BTN2']}}
diff --git a/BTPanel/templates/default/xterm.html b/BTPanel/templates/default/xterm.html
new file mode 100644
index 00000000..4280ca1d
--- /dev/null
+++ b/BTPanel/templates/default/xterm.html
@@ -0,0 +1,108 @@
+{% extends "layout.html" %}
+
+{% block content %}
+
+
+
+{% endblock %}
+{% block scripts %}
+
+
+
+
+
+{% endblock %}
diff --git a/class/cachelib/__init__.py b/class/cachelib/__init__.py
new file mode 100644
index 00000000..cae7aae9
--- /dev/null
+++ b/class/cachelib/__init__.py
@@ -0,0 +1,21 @@
+# -*- coding: utf-8 -*-
+
+from cachelib.base import BaseCache, NullCache
+from cachelib.simple import SimpleCache
+from cachelib.file import FileSystemCache
+from cachelib.memcached import MemcachedCache
+from cachelib.redis import RedisCache
+from cachelib.uwsgi import UWSGICache
+
+__all__ = [
+ 'BaseCache',
+ 'NullCache',
+ 'SimpleCache',
+ 'FileSystemCache',
+ 'MemcachedCache',
+ 'RedisCache',
+ 'UWSGICache',
+]
+
+__version__ = '0.1'
+__author__ = 'Pallets Team'
diff --git a/class/cachelib/_compat.py b/class/cachelib/_compat.py
new file mode 100644
index 00000000..d52e65b5
--- /dev/null
+++ b/class/cachelib/_compat.py
@@ -0,0 +1,26 @@
+# flake8: noqa
+import sys
+
+PY2 = sys.version_info[0] == 2
+
+if PY2:
+ text_type = unicode
+ string_types = (str, unicode)
+ integer_types = (int, long)
+ iteritems = lambda d, *args, **kwargs: d.iteritems(*args, **kwargs)
+
+ def to_native(x, charset=sys.getdefaultencoding(), errors='strict'):
+ if x is None or isinstance(x, str):
+ return x
+ return x.encode(charset, errors)
+
+else:
+ text_type = str
+ string_types = (str, )
+ integer_types = (int, )
+ iteritems = lambda d, *args, **kwargs: iter(d.items(*args, **kwargs))
+
+ def to_native(x, charset=sys.getdefaultencoding(), errors='strict'):
+ if x is None or isinstance(x, str):
+ return x
+ return x.decode(charset, errors)
diff --git a/class/cachelib/base.py b/class/cachelib/base.py
new file mode 100644
index 00000000..bc5d346b
--- /dev/null
+++ b/class/cachelib/base.py
@@ -0,0 +1,198 @@
+# -*- coding: utf-8 -*-
+from cachelib._compat import iteritems
+
+
+def _items(mappingorseq):
+ """Wrapper for efficient iteration over mappings represented by dicts
+ or sequences::
+
+ >>> for k, v in _items((i, i*i) for i in xrange(5)):
+ ... assert k*k == v
+
+ >>> for k, v in _items(dict((i, i*i) for i in xrange(5))):
+ ... assert k*k == v
+
+ """
+ if hasattr(mappingorseq, 'items'):
+ return iteritems(mappingorseq)
+ return mappingorseq
+
+
+class BaseCache(object):
+
+ """Baseclass for the cache systems. All the cache systems implement this
+ API or a superset of it.
+
+ :param default_timeout: the default timeout (in seconds) that is used if
+ no timeout is specified on :meth:`set`. A timeout
+ of 0 indicates that the cache never expires.
+ """
+
+ def __init__(self, default_timeout=300):
+ self.default_timeout = default_timeout
+
+ def _normalize_timeout(self, timeout):
+ if timeout is None:
+ timeout = self.default_timeout
+ return timeout
+
+ def get(self, key):
+ """Look up key in the cache and return the value for it.
+
+ :param key: the key to be looked up.
+ :returns: The value if it exists and is readable, else ``None``.
+ """
+ return None
+
+ def delete(self, key):
+ """Delete `key` from the cache.
+
+ :param key: the key to delete.
+ :returns: Whether the key existed and has been deleted.
+ :rtype: boolean
+ """
+ return True
+
+ def get_many(self, *keys):
+ """Returns a list of values for the given keys.
+ For each key an item in the list is created::
+
+ foo, bar = cache.get_many("foo", "bar")
+
+ Has the same error handling as :meth:`get`.
+
+ :param keys: The function accepts multiple keys as positional
+ arguments.
+ """
+ return [self.get(k) for k in keys]
+
+ def get_dict(self, *keys):
+ """Like :meth:`get_many` but return a dict::
+
+ d = cache.get_dict("foo", "bar")
+ foo = d["foo"]
+ bar = d["bar"]
+
+ :param keys: The function accepts multiple keys as positional
+ arguments.
+ """
+ return dict(zip(keys, self.get_many(*keys)))
+
+ def set(self, key, value, timeout=None):
+ """Add a new key/value to the cache (overwrites value, if key already
+ exists in the cache).
+
+ :param key: the key to set
+ :param value: the value for the key
+ :param timeout: the cache timeout for the key in seconds (if not
+ specified, it uses the default timeout). A timeout of
+ 0 indicates that the cache never expires.
+ :returns: ``True`` if key has been updated, ``False`` for backend
+ errors. Pickling errors, however, will raise a subclass of
+ ``pickle.PickleError``.
+ :rtype: boolean
+ """
+ return True
+
+ def add(self, key, value, timeout=None):
+ """Works like :meth:`set` but does not overwrite the values of already
+ existing keys.
+
+ :param key: the key to set
+ :param value: the value for the key
+ :param timeout: the cache timeout for the key in seconds (if not
+ specified, it uses the default timeout). A timeout of
+ 0 indicates that the cache never expires.
+ :returns: Same as :meth:`set`, but also ``False`` for already
+ existing keys.
+ :rtype: boolean
+ """
+ return True
+
+ def set_many(self, mapping, timeout=None):
+ """Sets multiple keys and values from a mapping.
+
+ :param mapping: a mapping with the keys/values to set.
+ :param timeout: the cache timeout for the key in seconds (if not
+ specified, it uses the default timeout). A timeout of
+ 0 indicates that the cache never expires.
+ :returns: Whether all given keys have been set.
+ :rtype: boolean
+ """
+ rv = True
+ for key, value in _items(mapping):
+ if not self.set(key, value, timeout):
+ rv = False
+ return rv
+
+ def delete_many(self, *keys):
+ """Deletes multiple keys at once.
+
+ :param keys: The function accepts multiple keys as positional
+ arguments.
+ :returns: Whether all given keys have been deleted.
+ :rtype: boolean
+ """
+ return all(self.delete(key) for key in keys)
+
+ def has(self, key):
+ """Checks if a key exists in the cache without returning it. This is a
+ cheap operation that bypasses loading the actual data on the backend.
+
+ This method is optional and may not be implemented on all caches.
+
+ :param key: the key to check
+ """
+ raise NotImplementedError(
+ '%s doesn\'t have an efficient implementation of `has`. That '
+ 'means it is impossible to check whether a key exists without '
+ 'fully loading the key\'s data. Consider using `self.get` '
+ 'explicitly if you don\'t care about performance.'
+ )
+
+ def clear(self):
+ """Clears the cache. Keep in mind that not all caches support
+ completely clearing the cache.
+
+ :returns: Whether the cache has been cleared.
+ :rtype: boolean
+ """
+ return True
+
+ def inc(self, key, delta=1):
+ """Increments the value of a key by `delta`. If the key does
+ not yet exist it is initialized with `delta`.
+
+ For supporting caches this is an atomic operation.
+
+ :param key: the key to increment.
+ :param delta: the delta to add.
+ :returns: The new value or ``None`` for backend errors.
+ """
+ value = (self.get(key) or 0) + delta
+ return value if self.set(key, value) else None
+
+ def dec(self, key, delta=1):
+ """Decrements the value of a key by `delta`. If the key does
+ not yet exist it is initialized with `-delta`.
+
+ For supporting caches this is an atomic operation.
+
+ :param key: the key to increment.
+ :param delta: the delta to subtract.
+ :returns: The new value or `None` for backend errors.
+ """
+ value = (self.get(key) or 0) - delta
+ return value if self.set(key, value) else None
+
+
+class NullCache(BaseCache):
+
+ """A cache that doesn't cache. This can be useful for unit testing.
+
+ :param default_timeout: a dummy parameter that is ignored but exists
+ for API compatibility with other caches.
+ """
+
+ def has(self, key):
+ return False
diff --git a/class/cachelib/file.py b/class/cachelib/file.py
new file mode 100644
index 00000000..8c0ba052
--- /dev/null
+++ b/class/cachelib/file.py
@@ -0,0 +1,190 @@
+# -*- coding: utf-8 -*-
+import os
+import errno
+import tempfile
+from hashlib import md5
+from time import time
+try:
+ import cPickle as pickle
+except ImportError: # pragma: no cover
+ import pickle
+
+from cachelib.base import BaseCache
+from cachelib._compat import text_type
+
+
+class FileSystemCache(BaseCache):
+
+ """A cache that stores the items on the file system. This cache depends
+ on being the only user of the `cache_dir`. Make absolutely sure that
+ nobody but this cache stores files there or otherwise the cache will
+ randomly delete files therein.
+
+ :param cache_dir: the directory where cache files are stored.
+ :param threshold: the maximum number of items the cache stores before
+ it starts deleting some. A threshold value of 0
+ indicates no threshold.
+ :param default_timeout: the default timeout that is used if no timeout is
+ specified on :meth:`~BaseCache.set`. A timeout of
+ 0 indicates that the cache never expires.
+ :param mode: the file mode wanted for the cache files, default 0600
+ """
+
+ #: used for temporary files by the FileSystemCache
+ _fs_transaction_suffix = '.__wz_cache'
+ #: keep amount of files in a cache element
+ _fs_count_file = '__wz_cache_count'
+
+ def __init__(self, cache_dir, threshold=500, default_timeout=300,
+ mode=0o600):
+ BaseCache.__init__(self, default_timeout)
+ self._path = cache_dir
+ self._threshold = threshold
+ self._mode = mode
+
+ try:
+ os.makedirs(self._path)
+ except OSError as ex:
+ if ex.errno != errno.EEXIST:
+ raise
+
+ # If there are many files and a zero threshold,
+ # the list_dir can slow initialisation massively
+ if self._threshold != 0:
+ self._update_count(value=len(self._list_dir()))
+
+ @property
+ def _file_count(self):
+ return self.get(self._fs_count_file) or 0
+
+ def _update_count(self, delta=None, value=None):
+ # If we have no threshold, don't count files
+ if self._threshold == 0:
+ return
+
+ if delta:
+ new_count = self._file_count + delta
+ else:
+ new_count = value or 0
+ self.set(self._fs_count_file, new_count, mgmt_element=True)
+
+ def _normalize_timeout(self, timeout):
+ timeout = BaseCache._normalize_timeout(self, timeout)
+ if timeout != 0:
+ timeout = time() + timeout
+ return int(timeout)
+
+ def _list_dir(self):
+ """return a list of (fully qualified) cache filenames
+ """
+ mgmt_files = [self._get_filename(name).split('/')[-1]
+ for name in (self._fs_count_file,)]
+ return [os.path.join(self._path, fn) for fn in os.listdir(self._path)
+ if not fn.endswith(self._fs_transaction_suffix)
+ and fn not in mgmt_files]
+
+ def _prune(self):
+ if self._threshold == 0 or not self._file_count > self._threshold:
+ return
+
+ entries = self._list_dir()
+ now = time()
+ for idx, fname in enumerate(entries):
+ try:
+ remove = False
+ with open(fname, 'rb') as f:
+ expires = pickle.load(f)
+ remove = (expires != 0 and expires <= now) or idx % 3 == 0
+
+ if remove:
+ os.remove(fname)
+ except (IOError, OSError):
+ pass
+ self._update_count(value=len(self._list_dir()))
+
+ def clear(self):
+ for fname in self._list_dir():
+ try:
+ os.remove(fname)
+ except (IOError, OSError):
+ self._update_count(value=len(self._list_dir()))
+ return False
+ self._update_count(value=0)
+ return True
+
+ def _get_filename(self, key):
+ if isinstance(key, text_type):
+ key = key.encode('utf-8') # XXX unicode review
+ hash = md5(key).hexdigest()
+ return os.path.join(self._path, hash)
+
+ def get(self, key):
+ filename = self._get_filename(key)
+ try:
+ with open(filename, 'rb') as f:
+ pickle_time = pickle.load(f)
+ if pickle_time == 0 or pickle_time >= time():
+ return pickle.load(f)
+ else:
+ os.remove(filename)
+ return None
+ except (IOError, OSError, pickle.PickleError):
+ return None
+
+ def add(self, key, value, timeout=None):
+ filename = self._get_filename(key)
+ if not os.path.exists(filename):
+ return self.set(key, value, timeout)
+ return False
+
+ def set(self, key, value, timeout=None, mgmt_element=False):
+ # Management elements have no timeout
+ if mgmt_element:
+ timeout = 0
+
+ # Don't prune on management element update, to avoid loop
+ else:
+ self._prune()
+
+ timeout = self._normalize_timeout(timeout)
+ filename = self._get_filename(key)
+ try:
+ fd, tmp = tempfile.mkstemp(suffix=self._fs_transaction_suffix,
+ dir=self._path)
+ with os.fdopen(fd, 'wb') as f:
+ pickle.dump(timeout, f, 1)
+ pickle.dump(value, f, pickle.HIGHEST_PROTOCOL)
+
+ os.rename(tmp, filename)
+ os.chmod(filename, self._mode)
+ except (IOError, OSError):
+ return False
+ else:
+ # Management elements should not count towards threshold
+ if not mgmt_element:
+ self._update_count(delta=1)
+ return True
+
+ def delete(self, key, mgmt_element=False):
+ try:
+ os.remove(self._get_filename(key))
+ except (IOError, OSError):
+ return False
+ else:
+ # Management elements should not count towards threshold
+ if not mgmt_element:
+ self._update_count(delta=-1)
+ return True
+
+ def has(self, key):
+ filename = self._get_filename(key)
+ try:
+ with open(filename, 'rb') as f:
+ pickle_time = pickle.load(f)
+ if pickle_time == 0 or pickle_time >= time():
+ return True
+ else:
+ os.remove(filename)
+ return False
+ except (IOError, OSError, pickle.PickleError):
+ return False
diff --git a/class/cachelib/memcached.py b/class/cachelib/memcached.py
new file mode 100644
index 00000000..f76cf328
--- /dev/null
+++ b/class/cachelib/memcached.py
@@ -0,0 +1,186 @@
+# -*- coding: utf-8 -*-
+
+import re
+from time import time
+from cachelib._compat import iteritems, to_native
+from cachelib.base import BaseCache, _items
+
+
+_test_memcached_key = re.compile(r'[^\x00-\x21\xff]{1,250}$').match
+
+
+class MemcachedCache(BaseCache):
+
+ """A cache that uses memcached as backend.
+
+ The first argument can either be an object that resembles the API of a
+ :class:`memcache.Client` or a tuple/list of server addresses. In the
+ event that a tuple/list is passed, Werkzeug tries to import the best
+ available memcache library.
+
+ This cache looks into the following packages/modules to find bindings for
+ memcached:
+
+ - ``pylibmc``
+ - ``google.appengine.api.memcached``
+ - ``memcached``
+ - ``libmc``
+
+ Implementation notes: This cache backend works around some limitations in
+ memcached to simplify the interface. For example unicode keys are encoded
+ to utf-8 on the fly. Methods such as :meth:`~BaseCache.get_dict` return
+ the keys in the same format as passed. Furthermore all get methods
+ silently ignore key errors to not cause problems when untrusted user data
+ is passed to the get methods which is often the case in web applications.
+
+ :param servers: a list or tuple of server addresses or alternatively
+ a :class:`memcache.Client` or a compatible client.
+ :param default_timeout: the default timeout that is used if no timeout is
+ specified on :meth:`~BaseCache.set`. A timeout of
+ 0 indicates that the cache never expires.
+ :param key_prefix: a prefix that is added before all keys. This makes it
+ possible to use the same memcached server for different
+ applications. Keep in mind that
+ :meth:`~BaseCache.clear` will also clear keys with a
+ different prefix.
+ """
+
+ def __init__(self, servers=None, default_timeout=300, key_prefix=None):
+ BaseCache.__init__(self, default_timeout)
+ if servers is None or isinstance(servers, (list, tuple)):
+ if servers is None:
+ servers = ['127.0.0.1:11211']
+ self._client = self.import_preferred_memcache_lib(servers)
+ if self._client is None:
+ raise RuntimeError('no memcache module found')
+ else:
+ # NOTE: servers is actually an already initialized memcache
+ # client.
+ self._client = servers
+
+ self.key_prefix = to_native(key_prefix)
+
+ def _normalize_key(self, key):
+ key = to_native(key, 'utf-8')
+ if self.key_prefix:
+ key = self.key_prefix + key
+ return key
+
+ def _normalize_timeout(self, timeout):
+ timeout = BaseCache._normalize_timeout(self, timeout)
+ if timeout > 0:
+ timeout = int(time()) + timeout
+ return timeout
+
+ def get(self, key):
+ key = self._normalize_key(key)
+ # memcached doesn't support keys longer than that. Because often
+ # checks for so long keys can occur because it's tested from user
+ # submitted data etc we fail silently for getting.
+ if _test_memcached_key(key):
+ return self._client.get(key)
+
+ def get_dict(self, *keys):
+ key_mapping = {}
+ have_encoded_keys = False
+ for key in keys:
+ encoded_key = self._normalize_key(key)
+ if not isinstance(key, str):
+ have_encoded_keys = True
+ if _test_memcached_key(key):
+ key_mapping[encoded_key] = key
+ _keys = list(key_mapping)
+ d = rv = self._client.get_multi(_keys)
+ if have_encoded_keys or self.key_prefix:
+ rv = {}
+ for key, value in iteritems(d):
+ rv[key_mapping[key]] = value
+ if len(rv) < len(keys):
+ for key in keys:
+ if key not in rv:
+ rv[key] = None
+ return rv
+
+ def add(self, key, value, timeout=None):
+ key = self._normalize_key(key)
+ timeout = self._normalize_timeout(timeout)
+ return self._client.add(key, value, timeout)
+
+ def set(self, key, value, timeout=None):
+ key = self._normalize_key(key)
+ timeout = self._normalize_timeout(timeout)
+ return self._client.set(key, value, timeout)
+
+ def get_many(self, *keys):
+ d = self.get_dict(*keys)
+ return [d[key] for key in keys]
+
+ def set_many(self, mapping, timeout=None):
+ new_mapping = {}
+ for key, value in _items(mapping):
+ key = self._normalize_key(key)
+ new_mapping[key] = value
+
+ timeout = self._normalize_timeout(timeout)
+ failed_keys = self._client.set_multi(new_mapping, timeout)
+ return not failed_keys
+
+ def delete(self, key):
+ key = self._normalize_key(key)
+ if _test_memcached_key(key):
+ return self._client.delete(key)
+
+ def delete_many(self, *keys):
+ new_keys = []
+ for key in keys:
+ key = self._normalize_key(key)
+ if _test_memcached_key(key):
+ new_keys.append(key)
+ return self._client.delete_multi(new_keys)
+
+ def has(self, key):
+ key = self._normalize_key(key)
+ if _test_memcached_key(key):
+ return self._client.append(key, '')
+ return False
+
+ def clear(self):
+ return self._client.flush_all()
+
+ def inc(self, key, delta=1):
+ key = self._normalize_key(key)
+ return self._client.incr(key, delta)
+
+ def dec(self, key, delta=1):
+ key = self._normalize_key(key)
+ return self._client.decr(key, delta)
+
+ def import_preferred_memcache_lib(self, servers):
+ """Returns an initialized memcache client. Used by the constructor."""
+ try:
+ import pylibmc
+ except ImportError:
+ pass
+ else:
+ return pylibmc.Client(servers)
+
+ try:
+ from google.appengine.api import memcache
+ except ImportError:
+ pass
+ else:
+ return memcache.Client()
+
+ try:
+ import memcache
+ except ImportError:
+ pass
+ else:
+ return memcache.Client(servers)
+
+ try:
+ import libmc
+ except ImportError:
+ pass
+ else:
+ return libmc.Client(servers)
diff --git a/class/cachelib/redis.py b/class/cachelib/redis.py
new file mode 100644
index 00000000..6199a0d4
--- /dev/null
+++ b/class/cachelib/redis.py
@@ -0,0 +1,154 @@
+# -*- coding: utf-8 -*-
+from __future__ import absolute_import
+try:
+ import cPickle as pickle
+except ImportError: # pragma: no cover
+ import pickle
+
+from cachelib.base import BaseCache, _items
+from cachelib._compat import string_types, integer_types
+
+
+class RedisCache(BaseCache):
+ """Uses the Redis key-value store as a cache backend.
+
+ The first argument can be either a string denoting address of the Redis
+ server or an object resembling an instance of a redis.Redis class.
+
+ Note: Python Redis API already takes care of encoding unicode strings on
+ the fly.
+
+ :param host: address of the Redis server or an object which API is
+ compatible with the official Python Redis client (redis-py).
+ :param port: port number on which Redis server listens for connections.
+ :param password: password authentication for the Redis server.
+ :param db: db (zero-based numeric index) on Redis Server to connect.
+ :param default_timeout: the default timeout that is used if no timeout is
+ specified on :meth:`~BaseCache.set`. A timeout of
+ 0 indicates that the cache never expires.
+ :param key_prefix: A prefix that should be added to all keys.
+
+ Any additional keyword arguments will be passed to ``redis.Redis``.
+ """
+
+ def __init__(self, host='localhost', port=6379, password=None,
+ db=0, default_timeout=300, key_prefix=None, **kwargs):
+ BaseCache.__init__(self, default_timeout)
+ if host is None:
+ raise ValueError('RedisCache host parameter may not be None')
+ if isinstance(host, string_types):
+ try:
+ import redis
+ except ImportError:
+ raise RuntimeError('no redis module found')
+ if kwargs.get('decode_responses', None):
+ raise ValueError('decode_responses is not supported by '
+ 'RedisCache.')
+ self._client = redis.Redis(host=host, port=port, password=password,
+ db=db, **kwargs)
+ else:
+ self._client = host
+ self.key_prefix = key_prefix or ''
+
+ def _normalize_timeout(self, timeout):
+ timeout = BaseCache._normalize_timeout(self, timeout)
+ if timeout == 0:
+ timeout = -1
+ return timeout
+
+ def dump_object(self, value):
+ """Dumps an object into a string for redis. By default it serializes
+ integers as regular string and pickle dumps everything else.
+ """
+ t = type(value)
+ if t in integer_types:
+ return str(value).encode('ascii')
+ return b'!' + pickle.dumps(value)
+
+ def load_object(self, value):
+ """The reversal of :meth:`dump_object`. This might be called with
+ None.
+ """
+ if value is None:
+ return None
+ if value.startswith(b'!'):
+ try:
+ return pickle.loads(value[1:])
+ except pickle.PickleError:
+ return None
+ try:
+ return int(value)
+ except ValueError:
+ # before 0.8 we did not have serialization. Still support that.
+ return value
+
+ def get(self, key):
+ return self.load_object(self._client.get(self.key_prefix + key))
+
+ def get_many(self, *keys):
+ if self.key_prefix:
+ keys = [self.key_prefix + key for key in keys]
+ return [self.load_object(x) for x in self._client.mget(keys)]
+
+ def set(self, key, value, timeout=None):
+ timeout = self._normalize_timeout(timeout)
+ dump = self.dump_object(value)
+ if timeout == -1:
+ result = self._client.set(name=self.key_prefix + key,
+ value=dump)
+ else:
+ result = self._client.setex(name=self.key_prefix + key,
+ value=dump, time=timeout)
+ return result
+
+ def add(self, key, value, timeout=None):
+ timeout = self._normalize_timeout(timeout)
+ dump = self.dump_object(value)
+ return (
+ self._client.setnx(name=self.key_prefix + key, value=dump) and
+ self._client.expire(name=self.key_prefix + key, time=timeout)
+ )
+
+ def set_many(self, mapping, timeout=None):
+ timeout = self._normalize_timeout(timeout)
+ # Use transaction=False to batch without calling redis MULTI
+ # which is not supported by twemproxy
+ pipe = self._client.pipeline(transaction=False)
+
+ for key, value in _items(mapping):
+ dump = self.dump_object(value)
+ if timeout == -1:
+ pipe.set(name=self.key_prefix + key, value=dump)
+ else:
+ pipe.setex(name=self.key_prefix + key, value=dump,
+ time=timeout)
+ return pipe.execute()
+
+ def delete(self, key):
+ return self._client.delete(self.key_prefix + key)
+
+ def delete_many(self, *keys):
+ if not keys:
+ return
+ if self.key_prefix:
+ keys = [self.key_prefix + key for key in keys]
+ return self._client.delete(*keys)
+
+ def has(self, key):
+ return self._client.exists(self.key_prefix + key)
+
+ def clear(self):
+ status = False
+ if self.key_prefix:
+ keys = self._client.keys(self.key_prefix + '*')
+ if keys:
+ status = self._client.delete(*keys)
+ else:
+ status = self._client.flushdb()
+ return status
+
+ def inc(self, key, delta=1):
+ return self._client.incr(name=self.key_prefix + key, amount=delta)
+
+ def dec(self, key, delta=1):
+ return self._client.decr(name=self.key_prefix + key, amount=delta)
diff --git a/class/cachelib/simple.py b/class/cachelib/simple.py
new file mode 100644
index 00000000..a0723e9f
--- /dev/null
+++ b/class/cachelib/simple.py
@@ -0,0 +1,135 @@
+# -*- coding: utf-8 -*-
+from time import time
+import os,struct
+try:
+ import cPickle as pickle
+except ImportError: # pragma: no cover
+ import pickle
+
+from cachelib.base import BaseCache
+
+
+class SimpleCache(BaseCache):
+
+ """Simple memory cache for single process environments. This class exists
+ mainly for the development server and is not 100% thread safe. It tries
+ to use as many atomic operations as possible and no locks for simplicity
+ but it could happen under heavy load that keys are added multiple times.
+
+ :param threshold: the maximum number of items the cache stores before
+ it starts deleting some.
+ :param default_timeout: the default timeout that is used if no timeout is
+ specified on :meth:`~BaseCache.set`. A timeout of
+ 0 indicates that the cache never expires.
+ """
+ __session_key = 'BT_:'
+ __session_basedir = '/www/server/panel/data/session'
+
+ def __init__(self, threshold=500, default_timeout=300):
+ BaseCache.__init__(self, default_timeout)
+ self._cache = {}
+ self.clear = self._cache.clear
+ self._threshold = threshold
+
+ def _prune(self):
+ if len(self._cache) > self._threshold:
+ now = time()
+ toremove = []
+ for idx, (key, (expires, _)) in enumerate(self._cache.items()):
+ if (expires != 0 and expires <= now) or idx % 3 == 0:
+ toremove.append(key)
+ for key in toremove:
+ self._cache.pop(key, None)
+
+
+ def _normalize_timeout(self, timeout):
+ timeout = BaseCache._normalize_timeout(self, timeout)
+ if timeout > 0:
+ timeout = time() + timeout
+ return timeout
+
+ def get(self, key):
+ try:
+
+ expires, value = self._cache[key]
+ if expires == 0 or expires > time():
+ return pickle.loads(value)
+
+ except (KeyError, pickle.PickleError):
+ try:
+ if key[:4] == self.__session_key:
+ filename = '/'.join((self.__session_basedir,self.md5(key)))
+ if not os.path.exists(filename): return None
+
+ with open(filename, 'rb') as fp:
+ _val = fp.read()
+ fp.close()
+
+ expires = struct.unpack('f',_val[:4])[0]
+ if expires == 0 or expires > time():
+ value = _val[4:]
+
+ self._cache[key] = (expires,value)
+ return pickle.loads(value)
+ except :pass
+ return None
+
+ def set(self, key, value, timeout=None):
+
+ expires = self._normalize_timeout(timeout)
+ self._prune()
+
+ _val = pickle.dumps(value, pickle.HIGHEST_PROTOCOL)
+ self._cache[key] = (expires,_val)
+ try:
+ if key[:4] == self.__session_key:
+ if len(_val) < 256: return True
+ if not os.path.exists(self.__session_basedir): os.makedirs(self.__session_basedir,384)
+
+ expires = struct.pack('f',expires)
+ filename = '/'.join((self.__session_basedir,self.md5(key)))
+ fp = open(filename, 'wb+')
+ fp.write(expires + _val)
+ fp.close()
+ os.chmod(filename,384)
+ except :pass
+ return True
+
+ def add(self, key, value, timeout=None):
+ expires = self._normalize_timeout(timeout)
+ self._prune()
+ item = (expires, pickle.dumps(value,
+ pickle.HIGHEST_PROTOCOL))
+ if key in self._cache:
+ return False
+ self._cache.setdefault(key, item)
+ return True
+
+ def delete(self, key):
+ result = self._cache.pop(key, None) is not None
+ try:
+ if key[:4] == self.__session_key:
+ filename = '/'.join((self.__session_basedir,self.md5(key)))
+ if os.path.exists(filename): os.remove(filename)
+ except : pass
+ return result
+
+ def has(self, key):
+ try:
+ expires, value = self._cache[key]
+ return expires == 0 or expires > time()
+ except KeyError:
+ return False
+
+ def md5(self,strings):
+ """
+ 生成MD5
+ @strings 要被处理的字符串
+ return string(32)
+ """
+ import hashlib
+ m = hashlib.md5()
+
+ m.update(strings.encode('utf-8'))
+ return m.hexdigest()
+
diff --git a/class/cachelib/uwsgi.py b/class/cachelib/uwsgi.py
new file mode 100644
index 00000000..97546094
--- /dev/null
+++ b/class/cachelib/uwsgi.py
@@ -0,0 +1,64 @@
+# -*- coding: utf-8 -*-
+import platform
+try:
+ import cPickle as pickle
+except ImportError: # pragma: no cover
+ import pickle
+
+from cachelib.base import BaseCache
+
+
+class UWSGICache(BaseCache):
+ """ Implements the cache using uWSGI's caching framework.
+
+ .. note::
+ This class cannot be used when running under PyPy, because the uWSGI
+ API implementation for PyPy is lacking the needed functionality.
+
+ :param default_timeout: The default timeout in seconds.
+ :param cache: The name of the caching instance to connect to, for
+ example: mycache@localhost:3031, defaults to an empty string, which
+ means uWSGI will cache in the local instance. If the cache is in the
+ same instance as the werkzeug app, you only have to provide the name of
+ the cache.
+ """
+ def __init__(self, default_timeout=300, cache=''):
+ BaseCache.__init__(self, default_timeout)
+
+ if platform.python_implementation() == 'PyPy':
+ raise RuntimeError("uWSGI caching does not work under PyPy, see "
+ "the docs for more details.")
+
+ try:
+ import uwsgi
+ self._uwsgi = uwsgi
+ except ImportError:
+ raise RuntimeError("uWSGI could not be imported, are you "
+ "running under uWSGI?")
+
+ self.cache = cache
+
+ def get(self, key):
+ rv = self._uwsgi.cache_get(key, self.cache)
+ if rv is None:
+ return
+ return pickle.loads(rv)
+
+ def delete(self, key):
+ return self._uwsgi.cache_del(key, self.cache)
+
+ def set(self, key, value, timeout=None):
+ return self._uwsgi.cache_update(key, pickle.dumps(value),
+ self._normalize_timeout(timeout),
+ self.cache)
+
+ def add(self, key, value, timeout=None):
+ return self._uwsgi.cache_set(key, pickle.dumps(value),
+ self._normalize_timeout(timeout),
+ self.cache)
+
+ def clear(self):
+ return self._uwsgi.cache_clear(self.cache)
+
+ def has(self, key):
+ return self._uwsgi.cache_exists(key, self.cache) is not None
diff --git a/class/common.py b/class/common.py
index a2ebba85..392e7db5 100644
--- a/class/common.py
+++ b/class/common.py
@@ -6,8 +6,7 @@
# +-------------------------------------------------------------------
# | Author: hwliang
# +-------------------------------------------------------------------
-from flask import request, redirect, g
-from BTPanel import session, cache
+from BTPanel import session, cache , request, redirect, g
from datetime import datetime
import os
import public
@@ -34,10 +33,11 @@ class panelSetup:
ua = ua.lower()
if ua.find('spider') != -1 or ua.find('bot') != -1:
return redirect('https://www.google.com')
- g.version = '6.8.2'
+ g.version = '6.8.4'
g.title = public.GetConfigValue('title')
g.uri = request.path
g.debug = os.path.exists('data/debug.pl')
+ g.pyversion = sys.version_info[0]
if not g.debug:
g.cdn_url = public.get_cdn_url()
if not g.cdn_url:
@@ -50,6 +50,19 @@ class panelSetup:
session['version'] = g.version
session['title'] = g.title
g.is_aes = False
+
+ dirPath = '/www/server/phpmyadmin/pma'
+ if os.path.exists(dirPath):
+ public.ExecShell("rm -rf {}".format(dirPath))
+
+ dirPath = '/www/server/adminer'
+ if os.path.exists(dirPath):
+ public.ExecShell("rm -rf {}".format(dirPath))
+
+ dirPath = '/www/server/panel/adminer'
+ if os.path.exists(dirPath):
+ public.ExecShell("rm -rf {}".format(dirPath))
+
return None
@@ -59,6 +72,9 @@ class panelAdmin(panelSetup):
# 本地请求
def local(self):
result = panelSetup().init()
+ if result:
+ return result
+ result = self.check_login()
if result:
return result
result = self.setSession()
@@ -68,9 +84,6 @@ class panelAdmin(panelSetup):
if result:
return result
result = self.checkWebType()
- if result:
- return result
- result = self.check_login()
if result:
return result
result = self.checkConfig()
@@ -99,7 +112,7 @@ class panelAdmin(panelSetup):
if not 'lan' in session:
session['lan'] = public.GetLanguage()
if not 'home' in session:
- session['home'] = 'http://www.aapanel.com'
+ session['home'] = 'https://console.aapanel.com'
return None
# 检查Web服务器类型
@@ -185,26 +198,37 @@ class panelAdmin(panelSetup):
return redirect('/login')
from BTPanel import get_input
get = get_input()
-
-
+ client_ip = public.GetClientIp()
if not 'client_bind_token' in get:
if not 'request_token' in get or not 'request_time' in get:
return redirect('/login')
- client_ip = public.GetClientIp()
+
+ num_key = client_ip + '_api'
+ if not public.get_error_num(num_key,20):
+ return public.returnMsg(False,'AUTH_FAILED1')
+
+
if not client_ip in api_config['limit_addr']:
- return public.returnJson(False,'%s[' % public.GetMsg("CHECK_IP_FALSE")+client_ip+']')
+ public.set_error_num(num_key)
+ return public.returnJson(False,'%s[' % public.GetMsg("AUTH_FAILED1")+client_ip+']')
else:
+ num_key = client_ip + '_app'
+ if not public.get_error_num(num_key,20):
+ return public.returnMsg(False,'AUTH_FAILED1')
a_file = '/dev/shm/' + get.client_bind_token
if not os.path.exists(a_file):
import panelApi
if not panelApi.panelApi().get_app_find(get.client_bind_token):
- return public.returnMsg(False, 'Unbound device')
- public.writeFile(a_file, '')
+ public.set_error_num(num_key)
+ return public.returnMsg(False,'UNBOUND_DEVICE')
+ public.writeFile(a_file,'')
if not 'key' in api_config:
- return public.returnJson(False, 'Key verification failed')
+ public.set_error_num(num_key)
+ return public.returnJson(False, 'KEY_ERR')
if not 'form_data' in get:
- return public.returnJson(False, 'No form_data data found')
+ public.set_error_num(num_key)
+ return public.returnJson(False, 'FORM_DATA_ERR')
g.form_data = json.loads(public.aes_decrypt(get.form_data, api_config['key']))
@@ -215,7 +239,9 @@ class panelAdmin(panelSetup):
g.aes_key = api_config['key']
request_token = public.md5(get.request_time + api_config['token'])
if get.request_token == request_token:
+ public.set_error_num(num_key,True)
return False
+ public.set_error_num(num_key)
return public.returnJson(False,'SECRET_KEY_CHECK_FALSE')
# 检查系统配置
diff --git a/class/config.py b/class/config.py
index 3a35503c..dcb0d0b5 100644
--- a/class/config.py
+++ b/class/config.py
@@ -12,8 +12,7 @@ try:
except:
public.ExecShell("pip install pyotp &")
try:
- from BTPanel import session,admin_path_checks,g
- from flask import request
+ from BTPanel import session,admin_path_checks,g,request
import send_mail
except:pass
class config:
diff --git a/class/db.py b/class/db.py
index 1fc0cab9..61721ef9 100644
--- a/class/db.py
+++ b/class/db.py
@@ -10,7 +10,8 @@
import sqlite3
import os,time,sys
os.chdir('/www/server/panel')
-sys.path.insert(0,'class')
+if not 'class/' in sys.path:
+ sys.path.insert(0,'class/')
import public
class Sql():
@@ -29,7 +30,13 @@ class Sql():
def __init__(self):
self.__DB_FILE = 'data/default.db'
-
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self,exc_type,exc_value,exc_trackback):
+ self.close()
+
def __GetConn(self):
#取数据库对象
try:
@@ -306,7 +313,8 @@ class Sql():
#写锁
def write_lock(self):
self.is_lock()
- open(self.__LOCK,'wb+').close()
+ with open(self.__LOCK,'wb+') as f:
+ f.close()
#解锁
def rm_lock(self):
diff --git a/class/files.py b/class/files.py
index bc06f456..ca82f391 100644
--- a/class/files.py
+++ b/class/files.py
@@ -164,7 +164,7 @@ session.save_handler = files'''.format(path, sess_path, sess_path)
# 上传文件
def UploadFile(self, get):
from werkzeug.utils import secure_filename
- from flask import request
+ from BTPanel import request
if sys.version_info[0] == 2:
get.path = get.path.encode('utf-8')
if not os.path.exists(get.path):
diff --git a/class/jobs.py b/class/jobs.py
index 5679926a..b4acad42 100644
--- a/class/jobs.py
+++ b/class/jobs.py
@@ -10,7 +10,21 @@ import time,public,db,os,sys,json,re
os.chdir('/www/server/panel')
def control_init():
+ dirPath = '/www/server/phpmyadmin/pma'
+ if os.path.exists(dirPath):
+ public.ExecShell("rm -rf {}".format(dirPath))
+
+ dirPath = '/www/server/adminer'
+ if os.path.exists(dirPath):
+ public.ExecShell("rm -rf {}".format(dirPath))
+
+ dirPath = '/www/server/panel/adminer'
+ if os.path.exists(dirPath):
+ public.ExecShell("rm -rf {}".format(dirPath))
+
+
time.sleep(1)
+
sql = db.Sql().dbfile('system')
if not sql.table('sqlite_master').where('type=? AND name=?', ('table', 'load_average')).count():
csql = '''CREATE TABLE IF NOT EXISTS `load_average` (
@@ -105,7 +119,7 @@ def control_init():
public.ExecShell(c)
p_file = 'class/plugin2.so'
if os.path.exists(p_file): public.ExecShell("rm -f class/*.so")
- # public.ExecShell("chmod -R 600 /www/server/panel/data;chmod -R 600 /www/server/panel/config;chmod -R 700 /www/server/cron;chmod -R 600 /www/server/cron/*.log;chown -R root:root /www/server/panel/data;chown -R root:root /www/server/panel/config;chown -R www:www /www/server/phpmyadmin;chmod -R 700 /www/server/phpmyadmin")
+ public.ExecShell("chmod -R 600 /www/server/panel/data;chmod -R 600 /www/server/panel/config;chmod -R 700 /www/server/cron;chmod -R 600 /www/server/cron/*.log;chown -R root:root /www/server/panel/data;chown -R root:root /www/server/panel/config;chown -R root:root /www/server/phpmyadmin;chmod -R 755 /www/server/phpmyadmin")
if os.path.exists("/www/server/mysql"):
public.ExecShell("chown mysql:mysql /etc/my.cnf;chmod 600 /etc/my.cnf")
stop_path = '/www/server/stop'
@@ -113,6 +127,14 @@ def control_init():
os.makedirs(stop_path)
public.ExecShell("chown -R root:root {path};chmod -R 755 {path}".format(path=stop_path))
public.ExecShell('chmod 755 /www;chmod 755 /www/server')
+ if os.path.exists('/www/server/phpmyadmin/pma'):
+ public.ExecShell("rm -rf /www/server/phpmyadmin/pma")
+ if os.path.exists("/www/server/adminer"):
+ public.ExecShell("rm -rf /www/server/adminer")
+ if os.path.exists("/www/server/panel/adminer"):
+ public.ExecShell("rm -rf /www/server/panel/adminer")
+ if os.path.exists('/dev/shm/session.db'):
+ os.remove('/dev/shm/session.db')
#disable_putenv('putenv')
clean_session()
#set_crond()
@@ -141,7 +163,15 @@ def files_set_mode():
["/www/server/speed","/*.lua","root",755,False],
["/www/server/speed/total","","www",755,True],
["/www/server/btwaf","/*.lua","root",755,False],
-
+ ["/www/backup","","root",600,True],
+ ["/www/wwwlogs","","www",700,True],
+ ["/www/enterprise_backup","","root",600,True],
+ ["/www/server/cron","","root",700,True],
+ ["/www/server/cron","/*.log","root",600,True],
+ ["/www/server/stop","","root",755,True],
+ ["/www/server/redis","","redis",700,True],
+ ["/www/server/redis/redis.conf","","redis",600,False],
+ ["/www/Recycle_bin","","root",600,True],
["/www/server/panel/class","","root",600,True],
["/www/server/panel/data","","root",600,True],
["/www/server/panel/plugin","","root",600,False],
@@ -163,8 +193,8 @@ def files_set_mode():
["/dev/shm/session.db","","root",600,False],
["/dev/shm/session_py3","","root",600,True],
["/dev/shm/session_py2","","root",600,True],
-
- ["/www/server/adminer","","www",700,True]
+ ["/www/server/phpmyadmin","","root",755,True],
+ ["/www/server/coll","","root",700,True]
]
for m in m_paths:
diff --git a/class/panelPHP.py b/class/panelPHP.py
index 0dc828c2..dba051e8 100644
--- a/class/panelPHP.py
+++ b/class/panelPHP.py
@@ -12,8 +12,6 @@
# +-------------------------------------------------------------------
import json,os,public,time,re,sys
-if __name__ != "__main__":
- from BTPanel import request,abort,send_file,Resp,cache
import time
import fastcgiClient as fcgi_client
import struct
@@ -57,11 +55,21 @@ class panelPHP:
#将参数写到文件
def __write_args(self,args):
+ from BTPanel import request
if os.path.exists(self.__args_tmp): os.remove(self.__args_tmp)
self.__clean_args_file()
data = {}
data['GET'] = request.args.to_dict()
- data['POST'] = request.form.to_dict()
+ data['POST'] = {}
+ x_token = request.headers.get('x-http-token')
+ if x_token:
+ aes_pwd = x_token[:8] + x_token[40:48]
+ for key in request.form.keys():
+ data['POST'][key] = str(request.form.get(key,''))
+ if x_token:
+ if len(data['POST'][key]) > 5:
+ if data['POST'][key][:6] == 'BT-CRT':
+ data['POST'][key] = public.aes_decrypt(data['POST'][key][6:],aes_pwd)
data['POST']['client_ip'] = public.GetClientIp()
data = json.dumps(data)
public.writeFile(self.__args_tmp,data)
@@ -127,273 +135,275 @@ class panelPHP:
break
return php_v
- def get_phpmyadmin_phpversion(self):
- '''
- @name 获取当前phpmyadmin设置的PHP版本
- @author hwliang<2020-07-13>
- @return string
- '''
- ikey = 'pma_phpv'
- phpv = cache.get(ikey)
- if phpv: return phpv
- webserver = public.get_webserver()
- if webserver == 'nginx':
- filename = public.GetConfigValue('setup_path') + '/nginx/conf/enable-php.conf'
- conf = public.readFile(filename)
- if not conf: return None
- rep = r"php-cgi-(\d+)\.sock"
- phpv = re.findall(rep,conf)
- elif webserver == 'openlitespeed':
- filename = public.GetConfigValue('setup_path') + "/panel/vhost/openlitespeed/detail/phpmyadmin.conf"
- conf = public.readFile(filename)
- if not conf: return None
- rep = r"/usr/local/lsws/lsphp(\d+)/bin/lsphp"
- phpv = re.findall(rep,conf)
- else:
- filename = public.GetConfigValue('setup_path') + '/apache/conf/extra/httpd-vhosts.conf'
- conf = public.readFile(filename)
- if not conf: return None
- rep = r"php-cgi-(\d+)\.sock"
- phpv = re.findall(rep,conf)
+# def get_phpmyadmin_phpversion(self):
+# '''
+# @name 获取当前phpmyadmin设置的PHP版本
+# @author hwliang<2020-07-13>
+# @return string
+# '''
+# from BTPanel import cache
+# ikey = 'pma_phpv'
+# phpv = cache.get(ikey)
+# if phpv: return phpv
+# webserver = public.get_webserver()
+# if webserver == 'nginx':
+# filename = public.GetConfigValue('setup_path') + '/nginx/conf/enable-php.conf'
+# conf = public.readFile(filename)
+# if not conf: return None
+# rep = r"php-cgi-(\d+)\.sock"
+# phpv = re.findall(rep,conf)
+# elif webserver == 'openlitespeed':
+# filename = public.GetConfigValue('setup_path') + "/panel/vhost/openlitespeed/detail/phpmyadmin.conf"
+# conf = public.readFile(filename)
+# if not conf: return None
+# rep = r"/usr/local/lsws/lsphp(\d+)/bin/lsphp"
+# phpv = re.findall(rep,conf)
+# else:
+# filename = public.GetConfigValue('setup_path') + '/apache/conf/extra/httpd-vhosts.conf'
+# conf = public.readFile(filename)
+# if not conf: return None
+# rep = r"php-cgi-(\d+)\.sock"
+# phpv = re.findall(rep,conf)
- if not phpv: return None
- cache.set(ikey,phpv[0],3)
- return phpv[0]
-
- def get_pma_root(self):
- '''
- @name 获取phpmyadmin根目录
- @author hwliang<2020-07-13>
- @return string
- '''
- pma_path = '/www/server/phpmyadmin/'
- if not os.path.exists(pma_path):
- os.makedirs(pma_path)
- for dname in os.listdir(pma_path):
- if dname.find('phpmyadmin_') != -1:
- return os.path.join(pma_path,dname)
- return None
-
- def check_phpmyadmin_phpversion(self):
- '''
- @name 检查当前phpmyadmin版本可用的php版本列表
- @author hwliang<2020-07-13>
- @return list
- '''
- pma_path = '/www/server/phpmyadmin/'
- pma_version_f1 = os.path.join(pma_path,'version_check.pl')
- pma_root = os.path.join(pma_path,'pma')
- pma_version_f2 = os.path.join(pma_root,'version_check.pl')
- if not os.path.exists(pma_version_f1):
- src_vfile = os.path.join(pma_path,'version.pl')
- if os.path.exists(src_vfile):
- public.writeFile(pma_version_f1,public.readFile(src_vfile))
- v_sync = public.readFile(pma_version_f1) == public.readFile(pma_version_f2)
-
- if not os.path.exists(pma_root + '/index.php') or not v_sync:
- o_pma_root = self.get_pma_root()
-
- if o_pma_root:
- if not os.path.exists(pma_root):
- os.makedirs(pma_root)
- public.ExecShell("\cp -arf {}/* {}/".format(o_pma_root,pma_root))
- public.ExecShell("chown -R www:www {}".format(pma_root))
- public.ExecShell("chmod -R 700 {}".format(pma_root))
- public.ExecShell("\cp -arf {} {}".format(pma_version_f1,pma_version_f2))
- index = public.readFile(pma_root + '/index.php')
- if index:
- if index.find("use PhpMyAdmin\\Util") != -1:
- resp = "use PhpMyAdmin\\Util;\nif(function_exists('opcache_invalidate')) opcache_invalidate('/www/server/phpmyadmin/pma/config.inc.php');"
- index = index.replace("use PhpMyAdmin\\Util;",resp)
- elif index.find("use PMA\libraries\LanguageManager;") != -1:
- resp = "use PMA\libraries\LanguageManager;\nif(function_exists('opcache_invalidate')) opcache_invalidate('/www/server/phpmyadmin/pma/config.inc.php');"
- index = index.replace("use PMA\libraries\LanguageManager;",resp)
- elif index.find("require_once 'libraries/common.inc.php';") != -1:
- resp = "if(function_exists('opcache_invalidate')) opcache_invalidate('/www/server/phpmyadmin/pma/config.inc.php');\nrequire_once 'libraries/common.inc.php';"
- index = index.replace("require_once 'libraries/common.inc.php';",resp)
-
-
- public.writeFile(pma_root + '/index.php',index)
-
- if not os.path.exists(pma_version_f2):
- return False
-
- pma_version = public.readFile(pma_version_f2)
- self.pma_version = pma_version
- if pma_version:
- pma_version = pma_version[:3]
-
- if pma_version == '4.4':
- return ['53','54','55','56']
- elif pma_version == '4.0':
- return ['52','53']
- elif pma_version == '4.6':
- return None
- elif pma_version == '4.7':
- return ['55','56','70','71','72']
- elif pma_version in ['4.8','4.9','5.0']:
- return ['70','71','72','73','74']
- else:
- return ['55','56','70','71','72']
-
- def get_mysql_port(self):
- '''
- @name 获取mysql当前端口号
- @author hwliang<2020-07-13>
- @return int
- '''
- try:
- myconf = public.readFile('/etc/my.cnf')
- rep = r"port\s*=\s*([0-9]+)"
- port = int(re.search(rep,myconf).groups()[0])
- if not port: port = 3306
- return port
- except:
- return 3306
-
- def write_pma_passwd(self,username,password):
- '''
- @name 写入mysql帐号密码到配置文件
- @author hwliang<2020-07-13>
- @param username string(用户名)
- @param password string(密码)
- @return bool
- '''
-
- self.check_phpmyadmin_phpversion()
- pconfig = 'cookie'
- if username:
- pconfig = 'config'
- pma_path = '/www/server/phpmyadmin/'
- pma_config_file = os.path.join(pma_path,'pma/config.inc.php')
- conf = public.readFile(pma_config_file)
- if not conf: return False
- rep = r"/\* Authentication type \*/(.|\n)+/\* Server parameters \*/"
- rstr = '''/* Authentication type */
-$cfg['Servers'][$i]['auth_type'] = '{}';
-$cfg['Servers'][$i]['host'] = 'localhost';
-$cfg['Servers'][$i]['port'] = '{}';
-$cfg['Servers'][$i]['user'] = '{}';
-$cfg['Servers'][$i]['password'] = '{}';
-/* Server parameters */'''.format(pconfig,self.get_mysql_port(),username,password)
- conf = re.sub(rep,rstr,conf)
- public.writeFile(pma_config_file,conf)
- return True
-
- def request_php(self,uri):
- '''
- @name 发起fastcgi请求到PHP-FPM
- @author hwliang<2020-07-11>
- @param puri string(URI地址)
- @return socket
- '''
- php_unix_socket = '/tmp/php-cgi-{}.sock'.format(self.php_version)
- f = FPM(php_unix_socket,self.document_root,self.last_path)
-
- if request.full_path.find('?') != -1:
- uri = request.full_path[request.full_path.find(uri):]
- if self.re_io:
- sock = f.load_url(uri,content=self.re_io)
- else:
- sock = f.load_url(uri,content=request.stream)
- return sock
-
- def start(self,puri,document_root,last_path = ''):
- '''
- @name 开始处理PHP请求
- @author hwliang<2020-07-11>
- @param puri string(URI地址)
- @return socket or Response
- '''
- if puri in ['/','',None]: puri = 'index.php'
- if puri[0] == '/': puri = puri[1:]
- self.document_root = document_root
- self.last_path = last_path
- filename = document_root + puri
-
-
- #如果是PHP文件
- if puri[-4:] == '.php':
- if request.path.find('/phpmyadmin/') != -1:
- ikey = 'pma_php_version'
- self.php_version = cache.get(ikey)
- if not self.php_version:
- php_version = self.get_phpmyadmin_phpversion()
- php_versions = self.check_phpmyadmin_phpversion()
- if not php_versions:
- if php_versions == False:
- return Resp(
- 'Phpmyadmin is not installed, or support for phpMyAdmin4.6 has been discontinued due to security issues, uninstall and install other secure versions in the software store!')
- else:
- return Resp('phpmyadmin is not installed')
- if not php_version or not php_version in php_versions:
- php_version = php_versions
- self.php_version = self.get_php_version(php_version)
- if not self.php_version:
- php_version = self.check_phpmyadmin_phpversion()
- self.php_version = self.get_php_version(php_version)
- if not php_version:
- return Resp('No supported PHP version found: {}'.format(php_versions))
-
- if not self.php_version in php_versions:
- self.php_version = self.get_php_version(php_versions)
-
- if not self.php_version:
- return Resp('No supported PHP version found: {}'.format(php_versions))
- cache.set(ikey,self.php_version,1)
- if request.method == 'POST':
- #登录phpmyadmin
- if puri in ['index.php','/index.php']:
- content = public.url_encode(request.form.to_dict())
- if not isinstance(content,bytes):
- content = content.encode()
- self.re_io = StringIO(content)
- username = request.form.get('pma_username')
- if username:
- password = request.form.get('pma_password')
- if not self.write_pma_passwd(username,password):
- return Resp('Phpmyadmin is not installed')
-
- if puri in ['logout.php', '/logout.php']:
- self.write_pma_passwd(None, None)
- else:
- src_path = '/www/server/panel/adminer'
- dst_path = '/www/server/adminer'
- if os.path.exists(src_path):
- if not os.path.exists(dst_path): os.makedirs(dst_path)
- public.ExecShell("\cp -arf {}/* {}/".format(src_path, dst_path))
- public.ExecShell("chown -R www:www {}".format(dst_path))
- public.ExecShell("chmod -R 700 {}".format(dst_path))
- public.ExecShell("rm -rf {}".format(src_path))
-
- if not os.path.exists(dst_path + '/index.php'):
- return Resp("The AdMiner file is missing. Please try again after the [Fix] panel on the first page!")
-
- ikey = 'aer_php_version'
- self.php_version = cache.get(ikey)
- if not self.php_version:
- self.php_version = self.get_php_version(None)
- cache.set(ikey, self.php_version, 10)
- if not self.php_version:
- return Resp('没有找到可用的PHP版本')
-
- #文件是否存在?
- if not os.path.exists(filename):
- return abort(404)
-
- #发送到FPM
- try:
- return self.request_php(puri)
- except Exception as ex:
- if str(ex).find('No such file or directory') != -1:
- return Resp('Specify PHP version: {}, not started, or unable to connect!'.format(self.php_version))
- return Resp(str(ex))
-
- if not os.path.exists(filename):
- return abort(404)
-
- #如果是静态文件
- return send_file(filename)
+# if not phpv: return None
+# cache.set(ikey,phpv[0],3)
+# return phpv[0]
+#
+# def get_pma_root(self):
+# '''
+# @name 获取phpmyadmin根目录
+# @author hwliang<2020-07-13>
+# @return string
+# '''
+# pma_path = '/www/server/phpmyadmin/'
+# if not os.path.exists(pma_path):
+# os.makedirs(pma_path)
+# for dname in os.listdir(pma_path):
+# if dname.find('phpmyadmin_') != -1:
+# return os.path.join(pma_path,dname)
+# return None
+#
+# def check_phpmyadmin_phpversion(self):
+# '''
+# @name 检查当前phpmyadmin版本可用的php版本列表
+# @author hwliang<2020-07-13>
+# @return list
+# '''
+# return
+# pma_path = '/www/server/phpmyadmin/'
+# pma_version_f1 = os.path.join(pma_path,'version_check.pl')
+# pma_root = os.path.join(pma_path,'pma')
+# pma_version_f2 = os.path.join(pma_root,'version_check.pl')
+# if not os.path.exists(pma_version_f1):
+# src_vfile = os.path.join(pma_path,'version.pl')
+# if os.path.exists(src_vfile):
+# public.writeFile(pma_version_f1,public.readFile(src_vfile))
+# v_sync = public.readFile(pma_version_f1) == public.readFile(pma_version_f2)
+#
+# if not os.path.exists(pma_root + '/index.php') or not v_sync:
+# o_pma_root = self.get_pma_root()
+#
+# if o_pma_root:
+# if not os.path.exists(pma_root):
+# os.makedirs(pma_root)
+# public.ExecShell("\cp -arf {}/* {}/".format(o_pma_root,pma_root))
+# public.ExecShell("chown -R www:www {}".format(pma_root))
+# public.ExecShell("chmod -R 700 {}".format(pma_root))
+# public.ExecShell("\cp -arf {} {}".format(pma_version_f1,pma_version_f2))
+# index = public.readFile(pma_root + '/index.php')
+# if index:
+# if index.find("use PhpMyAdmin\\Util") != -1:
+# resp = "use PhpMyAdmin\\Util;\nif(function_exists('opcache_invalidate')) opcache_invalidate('/www/server/phpmyadmin/pma/config.inc.php');"
+# index = index.replace("use PhpMyAdmin\\Util;",resp)
+# elif index.find("use PMA\libraries\LanguageManager;") != -1:
+# resp = "use PMA\libraries\LanguageManager;\nif(function_exists('opcache_invalidate')) opcache_invalidate('/www/server/phpmyadmin/pma/config.inc.php');"
+# index = index.replace("use PMA\libraries\LanguageManager;",resp)
+# elif index.find("require_once 'libraries/common.inc.php';") != -1:
+# resp = "if(function_exists('opcache_invalidate')) opcache_invalidate('/www/server/phpmyadmin/pma/config.inc.php');\nrequire_once 'libraries/common.inc.php';"
+# index = index.replace("require_once 'libraries/common.inc.php';",resp)
+#
+#
+# public.writeFile(pma_root + '/index.php',index)
+#
+# if not os.path.exists(pma_version_f2):
+# return False
+#
+# pma_version = public.readFile(pma_version_f2)
+# self.pma_version = pma_version
+# if pma_version:
+# pma_version = pma_version[:3]
+#
+# if pma_version == '4.4':
+# return ['53','54','55','56']
+# elif pma_version == '4.0':
+# return ['52','53']
+# elif pma_version == '4.6':
+# return None
+# elif pma_version == '4.7':
+# return ['55','56','70','71','72']
+# elif pma_version in ['4.8','4.9','5.0']:
+# return ['70','71','72','73','74']
+# else:
+# return ['55','56','70','71','72']
+#
+# def get_mysql_port(self):
+# '''
+# @name 获取mysql当前端口号
+# @author hwliang<2020-07-13>
+# @return int
+# '''
+# try:
+# myconf = public.readFile('/etc/my.cnf')
+# rep = r"port\s*=\s*([0-9]+)"
+# port = int(re.search(rep,myconf).groups()[0])
+# if not port: port = 3306
+# return port
+# except:
+# return 3306
+#
+# def write_pma_passwd(self,username,password):
+# '''
+# @name 写入mysql帐号密码到配置文件
+# @author hwliang<2020-07-13>
+# @param username string(用户名)
+# @param password string(密码)
+# @return bool
+# '''
+#
+# self.check_phpmyadmin_phpversion()
+# pconfig = 'cookie'
+# if username:
+# pconfig = 'config'
+# pma_path = '/www/server/phpmyadmin/'
+# pma_config_file = os.path.join(pma_path,'pma/config.inc.php')
+# conf = public.readFile(pma_config_file)
+# if not conf: return False
+# rep = r"/\* Authentication type \*/(.|\n)+/\* Server parameters \*/"
+# rstr = '''/* Authentication type */
+# $cfg['Servers'][$i]['auth_type'] = '{}';
+# $cfg['Servers'][$i]['host'] = 'localhost';
+# $cfg['Servers'][$i]['port'] = '{}';
+# $cfg['Servers'][$i]['user'] = '{}';
+# $cfg['Servers'][$i]['password'] = '{}';
+# /* Server parameters */'''.format(pconfig,self.get_mysql_port(),username,password)
+# conf = re.sub(rep,rstr,conf)
+# public.writeFile(pma_config_file,conf)
+# return True
+#
+# def request_php(self,uri):
+# '''
+# @name 发起fastcgi请求到PHP-FPM
+# @author hwliang<2020-07-11>
+# @param puri string(URI地址)
+# @return socket
+# '''
+# php_unix_socket = '/tmp/php-cgi-{}.sock'.format(self.php_version)
+# f = FPM(php_unix_socket,self.document_root,self.last_path)
+#
+# if request.full_path.find('?') != -1:
+# uri = request.full_path[request.full_path.find(uri):]
+# if self.re_io:
+# sock = f.load_url(uri,content=self.re_io)
+# else:
+# sock = f.load_url(uri,content=request.stream)
+# return sock
+#
+# def start(self,puri,document_root,last_path = ''):
+# '''
+# @name 开始处理PHP请求
+# @author hwliang<2020-07-11>
+# @param puri string(URI地址)
+# @return socket or Response
+# '''
+# if puri in ['/','',None]: puri = 'index.php'
+# if puri[0] == '/': puri = puri[1:]
+# self.document_root = document_root
+# self.last_path = last_path
+# filename = document_root + puri
+#
+#
+# #如果是PHP文件
+# if puri[-4:] == '.php':
+# if request.path.find('/phpmyadmin/') != -1:
+# ikey = 'pma_php_version'
+# self.php_version = cache.get(ikey)
+# if not self.php_version:
+# php_version = self.get_phpmyadmin_phpversion()
+# php_versions = self.check_phpmyadmin_phpversion()
+# if not php_versions:
+# if php_versions == False:
+# return Resp(
+# 'Phpmyadmin is not installed, or support for phpMyAdmin4.6 has been discontinued due to security issues, uninstall and install other secure versions in the software store!')
+# else:
+# return Resp('phpmyadmin is not installed')
+# if not php_version or not php_version in php_versions:
+# php_version = php_versions
+# self.php_version = self.get_php_version(php_version)
+# if not self.php_version:
+# php_version = self.check_phpmyadmin_phpversion()
+# self.php_version = self.get_php_version(php_version)
+# if not php_version:
+# return Resp('No supported PHP version found: {}'.format(php_versions))
+#
+# if not self.php_version in php_versions:
+# self.php_version = self.get_php_version(php_versions)
+#
+# if not self.php_version:
+# return Resp('No supported PHP version found: {}'.format(php_versions))
+# cache.set(ikey,self.php_version,1)
+# if request.method == 'POST':
+# #登录phpmyadmin
+# if puri in ['index.php','/index.php']:
+# content = public.url_encode(request.form.to_dict())
+# if not isinstance(content,bytes):
+# content = content.encode()
+# self.re_io = StringIO(content)
+# username = request.form.get('pma_username')
+# if username:
+# password = request.form.get('pma_password')
+# if not self.write_pma_passwd(username,password):
+# return Resp('Phpmyadmin is not installed')
+#
+# if puri in ['logout.php', '/logout.php']:
+# self.write_pma_passwd(None, None)
+# else:
+# src_path = '/www/server/panel/adminer'
+# dst_path = '/www/server/adminer'
+# if os.path.exists(src_path):
+# if not os.path.exists(dst_path): os.makedirs(dst_path)
+# public.ExecShell("\cp -arf {}/* {}/".format(src_path, dst_path))
+# public.ExecShell("chown -R www:www {}".format(dst_path))
+# public.ExecShell("chmod -R 700 {}".format(dst_path))
+# public.ExecShell("rm -rf {}".format(src_path))
+#
+# if not os.path.exists(dst_path + '/index.php'):
+# return Resp("The AdMiner file is missing. Please try again after the [Fix] panel on the first page!")
+#
+# ikey = 'aer_php_version'
+# self.php_version = cache.get(ikey)
+# if not self.php_version:
+# self.php_version = self.get_php_version(None)
+# cache.set(ikey, self.php_version, 10)
+# if not self.php_version:
+# return Resp('没有找到可用的PHP版本')
+#
+# #文件是否存在?
+# if not os.path.exists(filename):
+# return abort(404)
+#
+# #发送到FPM
+# try:
+# return self.request_php(puri)
+# except Exception as ex:
+# if str(ex).find('No such file or directory') != -1:
+# return Resp('Specify PHP version: {}, not started, or unable to connect!'.format(self.php_version))
+# return Resp(str(ex))
+#
+# if not os.path.exists(filename):
+# return abort(404)
+#
+# #如果是静态文件
+# return send_file(filename)
@@ -529,7 +539,7 @@ class FPM(object):
except ValueError:
script_name = url
query_string = ''
-
+ from BTPanel import request
env = {
'SCRIPT_FILENAME': '%s%s' % (self.document_root, script_name),
'QUERY_STRING': query_string,
diff --git a/class/panelPlugin.py b/class/panelPlugin.py
index 232f4fa1..13e1ce96 100644
--- a/class/panelPlugin.py
+++ b/class/panelPlugin.py
@@ -171,6 +171,8 @@ class panelPlugin:
if 'status' in result:
if result['status']:
public.httpPost(public.GetConfigValue('home') + '/api/panel/plugin_total',{"pid":pluginInfo['id'],'p_name':pluginInfo['name']},3)
+ get.force = 1
+ self.get_cloud_list(get)
except:pass
return result
@@ -1891,8 +1893,7 @@ class panelPlugin:
return panelPHP.panelPHP(get.name).exec_php_script(get)
return public.returnMsg(False,'PLUGIN_INPUT_B')
if not self.check_accept(get):return public.returnMsg(False,public.to_string([24744, 26410, 36141, 20080, 91, 37, 115, 93, 25110, 25480, 26435, 24050, 21040, 26399, 33]) % (self.get_title_byname(get),))
- if not path in sys.path:
- sys.path.insert(0,path)
+ public.package_path_append(path)
plugin_main = __import__(get.name+'_main')
try:
reload(plugin_main)
diff --git a/class/panelSite.py b/class/panelSite.py
index 4dd3d7f3..1e35bc68 100644
--- a/class/panelSite.py
+++ b/class/panelSite.py
@@ -11,7 +11,10 @@
# 网站管理类
#------------------------------
import io,re,public,os,sys,shutil,json,hashlib,socket,time
-from BTPanel import session
+try:
+ from BTPanel import session
+except:
+ pass
from panelRedirect import panelRedirect
import site_dir_auth
class panelSite(panelRedirect):
@@ -93,10 +96,10 @@ class panelSite(panelRedirect):
for key in tmp:
if key == port: return False
- listen = "\nListen "+tmp[0]
+ listen = "\nListen "+ tmp[0] + "\n"
listen_ipv6 = ''
#if self.is_ipv6: listen_ipv6 = "\nListen [::]:" + port
- allConf = allConf.replace(listen,listen + "\nListen " + port + listen_ipv6)
+ allConf = allConf.replace(listen,listen + "Listen " + port + listen_ipv6 + "\n")
public.writeFile(filename, allConf)
return True
@@ -633,7 +636,7 @@ include /www/server/panel/vhost/openlitespeed/proxy/BTSITENAME/*.conf
public.ExecShell("rm -f " + public.GetConfigValue('logs_path') + '/' + siteName + "-*")
#删除备份
- public.ExecShell("rm -f "+session['config']['backup_path']+'/site/'+siteName+'_*')
+ #public.ExecShell("rm -f "+session['config']['backup_path']+'/site/'+siteName+'_*')
#删除根目录
if 'path' in get:
@@ -1423,10 +1426,11 @@ listener SSL443 {
ssl_certificate /www/server/panel/vhost/cert/%s/fullchain.pem;
ssl_certificate_key /www/server/panel/vhost/cert/%s/privkey.pem;
ssl_protocols TLSv1.1 TLSv1.2%s;
- ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;
+ ssl_ciphers EECDH+CHACHA20:EECDH+CHACHA20-draft:EECDH+AES128:RSA+AES128:EECDH+AES256:RSA+AES256:EECDH+3DES:RSA+3DES:!MD5;
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
+ add_header Strict-Transport-Security "max-age=31536000";
error_page 497 https://$host$request_uri;
""" % (get.first_domain, get.first_domain,self.get_tls13())
if (conf.find('ssl_certificate') != -1):
@@ -1500,7 +1504,7 @@ listener SSL443 {
SSLEngine On
SSLCertificateFile /www/server/panel/vhost/cert/%s/fullchain.pem
SSLCertificateKeyFile /www/server/panel/vhost/cert/%s/privkey.pem
- SSLCipherSuite EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH
+ SSLCipherSuite EECDH+CHACHA20:EECDH+CHACHA20-draft:EECDH+AES128:RSA+AES128:EECDH+AES256:RSA+AES256:EECDH+3DES:RSA+3DES:!MD5
SSLProtocol All -SSLv2 -SSLv3 -TLSv1
SSLHonorCipherOrder On
%s
@@ -1701,7 +1705,6 @@ listener SSL443 {
detail_file = self.setupPath + '/panel/vhost/openlitespeed/detail/' + siteName + '.conf'
force_https = self.setupPath + '/panel/vhost/openlitespeed/redirect/' + siteName
string = 'rm -f {}/force_https.conf*'.format(force_https)
- public.writeFile("/tmp/2",string)
public.ExecShell(string)
detail_conf = public.readFile(detail_file)
if detail_conf:
@@ -1739,6 +1742,7 @@ listener SSL443 {
type = 0
if os.path.exists(path + '/README'): type = 1
if os.path.exists(path + '/partnerOrderId'): type = 2
+ if os.path.exists(path + '/certOrderId'): type = 3
csrpath = path + "/fullchain.pem" # 生成证书路径
keypath = path + "/privkey.pem" # 密钥文件路径
key = public.readFile(keypath)
@@ -1792,8 +1796,11 @@ listener SSL443 {
if 'dnsapi' in crontab_config[siteName]:
auth_type = 'dns'
-
- return {'status': status, 'domain': domains, 'key': key, 'csr': csr, 'type': type, 'httpTohttps': toHttps,'cert_data':cert_data,'email':email,"index":index,'auth_type':auth_type}
+ if os.path.exists(path + '/certOrderId'): type = 3
+ oid = -1
+ if type == 3:
+ oid = int(public.readFile(path + '/certOrderId'))
+ return {'status': status,'oid':oid, 'domain': domains, 'key': key, 'csr': csr, 'type': type, 'httpTohttps': toHttps,'cert_data':cert_data,'email':email,"index":index,'auth_type':auth_type}
#启动站点
@@ -2887,7 +2894,7 @@ server
if get.todomain:
if not re.search(tod,get.todomain):
return public.returnMsg(False, 'SENT_DOMAIN_FORMAT', (get.todomain,))
- else:
+ if public.get_webserver() != 'openlitespeed':
get.todomain = "$host"
# 检测目标URL格式
@@ -3085,9 +3092,10 @@ RewriteRule ^%s(.*)$ http://%s/$1 [P,E=Proxy-Host:%s]
status = self.SetProxy(get)
if not status["status"]:
return status
- get.version = '00'
- get.siteName = get.sitename
- self.SetPHPVersion(get)
+ if get.proxydir == '/':
+ get.version = '00'
+ get.siteName = get.sitename
+ self.SetPHPVersion(get)
public.serviceReload()
return public.returnMsg(True, 'ADD_SUCCESS')
diff --git a/class/panelTask.py b/class/panelTask.py
index 41edeeeb..113281d6 100644
--- a/class/panelTask.py
+++ b/class/panelTask.py
@@ -17,15 +17,16 @@ import public
import sys
import os
import re
-sys.path.insert(0, '/www/server/panel/class')
os.chdir('/www/server/panel')
-
+if not 'class/' in sys.path:
+ sys.path.insert(0,'class/')
class bt_task:
__table = 'task_list'
__task_tips = '/dev/shm/bt_task_now.pl'
__task_path = '/www/server/panel/tmp/'
down_log_total_file = '/tmp/download_total.pl'
+ not_web = False
def __init__(self):
# 创建数据表
@@ -66,7 +67,7 @@ class bt_task:
data = sql.field('id,name,type,shell,other,status,exectime,endtime,addtime').order(
'id asc').limit('10').select()
if type(data) == str:
- public.WriteLog('Task queue',data)
+ public.WriteLog('TASK_QUEUE',data)
return []
if not 'num' in get:
get.num = 15
@@ -139,7 +140,7 @@ class bt_task:
"kill -9 $(ps aux|grep '"+task_info['shell']+"'|grep -v grep|awk '{print $2}')")
public.ExecShell("/etc/init.d/bt start")
- return public.returnMsg(True, '任务已取消!')
+ return public.returnMsg(True, 'TASK_CANCEL')
# 取一条任务
def get_task_find(self, id):
@@ -219,7 +220,9 @@ class bt_task:
log_file = self.__task_path + str(id) + '.log'
if not os.path.exists(log_file):
data = ''
- if(task_type == '1'): data = {'name':public.GetMsg("DOWNLOAD_FILE"),'total':0,'used':0,'pre':0,'speed':0}
+ if(task_type == '1'):
+ data = {'name': public.GetMsg("DOWNLOAD_FILE"), 'total': 0, 'used': 0,
+ 'pre': 0, 'speed': 0, 'time': 0}
return data
if(task_type == '1'):
@@ -245,7 +248,7 @@ class bt_task:
speed_total = re.findall(
r"([\d\.]+[BbKkMmGg]).+\s+(\d+)%\s+([\d\.]+[KMBGkmbg])\s+(\w+[sS])", speed_tmp)
if not speed_total:
- data = {'name':'download file {}'.format(filename),'total':0,'used':0,'pre':0,'speed':0,'time':0}
+ data = {'name':public.getMsg('DOWNLOAD_FILE1',(filename,)),'total':0,'used':0,'pre':0,'speed':0,'time':0}
else:
speed_total = speed_total[0]
used = speed_total[0]
@@ -312,7 +315,7 @@ class bt_task:
return public.returnMsg(False,'NOT_SUP_COMP_FORMAT')
self.set_file_accept(dfile)
- public.WriteLog("TYPE_FILE", 'ZIP_SUCCESS', (sfiles, dfile))
+ public.WriteLog("TYPE_FILE", 'ZIP_SUCCESS', (sfiles, dfile),not_web = self.not_web)
return public.returnMsg(True, 'ZIP_SUCCESS')
# 文件解压
@@ -356,7 +359,7 @@ class bt_task:
user = pwd.getpwuid(os.stat(dfile).st_uid).pw_name
public.ExecShell("chown %s:%s %s" % (user, user, dfile))
- public.WriteLog("TYPE_FILE", 'UNZIP_SUCCESS', (sfile, dfile))
+ public.WriteLog("TYPE_FILE", 'UNZIP_SUCCESS', (sfile, dfile),not_web = self.not_web)
return public.returnMsg(True, 'UNZIP_SUCCESS')
# 备份网站
@@ -378,7 +381,7 @@ class bt_task:
sql = public.M('backup').add('type,name,pid,filename,size,addtime',
(0, fileName, find['id'], zipName, 0, public.getDate()))
- public.WriteLog('TYPE_SITE', 'SITE_BACKUP_SUCCESS', (find['name'],))
+ public.WriteLog('TYPE_SITE', 'SITE_BACKUP_SUCCESS', (find['name'],),not_web = self.not_web)
return public.returnMsg(True, 'BACKUP_SUCCESS')
# 备份数据库
@@ -405,7 +408,7 @@ class bt_task:
addTime = time.strftime('%Y-%m-%d %X', time.localtime())
sql.add('type,name,pid,filename,size,addtime',
(1, fileName, id, backupName, 0, addTime))
- public.WriteLog("TYPE_DATABASE", "DATABASE_BACKUP_SUCCESS", (name,))
+ public.WriteLog("TYPE_DATABASE", "DATABASE_BACKUP_SUCCESS", (name,),not_web = self.not_web)
return public.returnMsg(True, 'BACKUP_SUCCESS')
# 导入数据库
@@ -454,7 +457,7 @@ class bt_task:
'setup_path') + "/mysql/bin/mysql -uroot -p" + root + " --force \"" + name + "\" < " + file)
self.mypass(False, root)
- public.WriteLog("TYPE_DATABASE", 'DATABASE_INPUT_SUCCESS', (name,))
+ public.WriteLog("TYPE_DATABASE", 'DATABASE_INPUT_SUCCESS', (name,),not_web = self.not_web)
return public.returnMsg(True, 'DATABASE_INPUT_SUCCESS')
# 配置
@@ -479,7 +482,6 @@ class bt_task:
from collections import namedtuple
get = namedtuple('get',['path'])
get.path = filename
- public.writeFile('/tmp/2',str(get.path))
files.files().fix_permissions(get)
# 检查敏感目录
diff --git a/class/panel_restore.py b/class/panel_restore.py
index 2a46cae1..22a65a8e 100644
--- a/class/panel_restore.py
+++ b/class/panel_restore.py
@@ -164,7 +164,8 @@ class panel_restore:
result = self._restore_backup(self._local_file, site_info, args)
else:
return public.ExecShell(False,'Currently only supports restoring local, Google storage and AWS S3 backups')
- os.remove(self._local_file)
+ if os.path.exists(self._local_file):
+ os.remove(self._local_file)
if result:
self._progress_rewrite('Recovery failed: {}'.format(str(site_info['site_path'])))
return result
diff --git a/class/public.py b/class/public.py
index c46c3283..2372f71e 100644
--- a/class/public.py
+++ b/class/public.py
@@ -32,8 +32,9 @@ def M(table):
ps: 默认访问data/default.db
"""
import db
- sql = db.Sql()
- return sql.table(table)
+ with db.Sql() as sql:
+ #sql = db.Sql()
+ return sql.table(table)
def HttpGet(url,timeout = 6,headers = {}):
"""
@@ -317,7 +318,7 @@ def GetJson(data):
try:
return dumps(data,ensure_ascii=False)
except:
- return dumps(returnMsg(False,"Wrong response: %s" % str(data)))
+ return dumps(returnMsg(False,"WRONG_RESPONSE", (str(data))))
def getJson(data):
return GetJson(data)
@@ -341,10 +342,10 @@ def ReadFile(filename,mode = 'r'):
f_body = fp.read()
fp.close()
except Exception as ex2:
- WriteLog('Open File',str(ex2))
+ WriteLog('OPEN_FILE',str(ex2))
return False
else:
- WriteLog('Open File',str(ex))
+ WriteLog('OPEN_FILE',str(ex))
return False
return f_body
@@ -375,19 +376,20 @@ def WriteFile(filename,s_body,mode='w+'):
def writeFile(filename,s_body,mode='w+'):
return WriteFile(filename,s_body,mode)
-def WriteLog(type,logMsg,args=()):
+def WriteLog(type,logMsg,args=(),not_web = False):
#写日志
#try:
import time,db,json
username = 'system'
uid = 1
- try:
- from BTPanel import session
- if 'username' in session:
- username = session['username']
- uid = session['uid']
- except:
- pass
+ if not not_web:
+ try:
+ from BTPanel import session
+ if 'username' in session:
+ username = session['username']
+ uid = session['uid']
+ except:
+ pass
global _LAN_LOG
if not _LAN_LOG:
_LAN_LOG = json.loads(ReadFile('BTPanel/static/language/' + GetLanguage() + '/log.json'))
@@ -624,8 +626,10 @@ def get_url(timeout = 0.5):
mnode1 = []
mnode2 = []
mnode3 = []
+ new_node_list = {}
for node in node_list:
node['net'],node['ping'] = get_timeout(node['protocol'] + node['address'] + ':' + node['port'] + '/net_test',1)
+ new_node_list[node['address']] = node['ping']
if not node['ping']: continue
if node['ping'] < 100: #当响应时间<100ms且可用带宽大于1500KB时
if node['net'] > 1500:
@@ -645,6 +649,16 @@ def get_url(timeout = 0.5):
mnode = sorted(mnode2,key= lambda x:x['ping'],reverse=False)
if not mnode: return 'http://download.bt.cn'
+
+ new_node_keys = new_node_list.keys()
+ for i in range(len(node_list)):
+ if node_list[i]['address'] in new_node_keys:
+ node_list[i]['ping'] = new_node_list[node_list[i]['address']]
+ else:
+ node_list[i]['ping'] = 500
+
+ new_node_list = sorted(node_list,key=lambda x: x['ping'],reverse=False)
+ writeFile(nodeFile,json.dumps(new_node_list))
return mnode[0]['protocol'] + mnode[0]['address'] + ':' + mnode[0]['port']
except:
return 'http://download.bt.cn'
@@ -1356,7 +1370,7 @@ def write_request_log(reques = None):
log_file = getDate(format='%Y-%m-%d') + '.json'
if not os.path.exists(log_path): os.makedirs(log_path)
- from flask import request
+ from BTPanel import request
log_data = []
log_data.append(getDate())
log_data.append(GetClientIp() + ':' + str(request.environ.get('REMOTE_PORT')))
@@ -1364,6 +1378,7 @@ def write_request_log(reques = None):
log_data.append(request.full_path)
log_data.append(request.headers.get('User-Agent'))
WriteFile(log_path + '/' + log_file,json.dumps(log_data) + "\n",'a+')
+ rep_sys_path()
except: pass
# 重载模块
@@ -1545,6 +1560,7 @@ def auto_backup_panel():
shutil.copytree(panel_paeh + '/data',backup_path + '/data')
shutil.copytree(panel_paeh + '/config',backup_path + '/config')
shutil.copytree(panel_paeh + '/vhost',backup_path + '/vhost')
+ ExecShell("chmod -R 600 {path};chown -R root.root {path}".format(paht=b_path))
time_now = time.time() - (86400 * 15)
for f in os.listdir(b_path):
try:
@@ -1723,7 +1739,7 @@ def import_cdn_plugin():
try:
import static_cdn_main
except:
- sys.path.insert(0,plugin_path)
+ package_path_append(plugin_path)
import static_cdn_main
@@ -1737,6 +1753,8 @@ def get_cdn_hosts():
def get_cdn_url():
try:
+ if os.path.exists('plugin/static_cdn/not_open.pl'):
+ return False
from BTPanel import cache
cdn_url = cache.get('cdn_url')
if cdn_url: return cdn_url
@@ -1921,6 +1939,74 @@ def restore_file(file, act=None):
file_type = "_def"
ExecShell("/usr/bin/cp -p {1} {0}".format(file, file + file_type))
+
+def package_path_append(path):
+ if not path in sys.path:
+ sys.path.insert(0, path)
+
+
+def rep_sys_path():
+ sys_path = []
+ for p in sys.path:
+ if p in sys_path: continue
+ sys_path.append(p)
+ sys.path = sys_path
+
+
+def get_ssh_port():
+ '''
+ @name 获取本机SSH端口
+ @author hwliang<2020-08-07>
+ @return int
+ '''
+ s_file = '/etc/ssh/sshd_config'
+ conf = readFile(s_file)
+ if not conf: conf = ''
+ rep = r"#*Port\s+([0-9]+)\s*\n"
+ tmp1 = re.search(rep, conf)
+ ssh_port = 22
+ if tmp1:
+ ssh_port = int(tmp1.groups(0)[0])
+ return ssh_port
+
+def set_error_num(key,empty = False,expire=3600):
+ '''
+ @name 设置失败次数(每调用一次+1)
+ @author hwliang<2020-08-21>
+ @param key 索引
+ @param empty 是否清空计数
+ @param expire 计数器生命周期(秒)
+ @return bool
+ '''
+ from BTPanel import cache
+ num = cache.get(key)
+ if not num:
+ num = 0
+ else:
+ if empty:
+ cache.delete(key)
+ return True
+ cache.set(key,num + 1,expire)
+ return True
+
+def get_error_num(key,limit=False):
+ '''
+ @name 获取失败次数
+ @author hwliang<2020-08-21>
+ @param key 索引
+ @param limit 如果为False,则直接返回失败次数,否则与失败次数比较,若大于失败次数返回True,否则返回False
+ @return int or bool
+ '''
+ from BTPanel import cache
+ num = cache.get(key)
+ if not num: num = 0
+ if not limit:
+ return num
+ if limit > num:
+ return True
+ return False
+
+
#取通用对象
class dict_obj:
def __contains__(self, key):
diff --git a/class/ssh_terminal.py b/class/ssh_terminal.py
index 36231fe2..e50aaba8 100644
--- a/class/ssh_terminal.py
+++ b/class/ssh_terminal.py
@@ -6,200 +6,919 @@
# +-------------------------------------------------------------------
# | Author: hwliang
# +-------------------------------------------------------------------
-try:
- import paramiko
-except: pass
import json
import time
import os
import sys
import socket
import threading
+import re
-sys.path.insert(0, '/www/server/panel/class/')
-import public
+
+if not 'class/' in sys.path:
+ sys.path.insert(0,'class/')
from io import BytesIO, StringIO
-from BTPanel import session
+
+def returnMsg(status,msg):
+ return {'status':status,'msg':msg}
+
+import public
class ssh_terminal:
- __log_type = 'aaPanel terminal'
- _coll_user = None
+ _panel_path = '/www/server/panel'
+ _save_path = _panel_path + '/config/ssh_info/'
_host = None
- _web_socket = None
- _ssh_info = None
- _ssh_socket = None
- _en_key = '4BbA7076e19H'
- _thread = None
- _my_terms = {}
- _room = "ssh_data"
- _send_last = False
- _send_last_time = 0
- _connect_time = 0
+ _port = 22
+ _user = None
+ _pass = None
+ _pkey = None
+ _ws = None
+ _ssh = None
+ _last_cmd = ""
+ _last_cmd_tip = 0
+ _log_type = public.getMsg('TYPE_TERMINAL')
+ _history_len = 0
+ _client = ""
+ _rep_ssh_config = False
+ _sshd_config_backup = None
+ _rep_ssh_service = False
- def __init__(self):
- pass
+ def connect(self):
+ '''
+ @name 连接服务器
+ @author hwliang<2020-08-07>
+ @return dict{
+ status: bool 状态
+ msg: string 详情
+ }
+ '''
+ if not self._host: return returnMsg(False,'错误的连接地址')
+ if not self._user: self._user = 'root'
+ if not self._port: self._port = 22
+ self.is_local()
- def connect(self, ssh_info=None):
- if ssh_info: self._ssh_info = ssh_info
- if not self._host: self._host = self._ssh_info['host']
- # print('----------连接时的ssh_info--------------')
- if self._ssh_info['host'] in self._my_terms:
- if time.time() - self._my_terms[self._host].last_time < 86400:
- return True
try:
+ if self._rep_ssh_config: time.sleep(0.1)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 262144)
- sock.connect((self._ssh_info['host'], int(self._ssh_info['port'])))
+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 8192)
+ sock.connect((self._host, self._port))
except Exception as e:
- self._web_socket.send("\rServer connection failed!\r")
- return False
- # 使用Transport连接
- p1 = paramiko.Transport(sock)
- p1.start_client()
- if not 'pkey' in self._ssh_info: self._ssh_info['pkey'] = None
- if not 'c_type' in self._ssh_info: self._ssh_info['c_type'] = None
+ self.set_sshd_config(True)
+ return returnMsg(False,"CONCTION_FAILURE")
+ import paramiko
+
+ self._ssh = paramiko.Transport(sock)
+
try:
- # 如果有pkey时则使用RSA私钥登录
- if self._ssh_info['pkey'] and self._ssh_info['c_type']:
- # print('------使用私钥登陆---------')
- # 将RSA私钥转换为io对象,然后生成rsa_key对象
- p_file = StringIO(self._ssh_info['pkey'])
+ self._ssh.start_client()
+ if not self._pass and not self._pkey:
+ self.set_sshd_config(True)
+ return public.returnMsg(False,'SSH_LOGIN_INFO_ERR',(self._host,self._port))
+ self._ssh.banner_timeout=60
+ if self._pkey:
+ if sys.version_info[0] == 2:
+ p_file = BytesIO(self._pkey)
+ else:
+ p_file = StringIO(self._pkey)
pkey = paramiko.RSAKey.from_private_key(p_file)
- p1.auth_publickey(username=self._ssh_info['username'].strip(), key=pkey)
+ self._ssh.auth_publickey(username=self._user, key=pkey)
else:
- # print('-----------使用密码登陆-----------')
- p1.auth_password(username=self._ssh_info['username'].strip(), password=self._ssh_info['password'])
+ self._ssh.auth_password(username=self._user, password=self._pass)
except Exception as e:
- self._web_socket.send("\rWrong user name or password!\r")
- p1.close()
+ self.set_sshd_config(True)
+ self._ssh.close()
+ e = str(e)
+ if e.find('Authentication failed') != -1:
+ if self._host in ['127.0.0.1','localhost'] and self._pkey:
+ return returnMsg(False,'SSH_LOGIN_ERR')
+ return returnMsg(False,'SSH_LOGIN_ERR1',(e + "," + self._user,))
+ if e.find('Bad authentication type; allowed types') != -1:
+ return returnMsg(False,'SSH_LOGIN_ERR2',(e,))
+ if e.find('Connection reset by peer') != -1:
+ return returnMsg(False,'SSH_LOGIN_ERR3')
+ if e.find('Error reading SSH protocol banner') != -1:
+ return returnMsg(False,'SSH_LOGIN_ERR4',(e,))
+ if not e:
+ return returnMsg(False,"SSH_LOGIN_ERR5")
+ return returnMsg(False,"SSH_LOGIN_ERR6",(public.get_error_info(),))
+
+ self._ssh = self._ssh.open_session()
+ self._ssh.get_pty(term='xterm', width=100, height=34)
+ self._ssh.invoke_shell()
+ self._connect_time = time.time()
+ self._last_send = []
+ from BTPanel import request
+ self._client = public.GetClientIp() +':' + str(request.environ.get('REMOTE_PORT'))
+ public.WriteLog(self._log_type,'SSH_LOGIN',(self._host,self._port))
+ self.history_send("LOGIN_SUCCESS2")
+ self.set_sshd_config(True)
+ return returnMsg(True,'CONNECTION_SUCCEEDED')
+
+
+ def get_login_user(self):
+ '''
+ @name 获取本地登录用户
+ @author hwliang<2020-08-07>
+ @return string
+ '''
+
+ if self._user != 'root': return self._user
+ l_user = 'root'
+ ssh_config_file = '/etc/ssh/sshd_config'
+ ssh_config = public.readFile(ssh_config_file)
+ if not ssh_config: return l_user
+
+ if ssh_config.find('PermitRootLogin yes') != -1: return l_user
+
+
+ user_list = self.get_ulist()
+ login_user = ''
+ for u_info in user_list:
+ if u_info['user'] == 'root': continue
+ if u_info['login'] == '/bin/bash':
+ login_user = u_info['user']
+ break
+
+ if not login_user:
+ return l_user
+
+ return login_user
+
+
+ def get_ulist(self):
+ '''
+ @name 获取本地用户列表
+ @author hwliang<2020-08-07>
+ @return list
+ '''
+ u_data = public.readFile('/etc/passwd')
+ u_list = []
+ for i in u_data.split("\n"):
+ u_tmp = i.split(':')
+ if len(u_tmp) < 3: continue
+ u_info = {}
+ u_info['user'],u_info['pass'],u_info['uid'],u_info['gid'],u_info['user_msg'],u_info['home'],u_info['login'] = u_tmp
+ u_list.append(u_info)
+ return u_list
+
+ def is_local(self):
+ '''
+ @name 处理本地连接
+ @author hwliang<2020-08-07>
+ @ps 如果host为127.0.0.1或localhost,则尝试自动使用publicKey登录
+ @return void
+ '''
+
+ if self._pass: return
+ if self._host in ['127.0.0.1','localhost']:
+ try:
+ login_user = self.get_login_user()
+ self.set_sshd_config()
+ if self._user == 'root' and login_user == 'root':
+ id_rsa_file = ['/root/.ssh/id_rsa','/root/.ssh/id_rsa_bt']
+ for ifile in id_rsa_file:
+ if os.path.exists(ifile):
+ self._pkey = public.readFile(ifile)
+ host_path = self._save_path + self._host
+ if not os.path.exists(host_path):
+ os.makedirs(host_path,384)
+ return
+
+
+ if not self._pass or not self._pkey or not self._user:
+ home_path = '/home/' + login_user
+ if login_user == 'root':
+ home_path = '/root'
+ self._user = login_user
+ id_rsa_file = [home_path + '/.ssh/id_rsa',home_path + '/.ssh/id_rsa_bt']
+ for ifile in id_rsa_file:
+ if os.path.exists(ifile):
+ self._pkey = public.readFile(ifile)
+ return
+
+ _ssh_ks = home_path + '/.ssh'
+ if not os.path.exists(_ssh_ks):
+ os.makedirs(_ssh_ks,384)
+ os.system("ssh-keygen -t rsa -P '' -f {}/.ssh/id_rsa |echo y".format(home_path))
+ pub_file = home_path + '/.ssh/id_rsa.pub'
+ az_file = home_path + '/.ssh/authorized_keys'
+ rsa_file = home_path + '/.ssh/id_rsa'
+ public.ExecShell('cat {} >> {} && chmod 600 {} {}'.format(pub_file, az_file, az_file,rsa_file))
+ os.remove(pub_file)
+ public.ExecShell("chown -R {}:{} {}".format(self._user,self._user,_ssh_ks))
+ public.ExecShell("chmod -R 600 {}".format(_ssh_ks))
+ self._pkey = public.readFile(rsa_file)
+ except:
+ return
+
+ def get_sys_version(self):
+ '''
+ @name 获取操作系统版本
+ @author hwliang<2020-08-13>
+ @return bool
+ '''
+ version = public.readFile('/etc/redhat-release')
+ if not version:
+ version = public.readFile('/etc/issue').strip().split("\n")[0].replace('\\n','').replace('\l','').strip()
+ else:
+ version = version.replace('release ','').replace('Linux','').replace('(Core)','').strip()
+ return version
+
+ def get_ssh_status(self):
+ '''
+ @name 获取SSH服务状态
+ @author hwliang<2020-08-13>
+ @return bool
+ '''
+ version = self.get_sys_version()
+ if os.path.exists('/usr/bin/apt-get'):
+ if os.path.exists('/etc/init.d/sshd'):
+ status = public.ExecShell("service sshd status | grep -P '(dead|stop|not running)'|grep -v grep")
+ else:
+ status = public.ExecShell("service ssh status | grep -P '(dead|stop|not running)'|grep -v grep")
+ else:
+ if version.find(' 7.') != -1 or version.find(' 8.') != -1 or version.find('Fedora') != -1:
+ status = public.ExecShell("systemctl status sshd.service | grep 'dead'|grep -v grep")
+ else:
+ status = public.ExecShell("/etc/init.d/sshd status | grep -e 'stopped' -e '已停'|grep -v grep")
+ if len(status[0]) > 3:
+ status = False
+ else:
+ status = True
+ return status
+
+ def is_running(self,rep = False):
+ '''
+ @name 处理SSH服务状态
+ @author hwliang<2020-08-13>
+ @param rep 是否恢复原来的SSH服务状态
+ @return bool
+ '''
+ try:
+ if rep and self._rep_ssh_service:
+ self.restart_ssh('stop')
+ return True
+
+ ssh_status = self.get_ssh_status()
+ if not ssh_status:
+ self.restart_ssh('start')
+ self._rep_ssh_service = True
+ return True
+ return False
+ except:
return False
- self._my_terms[self._host] = public.dict_obj()
- self._my_terms[self._host].last_time = time.time()
- self._my_terms[self._host].connect_time = time.time()
- # 打开会话
- self._my_terms[self._host].tty = p1.open_session()
- # 获取终端对象
- self._my_terms[self._host].tty.get_pty(term='xterm', width=100, height=34)
- self._my_terms[self._host].tty.invoke_shell()
- # 记录登陆记录
- #public.M('ssh_records').add('coll_user,ssh_user,host,cmd,addtime', (self._coll_user, self._ssh_info['username'], self._ssh_info['host'], 'login', int(time.time())))
- #print("登录成功")
- self._my_terms[self._host].last_send = []
- self._send_last = True
- self._connect_time = time.time()
- return True
- def resize(self, data):
+ def set_sshd_config(self,rep = False):
+ '''
+ @name 设置本地SSH配置文件,以支持pubkey认证
+ @author hwliang<2020-08-13>
+ @param rep 是否恢复ssh配置文件
+ @return bool
+ '''
+ self.is_running(rep)
+ if rep and not self._rep_ssh_config:
+ return False
+
try:
- data = json.loads(data)
- self._my_terms[self._host].tty.resize_pty(width=data['width'], height=data['height'], width_pixels=data['width_px'], height_pixels=data['height_px'])
+ sshd_config_file = '/etc/ssh/sshd_config'
+ if not os.path.exists(sshd_config_file):
+ return False
+
+ sshd_config = public.readFile(sshd_config_file)
+
+ if not sshd_config:
+ return False
+
+ if rep:
+ if self._sshd_config_backup:
+ public.writeFile(sshd_config_file,self._sshd_config_backup)
+ self.restart_ssh()
+ return True
+
+ pin = r'^\s*PubkeyAuthentication\s+(yes|no)'
+ pubkey_status = re.findall(pin,sshd_config,re.I)
+ if pubkey_status:
+ if pubkey_status[0] == 'yes':
+ pubkey_status = True
+ else:
+ pubkey_status = False
+
+ pin = r'^\s*RSAAuthentication\s+(yes|no)'
+ rsa_status = re.findall(pin,sshd_config,re.I)
+ if rsa_status:
+ if rsa_status[0] == 'yes':
+ rsa_status = True
+ else:
+ rsa_status = False
+
+ self._sshd_config_backup = sshd_config
+ is_write = False
+ if not pubkey_status:
+ sshd_config = re.sub(r'\n#?PubkeyAuthentication\s\w+','\nPubkeyAuthentication yes',sshd_config)
+ is_write = True
+ if not rsa_status:
+ sshd_config = re.sub(r'\n#?RSAAuthentication\s\w+','\nRSAAuthentication yes',sshd_config)
+ is_write = True
+
+ if is_write:
+ public.writeFile(sshd_config_file,sshd_config)
+ self._rep_ssh_config = True
+ self.restart_ssh()
+ else:
+ self._sshd_config_backup = None
+
return True
except:
- print(public.get_error_info())
return False
- def send(self):
- try:
- while not self._web_socket.closed:
- c_data = self._web_socket.receive()
- if not c_data: continue
- if len(c_data) > 10:
- if c_data.find('new_terminal') != -1:
- if not self._host in self._my_terms:
- self.connect()
- else:
- if time.time() - self._connect_time > 3:
- self.last_send()
- continue
- if c_data.find("reset_connect") != -1:
- if not self._host in self._my_terms: self.connect()
- continue
+ def restart_ssh(self,act = 'reload'):
+ '''
+ 重启ssh 无参数传递
+ '''
+ version = public.readFile('/etc/redhat-release')
+ if not os.path.exists('/etc/redhat-release'):
+ public.ExecShell('service ssh ' + act)
+ elif version.find(' 7.') != -1 or version.find(' 8.') != -1:
+ public.ExecShell("systemctl " + act + " sshd.service")
+ else:
+ public.ExecShell("/etc/init.d/sshd " + act)
- if self._host in self._my_terms:
- self._my_terms[self._host].last_time = time.time()
- self._my_terms[self._host].tty.send(c_data)
- else:
- return
+ def resize(self, data):
+ '''
+ @name 调整终端大小
+ @author hwliang<2020-08-07>
+ @param data 终端尺寸数据
+ {
+ cols: int 列
+ rows: int 行
+ }
+ @return bool
+ '''
+ try:
+ data = json.loads(data)
+ self._ssh.resize_pty(width=data['cols'], height=data['rows'])
+ return True
except:
- print(public.get_error_info())
+ return False
+
def recv(self):
+ '''
+ @name 读取tty缓冲区数据
+ @author hwliang<2020-08-07>
+ @return void
+ '''
try:
- n = 0
- while not self._web_socket.closed:
- self.not_send()
- #if n == 0: self.last_send()
- data = self._my_terms[self._host].tty.recv(1024)
- self.not_send()
- if not data:
+ while not self._ws.closed:
+ resp_line = self._ssh.recv(1024)
+ if not resp_line:
+ self._ws.send(public.getMsg('RECONNECT_SSH'))
self.close()
- self._web_socket.send('The connection has been disconnected and pressing Enter will attempt to reconnect!')
+ return
+
+ if not resp_line: continue
+ if self._ws.closed:
return
try:
- result = data.decode()
+ result = resp_line.decode()
except:
- result = str(data)
- if not result: continue
- if self._web_socket.closed:
- self._my_terms[self._host].not_send = result
- return
- self.set_last_send(result)
- if not n: n = 1
- self._web_socket.send(result)
+ result = str(resp_line)
+ self._ws.send(result)
+
+ self.history_recv(result)
except:
- print(public.get_error_info())
+ self._ws.send(public.get_error_info())
+ self.close()
- def set_last_send(self,result):
- last_size = 1024
- if not 'last_send' in self._my_terms[self._host]:
- self._my_terms[self._host].last_send = []
+ def send(self):
+ '''
+ @name 写入数据到缓冲区
+ @author hwliang<2020-08-07>
+ @return void
+ '''
+ try:
+ while not self._ws.closed:
+ client_data = self._ws.receive()
+ if not client_data: continue
+ if len(client_data) > 10:
+ if client_data.find('{"host":"') != -1:
+ continue
+ if client_data.find('"resize":1') != -1:
+ self.resize(client_data)
+ continue
+ self._ssh.send(client_data)
+ self.history_send(client_data)
+ except Exception as ex:
+ ex = str(ex)
+ if ex.find('_io.BufferedReader') != -1:
+ self.send()
+ return
+ self.close()
- self._my_terms[self._host].last_send.append(result)
- last_len = len(self._my_terms[self._host].last_send)
- if last_len > last_size:
- self._my_terms[self._host].last_send = self._my_terms[self._host].last_send[last_len-last_size:]
- def not_send(self):
- if 'not_send' in self._my_terms[self._host]:
- if self._my_terms[self._host].not_send:
- self._web_socket.send(self._my_terms[self._host].not_send)
- self._my_terms[self._host].not_send = ""
+ def history_recv(self,recv_data):
+ '''
+ @name 从接收实体保存命令
+ @author hwliang<2020-08-12>
+ @param recv_data 数据实体
+ @return void
+ '''
+ #处理TAB补登
+ if self._last_cmd_tip == 1:
+ if not recv_data.startswith('\r\n'):
+ self._last_cmd += recv_data.replace('\u0007','').strip()
+ self._last_cmd_tip = 0
+
+ #上下切换命令
+ if self._last_cmd_tip == 2:
+ self._last_cmd = recv_data.strip().replace("\x08","").replace("\x07","").replace("\x1b[K","")
+ self._last_cmd_tip = 0
+
+ def history_send(self,send_data):
+ '''
+ @name 从发送实体保存命令
+ @author hwliang<2020-08-12>
+ @param send_data 数据实体
+ @return void
+ '''
+ if not send_data: return
+ his_path = self._save_path + self._host
+ if not os.path.exists(his_path): return
+ his_file = his_path + '/history.pl'
+
+ #上下切换命令
+ if send_data in ["\x1b[A","\x1b[B"]:
+ self._last_cmd_tip = 2
+ return
+
+ #退格
+ if send_data == "\x7f":
+ self._last_cmd = self._last_cmd[:-1]
+ return
+
+ #过滤特殊符号
+ if send_data in ["\x1b[C","\x1b[D","\x1b[K","\x07","\x08","\x03","\x01","\x02","\x04","\x05","\x06","\u0007"]:
+ return
+
+ #Tab补全处理
+ if send_data == '\t':
+ self._last_cmd_tip = 1
+ return
+
+ if send_data[-1] in ['\r','\n']:
+ if not self._last_cmd: return
+ his_shell = [int(time.time()),self._client,self._user,self._last_cmd]
+ public.writeFile(his_file, json.dumps(his_shell) + "\n","a+")
+ self._last_cmd = ""
+
+ #超过5M则保留最新的200行
+ if os.stat(his_file).st_size > 5242880:
+ his_tmp = public.GetNumLines(his_file,200)
+ public.writeFile(his_file, his_tmp)
+ else:
+ self._last_cmd += send_data
- def last_send(self):
- if time.time()- self._send_last_time < 3: return False
- self._send_last_time = time.time()
- time.sleep(0.3)
- if not self._host in self._my_terms: return False
- if 'last_send' in self._my_terms[self._host]:
- for d in self._my_terms[self._host].last_send:
- self._web_socket.send(d)
def close(self):
+ '''
+ @name 释放连接
+ @author hwliang<2020-08-07>
+ @return void
+ '''
try:
- self._my_terms[self._host].tty.close()
- except:pass
- if self._host in self._my_terms:
- del self._my_terms[self._host]
- self._thread = None
+ if self._ssh:
+ self._ssh.close()
+ self._ssh = None
+ if not self._ws.closed:
+ self._ws.close()
+ self._ws = None
+ except:
+ pass
+
+
+ def set_attr(self,ssh_info):
+ '''
+ @name 设置对象属性,并连接服务器
+ @author hwliang<2020-08-07>
+ @return void
+ '''
+ self._host = ssh_info['host'].strip()
+ self._port = int(ssh_info['port'])
+ if 'username' in ssh_info:
+ self._user = ssh_info['username']
+ if 'pkey' in ssh_info:
+ self._pkey = ssh_info['pkey']
+ if 'password' in ssh_info:
+ self._pass = ssh_info['password']
+
+ result = self.connect()
+ return result
def run(self,web_socket, ssh_info=None):
- self._web_socket = web_socket
- if 'id' in ssh_info:
- self._ssh_info = self.get_server_ssh_info(ssh_info)
+ '''
+ @name 启动SSH客户端对象
+ @author hwliang<2020-08-07>
+ @param web_socket websocket句柄对像
+ @param ssh_info SSH信息{
+ host: 主机地址,
+ port: 端口
+ username: 用户名
+ password: 密码
+ pkey: 密钥(如果不为空,将使用密钥连接)
+ }
+ @return void
+ '''
+ self._ws = web_socket
+ if not self._ssh:
+ if not ssh_info:
+ return
+
+ result = self.set_attr(ssh_info)
else:
- self._ssh_info = ssh_info
- if not self._ssh_info:
- return
- result = self.connect()
- time.sleep(0.1)
- if result:
+ result = returnMsg(True,'已连接')
+
+ if result['status']:
sendt = threading.Thread(target=self.send)
recvt = threading.Thread(target=self.recv)
sendt.start()
recvt.start()
sendt.join()
recvt.join()
- if time.time() - self._my_terms[self._host].last_time > 86400: self.close()
- self._web_socket = None
+ self.close()
+ self._ws = None
+ else:
+ self._ws.send(result['msg'])
+
+ def __del__(self):
+ '''
+ 自动释放
+ '''
+ self.close()
+
+
+
+class ssh_host_admin(ssh_terminal):
+ _panel_path = '/www/server/panel'
+ _save_path = _panel_path + '/config/ssh_info/'
+ _pass_file = _panel_path + '/data/a_pass.pl'
+ _user_command_file = _save_path + '/user_command.json'
+ _sys_command_file = _save_path + '/sys_command.json'
+ _pass_str = None
+
+ def __init__(self):
+ if not os.path.exists(self._save_path):
+ os.makedirs(self._save_path,384)
+ if not os.path.exists(self._pass_file):
+ public.writeFile(self._pass_file,public.GetRandomString(16))
+ public.set_mode(self._pass_file,600)
+ if not self._pass_str:
+ self._pass_str = public.readFile(self._pass_file)
+
+ def get_host_list(self,args = None):
+ '''
+ @name 获取本机保存的SSH信息列表
+ @author hwliang<2020-08-07>
+ @param args
+ @return list
+ '''
+
+ host_list = []
+ for name in os.listdir(self._save_path):
+ info_file = self._save_path + name +'/info.json'
+ if not os.path.exists(info_file): continue
+ info_tmp = self.get_ssh_info(name)
+ host_info = {}
+ host_info['host'] = name
+ host_info['port'] = info_tmp['port']
+ host_info['ps'] = info_tmp['ps']
+ host_info['sort'] = int(info_tmp['sort'])
+
+ host_list.append(host_info)
+
+ host_list = sorted(host_list,key=lambda x: x['sort'],reverse=False)
+ return host_list
+
+ def get_host_find(self,args):
+ '''
+ @name 获取指定SSH信息
+ @author hwliang<2020-08-07>
+ @param args{
+ host: 主机地址
+ }
+ @return dict
+ '''
+ args.host = args.host.strip()
+ info_file = self._save_path + args.host +'/info.json'
+ if not os.path.exists(info_file):
+ return public.returnMsg(False,'SSH_LOGIN_ERR7')
+ info_tmp = self.get_ssh_info(args.host)
+ host_info = {}
+ host_info['host'] = args.host
+ host_info['port'] = info_tmp['port']
+ host_info['ps'] = info_tmp['ps']
+ host_info['sort'] = info_tmp['sort']
+ host_info['username'] = info_tmp['username']
+ host_info['password'] = info_tmp['password']
+ host_info['pkey'] = info_tmp['pkey']
+ return host_info
+
+ def modify_host(self,args):
+ '''
+ @name 修改SSH信息
+ @author hwliang<2020-08-07>
+ @param args{
+ host: 被修改的主机地址,
+ new_host: 新的主机地址,
+ port: 端口
+ ps: 备注
+ sort: 排序(可选)
+ username: 用户名
+ password: 密码
+ pkey: 密钥(如果不为空,将使用密钥连接)
+ }
+ @return dict
+ '''
+ args.new_host = args.new_host.strip()
+ args.host = args.host.strip()
+ if args.host != args.new_host:
+ info_file = self._save_path + args.new_host +'/info.json'
+ if os.path.exists(info_file):
+ return public.returnMsg(False,'SSH_LOGIN_ERR8')
+
+ info_file = self._save_path + args.host +'/info.json'
+
+ if not os.path.exists(info_file):
+ return public.returnMsg(False,'SSH_LOGIN_ERR7')
+
+ if not 'sort' in args:
+ r_data = public.aes_decrypt(public.readFile(info_file),self._pass_str)
+ info_tmp = json.loads(r_data)
+ args.sort = info_tmp['sort']
+
+ host_info = {}
+ host_info['host'] = args.new_host
+ host_info['port'] = int(args['port'])
+ host_info['ps'] = args['ps']
+ host_info['sort'] = args['sort']
+ host_info['username'] = args['username']
+ host_info['password'] = args['password']
+ host_info['pkey'] = args['pkey']
+ if not host_info['pkey']: host_info['pkey'] = ''
+ result = self.set_attr(host_info)
+ if not result['status']: return result
+ self.save_ssh_info(args.host,host_info)
+ if args.host != args.new_host:
+ public.ExecShell('mv {} {}'.format(self._save_path + args.host,self._save_path + args.new_host))
+ public.WriteLog(self._log_type,'MODIFY_SSH_INFO',(args.host,))
+ return public.returnMsg(True,'EDIT_SUCCESS')
+
+ def create_host(self,args):
+ '''
+ @name 添加SSH信息
+ @author hwliang<2020-08-07>
+ @param args{
+ host: 主机地址,
+ port: 端口
+ ps: 备注
+ sort: 排序(可选,默认0)
+ username: 用户名
+ password: 密码
+ pkey: 密钥(如果不为空,将使用密钥连接)
+ }
+ @return dict
+ '''
+ args.host = args.host.strip()
+ host_path = self._save_path + args.host
+ info_file = host_path +'/info.json'
+ if os.path.exists(info_file):
+ return public.returnMsg(False,'SSH_LOGIN_ERR8')
+ if not os.path.exists(host_path):
+ os.makedirs(host_path,384)
+ if not 'sort' in args: args.sort = 0
+ if not 'ps' in args: args.ps = args.host
+ host_info = {}
+ host_info['host'] = args.host
+ host_info['port'] = int(args['port'])
+ host_info['ps'] = args['ps']
+ host_info['sort'] = int(args['sort'])
+ host_info['username'] = args['username']
+ host_info['password'] = args['password']
+ host_info['pkey'] = args['pkey']
+ result = self.set_attr(host_info)
+ if not result['status']: return result
+ self.save_ssh_info(args.host,host_info)
+ public.WriteLog(self._log_type,'ADD_SSH_INFO',(args.host,))
+ return public.returnMsg(True,'SET_SUCCESS')
+
+
+ def remove_host(self,args):
+ '''
+ @name 删除指定SSH信息
+ @author hwliang<2020-08-07>
+ @param args{
+ host: 主机地址
+ }
+ @return dict
+ '''
+ args.host = args.host.strip()
+ if not args.host: return public.returnMsg(False,'INIT_ARGS_ERR')
+ host_path = self._save_path + args.host
+ if not os.path.exists(host_path):
+ return public.returnMsg(False,'SSH_LOGIN_ERR7!')
+ public.ExecShell("rm -rf {}".format(host_path))
+ public.WriteLog(self._log_type,'DEL_SSH_INFO',(args.host,))
+ return public.returnMsg(True,'SET_SUCCESS')
+
+
+ def get_ssh_info(self,host):
+ '''
+ @name 获取并解密指定SSH信息
+ @author hwliang<2020-08-07>
+ @param host 主机地址
+ @return dict or False
+ '''
+ info_file = self._save_path + host + '/info.json'
+ if not os.path.exists(info_file): return False
+ r_data = public.aes_decrypt(public.readFile(info_file),self._pass_str)
+ return json.loads(r_data)
+
+ def save_ssh_info(self,host,host_info):
+ '''
+ @name 获取并解密指定SSH信息
+ @author hwliang<2020-08-07>
+ @param host 主机地址
+ @param host_info ssh信息字典
+ @return bool
+ '''
+ host_path = self._save_path + host
+ if not os.path.exists(host_path):
+ os.makedirs(host_path,384)
+ info_file = host_path +'/info.json'
+ r_data = public.aes_encrypt(json.dumps(host_info),self._pass_str)
+ public.writeFile(info_file,r_data)
+ return True
+
+ def set_sort(self,args):
+ '''
+ @name 获取并解密指定SSH信息
+ @author hwliang<2020-08-07>
+ @param args{
+ sort_list{
+ 主机host : 排序编号,
+ 主机host : 排序编号,
+ ...
+ }
+ }
+ @return bool
+ '''
+ if not 'sort_list' in args:
+ return public.returnMsg(False,'SSH_LOGIN_ERR9')
+ sort_list = json.loads(args.sort_list)
+ for name in sort_list.keys():
+ info_file = self._save_path + name + '/info.json'
+ if not os.path.exists(info_file): continue
+
+ ssh_info = self.get_ssh_info(name)
+ ssh_info['sort'] = int(sort_list[name])
+ self.save_ssh_info(name,ssh_info)
+ return public.returnMsg(True,'SET_SUCCESS')
+
+ def get_command_list(self,args = None, user_cmd = False , sys_cmd = False):
+ '''
+ @name 获取常用命令列表
+ @author hwliang<2020-08-08>
+ @param args
+ @param user_cmd 是否不获取用户配置
+ @param sys_cmd 是否不获取系统配置
+ @return list
+ '''
+
+ sys_command = []
+ if not sys_cmd:
+ if os.path.exists(self._sys_command_file):
+ sys_command = json.loads(public.readFile(self._sys_command_file))
+
+ user_command = []
+ if not user_cmd:
+ if os.path.exists(self._user_command_file):
+ user_command = json.loads(public.readFile(self._user_command_file))
+
+ command = sys_command + user_command
+ return command
+
+
+ def command_exists(self,command,title):
+ '''
+ @name 判断命令是否存在
+ @author hwliang<2020-08-08>
+ @param command 常用命令列表
+ @param title 命令标题
+ @return bool
+ '''
+ for cmd in command:
+ if cmd['title'] == title: return True
+ return False
+
+ def save_command(self,command,sys_cmd=False):
+ '''
+ @name 保存常用命令
+ @author hwliang<2020-08-08>
+ @param command 常用命令列表
+ @param sys_cmd 是否为系统配置
+ @return void
+ '''
+ s_file = self._user_command_file
+ if sys_cmd:
+ s_file = self._sys_command_file
+ public.writeFile(s_file,json.dumps(command))
+
+ def create_command(self,args):
+ '''
+ @name 创建常用命令
+ @author hwliang<2020-08-08>
+ @param args{
+ title 标题
+ shell 命令文本
+ }
+ @return dict
+ '''
+ args.title = args.title.strip()
+ command = self.get_command_list(sys_cmd=True)
+
+ if self.command_exists(command,args.title):
+ return public.returnMsg(False,'COMMAND_NAME_EXIST')
+
+ cmd = {
+ "title": args.title,
+ "shell": args.shell.strip()
+ }
+
+ command.append(cmd)
+ self.save_command(command)
+ public.WriteLog(self._log_type,'ADD_COMMAND_COMMAND',(args.title,))
+ return public.returnMsg(True,'SET_SUCCESS')
+
+ def get_command_find(self,args = None, title=None):
+ '''
+ @name 获取指定命令信息
+ @author hwliang<2020-08-08>
+ @param args{
+ title 标题
+ } 可选
+ @param title 标题 可选
+ @return dict
+ '''
+ if args: title = args.title.strip()
+ command = self.get_command_list()
+ for cmd in command:
+ if cmd['title'] == title:
+ return cmd
+ return public.returnMsg(False,'COMMAND_NOTEXIST')
+
+ def modify_command(self,args):
+ '''
+ @name 修改常用命令
+ @author hwliang<2020-08-08>
+ @param args{
+ title 标题
+ new_title 新标题
+ shell 命令文本
+ }
+ @return dict
+ '''
+ args.title = args.title.strip()
+ command = self.get_command_list(sys_cmd=True)
+ if not self.command_exists(command,args.title):
+ return public.returnMsg(False,'COMMAND_NOTEXIST')
+ for i in range(len(command)):
+ if command[i]['title'] == args.title:
+ command[i]['title'] = args.new_title
+ command[i]['shell'] = args.shell.strip()
+ break
+ self.save_command(command)
+ public.WriteLog(self._log_type,'EDIT_COMMAND_COMMAND',(args.title,))
+ return public.returnMsg(True,'SET_SUCCESS')
+
+ def remove_command(self,args):
+ '''
+ @name 删除指定命令
+ @author hwliang<2020-08-08>
+ @param args{
+ title 标题
+ }
+ @return dict
+ '''
+ args.title = args.title.strip()
+ command = self.get_command_list(sys_cmd=True)
+ if not self.command_exists(command,args.title):
+ return public.returnMsg(False,'COMMAND_NOTEXIST')
+ for i in range(len(command)):
+ if command[i]['title'] == args.title:
+ del(command[i])
+ break
+
+ self.save_command(command)
+ public.WriteLog(self._log_type,'DEL_COMMAND_COMMAND'.format(args.title))
+ return public.returnMsg(True,'SET_SUCCESS')
\ No newline at end of file
diff --git a/class/system.py b/class/system.py
index 5b9741ac..466dc170 100644
--- a/class/system.py
+++ b/class/system.py
@@ -12,19 +12,19 @@ try:
except:
pass
class system:
- setupPath = None;
+ setupPath = None
ssh = None
shell = None
def __init__(self):
- self.setupPath = public.GetConfigValue('setup_path');
+ self.setupPath = public.GetConfigValue('setup_path')
def GetConcifInfo(self,get=None):
#取环境配置信息
if not 'config' in session:
- session['config'] = public.M('config').where("id=?",('1',)).field('webserver,sites_path,backup_path,status,mysql_root').find();
+ session['config'] = public.M('config').where("id=?",('1',)).field('webserver,sites_path,backup_path,status,mysql_root').find()
if not 'email' in session['config']:
- session['config']['email'] = public.M('users').where("id=?",('1',)).getField('email');
+ session['config']['email'] = public.M('users').where("id=?",('1',)).getField('email')
data = {}
data = session['config']
data['webserver'] = session['config']['webserver']
@@ -66,8 +66,8 @@ class system:
if rtmp:
phpport = rtmp.groups()[0]
- if conf.find('AUTH_START') != -1: pauth = True;
- if conf.find(self.setupPath + '/stop') == -1: pstatus = True;
+ if conf.find('AUTH_START') != -1: pauth = True
+ if conf.find(self.setupPath + '/stop') == -1: pstatus = True
configFile = self.setupPath + '/nginx/conf/enable-php.conf'
conf = public.readFile(configFile)
rep = "php-cgi-([0-9]+)\.sock"
@@ -75,7 +75,7 @@ class system:
if rtmp:
phpversion = rtmp.groups()[0]
except:
- pass;
+ pass
elif os.path.exists(self.setupPath+'/apache'):
data['webserver'] = 'apache'
@@ -93,8 +93,8 @@ class system:
rtmp = re.search(rep,conf)
if rtmp:
phpport = rtmp.groups()[0]
- if conf.find('AUTH_START') != -1: pauth = True;
- if conf.find(self.setupPath + '/stop') == -1: pstatus = True;
+ if conf.find('AUTH_START') != -1: pauth = True
+ if conf.find(self.setupPath + '/stop') == -1: pstatus = True
except:
pass
elif os.path.exists('/usr/local/lsws/bin/lswsctrl'):
@@ -480,10 +480,16 @@ class system:
ntime = time.time()
networkInfo = {}
+ up = cache.get('up')
+ down = cache.get('down')
+ if not up:
+ up = networkIo[0]
+ if not down:
+ down = networkIo[1]
networkInfo['upTotal'] = networkIo[0]
networkInfo['downTotal'] = networkIo[1]
- networkInfo['up'] = round(float(networkIo[0] - cache.get("up")) / 1024 / (ntime - otime),2)
- networkInfo['down'] = round(float(networkIo[1] - cache.get("down")) / 1024 / (ntime - otime),2)
+ networkInfo['up'] = round(float(networkIo[0] - up) / 1024 / (ntime - otime),2)
+ networkInfo['down'] = round(float(networkIo[1] - down) / 1024 / (ntime - otime),2)
networkInfo['downPackets'] =networkIo[3]
networkInfo['upPackets'] =networkIo[2]
diff --git a/config/hosts.json b/config/hosts.json
index 563ad513..898af086 100644
--- a/config/hosts.json
+++ b/config/hosts.json
@@ -1 +1 @@
-["45.32.116.160", "103.224.251.67", "119.188.210.21", "183.60.107.171", "125.88.182.172"]
\ No newline at end of file
+[ "119.147.144.34", "103.224.251.67","45.76.53.20","120.206.184.160","[2001:19f0:7001:54fc:5400:2ff:fe9b:97f9]", "45.32.116.160", "[240e:ff:9000:1100:0:3:0:34]" ]
\ No newline at end of file
diff --git a/config/menu.json b/config/menu.json
index 028ef870..8959d033 100644
--- a/config/menu.json
+++ b/config/menu.json
@@ -48,32 +48,40 @@
"id": "memuAfiles",
"sort": 7
},
+ {
+ "title": "Terminal",
+ "href": "/xterm",
+ "class": "menu_xterm",
+ "id": "memuAxterm",
+ "sort": 8
+ },
{
"title": "Cron",
"href": "/crontab",
"class": "menu_day",
"id": "memuAcrontab",
- "sort": 8
+ "sort": 9
},
+
{
"title": "App Store",
"href": "/soft",
"class": "menu_soft",
"id": "memuAsoft",
- "sort": 9
+ "sort": 10
},
{
"title": "Settings",
"href": "/config",
"class": "menu_set",
"id": "memuAconfig",
- "sort": 10
+ "sort": 11
},
{
"title": "Log out",
"href": "/login?dologin=True",
"class": "menu_exit",
"id": "dologin",
- "sort": 11
+ "sort": 12
}
]
\ No newline at end of file
diff --git a/data/default.db b/data/default.db
index d673496b..e801a831 100644
Binary files a/data/default.db and b/data/default.db differ
diff --git a/data/node.json b/data/node.json
index 54be8df0..3824c76d 100644
--- a/data/node.json
+++ b/data/node.json
@@ -29,12 +29,6 @@
"port": "80",
"ping": 500
},
- {
- "protocol": "http://",
- "address": "125.88.182.172",
- "port": "5880",
- "ping": 500
- },
{
"protocol": "http://",
"address": "123.129.198.197",
diff --git a/init.sh b/init.sh
index 557ddac5..9aec922a 100644
--- a/init.sh
+++ b/init.sh
@@ -304,6 +304,7 @@ case "$1" in
$pythonV $panel_path/tools.py cli $2
;;
'default')
+ LOCAL_IP=$(ip addr | grep -E -o '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | grep -E -v "^127\.|^255\.|^0\." | head -n 1)
port=$(cat $panel_path/data/port.pl)
password=$(cat $panel_path/default.pl)
if [ -f $panel_path/data/domain.conf ];then
@@ -322,7 +323,8 @@ case "$1" in
echo -e "=================================================================="
echo -e "\033[32maaPanel default info!\033[0m"
echo -e "=================================================================="
- echo "Bt-Panel-URL: $pool://$address:$port$auth_path"
+ echo "aaPanel Internet Address: $pool://$address:$port$auth_path"
+ echo "aaPanel Internal Address: $pool://${LOCAL_IP}:$port$auth_path"
echo -e `$pythonV $panel_path/tools.py username`
echo -e "password: $password"
echo -e "\033[33mWarning:\033[0m"
diff --git a/script/logsBackup b/script/logsBackup
index d0ae72c7..943299e0 100644
--- a/script/logsBackup
+++ b/script/logsBackup
@@ -21,31 +21,55 @@ if os.path.exists('/www/server/nginx/logs/nginx.pid'): is_nginx = True
px = '.log'
if not is_nginx: px = '-access_log'
-def split_logs(oldFileName,num):
- global logsPath
- if not os.path.exists(oldFileName):
- print('|---'+oldFileName+'file does not exist!')
- return
+def build_errlog(sitename):
+ if is_nginx:
+ log = sitename + '.error.log'
+ elif os.path.exists('/usr/local/lsws/bin/lswsctrl'):
+ log = sitename + '_ols.error_log'
+ else:
+ log = sitename + '-error_log'
+ return log
- logs=sorted(glob.glob(oldFileName+"_*"))
+def clean_backlog(logname,num):
+ logs=sorted(glob.glob(logname+"_*"))
count=len(logs)
num=count - num
for i in range(count):
if i>num: break;
os.remove(logs[i])
- print('|---Extra log ['+logs[i]+'] has been deleted!')
+ print('|---The extra log ['+logs[i]+'] has been deleted!')
+
+def split_logs(oldFileName,num,site_name):
+ global logsPath
+ errlog_name = build_errlog(site_name)
+ old_errlog = logsPath + errlog_name
+
+ if not os.path.exists(oldFileName):
+ print('|---'+oldFileName+'file does not exist!')
+ return
+
+ clean_backlog(oldFileName,num)
+ clean_backlog(old_errlog,num)
newFileName=oldFileName+'_'+time.strftime("%Y-%m-%d_%H%M%S")+'.log'
shutil.move(oldFileName,newFileName)
- os.system("gzip %s" % newFileName)
- print('|---The log has been cut to: '+newFileName+'.gz')
+ new_errlog = old_errlog+'_'+time.strftime("%Y-%m-%d_%H%M%S")+'.log'
+ shutil.move(old_errlog, new_errlog)
+ if not os.path.exists('/www/server/panel/data/log_not_gzip.pl'):
+ os.system("gzip %s" % newFileName)
+ os.system("gzip %s" % new_errlog)
+ print('|---The log has been cut to:' + newFileName + '.gz')
+ print('|---The log has been cut to:' + new_errlog + '.gz')
+ else:
+ print('|---The log has been cut to:'+newFileName+'.log')
+ print('|---The log has been cut to:' + new_errlog + '.log')
def split_all(save):
sites = public.M('sites').field('name').select()
for site in sites:
oldFileName = logsPath + site['name'] + px
- split_logs(oldFileName,save)
+ split_logs(oldFileName,save,site['name'])
if __name__ == '__main__':
num = int(sys.argv[2])
@@ -53,14 +77,18 @@ if __name__ == '__main__':
split_all(num)
else:
siteName = sys.argv[1]
- if siteName[-4:] == '.log':
+ if siteName[-4:] == '.log':
siteName = siteName[:-4]
- else:
+ elif siteName[-11:] == '-access_log':
siteName = siteName.replace("-access_log",'')
+ else:
+ siteName = siteName.replace("_ols.access_log", '')
oldFileName = logsPath+sys.argv[1]
- split_logs(oldFileName,num)
+ split_logs(oldFileName,num,siteName)
if is_nginx:
- os.system("kill -USR1 `cat /www/server/nginx/logs/nginx.pid`");
+ os.system("kill -USR1 `cat /www/server/nginx/logs/nginx.pid`")
+ elif os.path.exists('/usr/local/lsws/bin/lswsctl'):
+ os.system('/usr/local/lsws/bin/lswsctl restart')
else:
- os.system('/etc/init.d/httpd reload');
\ No newline at end of file
+ os.system('/etc/init.d/httpd reload')
\ No newline at end of file
diff --git a/script/logsBackup.py b/script/logsBackup.py
index 6d19f136..6daa506f 100644
--- a/script/logsBackup.py
+++ b/script/logsBackup.py
@@ -21,13 +21,17 @@ if os.path.exists('/www/server/nginx/logs/nginx.pid'): is_nginx = True
px = '.log'
if not is_nginx: px = '-access_log'
-def split_logs(oldFileName,num):
- global logsPath
- if not os.path.exists(oldFileName):
- print('|---'+oldFileName+'file does not exist!')
- return
+def build_errlog(sitename):
+ if is_nginx:
+ log = sitename + '.error.log'
+ elif os.path.exists('/usr/local/lsws/bin/lswsctl'):
+ log = sitename + '-error_log'
+ else:
+ log = sitename + '_ols.error_log'
+ return log
- logs=sorted(glob.glob(oldFileName+"_*"))
+def clean_backlog(logname,num):
+ logs=sorted(glob.glob(logname+"_*"))
count=len(logs)
num=count - num
@@ -36,16 +40,33 @@ def split_logs(oldFileName,num):
os.remove(logs[i])
print('|---The extra log ['+logs[i]+'] has been deleted!')
+def split_logs(oldFileName,num,site_name):
+ global logsPath
+ errlog_name = build_errlog(site_name)
+ old_errlog = logsPath + errlog_name
+ if not os.path.exists(oldFileName):
+ print('|---'+oldFileName+'file does not exist!')
+ return
+
+ clean_backlog(oldFileName,num)
+ clean_backlog(old_errlog,num)
+
newFileName=oldFileName+'_'+time.strftime("%Y-%m-%d_%H%M%S")+'.log'
shutil.move(oldFileName,newFileName)
- os.system("gzip %s" % newFileName)
- print('|---The log has been cut to:'+newFileName+'.gz')
+ new_errlog = build_errlog(site_name)+'_'+time.strftime("%Y-%m-%d_%H%M%S")+'.log'
+ shutil.move(old_errlog, newFileName)
+ if not os.path.exists('/www/server/panel/data/log_not_gzip.pl'):
+ os.system("gzip %s" % newFileName)
+ os.system("gzip %s" % new_errlog)
+ print('|---The log has been cut to:' + newFileName + '.gz')
+ else:
+ print('|---The log has been cut to:'+newFileName+'.log')
def split_all(save):
sites = public.M('sites').field('name').select()
for site in sites:
oldFileName = logsPath + site['name'] + px
- split_logs(oldFileName,save)
+ split_logs(oldFileName,save,site['name'])
if __name__ == '__main__':
num = int(sys.argv[2])
@@ -53,14 +74,18 @@ if __name__ == '__main__':
split_all(num)
else:
siteName = sys.argv[1]
- if siteName[-4:] == '.log':
+ if siteName[-4:] == '.log':
siteName = siteName[:-4]
- else:
+ elif siteName[-11:] == '-access_log':
siteName = siteName.replace("-access_log",'')
+ else:
+ siteName = siteName.replace("_ols.access_log", '')
oldFileName = logsPath+sys.argv[1]
- split_logs(oldFileName,num)
+ split_logs(oldFileName,num,siteName)
if is_nginx:
- os.system("kill -USR1 `cat /www/server/nginx/logs/nginx.pid`");
+ os.system("kill -USR1 `cat /www/server/nginx/logs/nginx.pid`")
+ elif os.path.exists('/usr/local/lsws/bin/lswsctl'):
+ os.system('/usr/local/lsws/bin/lswsctl restart')
else:
- os.system('/etc/init.d/httpd reload');
\ No newline at end of file
+ os.system('/etc/init.d/httpd reload')
\ No newline at end of file
diff --git a/task.py b/task.py
index bd584552..a153483a 100644
--- a/task.py
+++ b/task.py
@@ -14,6 +14,7 @@
import sys
import os
+import logging
from json import dumps,loads
from psutil import Process,pids,cpu_count,cpu_percent,net_io_counters,disk_io_counters,virtual_memory
sys.path.insert(0,"/www/server/panel/class/")
@@ -21,7 +22,6 @@ import db
import public
import time
import panelTask
-import setPanelLets
global pre,timeoutCount,logPath,isTask,oldEdate,isCheck
pre = 0
timeoutCount = 0
@@ -30,29 +30,23 @@ oldEdate = None
logPath = '/tmp/panelExec.log'
isTask = '/tmp/panelTask.pl'
-class MyBad():
- _msg = None
- def __init__(self,msg):
- self._msg = msg
- def __repr__(self):
- return self._msg
-
+def get_python_bin():
+ bin_file = '/www/server/panel/pyenv/bin/python'
+ if os.path.exists(bin_file):
+ return bin_file
+ return '/usr/bin/python'
-def ExecShell(cmdstring, cwd=None, timeout=None, shell=True):
- try:
- global logPath
- import shlex
- import datetime
- import subprocess
- import time
- sub = subprocess.Popen(cmdstring+' &> '+logPath, cwd=cwd, stdin=subprocess.PIPE,shell=shell,bufsize=4096)
-
- while sub.poll() is None:
- time.sleep(0.1)
-
- return sub.returncode
- except:
- return None
+def ReadFile(filename,mode = 'r'):
+ """
+ 读取文件内容
+ @filename 文件名
+ return string(bin) 若文件不存在,则返回None
+ """
+ if not os.path.exists(filename): return False
+ f_body = None
+ with open(filename, mode) as fp:
+ f_body = fp.read()
+ return f_body
#下载文件
def DownloadFile(url,filename):
@@ -60,7 +54,7 @@ def DownloadFile(url,filename):
import urllib,socket
socket.setdefaulttimeout(10)
urllib.urlretrieve(url,filename=filename ,reporthook= DownloadHook)
- public.ExecShell('chown www.www ' + filename)
+ os.system('chown www.www ' + filename)
WriteLogs('done')
except:
WriteLogs('done')
@@ -82,41 +76,62 @@ def DownloadHook(count, blockSize, totalSize):
def WriteLogs(logMsg):
try:
global logPath
- fp = open(logPath,'w+')
- fp.write(logMsg)
- fp.close()
+ with open(logPath,'w+') as fp:
+ fp.write(logMsg)
+ fp.close()
except:
pass
-#任务队列
+
+def ExecShell(cmdstring, cwd=None, timeout=None, shell=True):
+ try:
+ global logPath
+ import shlex
+ import datetime
+ import subprocess
+ import time
+ sub = subprocess.Popen(cmdstring+' &> '+logPath, cwd=cwd, stdin=subprocess.PIPE,shell=shell,bufsize=4096)
+
+ while sub.poll() is None:
+ time.sleep(0.1)
+
+ return sub.returncode
+ except:
+ return None
+
+
+#任务队列
def startTask():
global isTask
try:
while True:
try:
if os.path.exists(isTask):
- sql = db.Sql()
- sql.table('tasks').where("status=?",('-1',)).setField('status','0')
- taskArr = sql.table('tasks').where("status=?",('0',)).field('id,type,execstr').order("id asc").select()
- for value in taskArr:
- start = int(time.time())
- if not sql.table('tasks').where("id=?",(value['id'],)).count(): continue
- sql.table('tasks').where("id=?",(value['id'],)).save('status,start',('-1',start))
- if value['type'] == 'download':
- argv = value['execstr'].split('|bt|')
- DownloadFile(argv[0],argv[1])
- elif value['type'] == 'execshell':
- ExecShell(value['execstr'])
- end = int(time.time())
- sql.table('tasks').where("id=?",(value['id'],)).save('status,end',('1',end))
- if(sql.table('tasks').where("status=?",('0')).count() < 1):
- if os.path.exists(isTask): os.remove(isTask)
- #ExecShell('rm -f ' + isTask)
+ with db.Sql() as sql:
+ sql.table('tasks').where("status=?",('-1',)).setField('status','0')
+ taskArr = sql.table('tasks').where("status=?",('0',)).field('id,type,execstr').order("id asc").select()
+ for value in taskArr:
+ start = int(time.time())
+ if not sql.table('tasks').where("id=?",(value['id'],)).count(): continue
+ sql.table('tasks').where("id=?",(value['id'],)).save('status,start',('-1',start))
+ if value['type'] == 'download':
+ argv = value['execstr'].split('|bt|')
+ DownloadFile(argv[0],argv[1])
+ elif value['type'] == 'execshell':
+ ExecShell(value['execstr'])
+ end = int(time.time())
+ sql.table('tasks').where("id=?",(value['id'],)).save('status,end',('1',end))
+ if(sql.table('tasks').where("status=?",('0')).count() < 1):
+ if os.path.exists(isTask): os.remove(isTask)
+ #ExecShell('rm -f ' + isTask)
+ sql.close()
+ taskArr = None
except:
pass
siteEdate()
time.sleep(2)
- except:
+ except Exception as ex:
+ logging.debug(ex)
time.sleep(60)
startTask()
@@ -124,22 +139,14 @@ def startTask():
def siteEdate():
global oldEdate
try:
- if not oldEdate: oldEdate = public.readFile('data/edate.pl')
+ if not oldEdate: oldEdate = ReadFile('data/edate.pl')
if not oldEdate: oldEdate = '0000-00-00'
mEdate = time.strftime('%Y-%m-%d',time.localtime())
if oldEdate == mEdate: return False
- edateSites = public.M('sites').where('edate>? AND edate AND (status=? OR status=?)',('0000-00-00',mEdate,1,u'running')).field('id,name').select()
- import panelSite
- siteObject = panelSite.panelSite()
- for site in edateSites:
- get = MyBad('')
- get.id = site['id']
- get.name = site['name']
- siteObject.SiteStop(get)
- oldEdate = mEdate
- public.writeFile('data/edate.pl',mEdate)
- except:
- pass
+ os.system(get_python_bin() + " /www/server/panel/script/site_task.py > /dev/null")
+ except Exception as ex:
+ logging.debug(ex)
+ pass
def GetLoadAverage():
c = os.getloadavg()
@@ -157,8 +164,9 @@ def GetLoadAverage():
def systemTask():
try:
filename = 'data/control.conf'
- sql = db.Sql().dbfile('system')
- csql = '''CREATE TABLE IF NOT EXISTS `load_average` (
+ with db.Sql() as sql:
+ sql = sql.dbfile('system')
+ csql = '''CREATE TABLE IF NOT EXISTS `load_average` (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`pro` REAL,
`one` REAL,
@@ -166,7 +174,9 @@ def systemTask():
`fifteen` REAL,
`addtime` INTEGER
)'''
- sql.execute(csql,())
+ sql.execute(csql,())
+ sql.close()
+
count = 0
reloadNum=0
network_up = network_down = diskio_1 = diskio_2 = networkInfo = cpuInfo = diskInfo = None
@@ -177,7 +187,7 @@ def systemTask():
day = 30
try:
- day = int(public.readFile(filename))
+ day = int(ReadFile(filename))
if day < 1:
time.sleep(10)
continue
@@ -243,14 +253,15 @@ def systemTask():
diskInfo['write_time'] += tmp['write_time']
diskio_1 = diskio_2
- except:disk_ios = False
+ except:
+ logging.info(public.get_error_info())
+ disk_ios = False
#print diskInfo
if count >= 12:
try:
- sql.close()
sql = db.Sql().dbfile('system')
addtime = int(time.time())
deltime = addtime - (day * 86400)
@@ -272,23 +283,26 @@ def systemTask():
lpro = round((load_average['one'] / load_average['max']) * 100,2)
if lpro > 100: lpro = 100
sql.table('load_average').add('pro,one,five,fifteen,addtime',(lpro,load_average['one'],load_average['five'],load_average['fifteen'],addtime))
-
+ sql.close()
+
lpro = None
load_average = None
cpuInfo = None
networkInfo = None
diskInfo = None
+ data = None
count = 0
reloadNum += 1
if reloadNum > 1440:
reloadNum = 0
except Exception as ex:
- print(str(ex))
+ logging.debug(str(ex))
del(tmp)
time.sleep(5)
count +=1
- except:
+ except Exception as ex:
+ logging.debug(ex)
time.sleep(30)
systemTask()
@@ -307,15 +321,15 @@ def GetMemUsed():
#检查502错误
def check502():
try:
- phpversions = ['53','54','55','56','70','71','72','73','74']
+ phpversions = ['53','54','55','56','70','71','72','73','74','80']
for version in phpversions:
php_path = '/www/server/php/' + version + '/sbin/php-fpm'
if not os.path.exists(php_path): continue
if checkPHPVersion(version): continue
if startPHPVersion(version):
- public.WriteLog('PHP守护程序','检测到PHP-' + version + '处理异常,已自动修复!')
- except:
- pass
+ public.WriteLog('PHP daemon','PHP-' + version + 'processing exception was detected and has been automatically fixed!',not_web = True)
+ except Exception as ex:
+ logging.info(ex)
#处理指定PHP版本
def startPHPVersion(version):
@@ -327,105 +341,44 @@ def startPHPVersion(version):
return False
#尝试重载服务
- public.ExecShell(fpm + ' reload')
+ os.system(fpm + ' reload')
if checkPHPVersion(version): return True
#尝试重启服务
cgi = '/tmp/php-cgi-'+version + '.sock'
pid = '/www/server/php/'+version+'/var/run/php-fpm.pid'
- public.ExecShell('pkill -9 php-fpm-'+version)
+ os.system('pkill -9 php-fpm-'+version)
time.sleep(0.5)
- if not os.path.exists(cgi): public.ExecShell('rm -f ' + cgi)
- if not os.path.exists(pid): public.ExecShell('rm -f ' + pid)
- public.ExecShell(fpm + ' start')
+ if not os.path.exists(cgi): os.system('rm -f ' + cgi)
+ if not os.path.exists(pid): os.system('rm -f ' + pid)
+ os.system(fpm + ' start')
if checkPHPVersion(version): return True
#检查是否正确启动
if os.path.exists(cgi): return True
- except:
+ except Exception as ex:
+ logging.debug(ex)
return True
#检查指定PHP版本
def checkPHPVersion(version):
try:
- url = 'http://127.0.0.1/phpfpm_'+version+'_status'
- result = HttpGet(url)
- #检查nginx
- if result.find('Bad Gateway') != -1: return False
- #检查Apache
- if result.find('Service Unavailable') != -1: return False
- if result.find('Not Found') != -1: CheckPHPINFO()
-
- #检查Web服务是否启动
- if result.find('Connection refused') != -1:
- global isTask
- if os.path.exists(isTask):
- isStatus = public.readFile(isTask)
- if isStatus == 'True': return True
- filename = '/etc/init.d/nginx'
- if os.path.exists(filename): public.ExecShell(filename + ' start')
- filename = '/etc/init.d/httpd'
- if os.path.exists(filename): public.ExecShell(filename + ' start')
-
+ uri = "/phpfpm_"+version+"_status?json"
+ result = public.request_php(version,uri,'')
+ loads(result)
return True
except:
- return True
+ logging.info("PHP-{} unreachable detected".format(version))
+ return False
-#检测PHPINFO配置
-def CheckPHPINFO():
- php_versions = ['53','54','55','56','70','71','72','73','74']
- setupPath = '/www/server'
- path = setupPath +'/panel/vhost/nginx/phpinfo.conf'
- if not os.path.exists(path):
- opt = ""
- for version in php_versions:
- opt += "\n\tlocation /"+version+" {\n\t\tinclude enable-php-"+version+".conf;\n\t}"
-
- phpinfoBody = '''server
-{
- listen 80;
- server_name 127.0.0.2;
- allow 127.0.0.1;
- index phpinfo.php index.html index.php;
- root /www/server/phpinfo;
-%s
-}''' % (opt,)
- public.writeFile(path,phpinfoBody)
-
-
- path = setupPath + '/panel/vhost/apache/phpinfo.conf'
- if not os.path.exists(path):
- opt = ""
- for version in php_versions:
- opt += """\n
- SetHandler "proxy:unix:/tmp/php-cgi-%s.sock|fcgi://localhost"
- """ % (version,version)
-
- phpinfoBody = '''
-
-DocumentRoot "/www/server/phpinfo"
-ServerAdmin phpinfo
-ServerName 127.0.0.2
-%s
-
- SetOutputFilter DEFLATE
- Options FollowSymLinks
- AllowOverride All
- Order allow,deny
- Allow from all
- DirectoryIndex index.php index.html index.htm default.php default.html default.htm
-
-
-''' % (opt,)
- public.writeFile(path,phpinfoBody)
-
#502错误检查线程
def check502Task():
try:
while True:
if os.path.exists('/www/server/panel/data/502Task.pl'): check502()
+ sess_expire()
time.sleep(600)
except:
time.sleep(600)
@@ -456,7 +409,7 @@ def panel_status():
pool = 'http://'
if os.path.exists(panel_path + '/data/ssl.pl'): pool = 'https://'
port = '8888'
- if os.path.exists(panel_path + '/data/port.pl'): port = public.readFile(panel_path + '/data/port.pl').strip()
+ if os.path.exists(panel_path + '/data/port.pl'): port = ReadFile(panel_path + '/data/port.pl').strip()
panel_url = pool + '127.0.0.1:' + port + '/service_status'
panel_pid = get_panel_pid()
n = 0
@@ -464,7 +417,6 @@ def panel_status():
v = 0
while True:
time.sleep(5)
- check_session()
if not panel_pid: panel_pid = get_panel_pid()
if not panel_pid: service_panel('start')
@@ -496,11 +448,11 @@ def panel_status():
if e_body.find('table session') != -1:
sess_file = '/dev/shm/session.db'
if os.path.exists(sess_file): os.remove(sess_file)
- public.ExecShell("bash /www/server/panel/init.sh reload &")
+ os.system("bash /www/server/panel/init.sh reload &")
time.sleep(10)
result = HttpGet(panel_url)
if result == 'True':
- public.WriteLog('TYPE_SOFE','Checked to panel service exception, has been automatically restored!')
+ public.WriteLog('TYPE_SOFE','Checked to panel service exception, has been automatically restored!',not_web = True)
if n > 18000:
n = 0
@@ -511,7 +463,7 @@ def panel_status():
update_panel()
result = HttpGet(panel_url)
if result == 'True':
- public.WriteLog('TYPE_SOFE','Checked to panel service exception, has been automatically restored!')
+ public.WriteLog('TYPE_SOFE','Checked to panel service exception, has been automatically restored!',not_web = True)
time.sleep(10)
continue
@@ -523,29 +475,7 @@ def service_panel(action = 'reload'):
if not os.path.exists('/www/server/panel/init.sh'):
update_panel()
else:
- public.ExecShell("bash /www/server/panel/init.sh {} &".format(action))
-
-
-def check_session():
- try:
- session_file = '/dev/shm/session.db'
- if not os.path.exists(session_file): #如果session文件不存在
- return False
- s_size = os.path.getsize(session_file)
- if s_size < 1024 * 1024 * 2: return False
- if s_size > 1024 * 1024 * 10:
- #大于10MB
- if os.path.exists(session_file): os.remove(session_file)
- public.ExecShell("bash /www/server/panel/init.sh reload &")
- else:
- sql = db.Sql()
- sql._Sql__DB_FILE = session_file
- sql.table('session').where('expiry',(public.format_date())).delete()
- sql.table('session').execute('VACUUM',())
- sql.close()
- return True
- except:
- return False
+ os.system("bash /www/server/panel/init.sh {} &".format(action))
#重启面板服务
def restart_panel_service():
@@ -562,6 +492,8 @@ def restart_panel_service():
#取面板pid
def get_panel_pid():
+ pid = ReadFile('/www/server/panel/logs/panel.pid')
+ if pid: return int(pid)
for pid in pids():
try:
p = Process(pid)
@@ -574,33 +506,42 @@ def get_panel_pid():
def HttpGet(url,timeout = 6,headers = {}):
if sys.version_info[0] == 2:
try:
- import urllib2,ssl
- if sys.version_info[0] == 2:
- reload(urllib2)
- reload(ssl)
- try:
- ssl._create_default_https_context = ssl._create_unverified_context
- except:pass
+ import urllib2
req = urllib2.Request(url, headers = headers)
response = urllib2.urlopen(req,timeout = timeout,)
return response.read()
except Exception as ex:
+ logging.debug(str(ex))
return str(ex)
else:
try:
- import urllib.request,ssl
- try:
- ssl._create_default_https_context = ssl._create_unverified_context
- except:pass
+ import urllib.request
req = urllib.request.Request(url,headers = headers)
response = urllib.request.urlopen(req,timeout = timeout)
result = response.read()
if type(result) == bytes: result = result.decode('utf-8')
return result
except Exception as ex:
+ logging.debug("URL: {} => {}".format(url,ex))
return str(ex)
+#定时任务去检测邮件信息
+def send_mail_time():
+ p_path = '/www/server/panel/data/'
+ p_reload = p_path + '/send_to_user.pl'
+ if not os.path.exists(p_path):
+ return
+ while True:
+ try:
+ if os.path.exists(p_reload):
+ os.system(get_python_bin() + " /www/server/panel/script/mail_task.py > /dev/null")
+ os.remove(p_reload)
+ time.sleep(60)
+ except:
+ time.sleep(180)
+ send_mail_time()
+
def main():
main_pid = 'logs/task.pid'
if os.path.exists(main_pid):
@@ -619,13 +560,9 @@ def main():
sys.stdout.flush()
sys.stderr.flush()
task_log_file='logs/task.log'
- if not os.path.exists(task_log_file):
- open(task_log_file,'w+').close()
- err_f = open(task_log_file,'a+')
- os.dup2(err_f.fileno(),sys.stderr.fileno())
- err_f.close()
- public.ExecShell('rm -rf /www/server/phpinfo/*')
+ logging.basicConfig(level = logging.DEBUG,format = '%(asctime)s [%(levelname)s] at %(lineno)d: %(message)s',datefmt = '%Y-%m-%d(%a)%H:%M:%S',filename = task_log_file,filemode = 'a+')
+ logging.info('Service started')
import threading
t = threading.Thread(target=systemTask)
@@ -648,7 +585,12 @@ def main():
p.setDaemon(True)
p.start()
+ p = threading.Thread(target=send_mail_time)
+ p.setDaemon(True)
+ p.start()
+
task_obj = panelTask.bt_task()
+ task_obj.not_web = True
p = threading.Thread(target=task_obj.start_task)
p.setDaemon(True)
p.start()