-
-
Notifications
You must be signed in to change notification settings - Fork 353
/
main.ts
303 lines (265 loc) · 7.72 KB
/
main.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
import { app, autoUpdater, BrowserWindow, dialog, WebContents } from 'electron';
const Bottle = require('bottlejs');
import log from 'electron-log';
import * as yargs from 'yargs';
import * as path from 'path';
import * as fs from 'fs';
import { randomBytes } from 'crypto';
import { AddressInfo, createServer } from 'net';
import { appConfig, getAppDir, isDevMode } from './utils';
import { execSync } from 'child_process';
autoUpdater.on('update-downloaded', (event, releaseNotes, releaseName) => {
const dialogOpts = {
type: 'info',
buttons: ['Restart', 'Later'],
title: 'Application Update',
message: process.platform === 'win32' ? releaseNotes : releaseName,
detail:
'A new version has been downloaded. Restart the application to apply the updates.'
};
dialog.showMessageBox(dialogOpts).then(returnValue => {
if (returnValue.response === 0) autoUpdater.quitAndInstall();
});
});
autoUpdater.on('error', message => {
log.error('There was a problem updating the application');
log.error(message);
});
if (process.platform === 'darwin') {
require('update-electron-app')();
}
async function getFreePort(): Promise<number> {
return new Promise<number>(resolve => {
const getPort = () => {
const server = createServer(socket => {
socket.write('Echo server\r\n');
socket.pipe(socket);
});
server.on('error', function (e) {
getPort();
});
server.on('listening', function (e: any) {
const port = (server.address() as AddressInfo).port;
server.close();
resolve(port);
});
server.listen(0, '127.0.0.1');
};
getPort();
});
}
async function setAppConfig(): Promise<void> {
return new Promise<void>(resolve => {
getFreePort().then(port => {
appConfig.jlabPort = port;
appConfig.token = randomBytes(24).toString('hex');
resolve();
});
});
}
// handle opening file or directory with command-line arguments
if (process.argv.length > 1) {
const openPath = path.resolve(process.argv[1]);
if (fs.existsSync(openPath)) {
if (fs.lstatSync(openPath).isDirectory()) {
process.env.JLAB_DESKTOP_HOME = openPath;
} else {
process.env.JLAB_DESKTOP_HOME = path.dirname(openPath);
}
}
}
/**
* * On Mac OSX the PATH env variable a packaged app gets does not
* contain all the information that is usually set in .bashrc, .bash_profile, etc.
* This package fixes the PATH variable
*/
require('fix-path')();
let argv = yargs
.option('v', {
alias: 'verbose',
count: true,
type: 'boolean',
describe: 'verbose output to terminal'
})
.help().argv;
/**
* Enabled separate logging for development and packaged environments.
* Also override console methods so that future addition will route to
* using this package.
*/
let adjustedVerbose = parseInt((argv.verbose as unknown) as string) - 2;
if (isDevMode()) {
if (adjustedVerbose === 0) {
log.transports.console.level = 'info';
} else if (adjustedVerbose === 1) {
log.transports.console.level = 'verbose';
} else if (adjustedVerbose >= 2) {
log.transports.console.level = 'debug';
}
log.transports.file.level = false;
log.info('In development mode');
log.info(`Logging to console at '${log.transports.console.level}' level`);
} else {
if (adjustedVerbose === 0) {
log.transports.file.level = 'info';
} else if (adjustedVerbose === 1) {
log.transports.file.level = 'verbose';
} else if (adjustedVerbose >= 2) {
log.transports.file.level = 'debug';
}
log.transports.console.level = false;
log.info('In production mode');
log.info(
`Logging to file (${log.transports.file.findLogPath()}) at '${
log.transports.console.level
}' level`
);
}
console.log = log.log;
console.error = log.error;
console.warn = log.warn;
console.info = log.info;
console.debug = log.debug;
/**
* A user-defined service.
*
* Services make up the core functionality of the
* application. Each service is instantiated
* once and then becomes available to every other service.
*/
export interface IService {
/**
* The required services.
*/
requirements: string[];
/**
* The service name that is required by other services.
*/
provides: string;
/**
* A function to create the service object.
*/
activate: (...x: any[]) => any;
/**
* Whether the service should be instantiated immediately,
* or lazy loaded.
*/
autostart?: boolean;
}
/**
* Services required by this application.
*/
const services = [
'./app',
'./sessions',
'./server',
'./menu',
'./shortcuts',
'./utils',
'./registry'
].map((service: string) => {
return require(service).default;
});
app.on('open-file', (event: Electron.Event, _path: string) => {
process.env.JLAB_DESKTOP_HOME = path.dirname(_path);
});
function setupJLabCommand() {
if (process.platform !== 'darwin') {
return;
}
const symlinkPath = '/usr/local/bin/jlab';
const targetPath = `${getAppDir()}/app/jlab`;
if (fs.existsSync(symlinkPath) || !fs.existsSync(targetPath)) {
return;
}
try {
const cmd = `ln -s ${targetPath} ${symlinkPath}`;
execSync(cmd, { shell: '/bin/bash' });
fs.chmodSync(symlinkPath, 0o755);
fs.chmodSync(targetPath, 0o755);
} catch (error) {
log.error(error);
}
}
/**
* Load all services when the electron app is
* ready.
*/
app.on('ready', () => {
Promise.all([setAppConfig(), handOverArguments()])
.then(() => {
setupJLabCommand();
let serviceManager = new Bottle();
let autostarts: string[] = [];
services.forEach((s: IService) => {
serviceManager.factory(s.provides, (container: any) => {
let args = s.requirements.map((r: string) => {
return container[r];
});
return s.activate(...args);
});
if (s.autostart) {
autostarts.push(s.provides);
}
});
serviceManager.digest(autostarts);
})
.catch(e => {
log.error(e);
app.quit();
});
});
app.on('web-contents-created', (_event: any, webContents: WebContents) => {
// Prevent navigation to local links on the same page and external links
webContents.on('will-navigate', (event: Event, navigationUrl) => {
const jlabBaseUrl = `http://localhost:${appConfig.jlabPort}/`;
if (
!(
navigationUrl.startsWith(jlabBaseUrl) &&
navigationUrl.indexOf('#') === -1
)
) {
console.warn(
`Navigation is not allowed; attempted navigation to: ${navigationUrl}`
);
event.preventDefault();
}
});
// handle page's beforeunload prompt natively
webContents.on('will-prevent-unload', (event: Event) => {
const win = BrowserWindow.fromWebContents(webContents);
const choice = dialog.showMessageBoxSync(win, {
type: 'warning',
message: 'Do you want to leave?',
detail: 'Changes you made may not be saved.',
buttons: ['Leave', 'Stay'],
defaultId: 1,
cancelId: 0
});
if (choice === 0) {
event.preventDefault();
}
});
});
/**
* When a second instance of the application is executed, this passes the arguments
* to first instance. Files that are opened with the application on Linux and Windows
* will by default instantiate a new instance of the app with the file name as the args.
* This instead opens the files in the first instance of the
* application.
*/
function handOverArguments(): Promise<void> {
let promise = new Promise<void>((resolve, reject) => {
app.requestSingleInstanceLock();
// TODO; double check this logic
app.on('second-instance', (event, argv, cwd) => {
// Skip JupyterLab Executable
for (let i = 1; i < argv.length; i++) {
app.emit('open-file', null, argv[i]);
}
reject();
});
resolve();
});
return promise;
}