Repository navigation
Expand file tree
/
Copy pathmain.js
More file actions
379 lines (333 loc) · 10.5 KB
/
Copy pathmain.js
File metadata and controls
379 lines (333 loc) · 10.5 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
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
const path = require('path')
const os = require('os')
const fs = require('fs')
const { app, BrowserWindow, Menu, ipcMain, shell, dialog } = require('electron')
const isMac = process.platform === 'darwin' ? true : false
const isDev = process.env.NODE_ENV !== 'production' && !app.isPackaged
function debugLog(message, data = null) {
if (!isDev) return
const timestamp = new Date().toISOString()
const logMessage = `[${timestamp}] ${message}${data ? '\n' + JSON.stringify(data, null, 2) : ''}\n`
console.log(logMessage)
}
// Set environment - force production for packaged apps
if (app.isPackaged) {
process.env.NODE_ENV = 'production'
debugLog('App is packaged, setting NODE_ENV to production')
} else {
debugLog('App is not packaged, keeping development mode')
}
// Load dependencies
const { resolvePackagedFfmpegPath } = require('./lib/ffmpeg-path')
const ffmpegBinary = resolvePackagedFfmpegPath(require('./lib/ffmpeg-binary'))
const { spawn } = require('child_process')
const { canSend } = require('./lib/ipc-send')
const { attachNavigationGuard } = require('./lib/navigation-guard')
const { createFfmpegSession } = require('./lib/ffmpeg-session')
const {
defaultPrefs,
parsePrefsJson,
filterMissingPaths,
serializePrefs,
resolveSaveDefaultPath,
prefsFileName,
} = require('./lib/prefs')
const appHtmlRoot = path.join(__dirname, 'app')
debugLog('FFmpeg setup:', { path: ffmpegBinary })
debugLog('Environment check:', {
NODE_ENV: process.env.NODE_ENV,
isDev: isDev,
isMac: isMac,
isPackaged: app.isPackaged,
platform: process.platform,
arch: process.arch
})
let mainWindow
let aboutWindow
function sendToRenderer(channel, ...args) {
if (canSend(mainWindow)) {
mainWindow.webContents.send(channel, ...args)
}
}
function prefsFilePath() {
return path.join(app.getPath('userData'), prefsFileName())
}
function readStoredPrefs() {
const file = prefsFilePath()
if (!fs.existsSync(file)) {
return defaultPrefs()
}
try {
return parsePrefsJson(fs.readFileSync(file, 'utf8'))
} catch {
return defaultPrefs()
}
}
function whenRendererReady() {
if (!canSend(mainWindow)) {
return Promise.reject(new Error('Window unavailable'))
}
if (!mainWindow.webContents.isLoading()) {
return Promise.resolve()
}
return new Promise((resolve) => {
mainWindow.webContents.once('did-finish-load', resolve)
})
}
async function exportLayout() {
if (ffmpegSession.isBusy()) {
dialog.showErrorBox('Export layout', 'A convert is running.')
return
}
await whenRendererReady()
mainWindow.webContents.send('prefs:collect')
}
async function importLayout() {
if (ffmpegSession.isBusy()) {
dialog.showErrorBox('Import layout', 'A convert is running.')
return
}
if (!canSend(mainWindow)) {
return
}
const { canceled, filePaths } = await dialog.showOpenDialog(mainWindow, {
title: 'Import layout',
filters: [{ name: 'JSON', extensions: ['json'] }],
properties: ['openFile'],
})
if (canceled || !filePaths || !filePaths[0]) {
return
}
let text
try {
text = fs.readFileSync(filePaths[0], 'utf8')
} catch {
dialog.showErrorBox('Import layout', 'Could not read that file.')
return
}
let raw
try {
raw = JSON.parse(text)
} catch {
dialog.showErrorBox('Import layout', 'That file is not valid JSON. The current grid was not changed.')
return
}
if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {
dialog.showErrorBox('Import layout', 'That file is not valid JSON. The current grid was not changed.')
return
}
const prefs = filterMissingPaths(parsePrefsJson(text), (p) => fs.existsSync(p))
await whenRendererReady()
sendToRenderer('prefs:imported', prefs)
await dialog.showMessageBox(mainWindow, {
type: 'info',
message: 'Clip paths are absolute. Files that are not on this computer are left empty.',
})
}
const ffmpegSession = createFfmpegSession({
spawn,
ffmpegBinary,
fs,
send: sendToRenderer,
log: debugLog,
})
function stopJobAndNotifyUnexpectedError() {
ffmpegSession.killActiveFfmpeg()
sendToRenderer('video:error', 'Unexpected error')
}
process.on('uncaughtException', (error) => {
debugLog('Uncaught Exception:', error.stack)
console.error(error)
stopJobAndNotifyUnexpectedError()
})
process.on('unhandledRejection', (reason, promise) => {
debugLog('Unhandled Rejection:', { reason: reason.toString(), promise: promise.toString() })
console.error(reason)
stopJobAndNotifyUnexpectedError()
})
// Set up IPC handlers before creating windows
function setupIPC() {
// Dialog IPC handlers
ipcMain.handle('dialog:openFile', async (event, options) => {
const result = await dialog.showOpenDialog(mainWindow, options)
return result
})
ipcMain.handle('dialog:saveFile', async (event, options) => {
const result = await dialog.showSaveDialog(mainWindow, options)
return result
})
// Path helper
ipcMain.handle('get-default-path', async (event, type) => {
if (type === 'desktop') {
return path.join(os.homedir(), 'Desktop')
} else if (type === 'saveFile') {
const desktop = path.join(os.homedir(), 'Desktop')
const lastSaveDir = readStoredPrefs().lastSaveDir
return resolveSaveDefaultPath(lastSaveDir, desktop, Date.now(), (p) => fs.existsSync(p))
}
return os.homedir()
})
ipcMain.handle('prefs:load', () => {
return filterMissingPaths(readStoredPrefs(), (p) => fs.existsSync(p))
})
ipcMain.handle('prefs:save', (event, raw) => {
fs.writeFileSync(prefsFilePath(), serializePrefs(raw), 'utf8')
return true
})
ipcMain.handle('prefs:collect', async (event, payload) => {
const { canceled, filePath } = await dialog.showSaveDialog(mainWindow, {
title: 'Export layout',
defaultPath: 'tessel-layout.json',
filters: [{ name: 'JSON', extensions: ['json'] }],
})
if (canceled || !filePath) {
return false
}
try {
fs.writeFileSync(filePath, serializePrefs(payload), 'utf8')
return true
} catch {
dialog.showErrorBox('Export layout', 'Could not write that file.')
return false
}
})
ipcMain.handle('app:getVersion', () => app.getVersion())
ipcMain.on('video:convert', (e, options) => {
debugLog('video:convert', { gridType: options.gridType })
ffmpegSession.convertVideo(options)
})
ipcMain.on('video:cancel', () => {
ffmpegSession.killActiveFfmpeg({ notify: 'cancelled' })
})
}
function createMainWindow() {
mainWindow = new BrowserWindow({
title: 'Tessel',
width: isDev ? 800 : 450,
height: 600,
icon: path.join(__dirname, 'assets/icons/icon-256.png'),
resizable: isDev ? true : false,
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
webSecurity: true,
preload: path.join(__dirname, 'preload.js')
}
})
attachNavigationGuard(mainWindow, appHtmlRoot, shell)
// Open dev tools only in development mode
if (isDev) {
mainWindow.webContents.openDevTools()
}
mainWindow.loadFile(path.join(__dirname, 'app/index.html'))
mainWindow.on('closed', () => {
ffmpegSession.killActiveFfmpeg()
mainWindow = null
})
}
function createAboutWindow() {
if (aboutWindow && !aboutWindow.isDestroyed()) {
aboutWindow.show()
aboutWindow.focus()
return
}
aboutWindow = new BrowserWindow({
title: 'About Tessel',
width: 300,
height: 300,
icon: path.join(__dirname, 'assets/icons/icon-256.png'),
resizable: false,
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
preload: path.join(__dirname, 'preload-about.js')
}
})
attachNavigationGuard(aboutWindow, appHtmlRoot, shell)
aboutWindow.loadFile(path.join(__dirname, 'app/about.html'))
aboutWindow.on('closed', () => {
aboutWindow = null
})
}
app.on('ready', () => {
setupIPC()
createMainWindow()
const mainMenu = Menu.buildFromTemplate(menu)
Menu.setApplicationMenu(mainMenu)
})
const menu = [
...(isMac
? [
{
label: app.name,
submenu: [
{
label: 'About',
click: createAboutWindow,
},
],
},
]
: []),
{
label: 'File',
submenu: [
{
label: 'Export layout…',
click: () => {
exportLayout().catch((err) => {
debugLog('exportLayout failed', { error: String(err) })
dialog.showErrorBox('Export layout', 'Could not export the layout.')
})
},
},
{
label: 'Import layout…',
click: () => {
importLayout().catch((err) => {
debugLog('importLayout failed', { error: String(err) })
dialog.showErrorBox('Import layout', 'Could not import the layout.')
})
},
},
{ type: 'separator' },
isMac ? { role: 'close' } : { role: 'quit' },
],
},
...(!isMac
? [
{
label: 'Help',
submenu: [
{ label: 'About Tessel', click: createAboutWindow },
],
},
]
: []),
...(isDev
? [
{
label: 'Developer',
submenu: [
{ role: 'reload' },
{ role: 'forcereload' },
{ type: 'separator' },
{ role: 'toggledevtools' },
],
},
]
: []),
]
app.on('before-quit', () => {
ffmpegSession.killActiveFfmpeg()
})
app.on('window-all-closed', () => {
if (!isMac) {
app.quit()
}
})
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createMainWindow()
}
})