forked from stream-labs/desktop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
497 lines (395 loc) · 13.3 KB
/
main.js
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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
'use strict';
////////////////////////////////////////////////////////////////////////////////
// Set Up Environment Variables
////////////////////////////////////////////////////////////////////////////////
const pjson = require('./package.json');
if (pjson.env === 'production') {
process.env.NODE_ENV = 'production';
}
process.env.SLOBS_VERSION = pjson.version;
////////////////////////////////////////////////////////////////////////////////
// Modules and other Requires
////////////////////////////////////////////////////////////////////////////////
const { app, BrowserWindow, ipcMain, session, crashReporter, dialog } = require('electron');
const bt = require('backtrace-node');
app.disableHardwareAcceleration();
function handleFinishedReport() {
dialog.showErrorBox(`Unhandled Exception`,
'An unexpected error occured and the application must be shut down.\n' +
'Information concerning this occasion has been sent for debugging purposes.\n' +
'Sorry for the inconvenience and thanks for your patience as we work out the bugs!\n' +
'Please restart the application.');
if (app) {
app.quit();
}
}
function handleUnhandledException(err) {
bt.report(err, {}, handleFinishedReport);
}
if (pjson.env === 'production') {
bt.initialize({
disableGlobalHandler: true,
endpoint: 'https://streamlabs.sp.backtrace.io:6098',
token: 'e3f92ff3be69381afe2718f94c56da4644567935cc52dec601cf82b3f52a06ce',
attributes: {
version: pjson.version,
processType: 'main'
}
});
process.on("uncaughtException", handleUnhandledException);
crashReporter.start({
productName: 'streamlabs-obs',
companyName: 'streamlabs',
submitURL:
'https://streamlabs.sp.backtrace.io:6098/post?' +
'format=minidump&' +
'token=e3f92ff3be69381afe2718f94c56da4644567935cc52dec601cf82b3f52a06ce',
extra: {
version: pjson.version,
processType: 'main'
}
});
}
const inAsar = process.mainModule.filename.indexOf('app.asar') !== -1;
const fs = require('fs');
const { Updater } = require('./updater/Updater.js');
const uuid = require('uuid/v4');
const rimraf = require('rimraf');
const path = require('path');
const windowStateKeeper = require('electron-window-state');
if (process.argv.includes('--clearCacheDir')) {
rimraf.sync(app.getPath('userData'));
}
// Initialize the keylistener
require('node-libuiohook').startHook();
////////////////////////////////////////////////////////////////////////////////
// Main Program
////////////////////////////////////////////////////////////////////////////////
function log(...args) {
if (!process.env.SLOBS_DISABLE_MAIN_LOGGING) {
console.log(...args);
}
}
// Windows
let mainWindow;
let childWindow;
let childWindowIsReadyToShow = false;
// Somewhat annoyingly, this is needed so that the child window
// can differentiate between a user closing it vs the app
// closing the windows before exit.
let allowMainWindowClose = false;
let shutdownStarted = false;
let appShutdownTimeout;
const indexUrl = 'file://' + __dirname + '/index.html';
function openDevTools() {
childWindow.webContents.openDevTools({ mode: 'undocked' });
mainWindow.webContents.openDevTools({ mode: 'undocked' });
}
// Lazy require OBS
let _obs;
function getObs() {
if (!_obs) {
_obs = require('obs-studio-node').NodeObs;
}
return _obs;
}
function startApp() {
const isDevMode = (process.env.NODE_ENV !== 'production') && (process.env.NODE_ENV !== 'test');
const mainWindowState = windowStateKeeper({
defaultWidth: 1600,
defaultHeight: 1000
});
mainWindow = new BrowserWindow({
width: mainWindowState.width,
height: mainWindowState.height,
x: mainWindowState.x,
y: mainWindowState.y,
show: false,
frame: false,
title: "Streamlabs OBS",
});
mainWindowState.manage(mainWindow);
mainWindow.setMenu(null);
// wait until devtools will be opened and load app into window
// it allows to start application with clean cache
// and handle breakpoints on startup
const LOAD_DELAY = 2000;
setTimeout(() => {
mainWindow.loadURL(indexUrl);
}, isDevMode ? LOAD_DELAY : 0);
mainWindow.on('close', e => {
if (!shutdownStarted) {
shutdownStarted = true;
childWindow.destroy();
mainWindow.send('shutdown');
// We give the main window 10 seconds to acknowledge a request
// to shut down. Otherwise, we just close it.
appShutdownTimeout = setTimeout(() => {
allowMainWindowClose = true;
if (!mainWindow.isDestroyed()) mainWindow.close();
}, 10 * 1000);
}
if (!allowMainWindowClose) e.preventDefault();
});
ipcMain.on('acknowledgeShutdown', () => {
if (appShutdownTimeout) clearTimeout(appShutdownTimeout);
});
ipcMain.on('shutdownComplete', () => {
allowMainWindowClose = true;
mainWindow.close();
});
mainWindow.on('closed', () => {
require('node-libuiohook').stopHook();
session.defaultSession.flushStorageData();
getObs().OBS_API_destroyOBS_API();
app.quit();
});
// Pre-initialize the child window
childWindow = new BrowserWindow({
show: false,
frame: false
});
childWindow.setMenu(null);
// The child window is never closed, it just hides in the
// background until it is needed.
childWindow.on('close', e => {
if (!shutdownStarted) {
childWindow.send('closeWindow');
// Prevent the window from actually closing
e.preventDefault();
}
});
// simple messaging system for services between windows
// WARNING! the child window use synchronous requests and will be frozen
// until main window asynchronous response
const requests = { };
function sendRequest(request, event = null) {
mainWindow.webContents.send('services-request', request);
if (!event) return;
requests[request.id] = Object.assign({}, request, { event });
}
// use this function to call some service method from the main process
function callService(resource, method, ...args) {
sendRequest({
jsonrpc: '2.0',
method,
params: {
resource,
args
}
});
}
ipcMain.on('services-ready', () => {
callService('AppService', 'setArgv', process.argv);
childWindow.loadURL(indexUrl + '?child=true');
});
ipcMain.on('window-childWindowIsReadyToShow', () => {
childWindowIsReadyToShow = true;
});
ipcMain.on('services-request', (event, payload) => {
sendRequest(payload, event);
});
ipcMain.on('services-response', (event, response) => {
if (!requests[response.id]) return;
requests[response.id].event.returnValue = response;
delete requests[response.id];
});
ipcMain.on('services-message', (event, payload) => {
if (!childWindow.isDestroyed()) childWindow.webContents.send('services-message', payload);
});
if (isDevMode) {
require('devtron').install();
// Vue dev tools appears to cause strange non-deterministic
// interference with certain NodeJS APIs, expecially asynchronous
// IO from the renderer process. Enable at your own risk.
// const devtoolsInstaller = require('electron-devtools-installer');
// devtoolsInstaller.default(devtoolsInstaller.VUEJS_DEVTOOLS);
setTimeout(() => {
openDevTools();
}, 10 * 1000);
}
// Initialize various OBS services
getObs().SetWorkingDirectory(
path.join(app.getAppPath().replace('app.asar', 'app.asar.unpacked') +
'/node_modules/obs-studio-node'));
getObs().OBS_API_initAPI(app.getPath('userData'));
}
// We use a special cache directory for running tests
if (process.env.SLOBS_CACHE_DIR) {
app.setPath('appData', process.env.SLOBS_CACHE_DIR);
}
app.setPath('userData', path.join(app.getPath('appData'), 'slobs-client'));
// This ensures that only one copy of our app can run at once.
const shouldQuit = app.makeSingleInstance(() => {
// Someone tried to run a second instance, we should focus our window.
if (mainWindow) {
if (mainWindow.isMinimized()) {
mainWindow.restore();
}
mainWindow.focus();
}
});
if (shouldQuit) {
app.quit();
}
app.on('ready', () => {
if ((process.env.NODE_ENV === 'production') || process.env.SLOBS_FORCE_AUTO_UPDATE) {
(new Updater(startApp)).run();
} else {
startApp();
}
});
ipcMain.on('openDevTools', () => {
openDevTools();
});
ipcMain.on('window-showChildWindow', (event, windowOptions) => {
if (windowOptions.size.width && windowOptions.size.height) {
// Center the child window on the main window
// For some unknown reason, electron sometimes gets into a
// weird state where this will always fail. Instead, we
// should recover by simply setting the size and forgetting
// about the bounds.
try {
const bounds = mainWindow.getBounds();
const childX = (bounds.x + (bounds.width / 2)) - (windowOptions.size.width / 2);
const childY = (bounds.y + (bounds.height / 2)) - (windowOptions.size.height / 2);
childWindow.restore();
childWindow.setBounds({
x: childX,
y: childY,
width: windowOptions.size.width,
height: windowOptions.size.height
});
} catch (err) {
log('Recovering from error:', err);
childWindow.setSize(windowOptions.size.width, windowOptions.size.height);
childWindow.center();
}
childWindow.focus();
}
// show the child window when it will be ready
new Promise(resolve => {
if (childWindowIsReadyToShow) {
resolve();
return;
}
ipcMain.once('window-childWindowIsReadyToShow', () => resolve());
}).then(() => {
// The child window will show itself when rendered
childWindow.send('window-setContents', windowOptions);
});
});
ipcMain.on('window-closeChildWindow', (event) => {
// never close the child window, hide it instead
childWindow.hide();
});
ipcMain.on('window-focusMain', () => {
mainWindow.focus();
});
// The main process acts as a hub for various windows
// syncing their vuex stores.
let registeredStores = {};
ipcMain.on('vuex-register', event => {
let win = BrowserWindow.fromWebContents(event.sender);
let windowId = win.id;
// Register can be received multiple times if the window is
// refreshed. We only want to register it once.
if (!registeredStores[windowId]) {
registeredStores[windowId] = win;
log('Registered vuex stores: ', Object.keys(registeredStores));
// Make sure we unregister is when it is closed
win.on('closed', () => {
delete registeredStores[windowId];
log('Registered vuex stores: ', Object.keys(registeredStores));
});
}
if (windowId !== mainWindow.id) {
// Tell the mainWindow to send its current store state
// to the newly registered window
mainWindow.webContents.send('vuex-sendState', windowId);
}
});
// Proxy vuex-mutation events to all other subscribed windows
ipcMain.on('vuex-mutation', (event, mutation) => {
const senderWindow = BrowserWindow.fromWebContents(event.sender);
if (senderWindow && !senderWindow.isDestroyed()) {
const windowId = senderWindow.id;
Object.keys(registeredStores).filter(id => id !== windowId.toString()).forEach(id => {
const win = registeredStores[id];
if (!win.isDestroyed()) win.webContents.send('vuex-mutation', mutation);
});
}
});
// Virtual node OBS calls:
//
// These are methods that appear upstream to be OBS
// API calls, but are actually Javascript functions.
// These should be used sparingly, and are used to
// ensure atomic operation of a handful of calls.
const nodeObsVirtualMethods = {
OBS_test_callbackProxy(num, cb) {
setTimeout(() => {
cb(num + 1);
}, 5000);
}
};
// These are called constantly and dirty up the logs.
// They can be commented out of this list on the rare
// occasional that they are useful in the log output.
const filteredObsApiMethods = [
'OBS_content_getSourceSize',
'OBS_content_getSourceFlags',
'OBS_API_getPerformanceStatistics'
];
// Proxy node OBS calls
ipcMain.on('obs-apiCall', (event, data) => {
let retVal;
const shouldLog = !filteredObsApiMethods.includes(data.method);
if (shouldLog) log('OBS API CALL', data);
const mappedArgs = data.args.map(arg => {
const isCallbackPlaceholder = (typeof arg === 'object') && arg && arg.__obsCallback;
if (isCallbackPlaceholder) {
return (...args) => {
if (!event.sender.isDestroyed()) {
event.sender.send('obs-apiCallback', {
id: arg.id,
args
});
}
};
}
return arg;
});
if (nodeObsVirtualMethods[data.method]) {
retVal = nodeObsVirtualMethods[data.method].apply(null, mappedArgs);
} else {
retVal = getObs()[data.method](...mappedArgs);
}
if (shouldLog) log('OBS RETURN VALUE', retVal);
// electron ipc doesn't like returning undefined, so
// we return null instead.
if (retVal == null) {
retVal = null;
}
event.returnValue = retVal;
});
// Used for guaranteeing unique ids for objects in the vuex store
ipcMain.on('getUniqueId', event => {
event.returnValue = uuid();
});
ipcMain.on('restartApp', () => {
app.relaunch();
// Closing the main window starts the shut down sequence
mainWindow.close();
});
ipcMain.on('requestSourceAttributes', (e, names) => {
const sizes = require('obs-studio-node').getSourcesSize(names);
e.sender.send('notifySourceAttributes', sizes);
});
ipcMain.on('streamlabels-writeFile', (e, info) => {
fs.writeFile(info.path, info.data, err => {
if (err) {
console.log('Streamlabels: Error writing file', err);
}
});
});