forked from glacambre/firenvim
-
Notifications
You must be signed in to change notification settings - Fork 0
/
NeovimFrame.ts
260 lines (245 loc) · 12 KB
/
NeovimFrame.ts
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
import { neovim } from "./nvimproc/Neovim";
import { page } from "./page/proxy";
import { getGridId, getWindowId, onKeyPressed as rendererOnKeyPressed, selectWindow } from "./render/Redraw";
import { confReady, getConfForUrl, getGlobalConf } from "./utils/configuration";
import { addModifier, nonLiteralKeys, translateKey } from "./utils/keys";
import { getCharSize, getGridSize, isFirefox, toFileName } from "./utils/utils";
const frameIdPromise = browser
.runtime
.sendMessage({ funcName: ["publishFrameId"] })
.then((f: number) => (window as any).frameId = f);
const infoPromise = frameIdPromise.then(() => page.getEditorInfo());
const connectionPromise = browser.runtime.sendMessage({ funcName: ["getNeovimInstance"] });
export const isReady = new Promise((resolve, reject) => {
window.addEventListener("load", async () => {
try {
const host = document.getElementById("host") as HTMLPreElement;
const extCmdline = document.getElementById("ext_cmdline") as HTMLSpanElement;
const extMessages = document.getElementById("ext_messages") as HTMLSpanElement;
const keyHandler = document.getElementById("keyhandler");
const [[url, selector, cursor, language], connectionData] =
await Promise.all([infoPromise, connectionPromise]);
const nvimPromise = neovim(host, extCmdline, extMessages, connectionData);
const contentPromise = page.getElementContent();
const [cols, rows] = getGridSize(host);
const nvim = await nvimPromise;
// We need to set client info before running ui_attach because we want this
// info to be available when UIEnter is triggered
const extInfo = browser.runtime.getManifest();
const [major, minor, patch] = extInfo.version.split(".");
nvim.set_client_info(extInfo.name + Math.random(),
{ major, minor, patch },
"ui",
{},
{},
);
await confReady;
const settings = getGlobalConf();
const persistent = settings.server === "persistent";
nvim.ui_attach(cols, rows, {
ext_linegrid: true,
ext_messages: getConfForUrl(url).cmdline === "firenvim" || persistent,
ext_multigrid: persistent,
rgb: true,
});
let resizeReqId = 0;
browser.runtime.onMessage.addListener((request: any, sender: any, sendResponse: any) => {
if (request.funcName[0] === "sendKey") {
nvim.input(request.args.join(""));
} else if (request.funcName[0] === "resize" && request.args[0] > resizeReqId) {
const [id, width, height] = request.args;
resizeReqId = id;
// We need to put the keyHandler at the origin in order to avoid
// issues when it slips out of the viewport
keyHandler.style.left = `0px`;
keyHandler.style.top = `0px`;
// It's tempting to try to optimize this by only calling
// ui_try_resize when nCols is different from cols and nRows is
// different from rows but we can't because redraw notifications
// might happen without us actually calling ui_try_resize and then
// the sizes wouldn't be in sync anymore
const [cellWidth, cellHeight] = getCharSize(host);
const nCols = Math.floor(width / cellWidth);
const nRows = Math.floor(height / cellHeight);
nvim.ui_try_resize_grid(getGridId(), nCols, nRows);
page.resizeEditor(nCols * cellWidth, nRows * cellHeight);
}
});
if (persistent) {
await nvim
.open_win(0, true, { width: cols, height: rows, focusable: true, external: true })
.then(selectWindow);
}
// Create file, set its content to the textarea's, write it
const filename = toFileName(url, selector, language);
const content = await contentPromise;
const [line, col] = cursor;
nvim.call_function("writefile", [content.split("\n"), filename])
.then(() => nvim.command(`noswapfile edit ${filename} `
+ `| call nvim_win_set_cursor(0, [${line}, ${col}])`));
window.addEventListener("beforeunload", () => {
nvim.ui_detach();
if (persistent) {
nvim.win_close(getWindowId(), true);
} else {
nvim.command("qall!");
}
});
// Keep track of last active instance (necessary for firenvim#focus_input() & others)
const chan = nvim.get_current_channel();
function setCurrentChan() {
nvim.set_var("last_focused_firenvim_channel", chan);
}
setCurrentChan();
window.addEventListener("focus", setCurrentChan);
window.addEventListener("click", setCurrentChan);
const augroupName = `FirenvimAugroupChan${chan}`;
// Cleanup means:
// - notify frontend that we're shutting down
// - delete file
// - remove own augroup
const cleanup = `call rpcnotify(${chan}, 'firenvim_vimleave') | `
+ `call delete('${filename}')`;
let winCleanup = "";
if (persistent) {
winCleanup = `autocmd WinClosed * `
+ `if expand("<afile>") == ${getWindowId()} | `
+ cleanup
+ ` | endif`;
}
// Ask for notifications when user writes/leaves firenvim
nvim.call_atomic((`augroup ${augroupName}
au!
autocmd BufWrite ${filename} `
+ `call rpcnotify(${chan}, `
+ `'firenvim_bufwrite', `
+ `{`
+ `'text': nvim_buf_get_lines(0, 0, -1, 0),`
+ `'cursor': nvim_win_get_cursor(0),`
+ `})
${winCleanup}
au VimLeave * ${cleanup}
augroup END`).split("\n").map(command => ["nvim_command", [command]]));
keyHandler.addEventListener("keydown", (evt) => {
if (evt.altKey && settings.alt === "alphanum" && !/[a-zA-Z0-9]/.test(evt.key)) {
return;
}
// Note: order of this array is important, we need to check OS before checking meta
const specialKeys = [["Alt", "A"], ["Control", "C"], ["OS", "D"], ["Meta", "D"]];
// The event has to be trusted and either have a modifier or a non-literal representation
if (evt.isTrusted
&& (nonLiteralKeys[evt.key] !== undefined
|| specialKeys.find(([mod, _]: [string, string]) =>
evt.key !== mod && (evt as any).getModifierState(mod)))) {
const text = specialKeys.concat([["Shift", "S"]])
.reduce((key: string, [attr, mod]: [string, string]) => {
if ((evt as any).getModifierState(attr)) {
return addModifier(mod, key);
}
return key;
}, translateKey(evt.key));
nvim.input(text);
evt.preventDefault();
evt.stopImmediatePropagation();
rendererOnKeyPressed(text);
}
});
function acceptInput (evt: any) {
nvim.input(evt.target.value);
evt.preventDefault();
evt.stopImmediatePropagation();
evt.target.innerText = "";
evt.target.value = "";
rendererOnKeyPressed(evt.target.value);
}
keyHandler.addEventListener("input", (evt: any) => {
if (evt.isTrusted && !evt.isComposing) {
acceptInput(evt);
}
});
// On Firefox, Pinyin input method for a single chinese character will
// result in the following sequence of events:
// - compositionstart
// - input (character)
// - compositionend
// - input (result)
// But on Chrome, we'll get this order:
// - compositionstart
// - input (character)
// - input (result)
// - compositionend
// So Chrome's input event will still have its isComposing flag set to
// true! This means that we need to add a chrome-specific event
// listener on compositionend to do what happens on input events for
// Firefox.
if (!isFirefox()) {
keyHandler.addEventListener("compositionend", (evt: any) => {
acceptInput(event);
});
}
window.addEventListener("mousemove", (evt: MouseEvent) => {
keyHandler.style.left = `${evt.clientX}px`;
keyHandler.style.top = `${evt.clientY}px`;
});
function onMouse(evt: MouseEvent, action: string) {
let button;
if (evt instanceof WheelEvent) {
button = "wheel";
} else {
if (evt.button !== 0 && evt.button !== 2) {
// Neovim doesn't handle other mouse buttons for now
return;
}
button = evt.button === 0 ? "left" : "right";
}
evt.preventDefault();
evt.stopImmediatePropagation();
const modifiers = (evt.altKey ? "A" : "") +
(evt.ctrlKey ? "V" : "") +
(evt.metaKey ? "D" : "") +
(evt.shiftKey ? "S" : "");
const [cWidth, cHeight] = getCharSize(host);
nvim.input_mouse(button,
action,
modifiers,
getGridId(),
Math.floor(evt.pageY / cHeight),
Math.floor(evt.pageX / cWidth));
keyHandler.focus();
setTimeout(() => keyHandler.focus(), 10);
}
window.addEventListener("mousedown", e => {
onMouse(e, "press");
});
window.addEventListener("mouseup", e => {
onMouse(e, "release");
});
window.addEventListener("wheel", evt => {
if (Math.abs(evt.deltaY) >= Math.abs(evt.deltaX)) {
onMouse(evt, evt.deltaY < 0 ? "up" : "down");
} else {
onMouse(evt, evt.deltaX < 0 ? "right" : "left");
}
});
// Let users know when they focus/unfocus the frame
window.addEventListener("focus", () => {
document.documentElement.style.opacity = "1";
keyHandler.focus();
nvim.command("doautocmd FocusGained");
});
window.addEventListener("blur", () => {
document.documentElement.style.opacity = "0.5";
nvim.command("doautocmd FocusLost");
});
keyHandler.focus();
setTimeout(() => {
keyHandler.focus();
resolve();
}, 10);
} catch (e) {
console.error(e);
page.killEditor();
reject();
}
});
});