forked from n-air-app/n-air-app
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
359 lines (281 loc) · 10.1 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
'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 inAsar = process.mainModule.filename.indexOf('app.asar') !== -1;
const { app, BrowserWindow, ipcMain } = require('electron');
const fs = require('fs');
const path = require('path');
const _ = require('lodash');
const obs = require(inAsar ? '../../node-obs' : './node-obs');
const { Updater } = require('./updater/Updater.js');
const uuid = require('uuid/v1');
// 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;
// This file determines whether we start up in SLOBS-mode or
// OBS-mode, so we need to load it on app startup.
function loadStartupConfig() {
const configLocation = path.join(app.getPath('userData'), 'startup.json');
if (fs.existsSync(configLocation)) {
return JSON.parse(fs.readFileSync(configLocation));
}
return null;
}
// 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 appExiting = false;
const indexUrl = 'file://' + __dirname + '/index.html';
function startApp() {
const isDevMode = process.env.NODE_ENV !== 'production';
// We use a special cache directory for running tests
if (process.env.SLOBS_CACHE_DIR) {
app.setPath('userData', process.env.SLOBS_CACHE_DIR);
}
mainWindow = new BrowserWindow({
width: 1600,
height: 1000,
show: false,
frame: false
});
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 (!appExiting) {
appExiting = true;
mainWindow.send('shutdown');
e.preventDefault();
}
});
mainWindow.on('closed', () => {
require('node-libuiohook').stopHook();
obs.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 (!appExiting) {
childWindow.send('closeWindow');
// Prevent the window from actually closing
e.preventDefault();
}
});
childWindow.loadURL(indexUrl + '?child=true');
if (isDevMode) {
childWindow.webContents.openDevTools();
mainWindow.webContents.openDevTools();
const devtoolsInstaller = require('electron-devtools-installer');
devtoolsInstaller.default(devtoolsInstaller.VUEJS_DEVTOOLS);
}
// Initialize various OBS services
obs.OBS_API_initOBS_API(app.getPath('userData'));
const startupConfig = loadStartupConfig();
if (startupConfig && startupConfig.obsMode) {
obs.OBS_API_setOBS_currentProfile(startupConfig.profile);
obs.OBS_API_setOBS_currentSceneCollection(startupConfig.sceneCollection);
}
obs.OBS_API_setPathConfigDirectory(app.getPath('userData'));
obs.OBS_API_openAllModules();
obs.OBS_API_initAllModules();
obs.OBS_service_createStreamingOutput();
obs.OBS_service_createRecordingOutput();
obs.OBS_service_createVideoStreamingEncoder();
obs.OBS_service_createVideoRecordingEncoder();
obs.OBS_service_createAudioEncoder();
obs.OBS_service_resetAudioContext();
obs.OBS_service_resetVideoContext();
obs.OBS_service_associateAudioAndVideoToTheCurrentStreamingContext();
obs.OBS_service_associateAudioAndVideoToTheCurrentRecordingContext();
obs.OBS_service_createService();
obs.OBS_service_associateAudioAndVideoEncodersToTheCurrentStreamingOutput();
obs.OBS_service_associateAudioAndVideoEncodersToTheCurrentRecordingOutput();
obs.OBS_service_setServiceToTheStreamingOutput();
}
// 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('window-showChildWindow', (event, data) => {
if (data.windowOptions.width && data.windowOptions.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)) - (data.windowOptions.width / 2);
const childY = (bounds.y + (bounds.height / 2)) - (data.windowOptions.height / 2);
childWindow.restore();
childWindow.setBounds({
x: childX,
y: childY,
width: data.windowOptions.width,
height: data.windowOptions.height
});
} catch (err) {
log('Recovering from error:', err);
childWindow.setSize(data.windowOptions.width, data.windowOptions.height);
childWindow.center();
}
childWindow.focus();
}
// The child window will show itself when rendered
childWindow.send('window-setContents', data.startupOptions);
});
// 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: ', _.keys(registeredStores));
// Make sure we unregister is when it is closed
win.on('closed', () => {
delete registeredStores[windowId];
log('Registered vuex stores: ', _.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) => {
let windowId = BrowserWindow.fromWebContents(event.sender).id;
_.each(_.omit(registeredStores, [windowId]), win => {
win.webContents.send('vuex-mutation', mutation);
});
});
// Handle service initialization
const servicesInitialized = new Set();
ipcMain.on('services-shouldInit', (event, service) => {
event.returnValue = !servicesInitialized.has(service);
servicesInitialized.add(service);
});
// 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 = {
// This needs to be done as a single IPC call, otherwise
// there is visible judder in the display output.
OBS_content_setSourcePositionAndScale(sceneName, sourceName, x, y, scaleX, scaleY) {
obs.OBS_content_setSourcePosition(sceneName, sourceName, x, y);
obs.OBS_content_setSourceScaling(sceneName, sourceName, scaleX, scaleY);
},
OBS_content_setSourcePositionAndCrop(sceneName, sourceName, x, y, crop) {
obs.OBS_content_setSourcePosition(sceneName, sourceName, x, y);
obs.OBS_content_setSceneItemCrop(sceneName, sourceName, crop);
},
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 = obs[data.method].apply(obs, 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();
});