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