-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
489 lines (415 loc) · 15.1 KB
/
main.js
File metadata and controls
489 lines (415 loc) · 15.1 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
const { app, BrowserWindow, ipcMain, dialog, Menu } = require('electron');
const path = require('path');
const fs = require('fs');
const fsPromises = fs.promises;
const { convertToMZFormat, isPathSafe } = require('./src/lib/mz-converter');
const { logger, isDev } = require('./src/lib/main-logger');
// Async helper to check if path exists
async function pathExists(p) {
try {
await fsPromises.access(p);
return true;
} catch {
return false;
}
}
// Use software rendering to avoid GPU errors
app.disableHardwareAcceleration();
app.commandLine.appendSwitch('use-gl', 'swiftshader');
let mainWindow;
let projectPath = null;
function createWindow() {
mainWindow = new BrowserWindow({
width: 1600,
height: 900,
minWidth: 1200,
minHeight: 700,
show: false, // Don't show until maximized
icon: path.join(__dirname, 'assets', 'icon.png'),
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
sandbox: true,
webSecurity: true,
preload: path.join(__dirname, 'preload.js'),
zoomFactor: 1.0 // No auto-scaling - user can adjust with Ctrl+/Ctrl-
},
title: 'Timeline Scene Builder'
});
// Maximize and show window when ready
mainWindow.once('ready-to-show', () => {
mainWindow.maximize();
mainWindow.show();
});
logger.info('Window created');
mainWindow.loadFile('src/index.html');
// Allow manual zoom with Ctrl+Plus/Minus
mainWindow.webContents.on('before-input-event', (event, input) => {
if (input.control) {
if (input.key === '=' || input.key === '+') {
mainWindow.webContents.setZoomFactor(mainWindow.webContents.getZoomFactor() + 0.1);
event.preventDefault();
} else if (input.key === '-') {
mainWindow.webContents.setZoomFactor(Math.max(0.5, mainWindow.webContents.getZoomFactor() - 0.1));
event.preventDefault();
} else if (input.key === '0') {
mainWindow.webContents.setZoomFactor(1.0);
event.preventDefault();
}
}
});
// Open DevTools in dev mode
if (process.argv.includes('--dev')) {
mainWindow.webContents.openDevTools();
}
}
app.whenReady().then(() => {
logger.info('App ready', isDev ? '(dev mode)' : '(production mode)');
Menu.setApplicationMenu(null); // Hide default menu bar
createWindow();
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
// IPC Handlers
// Open project folder
ipcMain.handle('open-project', async () => {
const result = await dialog.showOpenDialog(mainWindow, {
properties: ['openDirectory'],
title: 'Select RPG Maker MZ Project Folder'
});
if (!result.canceled && result.filePaths.length > 0) {
projectPath = result.filePaths[0];
// Verify it's an MZ project
const gameFile = path.join(projectPath, 'game.rmmzproject');
if (!(await pathExists(gameFile))) {
logger.warn('Invalid MZ project folder (game.rmmzproject not found):', projectPath);
return { error: 'Not a valid RPG Maker MZ project folder (game.rmmzproject not found)' };
}
logger.info('Project opened:', projectPath);
return { path: projectPath };
}
return null;
});
// Set project path directly (for recent projects)
ipcMain.handle('set-project-path', async (event, projPath) => {
if (!projPath || typeof projPath !== 'string' || !path.isAbsolute(projPath) || projPath.includes('\0')) {
return { error: 'Invalid project path' };
}
// Verify it's a valid RPG Maker MZ project
const gameFile = path.join(projPath, 'game.rmmzproject');
if (!(await pathExists(gameFile))) {
logger.warn('set-project-path: invalid MZ project folder:', projPath);
return { error: 'Not a valid RPG Maker MZ project folder' };
}
projectPath = projPath;
logger.info('Project path set:', projectPath);
return { success: true, path: projectPath };
});
// Get screen resolution from System.json
ipcMain.handle('get-screen-resolution', async () => {
if (!projectPath) return { width: 816, height: 624 }; // Default RPG Maker MZ
const systemPath = path.join(projectPath, 'data', 'System.json');
if (!(await pathExists(systemPath))) {
return { width: 816, height: 624 }; // Default RPG Maker MZ
}
try {
const data = JSON.parse(await fsPromises.readFile(systemPath, 'utf8'));
const width = data.advanced?.screenWidth ?? 816;
const height = data.advanced?.screenHeight ?? 624;
logger.debug('Screen resolution:', width, 'x', height);
return { width, height };
} catch (e) {
logger.warn('Failed to read System.json, using defaults:', e.message);
return { width: 816, height: 624 }; // Default on error
}
});
// Get pictures folder structure (lazy loading - only folder names first)
ipcMain.handle('get-pictures-folders', async () => {
if (!projectPath) return { error: 'No project loaded' };
const picturesPath = path.join(projectPath, 'img', 'pictures');
if (!(await pathExists(picturesPath))) {
logger.warn('Pictures folder not found:', picturesPath);
return { error: 'Pictures folder not found' };
}
logger.debug('Scanning pictures folders:', picturesPath);
return await scanDirectory(picturesPath, picturesPath);
});
async function scanDirectory(dirPath, basePath, depth = 0) {
const items = [];
let entries;
try {
entries = await fsPromises.readdir(dirPath, { withFileTypes: true });
} catch (e) {
logger.warn('Failed to read directory, skipping:', dirPath, e.message);
return items;
}
for (const entry of entries) {
const fullPath = path.join(dirPath, entry.name);
const relativePath = path.relative(basePath, fullPath);
if (entry.isDirectory()) {
// Skip claude_only folders
if (entry.name === 'claude_only') continue;
items.push({
type: 'folder',
name: entry.name,
path: relativePath.replace(/\\/g, '/'),
children: depth < 2 ? await scanDirectory(fullPath, basePath, depth + 1) : null // Lazy load deeper
});
} else if (entry.name.toLowerCase().endsWith('.png')) {
items.push({
type: 'file',
name: entry.name.replace('.png', ''),
path: relativePath.replace(/\\/g, '/').replace('.png', '')
});
}
}
return items;
}
// Get folder contents (for lazy loading) - returns both subfolders and images
ipcMain.handle('get-folder-contents', async (event, folderPath) => {
if (!projectPath) return { error: 'No project loaded' };
const picturesBase = path.join(projectPath, 'img', 'pictures');
if (!isPathSafe(picturesBase, folderPath)) {
logger.warn('Blocked unsafe folder path:', folderPath);
return { error: 'Invalid folder path' };
}
const fullPath = path.join(picturesBase, folderPath);
if (!(await pathExists(fullPath))) {
logger.warn('Folder not found:', fullPath);
return { error: 'Folder not found' };
}
logger.debug('Loading folder contents:', folderPath);
const items = [];
let entries;
try {
entries = await fsPromises.readdir(fullPath, { withFileTypes: true });
} catch (e) {
logger.error('Failed to read folder contents:', fullPath, e.message);
return { error: `Failed to read folder: ${e.message}` };
}
for (const entry of entries) {
// Skip claude_only folders
if (entry.name === 'claude_only') continue;
if (entry.isDirectory()) {
const relativePath = path.join(folderPath, entry.name).replace(/\\/g, '/');
items.push({
type: 'folder',
name: entry.name,
path: relativePath,
children: null // Will be lazy loaded when expanded
});
} else if (entry.isFile() && entry.name.toLowerCase().endsWith('.png')) {
const relativePath = path.join(folderPath, entry.name.replace('.png', '')).replace(/\\/g, '/');
items.push({
type: 'file',
name: entry.name.replace('.png', ''),
path: relativePath
});
}
}
return items;
});
// Get thumbnail for lazy loading (returns base64)
ipcMain.handle('get-thumbnail', async (event, imagePath) => {
if (!projectPath) return null;
const picturesBase = path.join(projectPath, 'img', 'pictures');
if (!isPathSafe(picturesBase, `${imagePath}.png`)) {
logger.warn('Blocked unsafe thumbnail path:', imagePath);
return null;
}
const fullPath = path.join(picturesBase, `${imagePath}.png`);
if (!(await pathExists(fullPath))) return null;
try {
const data = await fsPromises.readFile(fullPath);
return `data:image/png;base64,${data.toString('base64')}`;
} catch {
logger.debug('Failed to read thumbnail:', imagePath);
return null;
}
});
// Get full image path for preview
ipcMain.handle('get-image-path', async (event, imagePath) => {
if (!projectPath) return null;
const picturesBase = path.join(projectPath, 'img', 'pictures');
if (!isPathSafe(picturesBase, `${imagePath}.png`)) {
logger.warn('Blocked unsafe image path:', imagePath);
return null;
}
const fullPath = path.join(picturesBase, `${imagePath}.png`);
if (!(await pathExists(fullPath))) return null;
return fullPath;
});
// Export events to a Map JSON file (insert into specific event)
ipcMain.handle('export-to-map', async (event, { events: evtList, mapId, eventId, pageIndex }) => {
if (!projectPath) return { error: 'No project loaded' };
// Validate inputs from renderer
if (!Number.isInteger(mapId) || mapId < 1 || mapId > 999) {
return { error: 'Invalid map ID' };
}
if (!Number.isInteger(eventId) || eventId < 1) {
return { error: 'Invalid event ID' };
}
const safePageIndex = pageIndex ?? 0;
if (!Number.isInteger(safePageIndex) || safePageIndex < 0) {
return { error: 'Invalid page index' };
}
const mapFile = path.join(projectPath, 'data', `Map${String(mapId).padStart(3, '0')}.json`);
if (!(await pathExists(mapFile))) {
return { error: `Map file not found: Map${String(mapId).padStart(3, '0')}.json` };
}
logger.info('Export to map:', { mapId, eventId, pageIndex: safePageIndex });
try {
const mapData = JSON.parse(await fsPromises.readFile(mapFile, 'utf-8'));
const mzCommands = convertToMZFormat(evtList);
// Find the event
const mapEvent = mapData.events.find((e) => e && e.id === eventId);
if (!mapEvent) {
return { error: `Event ID ${eventId} not found in map` };
}
const page = mapEvent.pages[safePageIndex];
if (!page) {
return { error: `Page ${safePageIndex} not found in event` };
}
// Validate page structure
if (page.list.length === 0 || page.list[page.list.length - 1]?.code !== 0) {
return { error: 'Invalid event page structure: missing terminating command' };
}
// Replace existing content, keeping only the terminating {code: 0}
const terminator = page.list[page.list.length - 1];
page.list = [...mzCommands, terminator];
// Save the map file
await fsPromises.writeFile(mapFile, JSON.stringify(mapData, null, 2));
logger.info('Export success:', mzCommands.length, 'commands written');
return { success: true, commandCount: mzCommands.length };
} catch (e) {
logger.error('Export failed:', e.message);
return { error: e.message };
}
});
// Get list of maps in project
ipcMain.handle('get-maps', async () => {
if (!projectPath) return { error: 'No project loaded' };
const mapInfoFile = path.join(projectPath, 'data', 'MapInfos.json');
if (!(await pathExists(mapInfoFile))) {
return { error: 'MapInfos.json not found' };
}
try {
const mapInfos = JSON.parse(await fsPromises.readFile(mapInfoFile, 'utf-8'));
const maps = mapInfos.filter((m) => m).map((m) => ({ id: m.id, name: m.name }));
logger.debug('Loaded', maps.length, 'maps');
return maps;
} catch (e) {
logger.error('Failed to load maps:', e.message);
return { error: e.message };
}
});
// Get events in a map
ipcMain.handle('get-map-events', async (event, mapId) => {
if (!projectPath) return { error: 'No project loaded' };
if (!Number.isInteger(mapId) || mapId < 1 || mapId > 999) {
return { error: 'Invalid map ID' };
}
const mapFile = path.join(projectPath, 'data', `Map${String(mapId).padStart(3, '0')}.json`);
if (!(await pathExists(mapFile))) {
return { error: 'Map file not found' };
}
try {
const mapData = JSON.parse(await fsPromises.readFile(mapFile, 'utf-8'));
const events = mapData.events.filter((e) => e).map((e) => ({ id: e.id, name: e.name, pages: e.pages.length }));
logger.debug('Map', mapId, ':', events.length, 'events');
return events;
} catch (e) {
logger.error('Failed to load map events for map', mapId, ':', e.message);
return { error: e.message };
}
});
// Save scene to file
ipcMain.handle('save-scene', async (event, sceneData) => {
try {
const result = await dialog.showSaveDialog(mainWindow, {
title: 'Save Scene',
defaultPath: projectPath ? path.join(projectPath, 'scenes') : undefined,
filters: [{ name: 'Scene Files', extensions: ['mzscene'] }]
});
if (!result.canceled && result.filePath) {
await fsPromises.writeFile(result.filePath, JSON.stringify(sceneData, null, 2));
logger.info('Scene saved:', result.filePath);
return result.filePath;
}
return null;
} catch (e) {
logger.error('Failed to save scene:', e.message);
return { error: e.message };
}
});
// Load scene from file
ipcMain.handle('load-scene', async () => {
try {
const result = await dialog.showOpenDialog(mainWindow, {
title: 'Load Scene',
filters: [{ name: 'Scene Files', extensions: ['mzscene'] }],
properties: ['openFile']
});
if (!result.canceled && result.filePaths.length > 0) {
const data = await fsPromises.readFile(result.filePaths[0], 'utf-8');
logger.info('Scene loaded:', result.filePaths[0]);
return JSON.parse(data);
}
return null;
} catch (e) {
logger.error('Failed to load scene:', e.message);
return { error: e.message };
}
});
// Autosave handlers
const os = require('os');
const AUTOSAVE_PATH = path.join(os.tmpdir(), 'timeline-scene-builder', 'autosave.mzscene');
async function ensureAutosaveDir() {
const dir = path.dirname(AUTOSAVE_PATH);
if (!(await pathExists(dir))) {
await fsPromises.mkdir(dir, { recursive: true });
}
}
ipcMain.handle('autosave-write', async (event, sceneData) => {
try {
await ensureAutosaveDir();
await fsPromises.writeFile(AUTOSAVE_PATH, JSON.stringify(sceneData, null, 2));
logger.debug('Autosave written');
return { success: true };
} catch (e) {
return { error: e.message };
}
});
ipcMain.handle('autosave-read', async () => {
try {
if (!(await pathExists(AUTOSAVE_PATH))) return null;
const data = await fsPromises.readFile(AUTOSAVE_PATH, 'utf-8');
logger.debug('Autosave read');
return JSON.parse(data);
} catch (e) {
logger.warn('Failed to read autosave file:', e.message);
return null;
}
});
ipcMain.handle('autosave-delete', async () => {
try {
if (await pathExists(AUTOSAVE_PATH)) {
await fsPromises.unlink(AUTOSAVE_PATH);
logger.debug('Autosave deleted');
}
return { success: true };
} catch (e) {
return { error: e.message };
}
});
ipcMain.handle('autosave-exists', async () => {
return await pathExists(AUTOSAVE_PATH);
});