-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
636 lines (546 loc) · 22.6 KB
/
main.js
File metadata and controls
636 lines (546 loc) · 22.6 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
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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
/**
* @fileoverview Hexbloop Electron main process
* @author Hexbloop Audio Labs
* @description Main process for the chaos magic audio engine
*/
const { app, BrowserWindow, ipcMain, dialog, shell } = require('electron');
const path = require('path');
const fs = require('fs');
const os = require('os');
const { spawn } = require('child_process');
// Audio processing modules
const AudioProcessor = require('./src/audio-processor');
const NameGenerator = require('./src/name-generator');
const BatchNamingEngine = require('./src/batch/batch-naming-engine');
// Menu system
const { MenuBuilder } = require('./src/menu/menu-builder');
const { getPreferencesManager } = require('./src/menu/preferences');
const { PreferencesWindow } = require('./src/menu/preferences-window');
let mainWindow;
let preferencesWindow;
// === Window Management ===
function createWindow() {
mainWindow = new BrowserWindow({
width: 1200,
height: 800,
minWidth: 800,
minHeight: 600,
title: 'Hexbloop',
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
webSecurity: true, // Drag-drop works with webUtils now
sandbox: false, // Required for IPC functionality
enableRemoteModule: false,
allowRunningInsecureContent: false,
experimentalFeatures: false,
preload: path.join(__dirname, 'preload.js')
},
titleBarStyle: 'hiddenInset',
backgroundColor: '#0D0D1A',
show: false
});
mainWindow.loadFile('src/renderer/index.html');
// Initialize menu system
const menuBuilder = new MenuBuilder(mainWindow);
const menu = menuBuilder.buildMenu();
require('electron').Menu.setApplicationMenu(menu);
// Show window when ready to prevent visual flash
mainWindow.once('ready-to-show', () => {
mainWindow.show();
mainWindow.setTitle('Hexbloop');
});
// Workaround: intercept file:// navigation to handle drag-drop
mainWindow.webContents.on('will-navigate', (event, navigationUrl) => {
const parsedUrl = new URL(navigationUrl);
if (parsedUrl.protocol === 'file:') {
event.preventDefault();
const filePath = decodeURIComponent(parsedUrl.pathname);
console.log('🔍 Detected file drag:', filePath);
if (/\.(mp3|wav|m4a|aiff|aif|flac|ogg|aac|opus|wma|mka|ape|alac|wv|au|snd|voc|8svx|amb|caf)$/i.test(filePath)) {
mainWindow.webContents.send('file-dropped', [filePath]);
}
}
});
// Performance monitoring
mainWindow.webContents.on('did-finish-load', async () => {
try {
const memoryInfo = await process.getProcessMemoryInfo();
// Memory values are in KB, convert to MB
const privateMB = Math.round(memoryInfo.private / 1024);
console.log(`📊 Memory usage: ${privateMB}MB`);
} catch (err) {
console.log('📊 Memory monitoring available');
}
});
// Open DevTools in development
if (process.env.NODE_ENV === 'development') {
mainWindow.webContents.openDevTools();
}
}
// === Preferences Window ===
async function showPreferencesWindow() {
try {
console.log('🔧 showPreferencesWindow called');
if (!mainWindow) {
console.error('❌ Main window not available');
return;
}
if (!preferencesWindow) {
console.log('📦 Creating new PreferencesWindow instance');
preferencesWindow = new PreferencesWindow(mainWindow);
}
console.log('🎯 Calling preferencesWindow.show()');
const window = await preferencesWindow.show();
console.log('✅ Preferences window should be visible:', window ? 'YES' : 'NO');
// Force show and focus as a fallback
if (window && !window.isDestroyed()) {
window.show();
window.focus();
console.log('🔍 Forced show and focus on preferences window');
}
return window;
} catch (error) {
console.error('❌ Error showing preferences window:', error);
console.error('Stack trace:', error.stack);
}
}
// Export for menu-builder
module.exports.showPreferencesWindow = showPreferencesWindow;
// === App Lifecycle ===
app.setName('Hexbloop');
app.whenReady().then(() => {
app.setName('Hexbloop');
createWindow();
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
// === IPC Handlers ===
ipcMain.handle('open-preferences', async () => {
await showPreferencesWindow();
});
ipcMain.handle('process-audio', async (event, filePaths) => {
const results = [];
let firstSuccessfulOutput = null;
// Get user preferences for batch processing
const preferencesManager = getPreferencesManager();
const settings = preferencesManager.getSettings();
// Initialize batch naming engine with user preferences
const namingEngine = new BatchNamingEngine(settings.batch);
// Determine output directory (with optional session folder)
// Use the user's configured output folder; fallback matches settings-schema default
let outputDirectory = settings.ui.outputFolder || path.join(os.homedir(), 'Documents', 'HexbloopOutput');
// Create session folder if enabled
const sessionFolder = namingEngine.generateSessionFolder();
if (sessionFolder) {
outputDirectory = path.join(outputDirectory, sessionFolder);
}
// Ensure output directory exists
if (!fs.existsSync(outputDirectory)) {
fs.mkdirSync(outputDirectory, { recursive: true });
console.log(`✨ Created output directory: ${outputDirectory}`);
}
// Save manifest if session folders are enabled
if (sessionFolder) {
const manifest = {
timestamp: new Date().toISOString(),
moonPhase: namingEngine.moonPhase,
fileCount: filePaths.length,
settings: settings.batch,
files: []
};
// Will be updated as files are processed
results.manifest = manifest;
}
for (let i = 0; i < filePaths.length; i++) {
const filePath = filePaths[i];
try {
// Memory management: hint GC between files in large batches
// Canvas buffers and audio data can accumulate significantly
if (i > 0 && i % 5 === 0 && global.gc) {
global.gc();
console.log(`🧹 GC hint after ${i} files`);
}
// Send progress update
event.sender.send('processing-progress', {
current: i + 1,
total: filePaths.length,
fileName: path.basename(filePath),
status: 'processing'
});
// Validate and sanitize input file path
if (!filePath || typeof filePath !== 'string') {
throw new Error('Invalid file path provided');
}
// Resolve to absolute path and check it exists
const resolvedPath = path.resolve(filePath);
if (!fs.existsSync(resolvedPath)) {
throw new Error(`Input file not found: ${path.basename(filePath)}`);
}
// Ensure file is actually a file, not a directory
const stats = fs.statSync(resolvedPath);
if (!stats.isFile()) {
throw new Error(`Path is not a file: ${path.basename(filePath)}`);
}
// Validate audio file extension
// Expanded support for all sox and ffmpeg compatible formats
const validExtensions = [
// Core formats (well-tested)
'.mp3', '.wav', '.m4a', '.aiff', '.aif', '.flac', '.ogg', '.aac',
// Additional lossless formats
'.ape', '.alac', '.wv', // APE, ALAC, WavPack
// Additional lossy formats
'.opus', '.wma', '.mka', // Opus, Windows Media, Matroska
// Legacy/specialty formats
'.au', '.snd', '.voc', '.8svx', '.amb', '.caf' // Various legacy
];
const ext = path.extname(resolvedPath).toLowerCase();
if (!validExtensions.includes(ext)) {
throw new Error(`Unsupported audio format: ${ext}. Supported: ${validExtensions.slice(0, 8).join(', ')} and more.`);
}
// Generate name using batch naming engine
const generatedName = namingEngine.generateName(resolvedPath, i, filePaths.length);
const outputFormat = settings.output.format || 'mp3';
const outputPath = path.join(outputDirectory, `${generatedName}.${outputFormat}`);
console.log(`🎵 Processing ${i + 1}/${filePaths.length}: ${path.basename(resolvedPath)} -> ${generatedName}.${outputFormat}`);
// Process the audio file
await AudioProcessor.processFile(resolvedPath, outputPath);
// Check if file was actually created
if (!fs.existsSync(outputPath)) {
throw new Error('Output file was not created');
}
results.push({
success: true,
originalFile: filePath,
outputFile: outputPath,
mysticalName: generatedName
});
// Update manifest if session folders are enabled
if (results.manifest) {
results.manifest.files.push({
original: path.basename(filePath),
output: `${generatedName}.${outputFormat}`,
success: true
});
}
// Remember first successful output for folder opening
if (!firstSuccessfulOutput) {
firstSuccessfulOutput = outputPath;
}
} catch (error) {
console.error('Audio processing error:', error);
results.push({
success: false,
originalFile: filePath,
error: error.message
});
}
}
// Save manifest file if session folders are enabled
if (results.manifest && sessionFolder) {
const manifestPath = path.join(outputDirectory, 'manifest.json');
try {
fs.writeFileSync(manifestPath, JSON.stringify(results.manifest, null, 2));
console.log(`📝 Saved session manifest: ${manifestPath}`);
} catch (error) {
console.error('Failed to save manifest:', error);
}
}
// Log batch memory usage
try {
const memInfo = process.memoryUsage();
const heapMB = Math.round(memInfo.heapUsed / 1024 / 1024);
const rssMB = Math.round(memInfo.rss / 1024 / 1024);
console.log(`📊 Batch complete - Memory: ${heapMB}MB heap, ${rssMB}MB RSS (${filePaths.length} files)`);
} catch (e) { /* non-critical */ }
// Show processed files in Finder/Explorer
if (firstSuccessfulOutput) {
const successCount = results.filter(r => r.success).length;
console.log(`📁 Opening output folder for ${successCount} processed file${successCount !== 1 ? 's' : ''}`);
shell.showItemInFolder(firstSuccessfulOutput);
}
return results;
});
// Preview batch naming without processing
ipcMain.handle('preview-batch-naming', async (event, filePaths) => {
const preferencesManager = getPreferencesManager();
const settings = preferencesManager.getSettings();
const namingEngine = new BatchNamingEngine(settings.batch);
const outputFormat = settings.output.format || 'mp3';
return namingEngine.previewBatch(filePaths, outputFormat);
});
ipcMain.handle('select-files', async () => {
const result = await dialog.showOpenDialog(mainWindow, {
properties: ['openFile', 'multiSelections'],
filters: [
{ name: 'Audio Files', extensions: [
'mp3', 'wav', 'm4a', 'aiff', 'aif', 'flac', 'ogg', 'aac',
'opus', 'wma', 'ape', 'alac', 'wv', 'mka',
'au', 'snd', 'voc', '8svx', 'amb', 'caf'
]},
{ name: 'Common Formats', extensions: ['mp3', 'wav', 'flac', 'aac', 'm4a', 'ogg'] },
{ name: 'All Files', extensions: ['*'] }
]
});
return result.filePaths;
});
// Legacy drag-drop handler (kept for compatibility)
ipcMain.handle('get-file-paths-from-drop', async (event, fileData) => {
console.log('🔍 Processing drag-drop file data:', fileData);
const paths = [];
for (const file of fileData) {
if (file.path) {
paths.push(file.path);
} else if (file.name) {
console.log(`⚠️ Cannot determine full path for: ${file.name}`);
}
}
console.log('🔍 Extracted file paths from drop:', paths);
if (paths.length === 0) {
console.log('❌ Could not extract file paths from drag-drop');
return [];
}
return paths;
});
// Handle ambient audio toggle from menu
ipcMain.on('toggle-ambient-audio', (event, enabled) => {
// Forward to all renderer windows (in case we have multiple in the future)
mainWindow.webContents.send('toggle-ambient-audio', enabled);
});
// Get current settings for renderer
ipcMain.handle('get-settings', async () => {
try {
const preferencesManager = getPreferencesManager();
return preferencesManager.getSettings();
} catch (error) {
console.error('❌ Failed to get settings for renderer:', error);
// Return defaults if there's an error
const { DEFAULT_SETTINGS } = require('./src/shared/settings-schema');
return DEFAULT_SETTINGS;
}
});
// === Preferences IPC Handlers ===
/**
* Handle preferences operation errors consistently
* @param {string} operation - Description of the operation that failed
* @param {Error} error - The error that occurred
* @returns {{success: false, error: string}} Standardized error response
*/
function handlePreferencesError(operation, error) {
console.error(`❌ Failed to ${operation}:`, error);
return { success: false, error: error.message };
}
/**
* Get current preferences settings
* @returns {Promise<Object>} Current settings object
*/
ipcMain.handle('preferences-get-settings', async () => {
try {
const preferencesManager = getPreferencesManager();
return preferencesManager.getSettings();
} catch (error) {
console.error('❌ Failed to get settings:', error);
throw error; // Let the renderer handle this critical error
}
});
/**
* Update a single preference setting
* @param {Event} event - IPC event object
* @param {string} settingPath - Dot-notation path to setting (e.g., 'processing.compressing')
* @param {*} value - New value for the setting
* @returns {Promise<{success: boolean, error?: string}>} Operation result
*/
ipcMain.handle('preferences-update-setting', async (event, settingPath, value) => {
try {
// Basic validation
if (!settingPath || typeof settingPath !== 'string') {
throw new Error('Invalid setting path');
}
const preferencesManager = getPreferencesManager();
await preferencesManager.updateSetting(settingPath, value);
return { success: true };
} catch (error) {
return handlePreferencesError('update setting', error);
}
});
/**
* Update multiple preference settings
* @param {Event} event - IPC event object
* @param {Object} newSettings - Object containing multiple settings to update
* @returns {Promise<{success: boolean, error?: string}>} Operation result
*/
ipcMain.handle('preferences-update-settings', async (event, newSettings) => {
try {
if (!newSettings || typeof newSettings !== 'object') {
throw new Error('Invalid settings object');
}
const preferencesManager = getPreferencesManager();
await preferencesManager.updateSettings(newSettings);
return { success: true };
} catch (error) {
return handlePreferencesError('update multiple settings', error);
}
});
/**
* Reset all preferences to default values
* @returns {Promise<{success: boolean, error?: string}>} Operation result
*/
ipcMain.handle('preferences-reset-defaults', async () => {
try {
const preferencesManager = getPreferencesManager();
await preferencesManager.resetToDefaults();
console.log('🔄 Preferences reset to defaults');
return { success: true };
} catch (error) {
return handlePreferencesError('reset settings to defaults', error);
}
});
/**
* Export current preferences to a JSON object
* @returns {Promise<{success: boolean, data?: Object, error?: string}>} Export result with data
*/
ipcMain.handle('preferences-export', async () => {
try {
const preferencesManager = getPreferencesManager();
const exportData = await preferencesManager.exportSettings();
return { success: true, data: exportData };
} catch (error) {
return handlePreferencesError('export settings', error);
}
});
/**
* Import preferences from a JSON object
* @param {Event} event - IPC event object
* @param {Object} importData - Settings data to import
* @returns {Promise<{success: boolean, error?: string}>} Import result
*/
ipcMain.handle('preferences-import', async (event, importData) => {
try {
if (!importData || typeof importData !== 'object') {
throw new Error('Invalid import data');
}
const preferencesManager = getPreferencesManager();
await preferencesManager.importSettings(importData);
console.log('📥 Settings imported successfully');
return { success: true };
} catch (error) {
return handlePreferencesError('import settings', error);
}
});
/**
* Show native folder selection dialog for output directory
* @returns {Promise<{success: boolean, path?: string, error?: string}>} Selected folder path
*/
ipcMain.handle('preferences-choose-output-folder', async () => {
try {
const result = await dialog.showOpenDialog(mainWindow, {
properties: ['openDirectory'],
title: 'Choose Output Folder for Processed Audio Files',
defaultPath: path.join(app.getPath('documents'), 'HexbloopOutput')
});
if (!result.canceled && result.filePaths.length > 0) {
const selectedPath = result.filePaths[0];
// Validate folder is writable
try {
await fs.promises.access(selectedPath, fs.constants.W_OK);
} catch (accessError) {
console.error('❌ Selected folder is not writable:', selectedPath);
return {
success: false,
error: 'Selected folder is read-only. Please choose a folder where you have write permissions.'
};
}
// Check available disk space (basic check)
try {
const stats = await fs.promises.stat(selectedPath);
// Note: Node.js doesn't provide disk space info directly
// This is a basic existence check
if (!stats.isDirectory()) {
return {
success: false,
error: 'Selected path is not a directory.'
};
}
} catch (statError) {
return {
success: false,
error: 'Unable to access the selected folder.'
};
}
console.log('📁 Output folder selected and validated:', selectedPath);
return { success: true, path: selectedPath };
}
return { success: false, error: 'No folder selected' };
} catch (error) {
return handlePreferencesError('choose output folder', error);
}
});
/**
* Close the preferences window
* @returns {{success: boolean, error?: string}} Close operation result
*/
ipcMain.handle('preferences-close', () => {
try {
const { PreferencesWindow } = require('./src/menu/preferences-window');
const prefWindow = new PreferencesWindow(mainWindow);
if (prefWindow.isOpen()) {
prefWindow.close();
console.log('Preferences window closed');
return { success: true };
}
console.log('No preferences window found to close');
return { success: false, error: 'No preferences window found' };
} catch (error) {
return handlePreferencesError('close preferences window', error);
}
});
// === Startup & Dependencies ===
const binaries = require('./src/binary-resolver');
async function checkDependencies() {
// Use the binary resolver which checks bundled first, then system PATH
binaries.logStatus();
const results = {
ffmpeg: !!binaries.ffmpeg.path,
sox: !!binaries.sox.path
};
// Store results globally for the audio processor to check
global.availableDependencies = results;
// Log summary
if (!results.sox && !results.ffmpeg) {
console.log('⚠️ WARNING: Neither sox nor ffmpeg found. Audio processing will fail.');
console.log('Run "npm run vendor:setup" to download bundled binaries,');
console.log('or install with: brew install sox ffmpeg');
} else if (!results.ffmpeg) {
console.log('⚠️ FFmpeg not found. Using sox fallback (lower quality mastering)');
} else if (!results.sox) {
console.log('ℹ️ Sox not found - FFmpeg will handle all processing (this is fine!)');
}
return results;
}
// === Error Handling ===
process.on('uncaughtException', (error) => {
console.error('🚨 Uncaught Exception:', error);
});
process.on('unhandledRejection', (reason, promise) => {
console.error('🚨 Unhandled Rejection at:', promise, 'reason:', reason);
});
app.on('render-process-gone', (event, webContents, details) => {
console.error('🚨 Renderer process gone:', details);
if (details.reason === 'crashed') {
console.log('🔄 Attempting to reload...');
webContents.reload();
}
});
// === Startup ===
console.log('🔥 HEXBLOOP ELECTRON - CHAOS MAGIC AUDIO ENGINE 🔥');
console.log('Checking audio processing dependencies...');
checkDependencies();
console.log('Ready to process some mystical audio! 🤘');