-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.ts
More file actions
329 lines (277 loc) · 9.54 KB
/
main.ts
File metadata and controls
329 lines (277 loc) · 9.54 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
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
import { execFile } from 'child_process';
import crypto from 'crypto';
import { app, BrowserWindow, dialog, ipcMain, Menu, MenuItemConstructorOptions, protocol, shell } from 'electron';
import fetch from 'electron-fetch';
import fs from 'fs';
import i18n from 'i18next';
import i18nFsBackend from 'i18next-fs-backend';
import path from 'path';
import semver from 'semver';
import stream from 'stream';
import util from 'util';
import { PageId } from './Docs';
import { i18nConfig } from './shared/config';
const asyncExecFile = util.promisify(execFile);
const asyncPipeline = util.promisify(stream.pipeline);
declare const MAIN_WINDOW_WEBPACK_ENTRY: string;
declare const MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY: string;
// Handle creating/removing shortcuts on Windows when installing/uninstalling.
if (require('electron-squirrel-startup')) {
app.quit();
}
const isMac = process.platform === 'darwin';
const resourcesLocation = path.join(app.getAppPath(), app.isPackaged ? '..' : '.');
// Localization
i18n.use(i18nFsBackend).init({
...i18nConfig,
backend: {
loadPath: path.join(resourcesLocation, 'assets', 'locales', '{{lng}}/{{ns}}.json'),
addPath: path.join(resourcesLocation, 'assets', 'locales', '{{lng}}/{{ns}}.missing.json'),
ident: 2,
},
debug: i18nConfig.debug && !app.isPackaged,
initImmediate: false,
});
// App menu
function openDocs(page: PageId) {
const mainWindow = BrowserWindow.getAllWindows()[0];
mainWindow?.webContents.send('open_docs', page);
}
function openURL(url: string) {
shell.openExternal(url);
}
function setupMenu() {
const t = i18n.getFixedT(null, null, 'App::Menu');
const macAppMenu: MenuItemConstructorOptions = {
label: t(`AppMenu::${app.name}`),
submenu: [
{ role: 'about', label: t(`AppMenu::About ${app.name}`) },
{ type: 'separator' },
{ role: 'services', label: t('AppMenu::Services') },
{ type: 'separator' },
{ role: 'hide', label: t(`AppMenu::Hide ${app.name}`) },
{ role: 'hideOthers', label: t('AppMenu::Hide Others') },
{ role: 'unhide', label: t('AppMenu::Show All') },
{ type: 'separator' },
{ role: 'quit', label: t(`AppMenu::Quit ${app.name}`) },
],
};
const template: MenuItemConstructorOptions[] = [
...(isMac ? [macAppMenu] : []),
{
label: t('View::&View'),
submenu: [
{ role: 'copy', label: t('View::Copy') },
{ role: 'selectAll', label: t('View::Select All') },
{ type: 'separator' },
{ role: 'resetZoom', label: t('View::Actual Size') },
{ role: 'zoomIn', label: t('View::Zoom In') },
{ role: 'zoomOut', label: t('View::Zoom Out') },
{ type: 'separator' },
{ role: 'togglefullscreen', label: t('View::Toggle Full Screen') },
],
},
{
label: t('Settings::&Settings'),
submenu: [
{
label: t('Settings::Language'),
submenu: [
{
label: 'English',
type: 'radio',
checked: i18n.language === 'en',
click: () => i18n.changeLanguage('en'),
},
{
label: 'Deutsch',
type: 'radio',
checked: i18n.language === 'de',
click: () => i18n.changeLanguage('de'),
},
],
},
],
},
{
label: t('Help::&Help'),
submenu: [
{
label: t('Help::Documentation'),
click: () => openDocs('operation'),
},
{
label: t('Help::Changelog'),
click: () => openDocs('changelog'),
},
{
label: t('Help::License'),
click: () => openDocs('license'),
},
{ type: 'separator' },
{
label: t('Help::Learn More'),
click: () => openURL('https://open-diffix.org'),
},
{
label: t('Help::Community Discussions'),
click: () => openURL('https://github.com/diffix/desktop/discussions'),
},
{
label: t('Help::Search Issues'),
click: () => openURL('https://github.com/diffix/desktop/issues'),
},
{
label: t('Help::Latest Releases'),
click: () => openURL('https://github.com/diffix/desktop/releases'),
},
],
},
];
const menu = Menu.buildFromTemplate(template);
Menu.setApplicationMenu(menu);
}
// Protocol for docs file serving (docs://)
protocol.registerSchemesAsPrivileged([{ scheme: 'docs', privileges: { bypassCSP: true } }]);
function registerProtocols() {
protocol.registerFileProtocol('docs', (request, callback) => {
const url = request.url.substring('docs://'.length);
callback(path.join(resourcesLocation, 'docs', i18n.language, url));
});
}
// Main window
const ALLOWED_DOMAINS = ['https://open-diffix.org', 'https://github.com', 'https://arxiv.org', 'mailto:'];
function createWindow() {
const mainWindow = new BrowserWindow({
height: 800,
width: 1400,
webPreferences: {
contextIsolation: false,
preload: MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY,
additionalArguments: [`--language=${i18n.language}`],
},
icon: path.join(resourcesLocation, 'assets', 'icon.png'),
});
mainWindow.on('page-title-updated', function (e) {
e.preventDefault();
});
mainWindow.webContents.setWindowOpenHandler(({ url }) => {
if (ALLOWED_DOMAINS.some((domain) => url.startsWith(domain))) {
shell.openExternal(url);
} else {
console.warn(`Blocked URL ${url} by setWindowOpenHandler.`);
}
return { action: 'deny' };
});
mainWindow.loadURL(MAIN_WINDOW_WEBPACK_ENTRY);
if (!app.isPackaged) {
mainWindow.webContents.openDevTools();
}
}
// IPC
app.on('ready', () => {
// Feeding the locale to `changeLanguage` or extracting the language cause problems.
if (['de', 'de-AT', 'de-CH', 'de-DE', 'de-LI', 'de-LU'].includes(app.getLocale())) {
i18n.changeLanguage('de');
}
setupMenu();
registerProtocols();
createWindow();
});
app.on('window-all-closed', () => {
if (!isMac) {
app.quit();
}
});
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
i18n.on('languageChanged', (lng) => {
setupMenu();
const mainWindow = BrowserWindow.getAllWindows()[0];
mainWindow?.webContents.send('language_changed', lng);
});
const diffixName = 'OpenDiffix.Service' + (process.platform === 'win32' ? '.exe' : '');
const diffixPath = path.join(resourcesLocation, 'bin', diffixName);
const activeTasks = new Map<string, AbortController>();
async function runTask<T>(taskId: string, runner: (signal: AbortSignal) => Promise<T>): Promise<T> {
if (activeTasks.has(taskId)) throw new Error(`Duplicate task ID ${taskId}.`);
const abortController = new AbortController();
activeTasks.set(taskId, abortController);
const startTimestamp = performance.now();
try {
return await runner(abortController.signal);
} finally {
const taskTime = Math.round(performance.now() - startTimestamp);
console.debug(`Task ${taskId} took ${taskTime} ms.`);
activeTasks.delete(taskId);
}
}
ipcMain.on('cancel_task', async (_event, taskId: string) => {
console.info(`Cancelling task ${taskId}.`);
const controller = activeTasks.get(taskId);
if (controller) {
controller.abort();
activeTasks.delete(taskId);
} else {
console.info(`Task ${taskId} not found.`);
}
});
ipcMain.handle('call_service', (_event, taskId: string, request: string) =>
runTask(taskId, async (signal) => {
console.info(`(${taskId}) Calling service: ${request}.`);
const promise = asyncExecFile(diffixPath, null, { maxBuffer: 100 * 1024 * 1024, windowsHide: true, signal });
promise.child.stdin?.write(request);
promise.child.stdin?.end();
try {
const { stdout, stderr } = await promise;
console.log(stderr.trimEnd());
return stdout;
} catch (err) {
if ((err as Error)?.name === 'AbortError') {
throw 'Service call aborted.';
}
const stderr = (err as { stderr?: string })?.stderr;
if (stderr) {
console.log(stderr.trimEnd());
}
throw 'Service call failed.';
}
}),
);
ipcMain.handle('select_export_file', async (_event, defaultPath: string) => {
const options = {
defaultPath: defaultPath,
filters: [
{ name: 'CSV', extensions: ['csv'] },
{ name: 'All Files', extensions: ['*'] },
],
};
const dialogResult = await dialog.showSaveDialog(BrowserWindow.getAllWindows()[0], options);
return dialogResult.filePath;
});
ipcMain.handle('hash_file', (_event, taskId: string, fileName: string) =>
runTask(taskId, async (signal) => {
console.info(`(${taskId}) Hashing file ${fileName}.`);
const fileStream = stream.addAbortSignal(signal, fs.createReadStream(fileName));
const hash = crypto.createHash('sha256');
await asyncPipeline(fileStream, hash);
return hash.digest('hex');
}),
);
ipcMain.handle('set_main_window_title', (_event, title: string) => {
const mainWindow = BrowserWindow.getAllWindows()[0];
mainWindow?.setTitle(title);
});
ipcMain.handle('check_for_updates', async (_event) => {
const response = await fetch('https://api.github.com/repos/diffix/desktop/releases/latest');
// 404 here means there hasn't yet been a full release yet, just prerelases or drafts
if (response.status == 404) return null;
const data = await response.json();
const newestTagName = data['tag_name'];
const newestSemVer = semver.coerce(newestTagName);
const currentSemVer = semver.coerce(app.getVersion());
return newestSemVer && currentSemVer && semver.gt(newestSemVer, currentSemVer) ? newestTagName : null;
});