forked from opensumi/core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
window.ts
361 lines (313 loc) · 9.92 KB
/
window.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
import { ChildProcess, fork, ForkOptions } from 'child_process';
import qs from 'querystring';
import {
app,
BrowserWindow,
shell,
ipcMain,
BrowserWindowConstructorOptions,
IpcMainEvent,
WebPreferences,
} from 'electron';
import semver from 'semver';
import treeKill from 'tree-kill';
import { Injectable, Autowired } from '@opensumi/di';
import {
ExtensionCandidate,
getDebugLogger,
Disposable,
isMacintosh,
URI,
FileUri,
Deferred,
} from '@opensumi/ide-core-common';
import { normalizedIpcHandlerPathAsync } from '@opensumi/ide-core-common/lib/utils/ipc';
import { initForDevtools } from './devtools';
import { ElectronAppConfig, ICodeWindow, ICodeWindowOptions } from './types';
const DEFAULT_WINDOW_HEIGHT = 700;
const DEFAULT_WINDOW_WIDTH = 1000;
let windowClientCount = 0;
const defaultWebPreferences: WebPreferences = {
webviewTag: true,
contextIsolation: false,
defaultFontSize: 13,
minimumFontSize: 12,
};
@Injectable({ multiple: true })
export class CodeWindow extends Disposable implements ICodeWindow {
private _workspace: URI | undefined;
@Autowired(ElectronAppConfig)
private appConfig: ElectronAppConfig;
private extensionDir: string;
private extensionCandidate: ExtensionCandidate[] = [];
private query: qs.ParsedUrlQuery;
private browser: BrowserWindow;
private node: KTNodeProcess | null = null;
private windowClientId: string;
public isRemote = false;
public isReloading: boolean;
public metadata: any;
private _nodeReady = new Deferred<void>();
private rpcListenPath: string | undefined = undefined;
constructor(workspace?: string, metadata?: any, options: BrowserWindowConstructorOptions & ICodeWindowOptions = {}) {
super();
this.extensionDir = this.appConfig.extensionDir;
if (workspace) {
this._workspace = new URI(workspace);
}
this.metadata = metadata;
this.windowClientId = 'CODE_WINDOW_CLIENT_ID:' + ++windowClientCount;
this.browser = new BrowserWindow({
show: false,
webPreferences: {
...defaultWebPreferences,
...this.appConfig?.overrideWebPreferences,
nodeIntegration: this.appConfig?.browserNodeIntegrated,
preload: this.appConfig?.browserPreload,
},
frame: isMacintosh,
titleBarStyle: 'hidden',
height: DEFAULT_WINDOW_HEIGHT,
width: DEFAULT_WINDOW_WIDTH,
// trafficLight position: Center vertically
trafficLightPosition: { x: 10, y: 10 },
...this.appConfig.overrideBrowserOptions,
...options,
});
if (this.appConfig.devtools) {
// initialize for OpenSumi DevTools
initForDevtools(this.browser);
}
if (options) {
if (options.extensionDir) {
this.extensionDir = options.extensionDir;
}
if (options.extensionCandidate) {
this.extensionCandidate = options.extensionCandidate;
}
if (options.query) {
this.query = options.query;
}
if (options.isRemote) {
this.isRemote = options.isRemote;
}
}
this.browser.on('closed', () => {
this.dispose();
});
const metadataResponser = async (event: IpcMainEvent, windowId: number) => {
if (windowId === this.browser.id) {
event.returnValue = JSON.stringify({
workspace: this.workspace ? FileUri.fsPath(this.workspace) : undefined,
webview: {
webviewPreload: URI.file(this.appConfig.webviewPreload).toString(),
plainWebviewPreload: URI.file(this.appConfig.plainWebviewPreload).toString(),
},
extensionDir: this.extensionDir,
extensionCandidate: this.appConfig.extensionCandidate.concat(this.extensionCandidate).filter(Boolean),
...this.metadata,
isRemote: this.isRemote,
windowClientId: this.windowClientId,
workerHostEntry: this.appConfig.extensionWorkerEntry,
extensionDevelopmentHost: this.appConfig.extensionDevelopmentHost,
appPath: app.getAppPath(),
});
}
};
const rpcListenPathResponser = async (event: IpcMainEvent, windowId: number) => {
await this._nodeReady.promise;
if (windowId === this.browser.id) {
event.returnValue = this.rpcListenPath;
}
};
ipcMain.on('window-metadata', metadataResponser);
ipcMain.on('window-rpc-listen-path', rpcListenPathResponser);
this.addDispose({
dispose: () => {
ipcMain.removeListener('window-metadata', metadataResponser);
ipcMain.removeListener('window-rpc-listen-path', rpcListenPathResponser);
},
});
}
get workspace() {
return this._workspace;
}
setWorkspace(workspace: string, fsPath?: boolean) {
if (fsPath) {
this._workspace = URI.file(workspace);
} else {
this._workspace = new URI(workspace);
}
}
setExtensionDir(extensionDir: string) {
this.extensionDir = URI.file(extensionDir).toString();
}
setExtensionCandidate(extensionCandidate: ExtensionCandidate[]) {
this.extensionCandidate = extensionCandidate;
}
async start() {
if (this.isRemote) {
getDebugLogger().log('Remote 模式,停止创建 Server 进程');
} else {
this.startNode();
}
try {
getDebugLogger().log('starting browser window with url: ', this.appConfig.browserUrl);
const browserUrlParsed = URI.parse(this.appConfig.browserUrl);
const queryString = qs.stringify({
...qs.parse(browserUrlParsed.query),
...this.query,
windowId: this.browser.id,
webContentsId: this.browser.webContents.id,
});
const browserUrl = browserUrlParsed.withQuery(queryString).toString(true);
this.browser.loadURL(browserUrl);
this.browser.webContents.on('devtools-reload-page', () => {
this.isReloading = true;
});
this.bindEvents();
} catch (e) {
getDebugLogger().error(e);
}
}
async startNode() {
await this.clear();
this._nodeReady = new Deferred();
this.node = new KTNodeProcess(
this.appConfig.nodeEntry,
this.appConfig.extensionEntry,
this.windowClientId,
this.appConfig.extensionDir,
);
this.rpcListenPath = await normalizedIpcHandlerPathAsync('electron-window', true);
await this.node.start(this.rpcListenPath!, (this.workspace || '').toString());
this._nodeReady.resolve();
}
bindEvents() {
// 外部打开http
if (semver.lt(process.versions.electron, '13.0.0')) {
// Deprecated: WebContents new-window event
// https://www.electronjs.org/docs/latest/breaking-changes#deprecated-webcontents-new-window-event
this.browser.webContents.on('new-window', (event, url) => {
if (!event.defaultPrevented) {
event.preventDefault();
if (url.indexOf('http') === 0) {
shell.openExternal(url);
}
}
});
} else {
this.browser.webContents.setWindowOpenHandler((details) => {
if (details.url.indexOf('http') === 0) {
shell.openExternal(details.url);
}
return { action: 'deny' };
});
}
}
async clear() {
if (this.node) {
try {
await this.node.dispose();
} catch (error) {
const logger = getDebugLogger();
logger.error(error);
} finally {
this.node = null;
}
}
}
close() {
if (this.browser) {
this.browser.close();
}
}
getBrowserWindow() {
return this.browser;
}
reload() {
this.isReloading = true;
this.browser.webContents.reload();
}
}
export class KTNodeProcess {
private _process: ChildProcess;
private ready: Promise<void>;
constructor(
private forkPath: string,
private extensionEntry: string,
private windowClientId: string,
private extensionDir: string,
) {}
async start(rpcListenPath: string, workspace: string | undefined) {
if (!this.ready) {
this.ready = new Promise((resolve, reject) => {
try {
const forkOptions: ForkOptions = {
env: {
...process.env,
KTELECTRON: '1',
ELECTRON_RUN_AS_NODE: '1',
EXTENSION_HOST_ENTRY: this.extensionEntry,
EXTENSION_DIR: this.extensionDir,
CODE_WINDOW_CLIENT_ID: this.windowClientId,
},
stdio: ['pipe', 'pipe', 'pipe', 'ipc'],
};
const forkArgs: string[] = [];
forkOptions.env!.WORKSPACE_DIR = workspace;
forkArgs.push('--listenPath', rpcListenPath);
this._process = fork(this.forkPath, forkArgs, forkOptions);
this._process.on('message', (message) => {
if (message === 'ready') {
resolve();
}
});
this._process.on('error', (error) => {
reject(error);
});
this._process.stdout.on('data', (data) => {
data = data.toString();
if (data.length > 500) {
data = data.slice(0, 500) + '...';
}
process.stdout.write('[node]' + data);
});
this._process.stderr.on('data', (data) => {
data = data.toString();
if (data.length > 500) {
data = data.slice(0, 500) + '...';
}
process.stdout.write('[node]' + data);
});
} catch (e) {
reject(e);
}
});
}
return this.ready;
}
get process() {
return this._process;
}
/**
* 注意:方法需要的时间较长,需要执行完成后再关闭窗口
*/
async dispose() {
const logger = getDebugLogger();
logger.log('KTNodeProcess dispose', this._process.pid);
if (this._process) {
return new Promise<void>((resolve, reject) => {
treeKill(this._process.pid, 'SIGKILL', (err) => {
if (err) {
logger.error(`tree kill error \n ${err.message}`);
reject(err);
} else {
logger.log('kill fork process', this._process.pid);
resolve();
}
});
});
}
}
}