-
Notifications
You must be signed in to change notification settings - Fork 311
/
Copy pathmain.ts
1013 lines (900 loc) · 29.1 KB
/
main.ts
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
"use strict";
import path from "path";
import fs from "fs";
import { pathToFileURL } from "url";
import {
app,
protocol,
BrowserWindow,
dialog,
Menu,
shell,
nativeTheme,
net,
} from "electron";
import installExtension, { VUEJS_DEVTOOLS } from "electron-devtools-installer";
import log from "electron-log/main";
import dayjs from "dayjs";
import windowStateKeeper from "electron-window-state";
import { hasSupportedGpu } from "./device";
import {
getEngineInfoManager,
initializeEngineInfoManager,
} from "./manager/engineInfoManager";
import {
getEngineProcessManager,
initializeEngineProcessManager,
} from "./manager/engineProcessManager";
import { initializeVvppManager, isVvppFile } from "./manager/vvppManager";
import configMigration014 from "./configMigration014";
import { initializeRuntimeInfoManager } from "./manager/RuntimeInfoManager";
import { registerIpcMainHandle, ipcMainSendProxy, IpcMainHandle } from "./ipc";
import { getConfigManager } from "./electronConfig";
import { getEngineAndVvppController } from "./engineAndVvppController";
import { writeFileSafely } from "./fileHelper";
import { failure, success } from "@/type/result";
import { AssetTextFileNames } from "@/type/staticResources";
import {
EngineInfo,
SystemError,
defaultHotkeySettings,
defaultToolbarButtonSetting,
EngineId,
TextAsset,
} from "@/type/preload";
import { themes } from "@/domain/theme";
import { isMac } from "@/helpers/platform";
type SingleInstanceLockData = {
filePath: string | undefined;
};
const isDevelopment = import.meta.env.DEV;
const isTest = import.meta.env.MODE === "test";
if (isDevelopment) {
app.commandLine.appendSwitch("remote-debugging-port", "9222");
}
let suffix = "";
if (isTest) {
suffix = "-test";
} else if (isDevelopment) {
suffix = "-dev";
}
const appName = import.meta.env.VITE_APP_NAME + suffix;
console.log(`Environment: ${import.meta.env.MODE}, appData: ${appName}`);
// バージョン0.14より前の設定ファイルの保存場所
const beforeUserDataDir = app.getPath("userData"); // マイグレーション用
// app.getPath("userData")を呼ぶとディレクトリが作成されてしまうため空なら削除する。
let errorForRemoveBeforeUserDataDir: Error | undefined;
try {
fs.rmdirSync(beforeUserDataDir, { recursive: false });
} catch (e) {
const err = e as NodeJS.ErrnoException;
if (err?.code !== "ENOTEMPTY") {
// electron-logを初期化してからエラーを出力する
errorForRemoveBeforeUserDataDir = err;
}
}
// appnameをvoicevoxとしてsetする
app.setName(appName);
// Electronの設定ファイルの保存場所を変更
const fixedUserDataDir = path.join(app.getPath("appData"), appName);
if (!fs.existsSync(fixedUserDataDir)) {
fs.mkdirSync(fixedUserDataDir);
}
app.setPath("userData", fixedUserDataDir);
if (!isDevelopment) {
configMigration014({ fixedUserDataDir, beforeUserDataDir }); // 以前のファイルがあれば持ってくる
}
log.initialize({ preload: false });
// silly以上のログをコンソールに出力
log.transports.console.format = "[{h}:{i}:{s}.{ms}] [{level}] {text}";
log.transports.console.level = "silly";
// warn以上のログをファイルに出力
const prefix = dayjs().format("YYYYMMDD_HHmmss");
log.transports.file.format = "[{h}:{i}:{s}.{ms}] [{level}] {text}";
log.transports.file.level = "warn";
log.transports.file.fileName = `${prefix}_error.log`;
if (errorForRemoveBeforeUserDataDir != undefined) {
log.error(errorForRemoveBeforeUserDataDir);
}
let win: BrowserWindow;
process.on("uncaughtException", (error) => {
log.error(error);
if (isDevelopment) {
app.exit(1);
} else {
const { message, name } = error;
let detailedMessage = "";
detailedMessage += `メインプロセスで原因不明のエラーが発生しました。\n`;
detailedMessage += `エラー名: ${name}\n`;
detailedMessage += `メッセージ: ${message}\n`;
if (error.stack) {
detailedMessage += `スタックトレース: \n${error.stack}`;
}
dialog.showErrorBox("エラー", detailedMessage);
}
});
process.on("unhandledRejection", (reason) => {
log.error(reason);
});
let appDirPath: string;
let __static: string;
if (isDevelopment) {
// __dirnameはdist_electronを指しているので、一つ上のディレクトリに移動する
appDirPath = path.resolve(__dirname, "..");
__static = path.join(appDirPath, "public");
} else {
appDirPath = path.dirname(app.getPath("exe"));
process.chdir(appDirPath);
__static = __dirname;
}
protocol.registerSchemesAsPrivileged([
{ scheme: "app", privileges: { secure: true, standard: true, stream: true } },
]);
const firstUrl = import.meta.env.VITE_DEV_SERVER_URL ?? "app://./index.html";
// engine
const vvppEngineDir = path.join(app.getPath("userData"), "vvpp-engines");
if (!fs.existsSync(vvppEngineDir)) {
fs.mkdirSync(vvppEngineDir);
}
const onEngineProcessError = (engineInfo: EngineInfo, error: Error) => {
const engineId = engineInfo.uuid;
log.error(`ENGINE ${engineId} ERROR:`, error);
// winが作られる前にエラーが発生した場合はwinへの通知を諦める
// FIXME: winが作られた後にエンジンを起動させる
if (win != undefined) {
ipcMainSendProxy.DETECTED_ENGINE_ERROR(win, { engineId });
} else {
log.error(`onEngineProcessError: win is undefined`);
}
dialog.showErrorBox("音声合成エンジンエラー", error.message);
};
initializeRuntimeInfoManager({
runtimeInfoPath: path.join(app.getPath("userData"), "runtime-info.json"),
appVersion: app.getVersion(),
});
initializeEngineInfoManager({
defaultEngineDir: appDirPath,
vvppEngineDir,
});
initializeEngineProcessManager({ onEngineProcessError });
initializeVvppManager({ vvppEngineDir });
const configManager = getConfigManager();
const engineInfoManager = getEngineInfoManager();
const engineProcessManager = getEngineProcessManager();
const engineAndVvppController = getEngineAndVvppController();
// エンジンのフォルダを開く
function openEngineDirectory(engineId: EngineId) {
const engineDirectory = engineInfoManager.fetchEngineDirectory(engineId);
// Windows環境だとスラッシュ区切りのパスが動かない。
// path.resolveはWindowsだけバックスラッシュ区切りにしてくれるため、path.resolveを挟む。
void shell.openPath(path.resolve(engineDirectory));
}
/**
* マルチエンジン機能が有効だった場合はtrueを返す。
* 無効だった場合はダイアログを表示してfalseを返す。
*/
function checkMultiEngineEnabled(): boolean {
const enabled = configManager.get("enableMultiEngine");
if (!enabled) {
dialog.showMessageBoxSync(win, {
type: "info",
title: "マルチエンジン機能が無効です",
message: `マルチエンジン機能が無効です。vvppファイルを使用するには設定からマルチエンジン機能を有効にしてください。`,
buttons: ["OK"],
noLink: true,
});
}
return enabled;
}
const appState = {
willQuit: false,
};
let filePathOnMac: string | undefined = undefined;
// create window
async function createWindow() {
const mainWindowState = windowStateKeeper({
defaultWidth: 1024,
defaultHeight: 630,
});
const currentTheme = configManager.get("currentTheme");
const backgroundColor = themes.find((value) => value.name == currentTheme)
?.colors.background;
win = new BrowserWindow({
x: mainWindowState.x,
y: mainWindowState.y,
width: mainWindowState.width,
height: mainWindowState.height,
frame: false,
titleBarStyle: "hidden",
trafficLightPosition: { x: 6, y: 4 },
minWidth: 320,
show: false,
backgroundColor,
webPreferences: {
preload: path.join(__dirname, "preload.js"),
},
icon: path.join(__static, "icon.png"),
});
let projectFilePath = "";
if (isMac) {
if (filePathOnMac) {
if (filePathOnMac.endsWith(".vvproj")) {
projectFilePath = filePathOnMac;
}
filePathOnMac = undefined;
}
} else {
if (process.argv.length >= 2) {
const filePath = process.argv[1];
if (
fs.existsSync(filePath) &&
fs.statSync(filePath).isFile() &&
filePath.endsWith(".vvproj")
) {
projectFilePath = filePath;
}
}
}
// ソフトウェア起動時はプロトコルを app にする
if (import.meta.env.VITE_DEV_SERVER_URL == undefined) {
protocol.handle("app", (request) => {
// 読み取り先のファイルがインストールディレクトリ内であることを確認する
// ref: https://www.electronjs.org/ja/docs/latest/api/protocol#protocolhandlescheme-handler
const { pathname } = new URL(request.url);
const pathToServe = path.resolve(path.join(__dirname, pathname));
const relativePath = path.relative(__dirname, pathToServe);
const isUnsafe =
path.isAbsolute(relativePath) ||
relativePath.startsWith("..") ||
relativePath === "";
if (isUnsafe) {
log.error(`Bad Request URL: ${request.url}`);
return new Response("bad", {
status: 400,
headers: { "content-type": "text/html" },
});
}
return net.fetch(pathToFileURL(pathToServe).toString());
});
}
await loadUrl({ projectFilePath });
if (isDevelopment && !isTest) win.webContents.openDevTools();
win.on("maximize", () => {
ipcMainSendProxy.DETECT_MAXIMIZED(win);
});
win.on("unmaximize", () => {
ipcMainSendProxy.DETECT_UNMAXIMIZED(win);
});
win.on("enter-full-screen", () => {
ipcMainSendProxy.DETECT_ENTER_FULLSCREEN(win);
});
win.on("leave-full-screen", () => {
ipcMainSendProxy.DETECT_LEAVE_FULLSCREEN(win);
});
win.on("always-on-top-changed", () => {
win.isAlwaysOnTop()
? ipcMainSendProxy.DETECT_PINNED(win)
: ipcMainSendProxy.DETECT_UNPINNED(win);
});
win.on("close", (event) => {
if (!appState.willQuit) {
event.preventDefault();
ipcMainSendProxy.CHECK_EDITED_AND_NOT_SAVE(win, {
closeOrReload: "close",
});
return;
}
});
win.on("resize", () => {
const windowSize = win.getSize();
ipcMainSendProxy.DETECT_RESIZED(win, {
width: windowSize[0],
height: windowSize[1],
});
});
mainWindowState.manage(win);
}
/**
* 画面の読み込みを開始する。
* @param obj.isMultiEngineOffMode マルチエンジンオフモードにするかどうか。無指定時はfalse扱いになる。
* @param obj.projectFilePath 初期化時に読み込むプロジェクトファイル。無指定時は何も読み込まない。
* @returns ロードの完了を待つPromise。
*/
async function loadUrl(obj: {
isMultiEngineOffMode?: boolean;
projectFilePath?: string;
}) {
const url = new URL(firstUrl);
url.searchParams.append(
"isMultiEngineOffMode",
(obj?.isMultiEngineOffMode ?? false).toString(),
);
url.searchParams.append("projectFilePath", obj?.projectFilePath ?? "");
return win.loadURL(url.toString());
}
// 開始。その他の準備が完了した後に呼ばれる。
async function start() {
await engineAndVvppController.launchEngines();
await createWindow();
}
const menuTemplateForMac: Electron.MenuItemConstructorOptions[] = [
{
label: "VOICEVOX",
submenu: [{ role: "quit" }],
},
{
label: "Edit",
submenu: [
{ role: "cut" },
{ role: "copy" },
{ role: "paste" },
{ role: "selectAll" },
],
},
];
// For macOS, set the native menu to enable shortcut keys such as 'Cmd + V'.
if (isMac) {
Menu.setApplicationMenu(Menu.buildFromTemplate(menuTemplateForMac));
} else {
if (!isDevelopment) {
Menu.setApplicationMenu(null);
}
}
/**
* 保存に適した場所を選択するかキャンセルするまでダイアログを繰り返し表示する。
* アンインストール等で消えうる場所などを避ける。
* @param showDialogFunction ダイアログを表示する関数
*/
const retryShowSaveDialogWhileSafeDir = async <
T extends Electron.OpenDialogReturnValue | Electron.SaveDialogReturnValue,
>(
showDialogFunction: () => Promise<T>,
): Promise<T> => {
/**
* 指定されたパスが安全でないかどうかを判断する
*/
const isUnsafePath = (filePath: string) => {
const unsafeSaveDirs = [appDirPath, app.getPath("userData")]; // アンインストールで消えうるフォルダ
return unsafeSaveDirs.some((unsafeDir) => {
const relativePath = path.relative(unsafeDir, filePath);
return !(
path.isAbsolute(relativePath) ||
relativePath.startsWith(`..${path.sep}`) ||
relativePath === ".."
);
});
};
/**
* 警告ダイアログを表示し、ユーザーが再試行を選択したかどうかを返す
*/
const showWarningDialog = async () => {
const productName = app.getName().toUpperCase();
const warningResult = await dialog.showMessageBox(win, {
message: `指定された保存先は${productName}により自動的に削除される可能性があります。\n他の場所に保存することをおすすめします。`,
type: "warning",
buttons: ["保存場所を変更", "無視して保存"],
defaultId: 0,
title: "警告",
cancelId: 0,
});
return warningResult.response === 0 ? "retry" : "forceSave";
};
while (true) {
const result = await showDialogFunction();
// キャンセルされた場合、結果を直ちに返す
if (result.canceled) return result;
// 選択されたファイルパスを取得
const filePath =
"filePaths" in result ? result.filePaths[0] : result.filePath;
// 選択されたパスが安全かどうかを確認
if (isUnsafePath(filePath)) {
const result = await showWarningDialog();
if (result === "retry") continue; // ユーザーが保存場所を変更を選択した場合
}
return result; // 安全なパスが選択された場合
}
};
// プロセス間通信
registerIpcMainHandle<IpcMainHandle>({
GET_APP_INFOS: () => {
const name = app.getName();
const version = app.getVersion();
return {
name,
version,
};
},
GET_TEXT_ASSET: async (_, textType) => {
const fileName = path.join(__static, AssetTextFileNames[textType]);
const text = await fs.promises.readFile(fileName, "utf-8");
if (textType === "OssLicenses" || textType === "UpdateInfos") {
return JSON.parse(text) as TextAsset[typeof textType];
}
return text;
},
GET_ALT_PORT_INFOS: () => {
return engineInfoManager.altPortInfos;
},
SHOW_AUDIO_SAVE_DIALOG: async (_, { title, defaultPath }) => {
const result = await retryShowSaveDialogWhileSafeDir(() =>
dialog.showSaveDialog(win, {
title,
defaultPath,
filters: [
{
name: "WAVファイル",
extensions: ["wav"],
},
],
properties: ["createDirectory"],
}),
);
return result.filePath;
},
SHOW_TEXT_SAVE_DIALOG: async (_, { title, defaultPath }) => {
const result = await retryShowSaveDialogWhileSafeDir(() =>
dialog.showSaveDialog(win, {
title,
defaultPath,
filters: [{ name: "Text File", extensions: ["txt"] }],
properties: ["createDirectory"],
}),
);
return result.filePath;
},
/**
* 保存先になるディレクトリを選ぶダイアログを表示する。
*/
SHOW_SAVE_DIRECTORY_DIALOG: async (_, { title }) => {
const result = await retryShowSaveDialogWhileSafeDir(() =>
dialog.showOpenDialog(win, {
title,
properties: [
"openDirectory",
"createDirectory",
"treatPackageAsDirectory",
],
}),
);
if (result.canceled) {
return undefined;
}
return result.filePaths[0];
},
SHOW_VVPP_OPEN_DIALOG: async (_, { title, defaultPath }) => {
const result = await dialog.showOpenDialog(win, {
title,
defaultPath,
filters: [
{ name: "VOICEVOX Plugin Package", extensions: ["vvpp", "vvppp"] },
],
properties: ["openFile", "createDirectory", "treatPackageAsDirectory"],
});
return result.filePaths[0];
},
/**
* ディレクトリ選択ダイアログを表示する。
* 保存先として選ぶ場合は SHOW_SAVE_DIRECTORY_DIALOG を使うべき。
*/
SHOW_OPEN_DIRECTORY_DIALOG: async (_, { title }) => {
const result = await dialog.showOpenDialog(win, {
title,
properties: [
"openDirectory",
"createDirectory",
"treatPackageAsDirectory",
],
});
if (result.canceled) {
return undefined;
}
return result.filePaths[0];
},
SHOW_PROJECT_SAVE_DIALOG: async (_, { title, defaultPath }) => {
const result = await retryShowSaveDialogWhileSafeDir(() =>
dialog.showSaveDialog(win, {
title,
defaultPath,
filters: [{ name: "VOICEVOX Project file", extensions: ["vvproj"] }],
properties: ["showOverwriteConfirmation"],
}),
);
if (result.canceled) {
return undefined;
}
return result.filePath;
},
SHOW_PROJECT_LOAD_DIALOG: async (_, { title }) => {
const result = await dialog.showOpenDialog(win, {
title,
filters: [{ name: "VOICEVOX Project file", extensions: ["vvproj"] }],
properties: ["openFile", "createDirectory", "treatPackageAsDirectory"],
});
if (result.canceled) {
return undefined;
}
return result.filePaths;
},
SHOW_WARNING_DIALOG: (_, { title, message }) => {
return dialog.showMessageBox(win, {
type: "warning",
title,
message,
});
},
SHOW_ERROR_DIALOG: (_, { title, message }) => {
return dialog.showMessageBox(win, {
type: "error",
title,
message,
});
},
SHOW_IMPORT_FILE_DIALOG: (_, { title, name, extensions }) => {
return dialog.showOpenDialogSync(win, {
title,
filters: [{ name: name ?? "Text", extensions: extensions ?? ["txt"] }],
properties: ["openFile", "createDirectory", "treatPackageAsDirectory"],
})?.[0];
},
IS_AVAILABLE_GPU_MODE: () => {
return hasSupportedGpu(process.platform);
},
IS_MAXIMIZED_WINDOW: () => {
return win.isMaximized();
},
CLOSE_WINDOW: () => {
appState.willQuit = true;
win.destroy();
},
MINIMIZE_WINDOW: () => {
win.minimize();
},
MAXIMIZE_WINDOW: () => {
if (win.isMaximized()) {
win.unmaximize();
} else {
win.maximize();
}
},
OPEN_LOG_DIRECTORY: () => {
void shell.openPath(app.getPath("logs"));
},
ENGINE_INFOS: () => {
// エンジン情報を設定ファイルに保存しないためにelectron-storeは使わない
return engineInfoManager.fetchEngineInfos();
},
RESTART_ENGINE: async (_, { engineId }) => {
return engineProcessManager.restartEngine(engineId);
},
OPEN_ENGINE_DIRECTORY: async (_, { engineId }) => {
openEngineDirectory(engineId);
},
HOTKEY_SETTINGS: (_, { newData }) => {
if (newData != undefined) {
const hotkeySettings = configManager.get("hotkeySettings");
const hotkeySetting = hotkeySettings.find(
(hotkey) => hotkey.action == newData.action,
);
if (hotkeySetting != undefined) {
hotkeySetting.combination = newData.combination;
}
configManager.set("hotkeySettings", hotkeySettings);
}
return configManager.get("hotkeySettings");
},
ON_VUEX_READY: () => {
win.show();
},
CHECK_FILE_EXISTS: (_, { file }) => {
return fs.existsSync(file);
},
CHANGE_PIN_WINDOW: () => {
if (win.isAlwaysOnTop()) {
win.setAlwaysOnTop(false);
} else {
win.setAlwaysOnTop(true);
}
},
GET_DEFAULT_HOTKEY_SETTINGS: () => {
return defaultHotkeySettings;
},
GET_DEFAULT_TOOLBAR_SETTING: () => {
return defaultToolbarButtonSetting;
},
GET_SETTING: (_, key) => {
return configManager.get(key);
},
SET_SETTING: (_, key, newValue) => {
configManager.set(key, newValue);
return configManager.get(key);
},
SET_ENGINE_SETTING: async (_, engineId, engineSetting) => {
engineAndVvppController.updateEngineSetting(engineId, engineSetting);
},
SET_NATIVE_THEME: (_, source) => {
nativeTheme.themeSource = source;
},
INSTALL_VVPP_ENGINE: async (_, path: string) => {
return await engineAndVvppController.installVvppEngine(path);
},
UNINSTALL_VVPP_ENGINE: async (_, engineId: EngineId) => {
return await engineAndVvppController.uninstallVvppEngine(engineId);
},
VALIDATE_ENGINE_DIR: (_, { engineDir }) => {
return engineInfoManager.validateEngineDir(engineDir);
},
RELOAD_APP: async (_, { isMultiEngineOffMode }) => {
win.hide(); // FIXME: ダミーページ表示のほうが良い
// 一旦適当なURLに飛ばしてページをアンロードする
await win.loadURL("about:blank");
log.info("Checking ENGINE status before reload app");
const engineCleanupResult = engineAndVvppController.cleanupEngines();
// エンジンの停止とエンジン終了後処理の待機
if (engineCleanupResult != "alreadyCompleted") {
await engineCleanupResult;
}
log.info("Post engine kill process done. Now reloading app");
await engineAndVvppController.launchEngines();
await loadUrl({ isMultiEngineOffMode: !!isMultiEngineOffMode });
win.show();
},
WRITE_FILE: (_, { filePath, buffer }) => {
try {
writeFileSafely(
filePath,
new DataView(buffer instanceof Uint8Array ? buffer.buffer : buffer),
);
return success(undefined);
} catch (e) {
// throwだと`.code`の情報が消えるのでreturn
const a = e as SystemError;
return failure(a.code, a);
}
},
READ_FILE: async (_, { filePath }) => {
try {
const result = await fs.promises.readFile(filePath);
return success(result);
} catch (e) {
// throwだと`.code`の情報が消えるのでreturn
const a = e as SystemError;
return failure(a.code, a);
}
},
});
// app callback
app.on("web-contents-created", (_e, contents) => {
// リンククリック時はブラウザを開く
contents.setWindowOpenHandler(({ url }) => {
const { protocol } = new URL(url);
if (protocol.match(/^https?:/)) {
void shell.openExternal(url);
} else {
log.error(`許可されないリンクです。url: ${url}`);
}
return { action: "deny" };
});
// ナビゲーションを無効化
contents.on("will-navigate", (event) => {
// preloadスクリプト変更時のホットリロードを許容する
if (contents.getURL() !== event.url) {
log.error(`ナビゲーションは無効化されています。url: ${event.url}`);
event.preventDefault();
}
});
});
app.on("window-all-closed", () => {
log.info("All windows closed. Quitting app");
app.quit();
});
// Called before window closing
app.on("before-quit", async (event) => {
if (!appState.willQuit) {
event.preventDefault();
ipcMainSendProxy.CHECK_EDITED_AND_NOT_SAVE(win, { closeOrReload: "close" });
return;
}
log.info("Checking ENGINE status before app quit");
const { engineCleanupResult, configSavedResult } =
engineAndVvppController.gracefulShutdown();
// - エンジンの停止
// - エンジン終了後処理
// - 設定ファイルの保存
// が完了している
if (
engineCleanupResult === "alreadyCompleted" &&
configSavedResult === "alreadySaved"
) {
log.info("Post engine kill process and config save done. Quitting app");
return;
}
// すべてのエンジンプロセスのキルを開始
// 同期的にbefore-quitイベントをキャンセル
log.info("Interrupt app quit");
event.preventDefault();
if (engineCleanupResult !== "alreadyCompleted") {
log.info("Waiting for post engine kill process");
await engineCleanupResult;
}
if (configSavedResult !== "alreadySaved") {
log.info("Waiting for config save");
await configSavedResult;
}
// アプリケーションの終了を再試行する
log.info("Attempting to quit app again");
app.quit();
return;
});
app.once("will-finish-launching", () => {
// macOS only
app.once("open-file", (event, filePath) => {
event.preventDefault();
filePathOnMac = filePath;
});
});
app.on("ready", async () => {
await configManager.initialize().catch(async (e) => {
log.error(e);
const appExit = async () => {
await configManager?.ensureSaved();
app.exit(1);
};
const openConfigFolderAndExit = async () => {
await shell.openPath(app.getPath("userData"));
// 直後にexitするとフォルダが開かないため
await new Promise((resolve) => {
setTimeout(resolve, 500);
});
await appExit();
};
const resetConfig = async () => {
configManager.reset();
await configManager.ensureSaved();
};
// 実利用時はconfigファイル削除で解決する可能性があることを案内して終了
if (!isDevelopment) {
await dialog
.showMessageBox({
type: "error",
title: "設定ファイルの読み込みエラー",
message: `設定ファイルの読み込みに失敗しました。${app.getPath(
"userData",
)} にある config.json の名前を変えることで解決することがあります(ただし設定がすべてリセットされます)。設定ファイルがあるフォルダを開きますか?`,
buttons: ["いいえ", "はい"],
noLink: true,
cancelId: 0,
})
.then(async ({ response }) => {
switch (response) {
case 0:
await appExit();
break;
case 1:
await openConfigFolderAndExit();
break;
default:
throw new Error(`Unknown response: ${response}`);
}
});
}
// 開発時はconfigをリセットして起動を続行するかも問う
else {
await dialog
.showMessageBox({
type: "error",
title: "設定ファイルの読み込みエラー(開発者向け案内)",
message: `設定ファイルの読み込みに失敗しました。設定ファイルの名前を変更するか、設定をリセットしてください。`,
buttons: [
"何もせず終了",
"設定ファイルのフォルダを開いて終了",
"設定をリセットして続行",
],
noLink: true,
cancelId: 0,
})
.then(async ({ response }) => {
switch (response) {
case 0:
await appExit();
break;
case 1:
await openConfigFolderAndExit();
break;
case 2:
await resetConfig();
break;
default:
throw new Error(`Unknown response: ${response}`);
}
});
}
});
if (isDevelopment && !isTest) {
try {
await installExtension(VUEJS_DEVTOOLS);
} catch (e) {
log.error("Vue Devtools failed to install:", e);
}
}
// runEngineAllの前にVVPPを読み込む
let filePath: string | undefined;
if (process.platform === "darwin") {
filePath = filePathOnMac;
} else {
if (process.argv.length > 1) {
filePath = process.argv[1];
}
}
// 多重起動防止
if (
!isDevelopment &&
!isTest &&
!app.requestSingleInstanceLock({
filePath,
} as SingleInstanceLockData)
) {
log.info("VOICEVOX already running. Cancelling launch.");
log.info(`File path sent: ${filePath}`);
appState.willQuit = true;
app.quit();
return;
}
if (filePath && isVvppFile(filePath)) {
log.info(`vvpp file install: ${filePath}`);
// FIXME: GUI側に合流させる
if (checkMultiEngineEnabled()) {
await engineAndVvppController.installVvppEngineWithWarning({
vvppPath: filePath,
reloadNeeded: false,
win,
});
}
}
void start();
});
// 他のプロセスが起動したとき、`requestSingleInstanceLock`経由で`rawData`が送信される。
app.on("second-instance", async (_event, _argv, _workDir, rawData) => {
const data = rawData as SingleInstanceLockData;
if (!data.filePath) {
log.info("No file path sent");
} else if (isVvppFile(data.filePath)) {
log.info("Second instance launched with vvpp file");
// FIXME: GUI側に合流させる
if (checkMultiEngineEnabled()) {
await engineAndVvppController.installVvppEngineWithWarning({
vvppPath: data.filePath,
reloadNeeded: true,
reloadCallback: () => {
ipcMainSendProxy.CHECK_EDITED_AND_NOT_SAVE(win, {
closeOrReload: "reload",
});
},
win,
});
}
} else if (data.filePath.endsWith(".vvproj")) {
log.info("Second instance launched with vvproj file");
ipcMainSendProxy.LOAD_PROJECT_FILE(win, {
filePath: data.filePath,
confirm: true,
});
}
if (win) {
if (win.isMinimized()) win.restore();
win.focus();
}
});
if (isDevelopment) {