-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
505 lines (472 loc) · 15.3 KB
/
index.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
const uuid = require("uuid");
const FollowerSession = require("./follower-session");
const INSERT_KEYS = "1";
const INIT_STATE = "2";
const CLIENT_CLOSE_PANE = "3";
const APPEND_TO_PANE = "4";
const NEW_TAB = "5";
const SERVER_CLOSE_PANE = "8";
const NEW_SPLIT = "9";
const RESIZE_PANE = "A";
const DEBUG_LOG = "B";
const INSERT_DEBUG_KEYS = "C";
const SESSION_END = "D";
const UUID_LENGTH = 36;
const htmInitRegexp = new RegExp(/\u001b\u005b###q/);
const htmExitRegexp = new RegExp(/\u001b\u005b\$\$\$q/);
var window = null;
const snooze = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const getFirstSessionId = (htmState, paneOrSplit) => {
if (htmState.panes[paneOrSplit]) {
return paneOrSplit;
} else {
return getFirstSessionId(
htmState,
htmState.splits[paneOrSplit].panesOrSplits[0]
);
}
};
const addToUidBimap = function (window, htmUid, hyperUid) {
console.log(
"MAPPING HTM TO HYPER: " +
htmUid +
" <-> " +
hyperUid +
" " +
typeof hyperUid
);
window.htmHyperUidMap.set(htmUid, hyperUid);
window.hyperHtmUidMap.set(hyperUid, htmUid);
};
const createSessionForSplit = async function (
window,
htmState,
panesOrSplits,
vertical,
i
) {
const sourceId = getFirstSessionId(htmState, panesOrSplits[i - 1]);
const newId = getFirstSessionId(htmState, panesOrSplits[i]);
window.nextSessionHtmId = newId;
if (vertical) {
window.rpc.emit("split request vertical", {
activeUid: window.htmHyperUidMap.get(sourceId),
});
} else {
window.rpc.emit("split request horizontal", {
activeUid: window.htmHyperUidMap.get(sourceId),
});
}
while (window.nextSessionHtmId) {
await snooze(1000);
}
window.initializedSessions.add(newId);
};
const createSplit = async function (window, htmState, split) {
const panesOrSplits = split.panesOrSplits;
// Create the top-level panes (except the first one, which already exists)
for (var a = 1; a < panesOrSplits.length; a++) {
await createSessionForSplit(
window,
htmState,
panesOrSplits,
split.vertical,
a
);
}
// Go through the list looking for splits and handling accordingly.
for (var a = 0; a < panesOrSplits.length; a++) {
const innerSplit = htmState.splits[panesOrSplits[a]];
if (innerSplit) {
// We found a split, recurse
await createSplit(window, htmState, innerSplit);
}
}
};
const createTab = async function (
window,
htmState,
currentTab,
previousTabHyperId
) {
// When we create a tab (a term group in hyperjs terms), we must also create a session.
// We pick the first session and create it with the tab
const firstSessionId = getFirstSessionId(htmState, currentTab.paneOrSplit);
window.nextSessionHtmId = firstSessionId;
console.log("CREATING TAB: " + window.nextSessionHtmId);
window.rpc.emit("termgroup add req", {
activeUid: previousTabHyperId,
});
while (window.nextSessionHtmId) {
console.log("WAITING FOR TAB TO EXIST");
await snooze(1000);
}
console.log("TAB EXISTS");
window.initializedSessions.add(firstSessionId);
if (htmState.splits && htmState.splits[currentTab.paneOrSplit]) {
await createSplit(
window,
htmState,
htmState.splits[currentTab.paneOrSplit]
);
}
const tabHyperId = window.htmHyperUidMap.get(firstSessionId);
if (tabHyperId) {
return tabHyperId;
} else {
throw Exception("Could not find hyper tab id");
}
};
const initHtm = async function (window, htmState) {
var previousTabHyperId = window.leaderHyperUid;
for (var order = 0; order < Object.keys(htmState.tabs).length; order++) {
for (var property in htmState.tabs) {
if (!htmState.tabs.hasOwnProperty(property)) {
continue;
}
// Values set to 0 are not defined in proto -> JSON
const tab = htmState.tabs[property];
if (
tab.order != order &&
!(typeof tab.order === "undefined" && order == 0)
) {
continue;
}
previousTabHyperId = await createTab(
window,
htmState,
tab,
previousTabHyperId
);
}
}
};
const processHtmData = function () {
if (window.sessions.size == 0) {
// The window has been cleaned up. Bail.
return;
}
while (window.htmBuffer.length >= 9) {
if (window.waitingForInit) {
setTimeout(function () {
processHtmData();
}, 100);
return;
}
const packetHeader = window.htmBuffer[0];
if (packetHeader == SESSION_END) {
console.log("Got shutdown");
console.log("Exiting HTM mode");
const sessionsToClose = [];
window.sessions.forEach((session, key) => {
if (key != window.leaderHyperUid) {
console.log("CLOSING " + key);
sessionsToClose.push(key);
} else {
console.log("NOT CLOSING: " + key);
}
});
// Reset htm state
window.leaderHyperUid = null;
window.initializedSessions.clear();
// Close all followers (slowly so the UI has time to adjust)
const closeSessions = function (i) {
if (i == sessionsToClose.length) {
return;
}
window.rpc.emit("session exit", { uid: sessionsToClose[i] });
window.sessions.delete(sessionsToClose[i]);
setTimeout(() => {
closeSessions(i + 1);
}, 100);
};
closeSessions(0);
return;
}
let buf = Buffer.from(window.htmBuffer.substring(1, 9), "base64");
let length = buf.readInt32LE(0);
if (length < 0) {
console.log("Invalid length, shutting down");
window.clean();
window.close();
return;
}
if (window.htmBuffer.length - 9 < length) {
// Not enough data
break;
}
switch (packetHeader) {
case INIT_STATE: {
const rawJsonData = window.htmBuffer.substring(9, 9 + length);
const htmState = JSON.parse(rawJsonData);
console.log("INITIALIZING HTM");
window.waitingForInit = true;
initHtm(window, htmState).then(() => {
setTimeout(() => {
window.waitingForInit = false;
}, 1000);
});
break;
}
case APPEND_TO_PANE: {
const sessionId = window.htmBuffer.substring(9, 9 + UUID_LENGTH);
var paneData = window.htmBuffer.substring(9 + UUID_LENGTH, 9 + length);
paneData = Buffer.from(paneData, "base64").toString("utf8");
window.rpc.emit(
"session data",
window.htmHyperUidMap.get(sessionId) + paneData
);
break;
}
case DEBUG_LOG: {
var paneData = window.htmBuffer.substring(9, 9 + length);
paneData = Buffer.from(paneData, "base64").toString("utf8");
console.log("GOT DEBUG LOG: " + paneData);
window.rpc.emit("session data", window.leaderHyperUid + paneData);
break;
}
case SERVER_CLOSE_PANE: {
const sessionId = window.htmBuffer.substring(9, 9 + UUID_LENGTH);
console.log("CLOSING SESSION " + sessionId);
window.rpc.emit("session exit", {
uid: window.htmHyperUidMap.get(sessionId),
});
window.sessions.delete(window.htmHyperUidMap.get(sessionId));
break;
}
default: {
// Ignore
console.error("Ignoring packet with header: " + packetHeader);
break;
}
}
window.htmBuffer = (" " + window.htmBuffer).slice(1 + 9 + length);
}
};
exports.decorateSessionClass = (Session) => {
if (window && window.leaderHyperUid) {
return class HtmFollowerSession extends Session {
constructor(options) {
super(options);
this.uid = options.uid;
console.log("CREATING FOLLOWING SESSION: " + options.uid);
if (window.nextSessionHtmId == null) {
this.htmId = uuid.v4();
addToUidBimap(window, this.htmId, options.uid);
if (options.splitDirection) {
// We are splitting an existing tab
const splitFromUid = window.hyperHtmUidMap.get(options.activeUid);
console.log(
"Creating new split for htm: " + options.uid + " -> " + this.htmId
);
const vertical = options.splitDirection == "VERTICAL";
const length = splitFromUid.length + this.htmId.length + 1;
const buf = Buffer.allocUnsafe(4);
buf.writeInt32LE(length, 0);
const b64Length = buf.toString("base64");
const directionString = vertical ? "1" : "0";
const packet =
NEW_SPLIT +
b64Length +
splitFromUid +
this.htmId +
directionString;
window.initializedSessions.add(this.htmId);
window.sessions.get(window.leaderHyperUid).pty.write(packet);
} else {
// We are creating a new tab. Get the termgroup uid and inform htm.
let tabUid = uuid.v4();
console.log(
"CREATING NEW TAB FOR HTM: " +
tabUid +
" " +
options.uid +
" -> " +
this.htmId
);
const length = tabUid.length + this.htmId.length;
const buf = Buffer.allocUnsafe(4);
buf.writeInt32LE(length, 0);
const b64Length = buf.toString("base64");
const packet = NEW_TAB + b64Length + tabUid + this.htmId;
window.initializedSessions.add(this.htmId);
window.sessions.get(window.leaderHyperUid).pty.write(packet);
}
} else {
this.htmId = window.nextSessionHtmId;
}
addToUidBimap(window, this.htmId, this.uid);
window.nextSessionHtmId = null;
console.log("DONE WITH CONSTRUCTOR");
}
init(_) {}
exit() {
this.destroy();
}
recieveData(data) {
this.emit("data", data);
}
write(data) {
if (!window.initializedSessions.has(this.htmId)) {
if (window.leaderHyperUid == null) {
// HTM has ended.
return;
}
console.log("Waiting to write to " + this.htmId);
setTimeout(() => {
this.write(data);
}, 100);
return;
}
const b64Data = Buffer.from(data).toString("base64");
const length = this.htmId.length + b64Data.length;
const buf = Buffer.allocUnsafe(4);
buf.writeInt32LE(length, 0);
const b64Length = buf.toString("base64");
const packet = INSERT_KEYS + b64Length + this.htmId + b64Data;
window.sessions.get(window.leaderHyperUid).pty.write(packet);
}
resize({ cols, rows }) {
if (!window.initializedSessions.has(this.htmId)) {
if (window.leaderHyperUid == null) {
// HTM has ended.
return;
}
console.log("Waiting to resize " + this.htmId);
setTimeout(() => {
this.resize({ cols, rows });
}, 100);
return;
}
const buf = Buffer.allocUnsafe(4);
buf.writeInt32LE(cols, 0);
const b64Cols = buf.toString("base64");
buf.writeInt32LE(rows, 0);
const b64Rows = buf.toString("base64");
const length = b64Cols.length + b64Rows.length + this.htmId.length;
buf.writeInt32LE(length, 0);
const b64Length = buf.toString("base64");
const packet = RESIZE_PANE + b64Length + b64Cols + b64Rows + this.htmId;
console.log("LEADER UID: " + window.leaderHyperUid);
window.sessions.get(window.leaderHyperUid).pty.write(packet);
}
destroy() {
console.log("Closing follower");
/*
const length = this.htmId.length;
const buf = Buffer.allocUnsafe(4);
buf.writeInt32LE(length, 0);
const b64Length = buf.toString('base64');
const packet = CLIENT_CLOSE_PANE + b64Length + this.htmId;
const leaderSession = window.sessions.get(window.leaderHyperUid);
if (leaderSession) {
leaderSession.pty.write(packet);
}
*/
this.emit("exit");
this.ended = true;
}
};
} else {
return class HtmLeaderSession extends Session {
constructor(options) {
super(options);
this.uid = options.uid;
}
init(options) {
super.init(options);
this.pty.removeAllListeners("data");
this.pty.on("data", (chunk) => {
if (this.ended) {
return;
}
this.read(chunk);
});
}
read(data) {
if (window.leaderHyperUid == this.uid) {
if (htmExitRegexp.test(data)) {
console.log("Exiting HTM mode");
const sessionsToClose = [];
window.sessions.forEach((session, key) => {
if (key != window.leaderHyperUid) {
console.log("CLOSING " + key);
sessionsToClose.push(key);
} else {
console.log("NOT CLOSING: " + key);
}
});
// Reset htm state
window.leaderHyperUid = null;
window.initializedSessions.clear();
// Close all followers (slowly so the UI has time to adjust)
const closeSessions = function (i) {
if (i == sessionsToClose.length) {
return;
}
window.rpc.emit("session exit", { uid: sessionsToClose[i] });
window.sessions.delete(sessionsToClose[i]);
setTimeout(() => {
closeSessions(i + 1);
}, 500);
};
closeSessions(0);
return;
}
window.htmBuffer += data;
processHtmData();
} else {
if (htmInitRegexp.test(data)) {
// TODO: Close all other window.sessions
console.log("Enabling HTM mode");
window.leaderHyperUid = this.uid;
window.htmBuffer = data.substring(data.search(htmInitRegexp) + 6);
processHtmData();
} else {
this.batcher.write(data);
}
}
}
destroy() {
if (window.leaderHyperUid && window.leaderHyperUid === this.uid) {
window.leaderHyperUid = null;
console.log("Closing leader");
// Closing the leader causes the entire window to collapse
window.clean();
window.close();
}
super.destroy();
}
write(data) {
if (this.uid == window.leaderHyperUid) {
const length = data.length;
const buf = Buffer.allocUnsafe(4);
buf.writeInt32LE(length, 0);
const b64Length = buf.toString("base64");
const packet = INSERT_DEBUG_KEYS + b64Length + data;
super.write(packet);
} else {
super.write(data);
}
}
};
}
};
exports.onWindow = function (window_) {
window = window_;
if (window.htmMode) {
// Already managed by a plugin
console.log("A plugin is already managing this window");
return;
}
window.htmMode = true;
window.waitingForInit = false;
window.leaderHyperUid = null;
window.nextSessionHtmId = null;
window.initializedSessions = new Set();
// This bimap is needed to avoid recycling uuids in hyper since hyper doesn't clean up window.sessions.
// Note that only follower window.sessions are mapped. The leader retains it's uuid.
window.htmHyperUidMap = new Map();
window.hyperHtmUidMap = new Map();
window.htmBuffer = "";
};