Repository navigation
Expand file tree
/
Copy pathindex.ts
More file actions
299 lines (270 loc) · 10.3 KB
/
Copy pathindex.ts
File metadata and controls
299 lines (270 loc) · 10.3 KB
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
/**
* Main process of the Electron application.
*/
import { app, BrowserWindow, nativeTheme, session } from 'electron';
import * as path from 'path';
import Pluto from './pluto';
import './baseEventListeners.ts';
import { initGlobals, startup } from './startup.ts';
import { generalLogger } from './logger.ts';
import { GlobalWindowManager } from './windowHelpers.ts';
import { Globals } from './globals.ts';
import { getAssetPath } from './paths.ts';
import { firstNotebookPath, isExtMatch, withSearchParams } from './util.ts';
import { initializeAutoUpdates } from './updater.ts';
import { handleSquirrelFileAssociations } from './fileAssociations.ts';
// This allows TypeScript to pick up the magic constants that's auto-generated by Forge's Webpack
// plugin that tells the Electron app where to look for the Webpack-bundled app code (depending on
// whether you're running in development or production).
declare const MAIN_WINDOW_WEBPACK_ENTRY: string;
declare const MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY: string;
// On a Squirrel install/update/uninstall run, (un)register our .jl "Open with"
// file associations. This is a no-op on normal launches and on non-Windows.
handleSquirrelFileAssociations();
// Handle creating/removing shortcuts on Windows when installing/uninstalling.
if (require('electron-squirrel-startup')) {
app.quit();
} else if (!app.requestSingleInstanceLock()) {
// Another instance already owns the lock. Electron hands our argv (which may
// contain a .jl path from a double-click) to that instance via the
// 'second-instance' event below, so this one can just quit.
app.quit();
} else {
// Check for new releases on GitHub (via update.electronjs.org), download them
// in the background, and prompt the user to restart. No-op during development.
initializeAutoUpdates();
// A second launch — e.g. double-clicking a notebook while Pluto is already
// running — is routed here instead of spawning a new Julia server.
app.on('second-instance', (_event, argv) => {
const notebookPath = firstNotebookPath(argv);
if (notebookPath) {
void openExternalNotebook(notebookPath);
} else {
focusAnyWindow();
}
});
}
/**
* Create a new BrowserWindow and attach a Pluto instance to it.
* Returns the Pluto instance. Exported so the menu can spawn new windows.
*/
export const createPlutoWindow = (landingUrl?: string | null): Pluto => {
const win = new BrowserWindow({
title: 'Pluto.jl',
height: 800,
width: 700,
resizable: true,
show: true,
backgroundColor: nativeTheme.shouldUseDarkColors ? '#1F1F1F' : 'white',
icon: getAssetPath('icon.png'),
webPreferences: {
preload: MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY,
sandbox: false,
},
});
const defaultLandingUrl = Globals.PLUTO_STARTED
? Pluto.resolveHtmlPath('index.html')
: MAIN_WINDOW_WEBPACK_ENTRY;
const pluto = new Pluto(
win,
landingUrl === undefined ? defaultLandingUrl : landingUrl,
);
win.focus();
win.webContents.setVisualZoomLevelLimits(1, 3);
win.setMenuBarVisibility(false);
return pluto;
};
/**
* Open a notebook that was requested from outside the app (a double-clicked
* file, macOS "Open With", or a second launch) in a fresh window. Waits for the
* Pluto server to be ready first.
*/
const openExternalNotebook = async (filePath: string): Promise<void> => {
await Globals.whenStarted();
// Pass null so the window stays blank until open() navigates it to the
// notebook, rather than briefly flashing the welcome page.
const pluto = createPlutoWindow(null);
await pluto.open('path', filePath);
};
/** Bring an existing window to the front, or create one if none are open. */
const focusAnyWindow = (): void => {
const [existing] = BrowserWindow.getAllWindows();
if (existing) {
if (existing.isMinimized()) existing.restore();
existing.focus();
} else {
createPlutoWindow();
}
};
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(async () => {
// If we were launched to open a notebook (e.g. double-clicked .jl on Windows,
// where the path arrives in argv), route the first window straight to it.
const notebookArg = firstNotebookPath(process.argv);
// Show the loading window right away: initGlobals can take a while on first
// run (it copies the bundled Julia depot to a writable location).
const pluto = createPlutoWindow();
if (notebookArg) pluto.pendingNotebookPath = notebookArg;
await initGlobals();
startup(app, MAIN_WINDOW_WEBPACK_ENTRY);
// This is set here because it required the app to be ready
session.defaultSession.on('will-download', (_event, item) => {
const fileName = item.getFilename();
const ext = path.extname(fileName).slice(1);
const fileType =
ext === 'html'
? 'HTML file'
: ext === 'jl'
? 'Pluto Notebook'
: 'Pluto Statefile';
item.setSaveDialogOptions({
message: 'Select location to export file',
filters: [{ extensions: [ext], name: fileType }],
});
});
createRequestListener();
});
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', async () => {
// On OS X it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) {
createPlutoWindow();
}
});
// Kill the Julia/Pluto server process when the app quits.
app.on('will-quit', () => {
Pluto.close();
});
app.on('open-file', (event, file) => {
// macOS "Open With" / dock drop. (Windows delivers the path via argv instead:
// see firstNotebookPath usage above.)
event.preventDefault();
if (isExtMatch(file)) {
void openExternalNotebook(file);
} else {
generalLogger.info('open-file event: unsupported file type:', file);
}
});
// This handles custom Pluto.jl routes by intercepting web requests
function createRequestListener() {
session.defaultSession.webRequest.onBeforeRequest(async (details, next) => {
const cancel = false;
if (!details.webContentsId) {
generalLogger.warn('Web request was made without defined webContentsId');
next({ cancel });
return;
}
const plutoWindow =
GlobalWindowManager.getInstance().getWindowByWebContentsId(
details.webContentsId,
);
if (!plutoWindow) {
next({ cancel });
return;
}
// In development, our path usually looks like /.../Pluto.jl/frontend
// In production, our path usually looks like /.../Pluto/KkVLI/frontend
if (details.url.match(/\/Pluto(\.jl)?\/(.*\/)?frontend(-dist)?/g)) {
const url = new URL(details.url);
const tail = url.pathname.split('/').reverse()[0];
generalLogger.verbose(
'Triggered Pluto.jl server-side route detection!',
details.url,
);
if (url.pathname.endsWith('/')) {
next({ redirectURL: Pluto.resolveHtmlPath('index.html') });
return;
}
if (tail === 'new') {
// this should be synchronous so the user sees the Pluto.jl loading screen on index.html
await plutoWindow.open('new');
next({
cancel: true,
});
return;
}
if (tail === 'open') {
await plutoWindow.open('path', url.searchParams.get('path'));
next({
cancel: true,
});
return;
}
if (tail === 'edit') {
next({
redirectURL:
Pluto.resolveHtmlPath('editor.html') + url.search.replace('?', '&'),
});
return;
}
// this route gets called when pasting a notebook into the welcome page
if (tail === 'notebookupload') {
next({
redirectURL: new URL(
`notebookupload?secret=${Globals.PLUTO_SECRET}`,
Globals.PLUTO_URL,
).toString(),
});
return;
}
// The pluto.land upload flow (and any renderer-side `fetch` of the HTML
// export) hits this relative URL, which resolves against the file:// editor
// page and would otherwise 404. Redirect it to the real Pluto server,
// preserving `id`/`offline_bundle` and adding the secret for auth.
if (tail === 'notebookexport') {
next({
redirectURL: withSearchParams(`notebookexport${url.search}`, {
secret: Globals.PLUTO_SECRET,
}).toString(),
});
return;
}
}
next({ cancel });
});
// The editor loads from a file:// page (origin "null"), but export and other
// authenticated requests target the http://localhost Pluto server. So we need `Access-Control-Allow-Origin: *`. Since this is our own local server inside our own app, inject
// the header.
session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
if (Globals.PLUTO_STARTED && details.url.startsWith(Globals.PLUTO_URL.origin)) {
const responseHeaders = { ...details.responseHeaders };
for (const key of Object.keys(responseHeaders)) {
if (key.toLowerCase() === 'access-control-allow-origin') {
delete responseHeaders[key];
}
}
responseHeaders['Access-Control-Allow-Origin'] = ['*'];
callback({ responseHeaders });
return;
}
callback({});
});
// The pluto.land upload/delete requests are sent from the file:// editor, so
// the browser attaches `Origin: null`, which pluto.land's endpoint rejects
// ("Origin not allowed") even though it returns `Access-Control-Allow-Origin: *`.
// pluto.land allows its own origin, so present that instead. (The response is
// still `ACAO: *`, which satisfies the renderer's null-origin CORS check.)
session.defaultSession.webRequest.onBeforeSendHeaders(
{ urls: ['https://pluto.land/*'] },
(details, callback) => {
const requestHeaders = { ...details.requestHeaders };
for (const key of Object.keys(requestHeaders)) {
if (key.toLowerCase() === 'origin') {
delete requestHeaders[key];
}
}
requestHeaders.Origin = 'https://pluto.land';
callback({ requestHeaders });
},
);
}