forked from clickysteve/dmg-darkroom
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
532 lines (455 loc) · 19.5 KB
/
Copy pathmain.js
File metadata and controls
532 lines (455 loc) · 19.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
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
const { app, BrowserWindow, ipcMain, dialog, Menu, shell } = require('electron');
const path = require('path');
const fs = require('fs');
// ─── Coerce a file to a 128KB GB Camera SRAM ────────────────────────────────
// A plain .sav/.srm is already 131072 bytes. An Analogue Pocket savestate (.sta)
// embeds the cart RAM inside a larger blob; we locate it by the GB Camera
// management block — the "Magic" string appears twice, 0xFE apart (echo at cart
// RAM 0x10D2, primary at 0x11D0) — then slice 128KB from the cart-RAM base.
function coerceGbCamSave(buf) {
if (buf.length === 131072) return buf;
const isMagic = (p) => buf[p] === 0x4D && buf[p+1] === 0x61 && buf[p+2] === 0x67 && buf[p+3] === 0x69 && buf[p+4] === 0x63; // "Magic"
for (let i = 0x10D2; i + 0xFE + 5 <= buf.length; i++) {
if (isMagic(i) && isMagic(i + 0xFE)) { // echo + primary pair = the management block
const base = i - 0x10D2; // cart RAM offset 0
if (base < 0) continue;
const out = Buffer.alloc(131072, 0xFF);
buf.copy(out, 0, base, Math.min(buf.length, base + 131072));
return out;
}
}
return null; // no GB Camera cart RAM found inside
}
// ─── GB Camera 2bpp preview decoder ─────────────────────────────────────────
// Inline port of the decode logic from renderer/js/gbcam.js (Node-safe, no DOM).
// Returns a plain Array of pixel indices (0–3, length 14336) for the first
// non-empty photo in the given save file, or null if decoding fails / all empty.
function decodeFirstPhotoPreview(filePath) {
try {
const buf = fs.readFileSync(filePath);
if (buf.length !== 131072) return null;
const PHOTO_DATA_OFFSET = 0x2000;
const SLOT_SIZE = 0x1000;
const BYTES_PER_PHOTO = 3584; // 224 tiles × 16 bytes
const PHOTO_WIDTH = 128;
const PHOTO_HEIGHT = 112;
const TILES_WIDE = 16;
const TILES_TALL = 14;
const BYTES_PER_TILE = 16;
function isEmpty(idx) {
const off = PHOTO_DATA_OFFSET + idx * SLOT_SIZE;
const freq = new Uint32Array(256);
for (let i = 0; i < BYTES_PER_PHOTO; i++) freq[buf[off + i]]++;
return Math.max(...freq) / BYTES_PER_PHOTO > 0.96;
}
function decode(idx) {
const photoOff = PHOTO_DATA_OFFSET + idx * SLOT_SIZE;
const pixels = new Uint8Array(PHOTO_WIDTH * PHOTO_HEIGHT);
for (let tr = 0; tr < TILES_TALL; tr++) {
for (let tc = 0; tc < TILES_WIDE; tc++) {
const tOff = photoOff + (tr * TILES_WIDE + tc) * BYTES_PER_TILE;
for (let row = 0; row < 8; row++) {
const lo = buf[tOff + row * 2];
const hi = buf[tOff + row * 2 + 1];
for (let col = 0; col < 8; col++) {
const bit = 7 - col;
pixels[(tr * 8 + row) * PHOTO_WIDTH + tc * 8 + col] =
((hi >> bit) & 1) << 1 | ((lo >> bit) & 1);
}
}
}
}
return pixels;
}
for (let i = 0; i < 30; i++) {
if (!isEmpty(i)) return Array.from(decode(i));
}
return null;
} catch (_) {
return null;
}
}
// ─── Window ────────────────────────────────────────────────────────────────
let mainWindow;
function createWindow() {
mainWindow = new BrowserWindow({
width: 1200,
height: 800,
minWidth: 900,
minHeight: 600,
titleBarStyle: 'hiddenInset',
backgroundColor: '#111113',
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true,
nodeIntegration: false,
sandbox: false,
},
});
mainWindow.loadFile(path.join(__dirname, 'renderer', 'index.html'));
if (process.env.NODE_ENV === 'development') {
mainWindow.webContents.openDevTools();
}
}
app.whenReady().then(() => {
createWindow();
buildMenu();
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') app.quit();
});
// ─── Menu ───────────────────────────────────────────────────────────────────
function buildMenu() {
const template = [
{
label: app.name,
submenu: [
{ role: 'about' },
{ type: 'separator' },
{ role: 'hide' },
{ role: 'hideOthers' },
{ role: 'unhide' },
{ type: 'separator' },
{ role: 'quit' },
],
},
{
label: 'File',
submenu: [
{
label: 'Open .sav File…',
accelerator: 'CmdOrCtrl+O',
click: () => mainWindow.webContents.send('menu-open-sav'),
},
{
label: 'Open from Analogue Pocket…',
accelerator: 'CmdOrCtrl+Shift+O',
click: () => mainWindow.webContents.send('menu-open-pocket'),
},
{ type: 'separator' },
{
label: 'Export All Photos…',
accelerator: 'CmdOrCtrl+Shift+E',
click: () => mainWindow.webContents.send('menu-export-all'),
},
],
},
{
label: 'Edit',
submenu: [
{ role: 'undo' },
{ role: 'redo' },
{ type: 'separator' },
{ role: 'cut' },
{ role: 'copy' },
{ role: 'paste' },
{ type: 'separator' },
{ role: 'selectAll' },
],
},
{
label: 'View',
submenu: [
{ role: 'reload' },
{ role: 'forceReload' },
{ type: 'separator' },
{ role: 'togglefullscreen' },
],
},
];
Menu.setApplicationMenu(Menu.buildFromTemplate(template));
}
// ─── IPC: Open .sav ─────────────────────────────────────────────────────────
ipcMain.handle('open-sav-file', async () => {
const { canceled, filePaths } = await dialog.showOpenDialog(mainWindow, {
title: 'Open Game Boy Camera .sav file',
filters: [
{ name: 'Game Boy Camera Save / Savestate', extensions: ['sav', 'SAV', 'srm', 'SRM', 'sta', 'STA'] },
{ name: 'All files', extensions: ['*'] },
],
properties: ['openFile'],
});
if (canceled || filePaths.length === 0) return null;
const filePath = filePaths[0];
const raw = fs.readFileSync(filePath);
// Accept a 128KB .sav/.srm, or extract the cart RAM from a Pocket savestate (.sta etc.)
const buffer = coerceGbCamSave(raw);
if (!buffer) {
return { error: `Unexpected file size: ${raw.length} bytes (expected 131072, or a savestate containing a GB Camera save).`, buffer: raw.buffer.slice(raw.byteOffset, raw.byteOffset + raw.byteLength), name: path.basename(filePath) };
}
return {
buffer: buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength),
name: path.basename(filePath),
path: filePath,
};
});
// ─── IPC: Detect Analogue Pocket SD card ─────────────────────────────────
ipcMain.handle('detect-pocket', async () => {
if (process.platform !== 'darwin' && process.platform !== 'win32') {
return { saves: [] };
}
const volumeRoots = [];
if (process.platform === 'darwin') {
try {
const volumes = fs.readdirSync('/Volumes').filter(v => !v.startsWith('.'));
for (const vol of volumes) {
volumeRoots.push(path.join('/Volumes', vol));
}
} catch (_) {}
} else if (process.platform === 'win32') {
for (const letter of 'DEFGHIJKLMNOPQRSTUVWXYZ') {
volumeRoots.push(`${letter}:\\`);
}
}
const fsp = fs.promises;
const exists = async (p) => { try { await fsp.access(p); return true; } catch (_) { return false; } };
// Collect 128KB .sav/.srm files in a directory, with bounded (shallow) recursion.
// We deliberately keep maxDepth tiny so we never walk into the huge Assets/ tree —
// only the few folders where the Pocket actually stores camera saves get scanned.
async function collectSavFiles(dir, volumeName, out, depth, maxDepth) {
let entries;
try { entries = await fsp.readdir(dir, { withFileTypes: true }); } catch (_) { return; }
for (const entry of entries) {
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
if (depth < maxDepth) await collectSavFiles(fullPath, volumeName, out, depth + 1, maxDepth);
} else if (['sav','srm'].includes(entry.name.toLowerCase().split('.').pop())) {
try {
const st = await fsp.stat(fullPath);
if (st.size === 131072) out.push({ path: fullPath, name: entry.name, volume: volumeName });
} catch (_) {}
}
}
}
// Scan one volume root; returns the camera saves found on it (or []).
async function scanRoot(root) {
const volume = process.platform === 'win32' ? root.replace(/\\+$/, '') : path.basename(root);
const out = [];
// Identify an Analogue Pocket SD card: Assets/ (on every AP card) or Memories/.
const [hasAssets, hasMemories, hasSaves] = await Promise.all([
exists(path.join(root, 'Assets')),
exists(path.join(root, 'Memories')),
exists(path.join(root, 'Saves')),
]);
if (!hasAssets && !hasMemories) return out;
const jobs = [];
if (hasMemories) {
// Primary: Memories/Save States/ (Memories > Save States UI). Flat folder.
jobs.push(collectSavFiles(path.join(root, 'Memories', 'Save States'), volume, out, 0, 1));
// Flat-layout fallback: direct files in Memories/ only (no recursion).
jobs.push(collectSavFiles(path.join(root, 'Memories'), volume, out, 0, 0));
}
if (hasSaves) {
// openFPGA cores: Saves/<core>/ — known core folders only, shallow.
for (const core of ['gb', 'gbc', 'Game Boy', 'GameBoy', 'Analogue.gb', 'Analogue.gbc']) {
jobs.push(collectSavFiles(path.join(root, 'Saves', core), volume, out, 0, 1));
}
}
await Promise.all(jobs);
return out;
}
// Probe every candidate volume IN PARALLEL — a slow/phantom Windows drive no
// longer blocks the others (that serial probing was the main cause of the freeze).
const perRoot = await Promise.all(volumeRoots.map(scanRoot));
const saves = perRoot.flat();
// Deduplicate by path (Memories root scan + Save States scan may overlap)
const seen = new Set();
const unique = saves.filter(s => { if (seen.has(s.path)) return false; seen.add(s.path); return true; });
// Attach a preview (first non-empty photo, pixel indices 0–3) to each save
for (const save of unique) {
save.previewPixels = decodeFirstPhotoPreview(save.path);
}
return { saves: unique };
});
// ─── IPC: Delete a save from the Analogue Pocket SD card ─────────────────────
ipcMain.handle('delete-pocket-save', async (_event, saveObj) => {
const filePath = typeof saveObj === 'string' ? saveObj : saveObj.path;
if (!filePath) return { error: 'No file path provided.' };
// Safety net: only ever delete a genuine 128KB GB Camera save — never any
// other file the path might accidentally point at.
try {
const st = await fs.promises.stat(filePath);
if (!st.isFile() || st.size !== 131072) {
return { error: 'Refusing to delete: not a 128KB Game Boy Camera save.' };
}
} catch (e) {
return { error: e.message };
}
const { response } = await dialog.showMessageBox(mainWindow, {
type: 'warning',
buttons: ['Cancel', 'Delete'],
defaultId: 0,
cancelId: 0,
title: 'Delete save',
message: 'Delete this save from your Analogue Pocket?',
detail: `${path.basename(filePath)}\n\nThis permanently removes the file from the SD card. This cannot be undone.`,
});
if (response !== 1) return { canceled: true };
try {
await fs.promises.unlink(filePath);
return { deleted: true };
} catch (e) {
return { error: e.message };
}
});
ipcMain.handle('read-file', async (_event, saveObj) => {
// saveObj may be a string (legacy) or { path } object
const filePath = typeof saveObj === 'string' ? saveObj : saveObj.path;
try {
const raw = fs.readFileSync(filePath);
const buffer = coerceGbCamSave(raw);
if (!buffer) {
return { error: `Unexpected file size: ${raw.length} bytes (expected 131072, or a savestate containing a GB Camera save).` };
}
return {
buffer: buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength),
name: path.basename(filePath),
path: filePath,
};
} catch (e) {
return { error: e.message };
}
});
// ─── IPC: Save PNG ──────────────────────────────────────────────────────────
ipcMain.handle('save-png', async (_event, dataUrl, defaultName) => {
const { canceled, filePath } = await dialog.showSaveDialog(mainWindow, {
title: 'Export Photo as PNG',
defaultPath: defaultName,
filters: [{ name: 'PNG Images', extensions: ['png'] }],
});
if (canceled || !filePath) return null;
// dataUrl is "data:image/png;base64,..."
const base64 = dataUrl.replace(/^data:image\/png;base64,/, '');
fs.writeFileSync(filePath, Buffer.from(base64, 'base64'));
return filePath;
});
// ─── IPC: Save GIF ──────────────────────────────────────────────────────────
// Receives: { frames: [{indices: number[], palette: number[][], width, height}], delay, scale }
// Uses omggif (CommonJS) to encode the GIF in the main process
ipcMain.handle('save-gif', async (_event, options) => {
const { frames, delay, scale, loop, defaultName } = options;
const { canceled, filePath } = await dialog.showSaveDialog(mainWindow, {
title: 'Export Animated GIF',
defaultPath: defaultName || 'gbcam-animation.gif',
filters: [{ name: 'GIF Images', extensions: ['gif'] }],
});
if (canceled || !filePath) return null;
try {
const gifBuffer = encodeGif(frames, delay, scale, loop);
fs.writeFileSync(filePath, gifBuffer);
return filePath;
} catch (e) {
return { error: e.message };
}
});
// ─── IPC: Save batch PNGs ───────────────────────────────────────────────────
ipcMain.handle('save-png-batch', async (_event, photos) => {
// photos: [{ dataUrl, name }]
const { canceled, filePaths } = await dialog.showOpenDialog(mainWindow, {
title: 'Choose folder for batch export',
properties: ['openDirectory', 'createDirectory'],
});
if (canceled || filePaths.length === 0) return null;
const dir = filePaths[0];
for (const { dataUrl, name } of photos) {
const base64 = dataUrl.replace(/^data:image\/png;base64,/, '');
const outPath = path.join(dir, name);
fs.mkdirSync(path.dirname(outPath), { recursive: true }); // `name` may include a dated sub-folder
fs.writeFileSync(outPath, Buffer.from(base64, 'base64'));
}
return { dir, count: photos.length };
});
// ─── IPC: Export raw .sav ───────────────────────────────────────────────────
ipcMain.handle('export-sav', async (_event, { buffer, defaultName }) => {
const { canceled, filePath } = await dialog.showSaveDialog(mainWindow, {
title: 'Export .sav file',
defaultPath: defaultName,
filters: [{ name: 'GB Camera Save', extensions: ['sav', 'SAV'] }],
});
if (canceled || !filePath) return null;
fs.writeFileSync(filePath, Buffer.from(buffer));
return path.basename(filePath);
});
// ─── IPC: Save project (.gbcp) ──────────────────────────────────────────────
ipcMain.handle('save-project', async (_event, { json, defaultName }) => {
const { canceled, filePath } = await dialog.showSaveDialog(mainWindow, {
title: 'Save MugDump Project',
defaultPath: defaultName,
filters: [{ name: 'GB Camera Project', extensions: ['gbcp'] }],
});
if (canceled || !filePath) return null;
fs.writeFileSync(filePath, json, 'utf8');
return path.basename(filePath);
});
// ─── IPC: Open project (.gbcp) ──────────────────────────────────────────────
ipcMain.handle('open-project', async () => {
const { canceled, filePaths } = await dialog.showOpenDialog(mainWindow, {
title: 'Open MugDump Project',
filters: [{ name: 'GB Camera Project', extensions: ['gbcp'] }],
properties: ['openFile'],
});
if (canceled || filePaths.length === 0) return null;
try {
const json = fs.readFileSync(filePaths[0], 'utf8');
return { json, name: path.basename(filePaths[0]) };
} catch (e) {
return { error: e.message };
}
});
// ─── IPC: Reveal in Finder ──────────────────────────────────────────────────
ipcMain.handle('reveal-in-finder', async (_event, filePath) => {
shell.showItemInFolder(filePath);
});
// ─── IPC: Fetch JSON (for Lospec palette import) ─────────────────────────────
// Fetched in main process so it bypasses renderer CSP and CORS restrictions.
ipcMain.handle('fetch-json', async (_event, url) => {
const res = await fetch(url);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
});
// ─── GIF Encoder ────────────────────────────────────────────────────────────
function scaleIndices(indices, width, height, scale) {
if (scale === 1) return indices;
const sw = width * scale;
const sh = height * scale;
const out = new Uint8Array(sw * sh);
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const val = indices[y * width + x];
for (let dy = 0; dy < scale; dy++) {
for (let dx = 0; dx < scale; dx++) {
out[(y * scale + dy) * sw + (x * scale + dx)] = val;
}
}
}
}
return out;
}
function encodeGif(frames, delayMs, scale, loop) {
const { GifWriter } = require('omggif');
const width = frames[0].width * scale;
const height = frames[0].height * scale;
const delayCs = Math.max(1, Math.round(delayMs / 10)); // centiseconds
// loop: 'infinite' or 'bounce' → repeat forever (0); 'once' → no Netscape extension
const gwOpts = (loop === 'once') ? {} : { loop: 0 };
// Allocate a buffer large enough (frames × pixels × worst-case LZW expansion)
const bufSize = width * height * frames.length * 2 + 100000;
const buf = Buffer.alloc(bufSize);
const gw = new GifWriter(buf, width, height, gwOpts);
for (const frame of frames) {
const scaled = scaleIndices(new Uint8Array(frame.indices), frame.width, frame.height, scale);
// omggif expects palette as [0xRRGGBB, ...]
const palette = frame.palette.map(([r, g, b]) => (r << 16) | (g << 8) | b);
// Pad palette to power of 2 (minimum 4 entries for 2-bit)
while (palette.length < 4) palette.push(0);
gw.addFrame(0, 0, width, height, scaled, {
palette,
delay: delayCs,
disposal: 2,
});
}
return buf.slice(0, gw.end());
}