-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathelectron.js
More file actions
1708 lines (1537 loc) · 61.6 KB
/
Copy pathelectron.js
File metadata and controls
1708 lines (1537 loc) · 61.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
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { logger, electronLog } from './src/lib/logger.main.js';
// CRITICAL: Fix AppImage sandbox and shared memory issues
// Must inject flags into process.argv BEFORE importing electron
const isAppImage = process.env.APPIMAGE || process.env.APPDIR || /^\/tmp\/\.mount_/.test(process.execPath);
if (isAppImage) {
logger.info('[Vangard] Running in AppImage mode - injecting sandbox workarounds into process.argv');
if (!process.argv.includes('--no-sandbox')) {
process.argv.push('--no-sandbox');
}
if (!process.argv.includes('--disable-dev-shm-usage')) {
process.argv.push('--disable-dev-shm-usage');
}
logger.info('[Vangard] process.argv:', process.argv);
} else {
logger.info('[Vangard] Not running in AppImage mode');
}
import { app, BrowserWindow, ipcMain, dialog, Menu, protocol, shell, safeStorage, globalShortcut, Notification } from 'electron';
import electronUpdaterPkg from 'electron-updater';
const { autoUpdater } = electronUpdaterPkg;
import path from 'path';
import { fileURLToPath, pathToFileURL } from 'url';
import fs from 'fs/promises';
import { createReadStream, watch } from 'fs';
import { Readable } from 'stream';
import { spawn } from 'child_process';
import { Worker } from 'worker_threads';
import { deriveGuiColors } from './src/lib/colorUtils.js';
import { updateGuiRpy, updateOptionsRpy, generateSaveDirectory } from './src/lib/templateProcessor.js';
import { validateProjectPath, validateExternalUrl } from './src/lib/ipcSecurity.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// Lazy-load image generator to avoid blocking app startup if Sharp fails
let generateGuiImages = null;
let sharpLoadError = null;
// Register custom protocol privileges BEFORE app is ready
protocol.registerSchemesAsPrivileged([
{
scheme: 'media',
privileges: {
secure: true,
supportFetchAPI: true,
bypassCSP: true,
corsEnabled: true,
stream: true,
standard: true
}
}
]);
// --- CLI startup flags ---
// Supports: electron . --project /path/to/project
// electron . --user-data-dir /path/to/userData
// electron . --window-size 2560x1440
// Used by the Playwright demo recording script and power users.
const _projectArgIdx = process.argv.indexOf('--project');
const startupProjectPath = (_projectArgIdx !== -1 && _projectArgIdx + 1 < process.argv.length)
? process.argv[_projectArgIdx + 1]
: null;
const _windowSizeArgIdx = process.argv.indexOf('--window-size');
const _windowSizeArg = (_windowSizeArgIdx !== -1 && _windowSizeArgIdx + 1 < process.argv.length)
? process.argv[_windowSizeArgIdx + 1]
: null;
const _windowSizeMatch = _windowSizeArg?.match(/^(\d+)x(\d+)$/);
const startupWindowWidth = _windowSizeMatch ? parseInt(_windowSizeMatch[1], 10) : null;
const startupWindowHeight = _windowSizeMatch ? parseInt(_windowSizeMatch[2], 10) : null;
// Allow overriding settings via env var (used by Playwright screenshot capture).
// RENIDE_SETTINGS_OVERRIDE: JSON string of AppSettings to merge over the saved file.
// More reliable than --user-data-dir because Chromium intercepts that flag at the
// C++ level before process.argv is readable in Node.js code.
// --- Game Process Management ---
let gameProcess = null;
// --- Main Window Reference (for auto-updater callbacks) ---
let mainWindowRef = null;
// --- Project Root Tracking (for screenshots and other features) ---
let currentProjectRoot = null;
/**
* Throws ACCESS_DENIED if filePath is not within the current project root.
* Applied to all fs:* IPC handlers to prevent renderer-side path traversal.
*/
function guardProjectPath(filePath) {
const err = validateProjectPath(filePath, currentProjectRoot);
if (err) {
logger.warn(`IPC path guard blocked: ${err} — path: ${filePath}`);
throw new Error(`ACCESS_DENIED: ${err}`);
}
}
// --- External File Change Watcher ---
let projectWatcher = null;
const recentSelfWrites = new Map(); // normalizedAbsPath -> write timestamp ms
const watchDebounceTimers = new Map(); // normalizedAbsPath -> timeout id
const SELF_WRITE_SUPPRESS_MS = 3000;
const WATCH_DEBOUNCE_MS = 400;
function startProjectWatcher(rootPath) {
if (projectWatcher) {
try { projectWatcher.close(); } catch {
// Ignore errors when closing watcher
}
projectWatcher = null;
}
watchDebounceTimers.forEach(t => clearTimeout(t));
watchDebounceTimers.clear();
try {
projectWatcher = watch(rootPath, { recursive: true }, (eventType, filename) => {
if (!filename) return;
if (!/\.rpy$/i.test(filename)) return;
if (/^(renpy|lib|cache|tmp)[/\\]/i.test(filename)) return;
const absolutePath = path.join(rootPath, filename);
const normalizedAbs = absolutePath.replace(/\\/g, '/');
const existing = watchDebounceTimers.get(normalizedAbs);
if (existing) clearTimeout(existing);
watchDebounceTimers.set(normalizedAbs, setTimeout(() => {
watchDebounceTimers.delete(normalizedAbs);
const lastWrite = recentSelfWrites.get(normalizedAbs);
if (lastWrite && Date.now() - lastWrite < SELF_WRITE_SUPPRESS_MS) return;
const relativePath = path.relative(rootPath, absolutePath).replace(/\\/g, '/');
if (mainWindowRef && !mainWindowRef.isDestroyed()) {
mainWindowRef.webContents.send('fs:file-changed-externally', { relativePath, absolutePath: normalizedAbs });
}
}, WATCH_DEBOUNCE_MS));
});
} catch (err) {
logger.error('Failed to start file watcher:', err);
}
}
// --- Window State Management ---
const windowStatePath = path.join(app.getPath('userData'), 'window-state.json');
async function loadWindowState() {
try {
const data = await fs.readFile(windowStatePath, 'utf-8');
const state = JSON.parse(data);
if (typeof state.width === 'number' && typeof state.height === 'number') {
return state;
}
} catch {
// First launch or corrupted state — use defaults
}
return null;
}
function saveWindowState(window) {
if (!window) return;
try {
const bounds = window.getBounds();
fs.writeFile(windowStatePath, JSON.stringify(bounds));
} catch (error) {
logger.error('Failed to save window state:', error);
}
}
// --- App Settings Management ---
const appSettingsPath = path.join(app.getPath('userData'), 'app-settings.json');
async function loadAppSettings() {
let settings = null;
try {
const data = await fs.readFile(appSettingsPath, 'utf-8');
settings = JSON.parse(data);
} catch {
// No saved settings yet
}
// Playwright screenshot capture injects the production app's settings via
// this env var so the correct theme and layout prefs are used.
if (process.env.RENIDE_SETTINGS_OVERRIDE) {
try {
const override = JSON.parse(process.env.RENIDE_SETTINGS_OVERRIDE);
settings = { ...settings, ...override };
} catch { /* ignore malformed override */ }
}
return settings;
}
async function saveAppSettings(settings) {
try {
await fs.writeFile(appSettingsPath, JSON.stringify(settings, null, 2));
return { success: true };
} catch (error) {
logger.error('Failed to save app settings:', error);
return { success: false, error: error.message };
}
}
// --- API Key Management ---
const apiKeysPath = path.join(app.getPath('userData'), 'api-keys.enc');
async function loadApiKeys() {
try {
if (!safeStorage.isEncryptionAvailable()) {
return {};
}
const encryptedData = await fs.readFile(apiKeysPath);
const decryptedData = safeStorage.decryptString(encryptedData);
return JSON.parse(decryptedData);
} catch {
return {};
}
}
async function saveApiKey(provider, key) {
try {
if (!safeStorage.isEncryptionAvailable()) {
throw new Error('Safe storage encryption not available');
}
const keys = await loadApiKeys();
keys[provider] = key;
const jsonData = JSON.stringify(keys);
const encryptedData = safeStorage.encryptString(jsonData);
await fs.writeFile(apiKeysPath, encryptedData);
return { success: true };
} catch (error) {
logger.error('Failed to save API key:', error);
return { success: false, error: error.message };
}
}
async function getApiKey(provider) {
try {
const keys = await loadApiKeys();
return keys[provider] || null;
} catch (error) {
logger.error('Failed to get API key:', error);
return null;
}
}
async function checkRenpyProject(rootPath) {
try {
const entries = await fs.readdir(rootPath, { withFileTypes: true });
const hasGameFolder = entries.some(e => e.isDirectory() && e.name.toLowerCase() === 'game');
const hasRpyAtRoot = entries.some(e => e.isFile() && /\.rpy$/i.test(e.name));
let hasRpyInGame = false;
if (hasGameFolder) {
try {
const gameEntries = await fs.readdir(path.join(rootPath, 'game'), { withFileTypes: true });
hasRpyInGame = gameEntries.some(e => e.isFile() && /\.rpy$/i.test(e.name));
} catch { /* ignore */ }
}
return { hasGameFolder, isRenpyProject: hasGameFolder || hasRpyAtRoot || hasRpyInGame };
} catch {
return { hasGameFolder: false, isRenpyProject: false };
}
}
// Active worker for project loading — replaced on each load, terminated on cancel.
let activeLoadWorker = null;
// Inline worker code for reading project files in a dedicated thread.
// Using String.raw to preserve backslashes in regex patterns.
const PROJECT_LOAD_WORKER_CODE = String.raw`
const { workerData, parentPort } = require('worker_threads');
const path = require('path');
const fs = require('fs/promises');
const { pathToFileURL } = require('url');
const progress = (value, message) => parentPort.postMessage({ type: 'progress', value, message });
async function run() {
const { rootPath, readContent } = workerData;
const results = {
rootPath,
files: [],
images: [],
audios: [],
settings: null,
tree: { name: path.basename(rootPath), path: '', children: [] }
};
progress(5, 'Scanning directory...');
// Directories that are part of the Ren'Py SDK or build output — never contain
// user-authored .rpy files and must be excluded to avoid inflating file counts.
const EXCLUDED_DIRS = new Set(['renpy', 'lib', 'cache', 'tmp', '.git', 'node_modules']);
// Phase 1: Build directory tree and collect .rpy paths (no content yet)
const rpyPaths = [];
let scannedEntries = 0;
const readDirRecursive = async (dirPath, treeNode) => {
const entries = await fs.readdir(dirPath, { withFileTypes: true });
const children = [];
for (const entry of entries) {
scannedEntries++;
// Emit scan progress every 500 entries (5% → 18%, capped)
if (scannedEntries % 500 === 0) {
const pct = Math.min(18, 5 + Math.floor(scannedEntries / 500));
progress(pct, 'Scanning... (' + scannedEntries.toLocaleString() + ' entries)');
}
const fullPath = path.join(dirPath, entry.name);
const relativePath = path.relative(rootPath, fullPath).replace(/\\/g, '/');
const childNode = { name: entry.name, path: relativePath, children: entry.isDirectory() ? [] : undefined };
if (entry.isDirectory()) {
if (EXCLUDED_DIRS.has(entry.name.toLowerCase())) continue;
await readDirRecursive(fullPath, childNode);
} else if (entry.isFile()) {
if (/\.(rpy)$/i.test(entry.name)) {
rpyPaths.push({ fullPath, relativePath });
} else if (/\.(png|jpe?g|webp)$/i.test(entry.name)) {
const stats = await fs.stat(fullPath);
const mediaUrl = pathToFileURL(fullPath).toString().replace(/^file:/, 'media:');
results.images.push({ path: relativePath, dataUrl: mediaUrl, lastModified: stats.mtimeMs, size: stats.size });
} else if (/\.(mp3|ogg|wav|opus)$/i.test(entry.name)) {
const stats = await fs.stat(fullPath);
const mediaUrl = pathToFileURL(fullPath).toString().replace(/^file:/, 'media:');
results.audios.push({ path: relativePath, dataUrl: mediaUrl, lastModified: stats.mtimeMs, size: stats.size });
}
}
children.push(childNode);
}
children.sort((a, b) => {
if (a.children && !b.children) return -1;
if (!a.children && b.children) return 1;
return a.name.localeCompare(b.name);
});
treeNode.children = children;
};
await readDirRecursive(rootPath, results.tree);
progress(20, 'Found ' + rpyPaths.length + ' script file' + (rpyPaths.length !== 1 ? 's' : '') + ', ' + results.images.length + ' image' + (results.images.length !== 1 ? 's' : '') + '...');
// Phase 2: Read .rpy content with per-file progress (20% → 88%)
if (readContent) {
for (let i = 0; i < rpyPaths.length; i++) {
const { fullPath, relativePath } = rpyPaths[i];
const content = await fs.readFile(fullPath, 'utf-8');
results.files.push({ path: relativePath, content });
const pct = 20 + Math.round(((i + 1) / Math.max(rpyPaths.length, 1)) * 68);
progress(pct, 'Reading ' + path.basename(relativePath) + '...');
}
} else {
results.files = rpyPaths.map(({ relativePath }) => ({ path: relativePath, content: '' }));
}
progress(92, 'Loading project settings...');
try {
const settingsContent = await fs.readFile(path.join(rootPath, 'game', 'project.ide.json'), 'utf-8');
results.settings = JSON.parse(settingsContent);
} catch {
results.settings = {};
}
parentPort.postMessage({ type: 'result', ok: true, data: results });
}
run().catch(err => parentPort.postMessage({ type: 'result', ok: false, error: err.message }));
`;
function readProjectFiles(rootPath, { readContent = true } = {}, onProgress = null) {
return new Promise((resolve, reject) => {
const worker = new Worker(PROJECT_LOAD_WORKER_CODE, {
eval: true,
workerData: { rootPath, readContent }
});
activeLoadWorker = worker;
let settled = false;
worker.on('message', (msg) => {
if (msg.type === 'progress') {
if (onProgress) onProgress(msg.value, msg.message);
return;
}
// type === 'result'
settled = true;
activeLoadWorker = null;
if (msg.ok) {
resolve(msg.data);
} else {
reject(new Error(msg.error));
}
});
worker.on('error', (err) => {
if (settled) return;
settled = true;
activeLoadWorker = null;
reject(err);
});
worker.on('exit', (code) => {
if (activeLoadWorker === worker) activeLoadWorker = null;
// Non-zero exit without a prior message means the worker was terminated
// (e.g. via worker.terminate() on cancel) or crashed. Either way, reject
// so the caller's catch block runs; the cancel flag in App.tsx suppresses
// any UI error in the cancel case.
if (!settled && code !== 0) {
settled = true;
reject(new Error('LOAD_CANCELLED'));
}
});
});
}
async function scanDirectoryForAssets(dirPath) {
const results = {
images: [],
audios: []
};
const scanRecursive = async (currentPath) => {
const entries = await fs.readdir(currentPath, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(currentPath, entry.name);
// Normalize path separators to forward slashes for consistency in frontend
const normalizedPath = fullPath.replace(/\\/g, '/');
if (entry.isDirectory()) {
await scanRecursive(fullPath);
} else if (entry.isFile()) {
const ext = path.extname(entry.name).toLowerCase();
if (['.png', '.jpg', '.jpeg', '.webp'].includes(ext)) {
const stats = await fs.stat(fullPath);
const mediaUrl = pathToFileURL(fullPath).toString().replace(/^file:/, 'media:');
results.images.push({
path: normalizedPath,
fileName: entry.name,
dataUrl: mediaUrl,
lastModified: stats.mtimeMs,
size: stats.size
});
} else if (['.mp3', '.ogg', '.wav', '.opus'].includes(ext)) {
const stats = await fs.stat(fullPath);
const mediaUrl = pathToFileURL(fullPath).toString().replace(/^file:/, 'media:');
results.audios.push({
path: normalizedPath,
fileName: entry.name,
dataUrl: mediaUrl,
lastModified: stats.mtimeMs,
size: stats.size
});
}
}
}
};
await scanRecursive(dirPath);
return results;
}
function getMimeType(filePath) {
const ext = path.extname(filePath).toLowerCase();
switch (ext) {
case '.png': return 'image/png';
case '.jpg':
case '.jpeg': return 'image/jpeg';
case '.webp': return 'image/webp';
case '.gif': return 'image/gif';
case '.mp3': return 'audio/mpeg';
case '.ogg': return 'audio/ogg';
case '.wav': return 'audio/wav';
case '.opus': return 'audio/opus';
default: return 'application/octet-stream';
}
}
let forceQuit = false;
async function updateApplicationMenu() {
const settings = await loadAppSettings();
const recentProjects = settings?.recentProjects || [];
const openRecentSubmenu = recentProjects.length > 0
? recentProjects.map(p => ({
label: p,
click: (item, focusedWindow) => {
if (focusedWindow) focusedWindow.webContents.send('menu-command', { command: 'open-recent', path: p });
}
}))
: [{ label: 'No Recent Projects', enabled: false }];
const menuTemplate = [
...(process.platform === 'darwin' ? [{
label: app.getName(),
submenu: [
{ role: 'about' },
{ type: 'separator' },
{ role: 'services' },
{ type: 'separator' },
{ role: 'hide' },
{ role: 'hideOthers' },
{ role: 'unhide' },
{ type: 'separator' },
{ role: 'quit' }
]
}] : []),
{
label: 'File',
submenu: [
{
label: 'New Project...',
accelerator: 'CmdOrCtrl+N',
click: (item, focusedWindow) => { if (focusedWindow) focusedWindow.webContents.send('menu-command', { command: 'new-project' }); }
},
{
label: 'Open Project...',
accelerator: 'CmdOrCtrl+O',
click: (item, focusedWindow) => { if (focusedWindow) focusedWindow.webContents.send('menu-command', { command: 'open-project' }); }
},
{
label: 'Open Recent',
submenu: openRecentSubmenu
},
{ type: 'separator' },
{
label: 'Save All',
accelerator: 'CmdOrCtrl+S',
click: (item, focusedWindow) => { if (focusedWindow) focusedWindow.webContents.send('menu-command', { command: 'save-all' }); }
},
{
id: 'explorer-refresh',
label: 'Refresh',
enabled: false,
click: (item, focusedWindow) => { if (focusedWindow) focusedWindow.webContents.send('menu-command', { command: 'explorer-refresh' }); }
},
{
id: 'open-screenshots-folder',
label: 'Open Screenshots Folder',
enabled: false,
click: (item, focusedWindow) => { if (focusedWindow) focusedWindow.webContents.send('menu-command', { command: 'open-screenshots-folder' }); }
},
{ type: 'separator' },
{
id: 'explorer-new-file',
label: 'New File',
enabled: false,
click: (item, focusedWindow) => { if (focusedWindow) focusedWindow.webContents.send('menu-command', { command: 'explorer-new-file' }); }
},
{
id: 'explorer-new-folder',
label: 'New Folder',
enabled: false,
click: (item, focusedWindow) => { if (focusedWindow) focusedWindow.webContents.send('menu-command', { command: 'explorer-new-folder' }); }
},
{
id: 'explorer-rename',
label: 'Rename',
enabled: false,
click: (item, focusedWindow) => { if (focusedWindow) focusedWindow.webContents.send('menu-command', { command: 'explorer-rename' }); }
},
{
id: 'explorer-delete',
label: 'Delete',
enabled: false,
click: (item, focusedWindow) => { if (focusedWindow) focusedWindow.webContents.send('menu-command', { command: 'explorer-delete' }); }
},
{ type: 'separator' },
...(process.platform !== 'darwin' ? [{
label: 'Settings',
accelerator: 'CmdOrCtrl+,',
click: (item, focusedWindow) => { if (focusedWindow) focusedWindow.webContents.send('menu-command', { command: 'open-settings' }); }
},
{ type: 'separator' }] : []),
{
id: 'run-project',
label: 'Run Project',
accelerator: 'F5',
click: (item, focusedWindow) => { if (focusedWindow) focusedWindow.webContents.send('menu-command', { command: 'run-project' }); }
},
{
id: 'stop-project',
label: 'Stop Project',
accelerator: 'Shift+F5',
enabled: false,
click: (item, focusedWindow) => { if (focusedWindow) focusedWindow.webContents.send('menu-command', { command: 'stop-project' }); }
},
{ type: 'separator' },
{
label: 'Close Tab',
accelerator: 'CmdOrCtrl+W',
click: (item, focusedWindow) => { if (focusedWindow) focusedWindow.webContents.send('menu-command', { command: 'close-tab' }); }
},
{ type: 'separator' },
{ role: 'quit' }
]
},
{
label: 'Edit',
submenu: [
{ role: 'undo' },
{ role: 'redo' },
{ type: 'separator' },
{ role: 'cut' },
{ role: 'copy' },
{ role: 'paste' },
{ type: 'separator' },
{
label: 'Find in Files',
accelerator: 'CmdOrCtrl+Shift+F',
click: (item, focusedWindow) => { if (focusedWindow) focusedWindow.webContents.send('menu-command', { command: 'toggle-search' }); }
},
]
},
{
label: 'View',
submenu: [
{
label: 'Story Canvas',
click: (item, focusedWindow) => { if (focusedWindow) focusedWindow.webContents.send('menu-command', { command: 'open-static-tab', type: 'canvas' }); }
},
{
label: 'Route Canvas',
click: (item, focusedWindow) => { if (focusedWindow) focusedWindow.webContents.send('menu-command', { command: 'open-static-tab', type: 'route-canvas' }); }
},
{
label: 'Choice Canvas',
click: (item, focusedWindow) => { if (focusedWindow) focusedWindow.webContents.send('menu-command', { command: 'open-static-tab', type: 'choice-canvas' }); }
},
{
label: 'Diagnostics',
click: (item, focusedWindow) => { if (focusedWindow) focusedWindow.webContents.send('menu-command', { command: 'open-static-tab', type: 'diagnostics' }); }
},
{
label: 'Stats',
click: (item, focusedWindow) => { if (focusedWindow) focusedWindow.webContents.send('menu-command', { command: 'open-static-tab', type: 'stats' }); }
},
{
label: 'Translation Dashboard',
click: (item, focusedWindow) => { if (focusedWindow) focusedWindow.webContents.send('menu-command', { command: 'open-static-tab', type: 'translations' }); }
},
{ type: 'separator' },
{
label: 'Toggle Left Sidebar',
click: (item, focusedWindow) => { if (focusedWindow) focusedWindow.webContents.send('menu-command', { command: 'toggle-left-sidebar' }); }
},
{
label: 'Toggle Right Sidebar',
click: (item, focusedWindow) => { if (focusedWindow) focusedWindow.webContents.send('menu-command', { command: 'toggle-right-sidebar' }); }
},
{ type: 'separator' },
...(!app.isPackaged ? [
{ role: 'reload' },
{ role: 'forceReload' },
{ role: 'toggleDevTools' },
{ type: 'separator' },
] : []),
{ role: 'resetZoom' },
{ role: 'zoomIn' },
{ role: 'zoomOut' },
{ type: 'separator' },
{ role: 'togglefullscreen' }
]
},
{
role: 'window',
submenu: [
{ role: 'minimize' },
{ role: 'zoom' },
]
},
{
label: 'Help',
submenu: [
{
label: 'Show Tutorial',
click: (item, focusedWindow) => { if (focusedWindow) focusedWindow.webContents.send('menu-command', { command: 'show-tutorial' }); }
},
{
label: 'User Guide',
click: () => {
const userGuidePath = app.isPackaged
? path.join(process.resourcesPath, 'docs', 'Ren-IDE_User_Guide.html')
: path.join(__dirname, 'docs', 'Ren-IDE_User_Guide.html');
shell.openPath(userGuidePath).catch(err => {
logger.error('Failed to open user guide:', err);
dialog.showErrorBox('Error', 'Could not open the user guide. Please ensure it is installed correctly.');
});
}
},
{
label: 'Keyboard Shortcuts',
accelerator: 'CmdOrCtrl+/',
click: (item, focusedWindow) => { if (focusedWindow) focusedWindow.webContents.send('menu-command', { command: 'open-shortcuts' }); }
},
{
label: 'Documentation',
click: () => shell.openExternal('https://github.com/bluemoonfoundry/vangard-renpy-ide/wiki'),
},
{ type: 'separator' },
{
label: 'Show Logs',
click: async () => {
try {
const logPath = electronLog.transports.file.getFile()?.path;
if (logPath) {
// Open the directory containing the log file
const logDir = path.dirname(logPath);
await shell.openPath(logDir);
} else {
dialog.showErrorBox('Error', 'Log file not found.');
}
} catch (err) {
logger.error('Failed to open log directory', err);
dialog.showErrorBox('Error', 'Could not open log directory.');
}
}
},
{ type: 'separator' },
{
label: 'Check for Updates',
click: () => {
if (app.isPackaged) {
autoUpdater.checkForUpdates().catch(err => logger.error('Auto-update check failed:', err));
}
}
},
{ type: 'separator' },
...(process.platform !== 'darwin' ? [{
label: 'About',
click: (item, focusedWindow) => { if (focusedWindow) focusedWindow.webContents.send('menu-command', { command: 'open-about' }); }
}] : []),
]
},
];
const menu = Menu.buildFromTemplate(menuTemplate);
Menu.setApplicationMenu(menu);
}
async function createWindow() {
const savedState = await loadWindowState();
const mainWindow = new BrowserWindow({
width: startupWindowWidth || savedState?.width || 1280,
height: startupWindowHeight || savedState?.height || 800,
x: savedState?.x,
y: savedState?.y,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
nodeIntegration: false,
contextIsolation: true,
},
icon: path.join(__dirname, 'vangard.png')
});
mainWindowRef = mainWindow;
mainWindow.on('close', (e) => {
if (forceQuit) {
saveWindowState(mainWindow);
return;
}
e.preventDefault();
mainWindow.webContents.send('check-unsaved-changes-before-exit');
});
// Register global screenshot shortcut - handled entirely in main process for reliability
globalShortcut.register('CommandOrControl+Shift+C', async () => {
if (!mainWindow || mainWindow.isDestroyed()) return;
try {
// Capture immediately, bypassing renderer
if (!currentProjectRoot) {
logger.warn('Screenshot attempted but no project loaded');
return;
}
const screenshotsDir = path.join(currentProjectRoot, '.renide', 'screenshots');
await fs.mkdir(screenshotsDir, { recursive: true });
const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
const filename = `renide-screenshot-${timestamp}.png`;
const filepath = path.join(screenshotsDir, filename);
const image = await mainWindow.webContents.capturePage();
const buffer = image.toPNG();
await fs.writeFile(filepath, buffer);
logger.info(`Screenshot captured: ${filename}`);
// Try to notify renderer to update state (best effort - might fail if renderer crashed)
try {
if (!mainWindow.webContents.isDestroyed()) {
mainWindow.webContents.send('screenshot-captured', { filename, filepath });
}
} catch (e) {
logger.warn('Could not notify renderer of screenshot capture:', e.message);
}
// Show native OS notification (works even if renderer is dead)
if (Notification.isSupported()) {
const notification = new Notification({
title: 'Screenshot Captured',
body: `Saved to .renide/screenshots/`,
silent: true
});
notification.on('click', async () => {
await shell.openPath(screenshotsDir);
});
notification.show();
}
} catch (error) {
logger.error('Failed to capture screenshot:', error);
// Try to show error notification
try {
if (Notification.isSupported()) {
new Notification({
title: 'Screenshot Failed',
body: error.message,
silent: true
}).show();
}
} catch {
// Silently fail if even notification doesn't work
}
}
});
await updateApplicationMenu();
mainWindow.loadFile(path.join(__dirname, 'dist/index.html'));
}
async function searchInDirectory(directory, query, options) {
const results = [];
const entries = await fs.readdir(directory, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(directory, entry.name);
const relativePath = path.relative(options.projectPath, fullPath).replace(/\\/g, '/');
if (entry.isDirectory()) {
if (entry.name === '.git' || entry.name === 'node_modules') continue;
results.push(...await searchInDirectory(fullPath, query, options));
} else if (entry.isFile() && entry.name.endsWith('.rpy')) {
const content = await fs.readFile(fullPath, 'utf-8');
const lines = content.split('\n');
const matches = [];
let flags = 'g';
if (!options.isCaseSensitive) flags += 'i';
let searchPattern = options.isRegex ? query : query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
if (options.isWholeWord) {
searchPattern = `\\b${searchPattern}\\b`;
}
try {
const regex = new RegExp(searchPattern, flags);
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
let match;
while ((match = regex.exec(line)) !== null) {
matches.push({
lineNumber: i + 1,
lineContent: line,
startColumn: match.index + 1,
endColumn: match.index + match[0].length + 1,
});
}
}
} catch (e) {
logger.error(`Invalid regex for file ${relativePath}:`, e.message);
}
if (matches.length > 0) {
results.push({ filePath: relativePath, matches });
}
}
}
return results;
}
app.whenReady().then(() => {
// Robust 'media' protocol handler for serving local files with streaming support
protocol.handle('media', async (request) => {
try {
const parsedUrl = new URL(request.url);
let filePath;
// On Windows, if scheme is standard, URL parser might move drive letter to hostname
// e.g. media:///C:/path -> media://c:/path (hostname: c)
if (process.platform === 'win32' && parsedUrl.hostname && parsedUrl.hostname.length === 1) {
// Handle drive letters normalized as hostnames
// Reconstruct as c:/pathname
filePath = `${parsedUrl.hostname}:${decodeURIComponent(parsedUrl.pathname)}`;
} else if (parsedUrl.hostname) {
// UNC Path (Network share): //Server/Share/Path...
// parsedUrl.pathname will be /Share/Path...
// We reconstruct it as \\Server\Share\Path... or //Server/Share/Path...
filePath = `//${parsedUrl.hostname}${decodeURIComponent(parsedUrl.pathname)}`;
} else {
// Standard path with empty hostname (media:///path)
let pathPart = decodeURIComponent(parsedUrl.pathname);
// On Windows, URLs from pathToFileURL look like /C:/path/to/file
// We need to strip the leading slash to get C:/path/to/file
if (process.platform === 'win32' && /^\/[a-zA-Z]:/.test(pathPart)) {
pathPart = pathPart.substring(1);
}
filePath = pathPart;
}
// Use fs.stat to get size and createReadStream for streaming
const stats = await fs.stat(filePath);
const mimeType = getMimeType(filePath);
// Convert Node stream to Web stream for Response
const stream = createReadStream(filePath);
const webStream = Readable.toWeb(stream);
return new Response(webStream, {
status: 200,
headers: {
'Content-Type': mimeType,
'Content-Length': stats.size
}
});
} catch (e) {
logger.error(`Media protocol error for URL: ${request.url}`, e);
return new Response('Not Found', { status: 404 });
}
});
ipcMain.handle('app:get-startup-args', () => ({ projectPath: startupProjectPath }));
ipcMain.handle('dialog:openDirectory', async () => {
try {
const { canceled, filePaths } = await dialog.showOpenDialog({
properties: ['openDirectory']
});
if (canceled) {
return null;
} else {
return filePaths[0];
}
} catch (error) {
logger.error('Failed to open directory dialog:', error);
return null;
}
});
/**
* Resolve the Ren'Py executable from an SDK directory.
* Returns the full path to renpy.exe (Windows) or renpy.sh (macOS/Linux).
*/
function getRenpyExecutable(sdkDir) {
if (!sdkDir) return null;
const exe = process.platform === 'win32' ? 'renpy.exe' : 'renpy.sh';
return path.join(sdkDir, exe);
}
ipcMain.handle('dialog:selectRenpy', async () => {
try {
const { canceled, filePaths } = await dialog.showOpenDialog({
title: 'Select Ren\'Py SDK Directory',
properties: ['openDirectory'],
});
if (canceled) {
return null;
} else {
return filePaths[0];
}
} catch (error) {
logger.error('Failed to open Ren\'Py SDK selection dialog:', error);
return null;
}
});
ipcMain.handle('renpy:check-path', async (event, sdkDir) => {
if (!sdkDir) return false;
try {
const execPath = getRenpyExecutable(sdkDir);
if (!execPath) return false;
await fs.access(execPath, fs.constants.F_OK | fs.constants.X_OK);
return true;
} catch {
return false;
}
});
ipcMain.handle('renpy:generate-translations', async (event, sdkDir, projectPath, language) => {
const executable = getRenpyExecutable(sdkDir);
if (!executable) return { success: false, output: '', error: 'Ren\'Py SDK path is not configured' };
return new Promise((resolve) => {
let stdout = '';
let stderr = '';
let settled = false;
const proc = spawn(executable, [projectPath, 'translate', language]);