Repository navigation
Expand file tree
/
Copy pathmain.js
More file actions
472 lines (408 loc) · 15 KB
/
Copy pathmain.js
File metadata and controls
472 lines (408 loc) · 15 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
const { app, BrowserWindow, ipcMain, dialog, screen, nativeImage } = require('electron');
const path = require('path');
const fs = require('fs');
const AdmZip = require('adm-zip');
app.commandLine.appendSwitch('disable-gpu-shader-disk-cache');
const windows = new Map(); // windowId -> { window, id, controlsWindow, appState, controlsState }
let nextWindowId = 1;
// State file path
const stateFile = path.join(app.getPath('userData'), 'buddy-state.json');
const tutorialFile = path.join(app.getPath('userData'), 'tutorial-seen');
// Load saved state (array of buddy configs)
function loadAllState() {
try {
if (fs.existsSync(stateFile)) {
const data = JSON.parse(fs.readFileSync(stateFile, 'utf8'));
// Migrate old single-buddy format
if (data && !Array.isArray(data)) {
return [data];
}
return data;
}
} catch (e) {
console.error('Failed to load state:', e);
}
return null;
}
// Save all window states
function saveAllState() {
try {
const states = [];
for (const [id, entry] of windows) {
if (entry.window && !entry.window.isDestroyed()) {
const bounds = entry.window.getBounds();
states.push({
x: bounds.x,
y: bounds.y,
width: bounds.width,
height: bounds.height,
...(entry.appState || {})
});
}
}
fs.writeFileSync(stateFile, JSON.stringify(states, null, 2));
} catch (e) {
console.error('Failed to save state:', e);
}
}
function getWindowByWebContents(webContents) {
for (const [id, entry] of windows) {
if (entry.window && !entry.window.isDestroyed() && entry.window.webContents === webContents) {
return { id, entry };
}
}
return null;
}
function getEntryByControlsWebContents(webContents) {
for (const [id, entry] of windows) {
if (entry.controlsWindow && !entry.controlsWindow.isDestroyed() && entry.controlsWindow.webContents === webContents) {
return { id, entry };
}
}
return null;
}
function openControlsWindow(buddyId) {
const entry = windows.get(buddyId);
if (!entry || !entry.window || entry.window.isDestroyed()) return;
// If already open, focus it
if (entry.controlsWindow && !entry.controlsWindow.isDestroyed()) {
entry.controlsWindow.focus();
return;
}
const buddyBounds = entry.window.getBounds();
const controlsWin = new BrowserWindow({
width: 260,
height: 420,
x: buddyBounds.x + buddyBounds.width + 10,
y: buddyBounds.y,
frame: false,
transparent: false,
alwaysOnTop: true,
resizable: false,
skipTaskbar: true,
backgroundColor: '#1e1e1e',
webPreferences: {
preload: path.join(__dirname, 'controls-preload.js'),
contextIsolation: true,
nodeIntegration: false
}
});
controlsWin.loadFile('controls.html');
controlsWin.setAlwaysOnTop(true, 'floating');
entry.controlsWindow = controlsWin;
controlsWin.on('closed', () => {
entry.controlsWindow = null;
});
}
function createWindow(savedState = null) {
const { width, height } = screen.getPrimaryDisplay().workAreaSize;
const id = nextWindowId++;
const windowConfig = {
width: savedState?.width || 200,
height: savedState?.height || 200,
x: savedState?.x ?? (width - 250 - (windows.size * 50)),
y: savedState?.y ?? (height - 250),
frame: false,
transparent: true,
alwaysOnTop: true,
resizable: false,
skipTaskbar: false,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true,
nodeIntegration: false
}
};
const win = new BrowserWindow(windowConfig);
windows.set(id, { window: win, appState: savedState });
win.loadFile('index.html');
win.setAlwaysOnTop(true, 'floating');
win.setIgnoreMouseEvents(false);
win.on('closed', () => {
windows.delete(id);
});
return id;
}
app.whenReady().then(() => {
const savedStates = loadAllState();
if (savedStates && savedStates.length > 0) {
for (const state of savedStates) {
createWindow(state);
}
} else {
createWindow();
}
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
// Handle video file selection
ipcMain.handle('select-video', async (event) => {
const win = BrowserWindow.fromWebContents(event.sender);
const result = await dialog.showOpenDialog(win, {
properties: ['openFile'],
filters: [
{ name: 'Media Files', extensions: ['webm', 'mp4', 'gif', 'webp', 'png', 'jpg', 'jpeg'] }
]
});
if (!result.canceled && result.filePaths.length > 0) {
return result.filePaths[0];
}
return null;
});
// Handle window position (manual drag)
ipcMain.handle('get-position', (event) => {
const win = BrowserWindow.fromWebContents(event.sender);
if (win) return win.getPosition();
return [0, 0];
});
ipcMain.on('move-window', (event, x, y) => {
const win = BrowserWindow.fromWebContents(event.sender);
if (win) win.setPosition(Math.round(x), Math.round(y));
});
// Set window icon from a data URL (buddy thumbnail)
ipcMain.on('set-window-icon', (event, dataUrl) => {
const win = BrowserWindow.fromWebContents(event.sender);
if (win) {
try {
const img = nativeImage.createFromDataURL(dataUrl);
win.setIcon(img);
} catch (e) {
// ignore invalid image data
}
}
});
// Handle window resize (use setBounds to work with resizable:false)
ipcMain.on('resize-window', (event, width, height) => {
const win = BrowserWindow.fromWebContents(event.sender);
if (win) {
const [x, y] = win.getPosition();
win.setBounds({ x, y, width: Math.round(width), height: Math.round(height) });
}
});
// Update app state for a window (called from renderer)
ipcMain.on('update-app-state', (event, appState) => {
const match = getWindowByWebContents(event.sender);
if (match) {
match.entry.appState = appState;
}
});
// Handle close single window
ipcMain.on('close-app', (event, appState) => {
const match = getWindowByWebContents(event.sender);
if (match) {
match.entry.appState = appState;
}
// Save all before closing
saveAllState();
const win = BrowserWindow.fromWebContents(event.sender);
if (win) {
win.destroy();
}
});
// Spawn new buddy window
ipcMain.on('new-buddy', () => {
createWindow();
});
// Load app state for this window
ipcMain.handle('load-state', (event) => {
const match = getWindowByWebContents(event.sender);
if (match && match.entry.appState) {
return match.entry.appState;
}
return null;
});
// Toggle click-through mode
ipcMain.on('toggle-clickthrough', (event, enabled) => {
const win = BrowserWindow.fromWebContents(event.sender);
if (win) {
win.setIgnoreMouseEvents(enabled, { forward: true });
}
});
// Export buddy as .buddy file (zip archive containing video + config)
ipcMain.handle('export-buddy', async (event, appState) => {
const win = BrowserWindow.fromWebContents(event.sender);
if (!appState?.videoPath) return false;
const result = await dialog.showSaveDialog(win, {
defaultPath: 'my-buddy.buddy',
filters: [{ name: 'Desktop Buddy', extensions: ['buddy'] }]
});
if (result.canceled || !result.filePath) return false;
try {
const zip = new AdmZip();
// Add video file
const videoExt = path.extname(appState.videoPath);
const videoName = 'video' + videoExt;
zip.addLocalFile(appState.videoPath, '', videoName);
// Add config
const config = {
videoFile: videoName,
chromaColor: appState.chromaColor,
chromaTolerance: appState.chromaTolerance,
opacity: appState.opacity,
maskData: appState.maskData
};
zip.addFile('buddy.json', Buffer.from(JSON.stringify(config, null, 2), 'utf8'));
zip.writeZip(result.filePath);
return true;
} catch (e) {
console.error('Export failed:', e);
return false;
}
});
// Import a .buddy file
ipcMain.handle('import-buddy', async (event) => {
const win = BrowserWindow.fromWebContents(event.sender);
const result = await dialog.showOpenDialog(win, {
properties: ['openFile'],
filters: [{ name: 'Desktop Buddy', extensions: ['buddy'] }]
});
if (result.canceled || !result.filePaths.length) return null;
try {
const zip = new AdmZip(result.filePaths[0]);
const configEntry = zip.getEntry('buddy.json');
if (!configEntry) return null;
const config = JSON.parse(zip.readAsText(configEntry));
// Extract video to a temp dir in userData
const buddyDir = path.join(app.getPath('userData'), 'imported-buddies', path.basename(result.filePaths[0], '.buddy') + '-' + Date.now());
fs.mkdirSync(buddyDir, { recursive: true });
zip.extractAllTo(buddyDir, true);
const videoPath = path.join(buddyDir, config.videoFile);
if (!fs.existsSync(videoPath)) return null;
const state = {
videoPath: videoPath,
chromaEnabled: !!config.chromaColor,
chromaColor: config.chromaColor,
chromaTolerance: config.chromaTolerance,
opacity: config.opacity,
maskData: config.maskData
};
createWindow(state);
return true;
} catch (e) {
console.error('Import failed:', e);
return null;
}
});
// Save all state before quitting
app.on('before-quit', () => {
saveAllState();
});
// Tutorial tracking via file (reliable across all windows)
ipcMain.handle('should-show-tutorial', () => {
return !fs.existsSync(tutorialFile);
});
ipcMain.on('tutorial-seen', () => {
try {
fs.writeFileSync(tutorialFile, '1');
} catch (e) { /* ignore */ }
});
// --- Controls window IPC ---
// Buddy requests to open controls
ipcMain.on('open-controls', (event, controlsState) => {
const match = getWindowByWebContents(event.sender);
if (match) {
match.entry.controlsState = controlsState;
openControlsWindow(match.id);
}
});
// Controls window requests its initial state
ipcMain.handle('controls-get-state', (event) => {
const match = getEntryByControlsWebContents(event.sender);
if (match) {
return match.entry.controlsState || {};
}
return {};
});
// Controls sends a setting update → relay to buddy
ipcMain.on('controls-update-setting', (event, key, value) => {
const match = getEntryByControlsWebContents(event.sender);
if (match && match.entry.window && !match.entry.window.isDestroyed()) {
match.entry.window.webContents.send('setting-update', key, value);
}
});
// Controls requests eyedropper mode → relay to buddy
ipcMain.on('controls-start-eyedropper', (event) => {
const match = getEntryByControlsWebContents(event.sender);
if (match && match.entry.window && !match.entry.window.isDestroyed()) {
match.entry.window.webContents.send('start-eyedropper');
}
});
// Buddy picked a color → relay to controls
ipcMain.on('buddy-color-picked', (event, color) => {
const match = getWindowByWebContents(event.sender);
if (match && match.entry.controlsWindow && !match.entry.controlsWindow.isDestroyed()) {
match.entry.controlsWindow.webContents.send('buddy-color-picked', color);
}
});
// Controls toggles mask → relay to buddy
ipcMain.on('controls-toggle-mask', (event) => {
const match = getEntryByControlsWebContents(event.sender);
if (match && match.entry.window && !match.entry.window.isDestroyed()) {
match.entry.window.webContents.send('toggle-mask');
}
});
// Buddy reports mask state → relay to controls
ipcMain.on('buddy-mask-state', (event, active) => {
const match = getWindowByWebContents(event.sender);
if (match && match.entry.controlsWindow && !match.entry.controlsWindow.isDestroyed()) {
match.entry.controlsWindow.webContents.send('buddy-mask-state', active);
}
});
// Controls clears mask → relay to buddy
ipcMain.on('controls-clear-mask', (event) => {
const match = getEntryByControlsWebContents(event.sender);
if (match && match.entry.window && !match.entry.window.isDestroyed()) {
match.entry.window.webContents.send('clear-mask');
}
});
// Controls requests video change → open dialog for buddy
ipcMain.handle('controls-change-video', async (event) => {
const match = getEntryByControlsWebContents(event.sender);
if (match && match.entry.window && !match.entry.window.isDestroyed()) {
const result = await dialog.showOpenDialog(match.entry.window, {
properties: ['openFile'],
filters: [{ name: 'Media Files', extensions: ['webm', 'mp4', 'gif', 'webp', 'png', 'jpg', 'jpeg'] }]
});
if (!result.canceled && result.filePaths.length > 0) {
match.entry.window.webContents.send('load-new-video', result.filePaths[0]);
return true;
}
}
return false;
});
// Controls requests size reset → relay to buddy
ipcMain.on('controls-reset-size', (event) => {
const match = getEntryByControlsWebContents(event.sender);
if (match && match.entry.window && !match.entry.window.isDestroyed()) {
match.entry.window.webContents.send('reset-size');
}
});
// Controls requests export → relay through buddy
ipcMain.handle('controls-export-buddy', async (event) => {
const match = getEntryByControlsWebContents(event.sender);
if (match && match.entry.window && !match.entry.window.isDestroyed()) {
match.entry.window.webContents.send('do-export');
return true;
}
return false;
});
// Controls requests close buddy
ipcMain.on('controls-close-buddy', (event) => {
const match = getEntryByControlsWebContents(event.sender);
if (match && match.entry.window && !match.entry.window.isDestroyed()) {
// Close controls first
if (match.entry.controlsWindow && !match.entry.controlsWindow.isDestroyed()) {
match.entry.controlsWindow.destroy();
}
// Tell buddy to save state and close
match.entry.window.webContents.send('close-requested');
}
});