-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
837 lines (733 loc) · 26.1 KB
/
Copy pathmain.js
File metadata and controls
837 lines (733 loc) · 26.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
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
const { app, BrowserWindow, ipcMain, dialog, Menu, webContents, components, Notification, session } = require('electron');
const path = require('path');
const fs = require('fs');
const os = require('os');
const http = require('http');
app.setAppUserModelId('com.trendcreate.browser.v2');
// Config Management
function getConfigPath() {
return path.join(app.getPath('userData'), 'trendcreate-config.json');
}
function loadConfig() {
let config = {};
try {
const p = getConfigPath();
if (fs.existsSync(p)) config = JSON.parse(fs.readFileSync(p, 'utf8'));
} catch (e) { console.error("Failed to load config", e); }
// Default theme properties
if (!config.theme) {
config.theme = {
preset: 'dark', // 'dark', 'light', 'glass', etc.
primaryColor: '#ffffff',
bgColor: '#121212',
bgImage: '',
bgOverlayOpacity: 0.5,
accentColor: '#007acc'
};
}
if (config.verticalTabs === undefined) {
config.verticalTabs = false;
}
return config;
}
function saveConfig(config) {
try {
fs.writeFileSync(getConfigPath(), JSON.stringify(config), 'utf8');
} catch (e) { console.error("Failed to save config", e); }
}
const appConfig = loadConfig();
if (appConfig.darkMode) {
app.commandLine.appendSwitch('enable-features', 'WebContentsForceDark');
}
// Password Management
function getPasswordsPath() {
return path.join(app.getPath('userData'), 'trendcreate-passwords.json');
}
function loadPasswords() {
try {
const p = getPasswordsPath();
if (fs.existsSync(p)) return JSON.parse(fs.readFileSync(p, 'utf8'));
} catch (e) { console.error("Failed to load passwords", e); }
return {};
}
function savePasswords(passwords) {
try {
fs.writeFileSync(getPasswordsPath(), JSON.stringify(passwords), 'utf8');
} catch (e) { console.error("Failed to save passwords", e); }
}
let mainWindow = null;
const activeDownloads = new Set();
const preparedPartitions = new Set();
// Apply Chrome-equivalent request headers and download tracking to a session.
// Used for the default session and every per-profile partition session.
function setupSession(sess) {
if (!sess) return;
sess.webRequest.onBeforeSendHeaders((details, callback) => {
details.requestHeaders['User-Agent'] = app.userAgentFallback;
details.requestHeaders['sec-ch-ua'] = '"Not/A)Brand";v="8", "Chromium";v="126", "Google Chrome";v="126"';
details.requestHeaders['sec-ch-ua-mobile'] = '?0';
details.requestHeaders['sec-ch-ua-platform'] = '"Windows"';
callback({ requestHeaders: details.requestHeaders });
});
sess.on('will-download', (event, item, webContents) => {
activeDownloads.add(item);
const targetWin = BrowserWindow.fromWebContents(webContents) || mainWindow;
if (targetWin) {
const fileName = item.getFilename();
const totalBytes = item.getTotalBytes();
item.on('updated', (event, state) => {
if (state === 'interrupted') {
console.log('Download is interrupted but can be resumed');
} else if (state === 'progressing') {
if (item.isPaused()) {
console.log('Download is paused');
} else {
if (!targetWin.isDestroyed() && !targetWin.webContents.isDestroyed()) {
targetWin.webContents.send('download-progress', {
filename: fileName,
received: item.getReceivedBytes(),
total: totalBytes
});
}
}
}
});
item.once('done', (event, state) => {
activeDownloads.delete(item);
if (!targetWin.isDestroyed() && !targetWin.webContents.isDestroyed()) {
targetWin.webContents.send('download-done', {
filename: fileName,
state: state
});
}
});
} else {
item.once('done', () => activeDownloads.delete(item));
}
});
}
const gotTheLock = app.requestSingleInstanceLock();
if (!gotTheLock) {
app.quit();
process.exit(0);
} else {
app.on('second-instance', (event, commandLine, workingDirectory) => {
if (mainWindow) {
if (mainWindow.isMinimized()) mainWindow.restore();
mainWindow.focus();
const fileArg = commandLine.find(arg => arg.toLowerCase().endsWith('.html') || arg.toLowerCase().endsWith('.pdf'));
if (fileArg && fs.existsSync(fileArg)) {
mainWindow.webContents.send('open-external-file', fileArg);
}
}
});
}
function createWindow(initialUrl = null) {
let closeConfirmed = false;
mainWindow = new BrowserWindow({
width: 1200,
height: 800,
icon: path.join(__dirname, 'icon.ico'),
titleBarStyle: 'hidden',
titleBarOverlay: {
color: '#000000',
symbolColor: '#ffffff'
},
webPreferences: {
webviewTag: true,
nodeIntegration: true,
contextIsolation: false,
plugins: true
}
});
const win = mainWindow; // Keep win reference for the rest of the function
const template = [
{
label: 'Edit',
submenu: [
{ role: 'undo', label: 'Undo' },
{ role: 'redo', label: 'Redo' },
{ type: 'separator' },
{ role: 'cut', label: 'Cut' },
{ role: 'copy', label: 'Copy' },
{ role: 'paste', label: 'Paste' },
{ role: 'delete', label: 'Delete' },
{ type: 'separator' },
{ role: 'selectAll', label: 'Select All' }
]
}
];
Menu.setApplicationMenu(Menu.buildFromTemplate(template));
win.setMenuBarVisibility(false);
win.setAutoHideMenuBar(true);
const options = initialUrl ? { query: { url: initialUrl } } : {};
win.loadFile(path.join(__dirname, 'src', 'index.html'), options);
win.webContents.on('did-finish-load', () => {
const fileArg = process.argv.find(arg => arg.toLowerCase().endsWith('.html') || arg.toLowerCase().endsWith('.pdf'));
if (fileArg && fs.existsSync(fileArg)) {
win.webContents.send('open-external-file', fileArg);
}
});
win.on('close', async (event) => {
if (closeConfirmed) return;
event.preventDefault();
let hasUnsavedChanges = false;
try {
hasUnsavedChanges = await win.webContents.executeJavaScript(
'Boolean(window.__trendHasUnsavedChanges)',
true
);
} catch {
hasUnsavedChanges = false;
}
if (hasUnsavedChanges) {
const result = await dialog.showMessageBox(win, {
type: 'warning',
buttons: ['Close', 'Cancel'],
defaultId: 1,
cancelId: 1,
title: 'Unsaved Changes',
message: 'There are unsaved changes. Do you want to close?',
detail: 'Your unsaved changes will be lost if you close.'
});
if (result.response !== 0) return;
}
if (activeDownloads.size > 0) {
const result = await dialog.showMessageBox(win, {
type: 'warning',
buttons: ['閉じる', 'キャンセル'],
defaultId: 1,
cancelId: 1,
title: 'ダウンロード中',
message: 'ダウンロードを中止しますか?',
detail: 'アプリを閉じると、進行中のダウンロードがキャンセルされます。'
});
if (result.response !== 0) return;
}
closeConfirmed = true;
win.close();
});
function sendBrowserHistoryCommand(command) {
if (!win.isDestroyed()) {
win.webContents.send('browser-history-command', command);
}
}
function toggleHostDevTools() {
if (win.webContents.isDevToolsOpened()) {
win.webContents.closeDevTools();
} else {
win.webContents.openDevTools({ mode: 'detach' });
}
}
function handleInputShortcut(event, input) {
if (input.type !== 'keyDown') return;
if (input.key === 'F12') {
if (!win.isDestroyed()) {
win.webContents.send('browser-f12-command');
}
event.preventDefault();
return;
}
if (input.key === 'F5' || (input.control && input.key.toLowerCase() === 'r')) {
if (!win.isDestroyed()) {
win.webContents.send('browser-reload-command', input.shift);
}
event.preventDefault();
return;
}
if (input.control && !input.shift && !input.alt && input.key.toLowerCase() === 'f') {
if (!win.isDestroyed()) {
win.webContents.send('browser-find-command');
}
event.preventDefault();
return;
}
if (
input.key === 'BrowserBack' ||
input.key === 'MouseBack' ||
(input.alt && input.key === 'ArrowLeft')
) {
sendBrowserHistoryCommand('back');
event.preventDefault();
return;
}
if (
input.key === 'BrowserForward' ||
input.key === 'MouseForward' ||
(input.alt && input.key === 'ArrowRight')
) {
sendBrowserHistoryCommand('forward');
event.preventDefault();
}
}
win.webContents.on('before-input-event', handleInputShortcut);
win.on('app-command', (event, command) => {
if (command === 'browser-backward') {
sendBrowserHistoryCommand('back');
event.preventDefault();
} else if (command === 'browser-forward') {
sendBrowserHistoryCommand('forward');
event.preventDefault();
}
});
if (!global.ipcRegistered) {
global.ipcRegistered = true;
app.on('web-contents-created', (event, contents) => {
contents.on('before-input-event', handleInputShortcut);
contents.setWindowOpenHandler(({ url }) => {
const ownerWindow = BrowserWindow.getFocusedWindow() || BrowserWindow.getAllWindows()[0];
if (ownerWindow && !ownerWindow.isDestroyed()) {
ownerWindow.webContents.send('open-new-tab', url);
}
return { action: 'deny' };
});
});
ipcMain.on('tear-off-tab', (event, data) => {
if (data && data.url) {
createWindow(data.url);
}
});
ipcMain.handle('prepare-session-partition', (event, partition) => {
if (!partition || preparedPartitions.has(partition)) return;
preparedPartitions.add(partition);
setupSession(session.fromPartition(partition));
});
ipcMain.handle('get-config', () => loadConfig());
ipcMain.handle('save-config', (event, config) => {
saveConfig(config);
BrowserWindow.getAllWindows().forEach(win => {
if (!win.isDestroyed()) {
win.webContents.send('config-changed', config);
}
});
});
ipcMain.on('tab-moved', (event, data) => {
BrowserWindow.getAllWindows().forEach(win => {
if (!win.isDestroyed()) {
win.webContents.send('tab-moved-event', data);
}
});
});
ipcMain.handle('get-passwords', (event, hostname) => {
const passwords = loadPasswords();
return passwords[hostname] || [];
});
ipcMain.on('prompt-save-password', async (event, data) => {
const { hostname, username, password } = data;
if (!hostname || !password) return;
const passwords = loadPasswords();
if (!passwords[hostname]) passwords[hostname] = [];
// Check if already saved
const existing = passwords[hostname].find(p => p.username === username && p.password === password);
if (existing) return;
const response = await dialog.showMessageBox(mainWindow, {
type: 'question',
buttons: ['保存する', '保存しない'],
title: 'パスワードの保存',
message: `${hostname} のパスワードを保存しますか?\n(ID: ${username || 'なし'})`,
defaultId: 0,
cancelId: 1
});
if (response.response === 0) {
passwords[hostname] = passwords[hostname].filter(p => p.username !== username); // overwrite old if same username
passwords[hostname].push({ username, password });
savePasswords(passwords);
}
});
ipcMain.handle('show-open-dialog', async () => {
return dialog.showOpenDialog(mainWindow, {
properties: ['openDirectory']
});
});
ipcMain.handle('read-dir', async (event, dirPath) => {
try {
const items = fs.readdirSync(dirPath, { withFileTypes: true });
return items.map((item) => ({
name: item.name,
isDirectory: item.isDirectory(),
path: path.join(dirPath, item.name)
}));
} catch (e) {
console.error(e);
return [];
}
});
ipcMain.handle('read-file', async (event, filePath) => {
try {
return fs.readFileSync(filePath, 'utf-8');
} catch (e) {
console.error(e);
return null;
}
});
ipcMain.handle('get-license-text', async () => {
const appLicensePath = path.join(__dirname, 'src', 'LICENSE.txt');
const fallbackAppLicensePath = path.join(__dirname, 'LICENSE');
const jsMediaLicensePath = path.join(__dirname, 'src', 'LICENSE-jsmediatags.txt');
const monacoLicensePath = path.join(__dirname, 'src', 'LICENSE-monaco-editor.txt');
let appLicense = 'App License not found.';
if (fs.existsSync(appLicensePath)) {
appLicense = fs.readFileSync(appLicensePath, 'utf-8');
} else if (fs.existsSync(fallbackAppLicensePath)) {
appLicense = fs.readFileSync(fallbackAppLicensePath, 'utf-8');
}
const jsMediaTagsLicense = fs.existsSync(jsMediaLicensePath) ? fs.readFileSync(jsMediaLicensePath, 'utf-8') : 'jsmediatags License not found.';
const monacoLicense = fs.existsSync(monacoLicensePath) ? fs.readFileSync(monacoLicensePath, 'utf-8') : 'Monaco Editor License not found.';
return { appLicense, jsMediaTagsLicense, monacoLicense };
});
ipcMain.handle('write-file', async (event, filePath, content) => {
try {
fs.writeFileSync(filePath, content, 'utf-8');
return true;
} catch (e) {
console.error(e);
return false;
}
});
ipcMain.handle('show-save-dialog', async (event, options = {}) => {
return dialog.showSaveDialog(mainWindow, {
title: 'Save file',
defaultPath: options.defaultPath || 'untitled.html',
filters: [
{ name: 'Web files', extensions: ['html', 'css', 'js', 'json', 'md', 'txt'] },
{ name: 'All files', extensions: ['*'] }
]
});
});
ipcMain.handle('show-message-box', async (event, options = {}) => {
return dialog.showMessageBox(mainWindow, options);
});
ipcMain.handle('write-preview-file', async (event, content) => {
try {
const previewDir = path.join(os.tmpdir(), 'trendcreate-browser-preview');
fs.mkdirSync(previewDir, { recursive: true });
const previewPath = path.join(previewDir, 'preview.html');
fs.writeFileSync(previewPath, content, 'utf-8');
return previewPath;
} catch (e) {
console.error(e);
return null;
}
});
ipcMain.on('show-notification', (event, { title, body }) => {
if (Notification.isSupported()) {
new Notification({ title, body }).show();
}
});
previewServer = null;
let previewServerPort = 0;
let previewRoot = null;
let currentPreviewContent = {};
function resolveBareModules(code) {
code = code.replace(/https?:\/\/(?:cdn\.jsdelivr\.net\/npm\/|unpkg\.com\/)([^'"]+)/gi, 'https://esm.sh/$1');
return code
.replace(/\b(import|export)\s+([^'"]+?)\s+from\s+["'](?![.\/]|https?:\/\/)([^'"]+)["']/g, '$1 $2 from "https://esm.sh/$3"')
.replace(/\bimport\s+["'](?![.\/]|https?:\/\/)([^'"]+)["']/g, 'import "https://esm.sh/$1"')
.replace(/\bimport\s*\(\s*["'](?![.\/]|https?:\/\/)([^'"]+)["']\s*\)/g, 'import("https://esm.sh/$1")');
}
ipcMain.handle('stop-live-server', async () => {
if (previewServer) {
previewServer.close();
previewServer = null;
}
previewServerPort = 0;
return true;
});
ipcMain.handle('toggle-host-devtools', () => {
toggleHostDevTools();
});
ipcMain.handle('attach-devtools-to-tab', async (event, targetId, devtoolsId) => {
const target = webContents.fromId(targetId);
const devtools = webContents.fromId(devtoolsId);
if (target && devtools) {
target.setDevToolsWebContents(devtools);
target.openDevTools();
return true;
}
return false;
});
ipcMain.handle('open-webview-devtools', (event, targetId) => {
const target = webContents.fromId(targetId);
if (target) {
target.openDevTools({ mode: 'detach' });
return true;
}
return false;
});
ipcMain.handle('close-webview-devtools', (event, targetId) => {
const target = webContents.fromId(targetId);
if (target) {
if (target.isDevToolsOpened()) target.closeDevTools();
try {
target.setDevToolsWebContents(null);
} catch (e) {
console.error("Failed to unset devtools webcontents:", e);
}
return true;
}
return false;
});
ipcMain.handle('start-live-server', async (event, dirPath, port = 0) => {
if (previewServer) {
previewServer.close();
previewServer = null;
}
previewRoot = dirPath;
currentPreviewContent = {};
return new Promise((resolve) => {
previewServer = http.createServer((req, res) => {
let pathname = decodeURIComponent(req.url.split('?')[0]);
if (pathname === '/') pathname = '/index.html';
if (currentPreviewContent[pathname] !== undefined) {
let content = currentPreviewContent[pathname];
if (pathname.endsWith('.html') || pathname.endsWith('.js')) {
content = resolveBareModules(content);
}
res.writeHead(200, { 'Content-Type': pathname.endsWith('.html') ? 'text/html' : (pathname.endsWith('.js') ? 'application/javascript' : 'text/plain') });
res.end(content);
return;
}
if (!previewRoot) {
res.writeHead(404);
res.end('Not Found');
return;
}
const filePath = path.join(previewRoot, pathname);
if (!filePath.startsWith(previewRoot)) {
res.writeHead(403);
res.end('Forbidden');
return;
}
fs.readFile(filePath, (err, data) => {
if (err) {
res.writeHead(404);
res.end('Not Found');
return;
}
let contentType = 'application/octet-stream';
if (filePath.endsWith('.html')) contentType = 'text/html';
else if (filePath.endsWith('.js')) contentType = 'application/javascript';
else if (filePath.endsWith('.css')) contentType = 'text/css';
else if (filePath.endsWith('.json')) contentType = 'application/json';
else if (filePath.endsWith('.png')) contentType = 'image/png';
else if (filePath.endsWith('.jpg') || filePath.endsWith('.jpeg')) contentType = 'image/jpeg';
else if (filePath.endsWith('.svg')) contentType = 'image/svg+xml';
res.writeHead(200, { 'Content-Type': contentType });
if (filePath.endsWith('.html') || filePath.endsWith('.js')) {
let content = data.toString('utf-8');
content = resolveBareModules(content);
res.end(content);
} else {
res.end(data);
}
});
});
previewServer.on('error', (err) => {
if (err.code === 'EADDRINUSE') {
previewServer = null;
resolve(-1);
} else {
resolve(0);
}
});
previewServer.listen(port, '127.0.0.1', () => {
previewServerPort = previewServer.address().port;
resolve(previewServerPort);
});
});
});
ipcMain.handle('update-live-preview-content', (event, pathname, content) => {
currentPreviewContent[pathname] = content;
});
ipcMain.handle('show-webview-context-menu', (event, params = {}) => {
return new Promise((resolve) => {
let settled = false;
const done = (action) => { if (!settled) { settled = true; resolve(action); } };
const tpl = [
{ label: '戻る', enabled: !!params.canGoBack, click: () => done('back') },
{ label: '進む', enabled: !!params.canGoForward, click: () => done('forward') },
{ label: '再読み込み', click: () => done('reload') },
{ type: 'separator' }
];
if (params.linkURL) {
tpl.push({ label: 'リンクを新しいタブで開く', click: () => done('openLink') });
tpl.push({ label: 'リンクのアドレスをコピー', click: () => done('copyLink') });
tpl.push({ type: 'separator' });
}
if (params.selectionText) {
tpl.push({ label: 'コピー', click: () => done('copy') });
tpl.push({ label: '選択範囲を翻訳', click: () => done('translateSelection') });
tpl.push({ type: 'separator' });
}
tpl.push({ label: 'このページを日本語に翻訳', click: () => done('translatePage') });
tpl.push({ type: 'separator' });
tpl.push({ label: '検証 (DevTools)', click: () => done('inspect') });
const menu = Menu.buildFromTemplate(tpl);
menu.popup({ window: BrowserWindow.fromWebContents(event.sender), callback: () => done(null) });
});
});
ipcMain.handle('show-context-menu', (event) => {
const template = [
{ role: 'undo', label: 'Undo' },
{ role: 'redo', label: 'Redo' },
{ type: 'separator' },
{ role: 'cut', label: 'Cut' },
{ role: 'copy', label: 'Copy' },
{ role: 'paste', label: 'Paste' },
{ role: 'delete', label: 'Delete' },
{ type: 'separator' },
{ role: 'selectAll', label: 'Select All' }
];
const menu = Menu.buildFromTemplate(template);
menu.popup({ window: BrowserWindow.fromWebContents(event.sender) });
});
ipcMain.handle('show-unsaved-dialog', async (event) => {
const win = BrowserWindow.fromWebContents(event.sender);
const result = await dialog.showMessageBox(win, {
type: 'warning',
buttons: ['Close without saving', 'Cancel'],
defaultId: 1,
cancelId: 1,
title: 'Unsaved Changes',
message: 'There are unsaved changes in the IDE. Do you really want to close this tab?',
detail: 'Your unsaved changes will be lost.'
});
return result.response;
});
ipcMain.on('show-file-context-menu', (event, targetPath, isDirectory) => {
const template = [
{
label: '名前を変更',
click: () => {
event.sender.send('file-context-action', { action: 'rename', path: targetPath, isDirectory });
}
},
{
label: '削除',
click: () => {
event.sender.send('file-context-action', { action: 'delete', path: targetPath, isDirectory });
}
}
];
const menu = Menu.buildFromTemplate(template);
menu.popup({ window: BrowserWindow.fromWebContents(event.sender) });
});
ipcMain.handle('delete-file', async (event, targetPath) => {
const response = await dialog.showMessageBox(mainWindow, {
type: 'warning',
buttons: ['削除する', 'キャンセル'],
defaultId: 1,
cancelId: 1,
title: '削除の確認',
message: `本当に削除しますか?\n${targetPath}`
});
if (response.response === 0) {
try {
fs.rmSync(targetPath, { recursive: true, force: true });
return true;
} catch (e) {
console.error("Delete failed", e);
}
}
return false;
});
ipcMain.handle('rename-file', async (event, oldPath, newPath) => {
try {
if (fs.existsSync(newPath)) return false; // Already exists
fs.renameSync(oldPath, newPath);
return true;
} catch (e) {
console.error("Rename failed", e);
return false;
}
});
ipcMain.handle('get-portfolio-projects', async (event, workspacePath) => {
if (!workspacePath) {
workspacePath = path.join(app.getPath('documents'), 'TRENDcreate_Projects');
}
// Ensure default workspace exists
if (!fs.existsSync(workspacePath)) {
try {
fs.mkdirSync(workspacePath, { recursive: true });
} catch (e) {
return [];
}
}
const projects = [];
try {
const items = fs.readdirSync(workspacePath, { withFileTypes: true });
for (const item of items) {
if (item.isDirectory()) {
const projectPath = path.join(workspacePath, item.name);
const indexPath = path.join(projectPath, 'index.html');
let title = item.name;
if (fs.existsSync(indexPath)) {
try {
const htmlContent = fs.readFileSync(indexPath, 'utf8');
const titleMatch = htmlContent.match(/<title>([^<]*)<\/title>/i);
if (titleMatch && titleMatch[1]) {
title = titleMatch[1].trim();
}
} catch (e) {
console.error("Failed to read title for", projectPath, e);
}
}
const stats = fs.statSync(projectPath);
projects.push({
name: item.name,
title: title,
path: projectPath,
modifiedAt: stats.mtimeMs,
type: 'directory'
});
} else if (item.isFile()) {
const filePath = path.join(workspacePath, item.name);
const stats = fs.statSync(filePath);
projects.push({
name: item.name,
title: item.name,
path: filePath,
modifiedAt: stats.mtimeMs,
type: 'file'
});
}
}
} catch (e) {
console.error("Failed to read portfolio projects", e);
}
// Sort by most recently modified
return projects.sort((a, b) => b.modifiedAt - a.modifiedAt);
});
} // end of if(!global.ipcRegistered)
}
app.commandLine.appendSwitch('lang', 'ja-JP');
app.commandLine.appendSwitch('no-verify-widevine-cdm');
let widevineReady = false;
app.on('widevine-ready', (version, lastVersion) => {
console.log(`Widevine ${version} is ready!`);
widevineReady = true;
});
app.on('widevine-error', (error) => {
console.error('Widevine installation encountered an error:', error);
});
// UA偽装: Electronという文字列を消して標準のChromeとして認識させる
app.userAgentFallback = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36";
app.whenReady().then(async () => {
if (appConfig.darkMode) {
const { nativeTheme } = require('electron');
nativeTheme.themeSource = 'dark';
}
if (components) {
await components.whenReady();
console.log('Components ready:', components.status());
}
// Setup default session (used by internal app pages) for login and downloads.
setupSession(session.defaultSession);
createWindow();
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') app.quit();
});