|
| 1 | +// This is a custom AttachAddon implementation |
| 2 | + |
| 3 | +function addSocketListener(socket, type, handler) { |
| 4 | + socket.addEventListener(type, handler); |
| 5 | + return { |
| 6 | + dispose: () => { |
| 7 | + if (!handler) { |
| 8 | + // Already disposed |
| 9 | + return; |
| 10 | + } |
| 11 | + socket.removeEventListener(type, handler); |
| 12 | + } |
| 13 | + }; |
| 14 | +} |
| 15 | + |
| 16 | +export class AttachAddon { |
| 17 | + constructor(socket, options) { |
| 18 | + this._socket = socket; |
| 19 | + // always set binary type to arraybuffer, we do not handle blobs |
| 20 | + this._socket.binaryType = 'arraybuffer'; |
| 21 | + this._bidirectional = (options && options.bidirectional === false) ? false : true; |
| 22 | + this._disposables = []; |
| 23 | + } |
| 24 | + |
| 25 | + activate(terminal) { |
| 26 | + this._disposables.push( |
| 27 | + addSocketListener(this._socket, 'message', ev => { |
| 28 | + const data = ev.data; |
| 29 | + if (typeof data === 'string') { |
| 30 | + const message = JSON.parse(data); |
| 31 | + if (message.content) { |
| 32 | + terminal.write(message.content); |
| 33 | + } |
| 34 | + } else { |
| 35 | + terminal.write(new Uint8Array(data)); |
| 36 | + } |
| 37 | + }) |
| 38 | + ); |
| 39 | + |
| 40 | + if (this._bidirectional) { |
| 41 | + this._disposables.push(terminal.onData(data => this._sendData(data))); |
| 42 | + this._disposables.push(terminal.onBinary(data => this._sendBinary(data))); |
| 43 | + } |
| 44 | + |
| 45 | + this._disposables.push(addSocketListener(this._socket, 'close', () => this.dispose())); |
| 46 | + this._disposables.push(addSocketListener(this._socket, 'error', () => this.dispose())); |
| 47 | + } |
| 48 | + |
| 49 | + dispose() { |
| 50 | + this._disposables.forEach(d => d.dispose()); |
| 51 | + } |
| 52 | + |
| 53 | + _sendData(data) { |
| 54 | + // TODO: do something better than just swallowing |
| 55 | + // the data if the socket is not in a working condition |
| 56 | + if (this._socket.readyState !== 1) { |
| 57 | + return; |
| 58 | + } |
| 59 | + this._socket.send(JSON.stringify({data})); |
| 60 | + } |
| 61 | + |
| 62 | + _sendBinary(data) { |
| 63 | + if (this._socket.readyState !== 1) { |
| 64 | + return; |
| 65 | + } |
| 66 | + const buffer = new Uint8Array(data.length); |
| 67 | + for (let i = 0; i < data.length; ++i) { |
| 68 | + buffer[i] = data.charCodeAt(i) & 255; |
| 69 | + } |
| 70 | + this._socket.send(buffer); |
| 71 | + } |
| 72 | +} |
0 commit comments