-
Notifications
You must be signed in to change notification settings - Fork 5.9k
/
Copy pathelectron.ts
473 lines (405 loc) · 12.5 KB
/
electron.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
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
/// <reference path="../../../../lib/vscode/src/typings/electron.d.ts" />
import { EventEmitter } from "events";
import * as fs from "fs";
import * as trash from "trash";
import { logger, field } from "@coder/logger";
import { IKey, Dialog as DialogBox } from "./dialog";
import { clipboard } from "./clipboard";
// tslint:disable-next-line no-any
(global as any).getOpenUrls = (): string[] => {
return [];
};
// This is required to make the fill load in Node without erroring.
if (typeof document === "undefined") {
// tslint:disable-next-line no-any
(global as any).document = {} as any;
}
const oldCreateElement = document.createElement;
const newCreateElement = <K extends keyof HTMLElementTagNameMap>(tagName: K): HTMLElementTagNameMap[K] => {
const createElement = <K extends keyof HTMLElementTagNameMap>(tagName: K): HTMLElementTagNameMap[K] => {
// tslint:disable-next-line:no-any
return oldCreateElement.call(document, tagName as any);
};
// tslint:disable-next-line:no-any
const getPropertyDescriptor = (object: any, id: string): PropertyDescriptor | undefined => {
let op = Object.getPrototypeOf(object);
while (!Object.getOwnPropertyDescriptor(op, id)) {
op = Object.getPrototypeOf(op);
}
return Object.getOwnPropertyDescriptor(op, id);
};
if (tagName === "img") {
const img = createElement("img");
const oldSrc = getPropertyDescriptor(img, "src");
if (!oldSrc) {
throw new Error("Failed to find src property");
}
Object.defineProperty(img, "src", {
get: (): string => {
return oldSrc!.get!.call(img);
},
set: (value: string): void => {
if (value) {
const resourceBaseUrl = location.pathname.replace(/\/$/, "") + "/resource";
value = value.replace(/file:\/\//g, resourceBaseUrl);
}
oldSrc!.set!.call(img, value);
},
});
return img;
}
if (tagName === "style") {
const style = createElement("style");
const oldInnerHtml = getPropertyDescriptor(style, "innerHTML");
if (!oldInnerHtml) {
throw new Error("Failed to find innerHTML property");
}
Object.defineProperty(style, "innerHTML", {
get: (): string => {
return oldInnerHtml!.get!.call(style);
},
set: (value: string): void => {
if (value) {
const resourceBaseUrl = location.pathname.replace(/\/$/, "") + "/resource";
value = value.replace(/file:\/\//g, resourceBaseUrl);
}
oldInnerHtml!.set!.call(style, value);
},
});
let overridden = false;
const oldSheet = getPropertyDescriptor(style, "sheet");
Object.defineProperty(style, "sheet", {
// tslint:disable-next-line:no-any
get: (): any => {
const sheet = oldSheet!.get!.call(style);
if (sheet && !overridden) {
const oldInsertRule = sheet.insertRule;
sheet.insertRule = (rule: string, index?: number): void => {
const resourceBaseUrl = location.pathname.replace(/\/$/, "") + "/resource";
rule = rule.replace(/file:\/\//g, resourceBaseUrl);
oldInsertRule.call(sheet, rule, index);
};
overridden = true;
}
return sheet;
},
});
return style;
}
if (tagName === "webview") {
const view = createElement("iframe") as HTMLIFrameElement;
view.style.border = "0px";
const frameID = Math.random().toString();
view.addEventListener("error", (event) => {
logger.error("iframe error", field("event", event));
});
window.addEventListener("message", (event) => {
if (!event.data || !event.data.id) {
return;
}
if (event.data.id !== frameID) {
return;
}
const e = new CustomEvent("ipc-message");
(e as any).channel = event.data.channel; // tslint:disable-line no-any
(e as any).args = event.data.data; // tslint:disable-line no-any
view.dispatchEvent(e);
});
view.sandbox.add("allow-same-origin", "allow-scripts", "allow-popups", "allow-forms");
Object.defineProperty(view, "preload", {
set: (url: string): void => {
view.onload = (): void => {
if (view.contentDocument) {
view.contentDocument.body.id = frameID;
view.contentDocument.body.parentElement!.style.overflow = "hidden";
const script = createElement("script");
script.src = url;
script.addEventListener("load", () => {
view.contentDocument!.dispatchEvent(new Event("DOMContentLoaded", {
bubbles: true,
cancelable: true,
}));
// const e = new CustomEvent("ipc-message");
// (e as any).channel = "webview-ready"; // tslint:disable-line no-any
// (e as any).args = [frameID]; // tslint:disable-line no-any
// view.dispatchEvent(e);
});
view.contentDocument.head.appendChild(script);
}
};
},
});
view.src = require("!!file-loader?name=[path][name].[ext]!./webview.html");
Object.defineProperty(view, "src", {
set: (): void => { /* Nope. */ },
});
(view as any).getWebContents = (): void => undefined; // tslint:disable-line no-any
(view as any).send = (channel: string, ...args: any[]): void => { // tslint:disable-line no-any
if (args[0] && typeof args[0] === "object" && args[0].contents) {
// TODO
const resourceBaseUrl = location.pathname.replace(/\/$/, "") + "/resource";
args[0].contents = (args[0].contents as string).replace(/"(file:\/\/[^"]*)"/g, (m1) => `"${resourceBaseUrl}${m1}"`);
args[0].contents = (args[0].contents as string).replace(/"vscode-resource:([^"]*)"/g, (m, m1) => `"${resourceBaseUrl}${m1}"`);
args[0].contents = (args[0].contents as string).replace(/style-src vscode-core-resource:/g, "style-src 'self'");
}
if (view.contentWindow) {
view.contentWindow.postMessage({
channel,
data: args,
id: frameID,
}, "*");
}
};
return view;
}
return createElement(tagName);
};
document.createElement = newCreateElement;
class Clipboard {
private readonly buffers = new Map<string, Buffer>();
public has(format: string): boolean {
return this.buffers.has(format);
}
public readFindText(): string {
return "";
}
public writeFindText(_text: string): void {
// Nothing.
}
public writeText(value: string): Promise<void> {
return clipboard.writeText(value);
}
public readText(): Promise<string> {
return clipboard.readText();
}
public writeBuffer(format: string, buffer: Buffer): void {
this.buffers.set(format, buffer);
}
public readBuffer(format: string): Buffer | undefined {
return this.buffers.get(format);
}
}
class Shell {
public async moveItemToTrash(path: string): Promise<void> {
await trash(path);
}
}
class App extends EventEmitter {
public isAccessibilitySupportEnabled(): boolean {
return false;
}
public setAsDefaultProtocolClient(): void {
throw new Error("not implemented");
}
}
class Dialog {
public showSaveDialog(_: void, options: Electron.SaveDialogOptions, callback: (filename: string | undefined) => void): void {
const defaultPath = options.defaultPath || "/untitled";
const fileIndex = defaultPath.lastIndexOf("/");
const extensionIndex = defaultPath.lastIndexOf(".");
const saveDialogOptions = {
buttons: ["Cancel", "Save"],
detail: "Enter a path for this file",
input: {
value: defaultPath,
selection: {
start: fileIndex === -1 ? 0 : fileIndex + 1,
end: extensionIndex === -1 ? defaultPath.length : extensionIndex,
},
},
message: "Save file",
};
const dialog = new DialogBox(saveDialogOptions);
dialog.onAction((action) => {
if (action.key !== IKey.Enter && action.buttonIndex !== 1) {
dialog.hide();
return callback(undefined);
}
const inputValue = dialog.inputValue || "";
const filePath = inputValue.replace(/\/+$/, "");
const split = filePath.split("/");
const fileName = split.pop();
const parentName = split.pop() || "/";
if (fileName === "") {
dialog.error = "You must enter a file name.";
return;
}
fs.stat(filePath, (error, stats) => {
if (error && error.code === "ENOENT") {
dialog.hide();
callback(filePath);
} else if (error) {
dialog.error = error.message;
} else if (stats.isDirectory()) {
dialog.error = `A directory named "${fileName}" already exists.`;
} else {
dialog.error = undefined;
const confirmDialog = new DialogBox({
message: `A file named "${fileName}" already exists. Do you want to replace it?`,
detail: `The file already exists in "${parentName}". Replacing it will overwrite its contents.`,
buttons: ["Cancel", "Replace"],
});
confirmDialog.onAction((action) => {
if (action.buttonIndex === 1) {
confirmDialog.hide();
return callback(filePath);
}
confirmDialog.hide();
dialog.show();
});
dialog.hide();
confirmDialog.show();
}
});
});
dialog.show();
}
public showOpenDialog(): void {
throw new Error("not implemented");
}
public showMessageBox(_: void, options: Electron.MessageBoxOptions, callback: (button: number | undefined, checked: boolean) => void): void {
const dialog = new DialogBox(options);
dialog.onAction((action) => {
dialog.hide();
callback(action.buttonIndex, false);
});
dialog.show();
}
}
class WebFrame {
public getZoomFactor(): number {
return 1;
}
public getZoomLevel(): number {
return 1;
}
public setZoomLevel(): void {
// Nothing.
}
}
class Screen {
public getAllDisplays(): [] {
return [];
}
}
class WebRequest extends EventEmitter {
public onBeforeRequest(): void {
throw new Error("not implemented");
}
public onBeforeSendHeaders(): void {
throw new Error("not implemented");
}
public onHeadersReceived(): void {
throw new Error("not implemented");
}
}
class Session extends EventEmitter {
public webRequest = new WebRequest();
public resolveProxy(url: string, callback: (proxy: string) => void): void {
// TODO: not sure what this actually does.
callback(url);
}
}
class WebContents extends EventEmitter {
public session = new Session();
}
class BrowserWindow extends EventEmitter {
public webContents = new WebContents();
private representedFilename: string = "";
public static getFocusedWindow(): undefined {
return undefined;
}
public focus(): void {
window.focus();
}
public show(): void {
window.focus();
}
public reload(): void {
location.reload();
}
public isMaximized(): boolean {
return false;
}
public setFullScreen(fullscreen: boolean): void {
if (fullscreen) {
document.documentElement.requestFullscreen();
} else {
document.exitFullscreen();
}
}
public isFullScreen(): boolean {
return document.fullscreenEnabled;
}
public isFocused(): boolean {
return document.hasFocus();
}
public setMenuBarVisibility(): void {
throw new Error("not implemented");
}
public setAutoHideMenuBar(): void {
throw new Error("not implemented");
}
public setRepresentedFilename(filename: string): void {
this.representedFilename = filename;
}
public getRepresentedFilename(): string {
return this.representedFilename;
}
public setTitle(value: string): void {
document.title = value;
}
}
/**
* We won't be able to do a 1 to 1 fill because things like moveItemToTrash for
* example returns a boolean while we need a promise.
*/
class ElectronFill {
public readonly shell = new Shell();
public readonly clipboard = new Clipboard();
public readonly app = new App();
public readonly dialog = new Dialog();
public readonly webFrame = new WebFrame();
public readonly screen = new Screen();
private readonly rendererToMainEmitter = new EventEmitter();
private readonly mainToRendererEmitter = new EventEmitter();
public get BrowserWindow(): typeof BrowserWindow {
return BrowserWindow;
}
// tslint:disable no-any
public get ipcRenderer(): object {
return {
send: (str: string, ...args: any[]): void => {
this.rendererToMainEmitter.emit(str, {
sender: module.exports.ipcMain,
}, ...args);
},
on: (str: string, listener: (...args: any[]) => void): void => {
this.mainToRendererEmitter.on(str, listener);
},
once: (str: string, listener: (...args: any[]) => void): void => {
this.mainToRendererEmitter.once(str, listener);
},
removeListener: (str: string, listener: (...args: any[]) => void): void => {
this.mainToRendererEmitter.removeListener(str, listener);
},
};
}
public get ipcMain(): object {
return {
send: (str: string, ...args: any[]): void => {
this.mainToRendererEmitter.emit(str, {
sender: module.exports.ipcRenderer,
}, ...args);
},
on: (str: string, listener: (...args: any[]) => void): void => {
this.rendererToMainEmitter.on(str, listener);
},
once: (str: string, listener: (...args: any[]) => void): void => {
this.rendererToMainEmitter.once(str, listener);
},
};
}
// tslint:enable no-any
}
module.exports = new ElectronFill();