-
Notifications
You must be signed in to change notification settings - Fork 305
/
background.ts
1080 lines (953 loc) · 30.3 KB
/
background.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 {
app,
protocol,
BrowserWindow,
dialog,
Menu,
shell,
nativeTheme,
} from "electron";
import installExtension, { VUEJS3_DEVTOOLS } from "electron-devtools-installer";
import Store, { Schema } from "electron-store";
import dotenv from "dotenv";
import log from "electron-log";
import dayjs from "dayjs";
import windowStateKeeper from "electron-window-state";
import zodToJsonSchema from "zod-to-json-schema";
import { hasSupportedGpu } from "./electron/device";
import { textEditContextMenu } from "./electron/contextMenu";
import {
HotkeySetting,
ThemeConf,
AcceptTermsStatus,
EngineInfo,
ElectronStoreType,
SystemError,
electronStoreSchema,
defaultHotkeySettings,
isMac,
defaultToolbarButtonSetting,
engineSettingSchema,
EngineId,
} from "./type/preload";
import EngineManager from "./background/engineManager";
import VvppManager, { isVvppFile } from "./background/vvppManager";
import configMigration014 from "./background/configMigration014";
import { ipcMainHandle, ipcMainSend } from "@/electron/ipc";
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";
}
console.log(`Environment: ${import.meta.env.MODE}, appData: voicevox${suffix}`);
// Electronの設定ファイルの保存場所を変更
const beforeUserDataDir = app.getPath("userData"); // 設定ファイルのマイグレーション用
const fixedUserDataDir = path.join(app.getPath("appData"), `voicevox${suffix}`);
if (!fs.existsSync(fixedUserDataDir)) {
fs.mkdirSync(fixedUserDataDir);
}
app.setPath("userData", fixedUserDataDir);
if (!isDevelopment) {
configMigration014({ fixedUserDataDir, beforeUserDataDir }); // 以前のファイルがあれば持ってくる
}
// silly以上のログをコンソールに出力
log.transports.console.format = "[{h}:{i}:{s}.{ms}] [{level}] {text}";
log.transports.console.level = "silly";
// warn以上のログをファイルに出力
const prefix = dayjs().format("YYYYMMDD_HHmmss");
const logPath = app.getPath("logs");
log.transports.file.format = "[{h}:{i}:{s}.{ms}] [{level}] {text}";
log.transports.file.level = "warn";
log.transports.file.fileName = `${prefix}_error.log`;
log.transports.file.resolvePath = (variables) => {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return path.join(logPath, variables.fileName!);
};
let win: BrowserWindow;
process.on("uncaughtException", (error) => {
log.error(error);
});
process.on("unhandledRejection", (reason) => {
log.error(reason);
});
// .envから設定をprocess.envに読み込み
let appDirPath: string;
let __static: string;
// NOTE: 開発版では、カレントディレクトリにある .env ファイルを読み込む。
// 一方、配布パッケージ版では .env ファイルが実行ファイルと同じディレクトリに配置されているが、
// Linux・macOS ではそのディレクトリはカレントディレクトリとはならないため、.env ファイルの
// パスを明示的に指定する必要がある。Windows の配布パッケージ版でもこの設定で起動できるため、
// 全 OS で共通の条件分岐とした。
if (isDevelopment) {
// __dirnameはdist_electronを指しているので、一つ上のディレクトリに移動する
appDirPath = path.resolve(__dirname, "..");
dotenv.config({ override: true });
__static = path.join(appDirPath, "public");
} else {
appDirPath = path.dirname(app.getPath("exe"));
const envPath = path.join(appDirPath, ".env");
dotenv.config({ path: envPath });
process.chdir(appDirPath);
__static = __dirname;
}
protocol.registerSchemesAsPrivileged([
{ scheme: "app", privileges: { secure: true, standard: true, stream: true } },
]);
// 設定ファイル
const electronStoreJsonSchema = zodToJsonSchema(electronStoreSchema);
if (!("properties" in electronStoreJsonSchema)) {
throw new Error("electronStoreJsonSchema must be object");
}
let store: Store<ElectronStoreType>;
try {
store = new Store<ElectronStoreType>({
schema: electronStoreJsonSchema.properties as Schema<ElectronStoreType>,
migrations: {
">=0.13": (store) => {
// acceptTems -> acceptTerms
const prevIdentifier = "acceptTems";
const prevValue = store.get(prevIdentifier, undefined) as
| AcceptTermsStatus
| undefined;
if (prevValue) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
store.delete(prevIdentifier as any);
store.set("acceptTerms", prevValue);
}
},
">=0.14": (store) => {
// FIXME: できるならEngineManagerからEnginIDを取得したい
if (process.env.DEFAULT_ENGINE_INFOS == undefined)
throw new Error("DEFAULT_ENGINE_INFOS == undefined");
const engineId = EngineId(
JSON.parse(process.env.DEFAULT_ENGINE_INFOS)[0].uuid
);
if (engineId == undefined)
throw new Error("DEFAULT_ENGINE_INFOS[0].uuid == undefined");
const prevDefaultStyleIds = store.get("defaultStyleIds");
store.set(
"defaultStyleIds",
prevDefaultStyleIds.map((defaultStyle) => ({
engineId,
speakerUuid: defaultStyle.speakerUuid,
defaultStyleId: defaultStyle.defaultStyleId,
}))
);
const outputSamplingRate: number =
// @ts-expect-error 削除されたパラメータ。
store.get("savingSetting").outputSamplingRate;
store.set(`engineSettings.${engineId}`, {
useGpu: store.get("useGpu"),
outputSamplingRate:
outputSamplingRate === 24000 ? "engineDefault" : outputSamplingRate,
});
// @ts-expect-error 削除されたパラメータ。
store.delete("savingSetting.outputSamplingRate");
// @ts-expect-error 削除されたパラメータ。
store.delete("useGpu");
},
},
});
} catch (e) {
log.error(e);
dialog.showErrorBox(
"設定ファイルの読み込みに失敗しました。",
`${app.getPath(
"userData"
)} にある config.json の名前を変えることで解決することがあります(ただし設定がすべてリセットされます)。`
);
app.exit(1);
throw e;
}
// engine
const vvppEngineDir = path.join(app.getPath("userData"), "vvpp-engines");
if (!fs.existsSync(vvppEngineDir)) {
fs.mkdirSync(vvppEngineDir);
}
const engineManager = new EngineManager({
store,
defaultEngineDir: appDirPath,
vvppEngineDir,
});
const vvppManager = new VvppManager({ vvppEngineDir });
// エンジンのフォルダを開く
function openEngineDirectory(engineId: EngineId) {
const engineDirectory = engineManager.fetchEngineDirectory(engineId);
// Windows環境だとスラッシュ区切りのパスが動かない。
// path.resolveはWindowsだけバックスラッシュ区切りにしてくれるため、path.resolveを挟む。
shell.openPath(path.resolve(engineDirectory));
}
/**
* VVPPエンジンをインストールする。
*/
async function installVvppEngine(vvppPath: string) {
try {
await vvppManager.install(vvppPath);
return true;
} catch (e) {
dialog.showErrorBox(
"インストールエラー",
`${vvppPath} をインストールできませんでした。`
);
log.error(`Failed to install ${vvppPath}, ${e}`);
return false;
}
}
/**
* 危険性を案内してからVVPPエンジンをインストールする。
* FIXME: こちらで案内せず、GUIでのインストール側に合流させる
*/
async function installVvppEngineWithWarning({
vvppPath,
restartNeeded,
}: {
vvppPath: string;
restartNeeded: boolean;
}) {
const result = dialog.showMessageBoxSync(win, {
type: "warning",
title: "エンジン追加の確認",
message: `この操作はコンピュータに損害を与える可能性があります。エンジンの配布元が信頼できない場合は追加しないでください。`,
buttons: ["追加", "キャンセル"],
noLink: true,
cancelId: 1,
});
if (result == 1) {
return;
}
await installVvppEngine(vvppPath);
if (restartNeeded) {
dialog
.showMessageBox(win, {
type: "info",
title: "再起動が必要です",
message:
"VVPPファイルを読み込みました。反映には再起動が必要です。今すぐ再起動しますか?",
buttons: ["再起動", "キャンセル"],
noLink: true,
cancelId: 1,
})
.then((result) => {
if (result.response === 0) {
appState.willRestart = true;
app.quit();
}
});
}
}
/**
* マルチエンジン機能が有効だった場合はtrueを返す。
* 無効だった場合はダイアログを表示してfalseを返す。
*/
function checkMultiEngineEnabled(): boolean {
const enabled = store.get("experimentalSetting").enableMultiEngine;
if (!enabled) {
dialog.showMessageBoxSync(win, {
type: "info",
title: "マルチエンジン機能が無効です",
message: `マルチエンジン機能が無効です。vvppファイルを使用するには設定からマルチエンジン機能を有効にしてください。`,
buttons: ["OK"],
noLink: true,
});
}
return enabled;
}
/**
* VVPPエンジンをアンインストールする。
* 関数を呼んだタイミングでアンインストール処理を途中まで行い、アプリ終了時に完遂する。
*/
async function uninstallVvppEngine(engineId: EngineId) {
let engineInfo: EngineInfo | undefined = undefined;
try {
engineInfo = engineManager.fetchEngineInfo(engineId);
if (!engineInfo) {
throw new Error(`No such engineInfo registered: engineId == ${engineId}`);
}
if (!vvppManager.canUninstall(engineInfo)) {
throw new Error(`Cannot uninstall: engineId == ${engineId}`);
}
// Windows環境だとエンジンを終了してから削除する必要がある。
// そのため、アプリの終了時に削除するようにする。
vvppManager.markWillDelete(engineId);
return true;
} catch (e) {
const engineName = engineInfo?.name ?? engineId;
dialog.showErrorBox(
"アンインストールエラー",
`${engineName} をアンインストールできませんでした。`
);
log.error(`Failed to uninstall ${engineId}, ${e}`);
return false;
}
}
// temp dir
const tempDir = path.join(app.getPath("temp"), "VOICEVOX");
if (!fs.existsSync(tempDir)) {
fs.mkdirSync(tempDir);
}
// 使い方テキストの読み込み
const howToUseText = fs.readFileSync(
path.join(__static, "howtouse.md"),
"utf-8"
);
// OSSコミュニティ情報の読み込み
const ossCommunityInfos = fs.readFileSync(
path.join(__static, "ossCommunityInfos.md"),
"utf-8"
);
// 利用規約テキストの読み込み
const policyText = fs.readFileSync(path.join(__static, "policy.md"), "utf-8");
// OSSライセンス情報の読み込み
const ossLicenses = JSON.parse(
fs.readFileSync(path.join(__static, "licenses.json"), { encoding: "utf-8" })
);
// 問い合わせの読み込み
const contactText = fs.readFileSync(path.join(__static, "contact.md"), "utf-8");
// Q&Aの読み込み
const qAndAText = fs.readFileSync(path.join(__static, "qAndA.md"), "utf-8");
// アップデート情報の読み込み
const updateInfos = JSON.parse(
fs.readFileSync(path.join(__static, "updateInfos.json"), {
encoding: "utf-8",
})
);
const privacyPolicyText = fs.readFileSync(
path.join(__static, "privacyPolicy.md"),
"utf-8"
);
// hotkeySettingsのマイグレーション
function migrateHotkeySettings() {
const COMBINATION_IS_NONE = "####";
const loadedHotkeys = store.get("hotkeySettings");
const hotkeysWithoutNewCombination = defaultHotkeySettings.map(
(defaultHotkey) => {
const loadedHotkey = loadedHotkeys.find(
(loadedHotkey) => loadedHotkey.action === defaultHotkey.action
);
const hotkeyWithoutCombination: HotkeySetting = {
action: defaultHotkey.action,
combination: COMBINATION_IS_NONE,
};
return loadedHotkey || hotkeyWithoutCombination;
}
);
const migratedHotkeys = hotkeysWithoutNewCombination.map((hotkey) => {
if (hotkey.combination === COMBINATION_IS_NONE) {
const newHotkey =
defaultHotkeySettings.find(
(defaultHotkey) => defaultHotkey.action === hotkey.action
) || hotkey; // ここの find が undefined を返すケースはないが、ts のエラーになるので入れた
const combinationExists = hotkeysWithoutNewCombination.some(
(hotkey) => hotkey.combination === newHotkey.combination
);
if (combinationExists) {
const emptyHotkey = {
action: newHotkey.action,
combination: "",
};
return emptyHotkey;
} else {
return newHotkey;
}
} else {
return hotkey;
}
});
store.set("hotkeySettings", migratedHotkeys);
}
migrateHotkeySettings();
const appState = {
willQuit: false,
willRestart: false,
isMultiEngineOffMode: false,
};
let filePathOnMac: string | undefined = undefined;
// create window
async function createWindow() {
const mainWindowState = windowStateKeeper({
defaultWidth: 800,
defaultHeight: 600,
});
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,
webPreferences: {
preload: path.join(__dirname, "preload.js"),
nodeIntegration: false,
contextIsolation: true,
sandbox: false, // TODO: 外しても問題ないか検証して外す
},
icon: path.join(__static, "icon.png"),
});
let projectFilePath: string | undefined = "";
if (isMac) {
if (filePathOnMac) {
if (filePathOnMac.endsWith(".vvproj")) {
projectFilePath = encodeURI(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 = encodeURI(filePath);
}
}
}
const parameter =
"#/home?isMultiEngineOffMode=" +
appState.isMultiEngineOffMode +
"&projectFilePath=" +
projectFilePath;
if (process.env.VITE_DEV_SERVER_URL) {
await win.loadURL(process.env.VITE_DEV_SERVER_URL + parameter);
} else {
protocol.registerFileProtocol("app", (request, callback) => {
const filePath = new URL(request.url).pathname;
callback(path.join(__dirname, filePath));
});
win.loadURL("app://./index.html" + parameter);
}
if (isDevelopment && !isTest) win.webContents.openDevTools();
win.on("maximize", () => win.webContents.send("DETECT_MAXIMIZED"));
win.on("unmaximize", () => win.webContents.send("DETECT_UNMAXIMIZED"));
win.on("enter-full-screen", () =>
win.webContents.send("DETECT_ENTER_FULLSCREEN")
);
win.on("leave-full-screen", () =>
win.webContents.send("DETECT_LEAVE_FULLSCREEN")
);
win.on("always-on-top-changed", () => {
win.webContents.send(
win.isAlwaysOnTop() ? "DETECT_PINNED" : "DETECT_UNPINNED"
);
});
win.on("close", (event) => {
if (!appState.willQuit) {
event.preventDefault();
ipcMainSend(win, "CHECK_EDITED_AND_NOT_SAVE");
return;
}
});
win.on("resize", () => {
const windowSize = win.getSize();
win.webContents.send("DETECT_RESIZED", {
width: windowSize[0],
height: windowSize[1],
});
});
mainWindowState.manage(win);
}
// UI処理を開始。その他の準備が完了した後に呼ばれる。
async function start() {
const engineInfos = engineManager.fetchEngineInfos();
const engineSettings = store.get("engineSettings");
for (const engineInfo of engineInfos) {
if (!engineSettings[engineInfo.uuid]) {
// 空オブジェクトをパースさせることで、デフォルト値を取得する
engineSettings[engineInfo.uuid] = engineSettingSchema.parse({});
}
}
store.set("engineSettings", engineSettings);
await createWindow();
await engineManager.runEngineAll(win);
}
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);
}
}
// プロセス間通信
ipcMainHandle("GET_APP_INFOS", () => {
const name = app.getName();
const version = app.getVersion();
return {
name,
version,
};
});
ipcMainHandle("GET_TEMP_DIR", () => {
return tempDir;
});
ipcMainHandle("GET_HOW_TO_USE_TEXT", () => {
return howToUseText;
});
ipcMainHandle("GET_POLICY_TEXT", () => {
return policyText;
});
ipcMainHandle("GET_OSS_LICENSES", () => {
return ossLicenses;
});
ipcMainHandle("GET_UPDATE_INFOS", () => {
return updateInfos;
});
ipcMainHandle("GET_OSS_COMMUNITY_INFOS", () => {
return ossCommunityInfos;
});
ipcMainHandle("GET_CONTACT_TEXT", () => {
return contactText;
});
ipcMainHandle("GET_Q_AND_A_TEXT", () => {
return qAndAText;
});
ipcMainHandle("GET_PRIVACY_POLICY_TEXT", () => {
return privacyPolicyText;
});
ipcMainHandle("GET_ALT_PORT_INFOS", () => {
return engineManager.altPortInfo;
});
ipcMainHandle("SHOW_AUDIO_SAVE_DIALOG", async (_, { title, defaultPath }) => {
const result = await dialog.showSaveDialog(win, {
title,
defaultPath,
filters: [{ name: "Wave File", extensions: ["wav"] }],
properties: ["createDirectory"],
});
return result.filePath;
});
ipcMainHandle("SHOW_TEXT_SAVE_DIALOG", async (_, { title, defaultPath }) => {
const result = await dialog.showSaveDialog(win, {
title,
defaultPath,
filters: [{ name: "Text File", extensions: ["txt"] }],
properties: ["createDirectory"],
});
return result.filePath;
});
ipcMainHandle("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];
});
ipcMainHandle("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];
});
ipcMainHandle("SHOW_PROJECT_SAVE_DIALOG", async (_, { title, defaultPath }) => {
const result = await dialog.showSaveDialog(win, {
title,
defaultPath,
filters: [{ name: "VOICEVOX Project file", extensions: ["vvproj"] }],
properties: ["showOverwriteConfirmation"],
});
if (result.canceled) {
return undefined;
}
return result.filePath;
});
ipcMainHandle("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;
});
ipcMainHandle("SHOW_MESSAGE_DIALOG", (_, { type, title, message }) => {
return dialog.showMessageBox(win, {
type,
title,
message,
});
});
ipcMainHandle(
"SHOW_QUESTION_DIALOG",
(_, { type, title, message, buttons, cancelId, defaultId }) => {
return dialog
.showMessageBox(win, {
type,
buttons,
title,
message,
noLink: true,
cancelId,
defaultId,
})
.then((value) => {
return value.response;
});
}
);
ipcMainHandle("SHOW_WARNING_DIALOG", (_, { title, message }) => {
return dialog.showMessageBox(win, {
type: "warning",
title,
message,
});
});
ipcMainHandle("SHOW_ERROR_DIALOG", (_, { title, message }) => {
return dialog.showMessageBox(win, {
type: "error",
title,
message,
});
});
ipcMainHandle("SHOW_IMPORT_FILE_DIALOG", (_, { title }) => {
return dialog.showOpenDialogSync(win, {
title,
filters: [{ name: "Text", extensions: ["txt"] }],
properties: ["openFile", "createDirectory", "treatPackageAsDirectory"],
})?.[0];
});
ipcMainHandle("OPEN_TEXT_EDIT_CONTEXT_MENU", () => {
textEditContextMenu.popup({ window: win });
});
ipcMainHandle("IS_AVAILABLE_GPU_MODE", () => {
return hasSupportedGpu(process.platform);
});
ipcMainHandle("IS_MAXIMIZED_WINDOW", () => {
return win.isMaximized();
});
ipcMainHandle("CLOSE_WINDOW", () => {
appState.willQuit = true;
win.destroy();
});
ipcMainHandle("MINIMIZE_WINDOW", () => win.minimize());
ipcMainHandle("MAXIMIZE_WINDOW", () => {
if (win.isMaximized()) {
win.unmaximize();
} else {
win.maximize();
}
});
ipcMainHandle("LOG_ERROR", (_, ...params) => {
log.error(...params);
});
ipcMainHandle("LOG_WARN", (_, ...params) => {
log.warn(...params);
});
ipcMainHandle("LOG_INFO", (_, ...params) => {
log.info(...params);
});
ipcMainHandle("ENGINE_INFOS", () => {
// エンジン情報を設定ファイルに保存しないためにstoreは使わない
return engineManager.fetchEngineInfos();
});
/**
* エンジンを再起動する。
* エンジンの起動が開始したらresolve、起動が失敗したらreject。
*/
ipcMainHandle("RESTART_ENGINE", async (_, { engineId }) => {
await engineManager.restartEngine(engineId, win);
});
ipcMainHandle("OPEN_ENGINE_DIRECTORY", async (_, { engineId }) => {
openEngineDirectory(engineId);
});
ipcMainHandle("HOTKEY_SETTINGS", (_, { newData }) => {
if (newData !== undefined) {
const hotkeySettings = store.get("hotkeySettings");
const hotkeySetting = hotkeySettings.find(
(hotkey) => hotkey.action == newData.action
);
if (hotkeySetting !== undefined) {
hotkeySetting.combination = newData.combination;
}
store.set("hotkeySettings", hotkeySettings);
}
return store.get("hotkeySettings");
});
ipcMainHandle("THEME", (_, { newData }) => {
if (newData !== undefined) {
store.set("currentTheme", newData);
return;
}
const dir = path.join(__static, "themes");
const themes: ThemeConf[] = [];
const files = fs.readdirSync(dir);
files.forEach((file) => {
const theme = JSON.parse(fs.readFileSync(path.join(dir, file)).toString());
themes.push(theme);
});
return { currentTheme: store.get("currentTheme"), availableThemes: themes };
});
ipcMainHandle("ON_VUEX_READY", () => {
win.show();
});
ipcMainHandle("CHECK_FILE_EXISTS", (_, { file }) => {
return fs.existsSync(file);
});
ipcMainHandle("CHANGE_PIN_WINDOW", () => {
if (win.isAlwaysOnTop()) {
win.setAlwaysOnTop(false);
} else {
win.setAlwaysOnTop(true);
}
});
ipcMainHandle("GET_DEFAULT_HOTKEY_SETTINGS", () => {
return defaultHotkeySettings;
});
ipcMainHandle("GET_DEFAULT_TOOLBAR_SETTING", () => {
return defaultToolbarButtonSetting;
});
ipcMainHandle("GET_SETTING", (_, key) => {
return store.get(key);
});
ipcMainHandle("SET_SETTING", (_, key, newValue) => {
store.set(key, newValue);
return store.get(key);
});
ipcMainHandle("SET_ENGINE_SETTING", (_, engineId, engineSetting) => {
store.set(`engineSettings.${engineId}`, engineSetting);
});
ipcMainHandle("SET_NATIVE_THEME", (_, source) => {
nativeTheme.themeSource = source;
});
ipcMainHandle("INSTALL_VVPP_ENGINE", async (_, path: string) => {
return await installVvppEngine(path);
});
ipcMainHandle("UNINSTALL_VVPP_ENGINE", async (_, engineId: EngineId) => {
return await uninstallVvppEngine(engineId);
});
ipcMainHandle("VALIDATE_ENGINE_DIR", (_, { engineDir }) => {
return engineManager.validateEngineDir(engineDir);
});
ipcMainHandle("RESTART_APP", async (_, { isMultiEngineOffMode }) => {
appState.willRestart = true;
appState.isMultiEngineOffMode = isMultiEngineOffMode;
win.close();
});
ipcMainHandle("WRITE_FILE", (_, { filePath, buffer }) => {
try {
fs.writeFileSync(filePath, new DataView(buffer));
} catch (e) {
// throwだと`.code`の情報が消えるのでreturn
const a = e as SystemError;
return { code: a.code, message: a.message };
}
return undefined;
});
ipcMainHandle("JOIN_PATH", (_, { pathArray }) => {
return path.join(...pathArray);
});
ipcMainHandle("READ_FILE", (_, { filePath }) => {
return fs.promises.readFile(filePath);
});
// app callback
app.on("web-contents-created", (e, contents) => {
// リンククリック時はブラウザを開く
contents.setWindowOpenHandler(({ url }) => {
if (url.match(/^http/)) {
shell.openExternal(url);
return { action: "deny" };
}
return { action: "allow" };
});
});
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();
ipcMainSend(win, "CHECK_EDITED_AND_NOT_SAVE");
return;
}
log.info("Checking ENGINE status before app quit");
const killingProcessPromises = engineManager.killEngineAll();
const numLivingEngineProcess = Object.entries(killingProcessPromises).length;
// すべてのエンジンプロセスが停止している
if (numLivingEngineProcess === 0) {
log.info(
"All ENGINE processes are killed, running post engine kill process"
);
if (appState.willRestart) {
// awaitする前にevent.preventDefault()を呼び出さないとアプリがそのまま終了してしまう
event.preventDefault();
}
// エンジン終了後の処理を実行
await vvppManager.handleMarkedEngineDirs();
if (appState.willRestart) {
// 再起動フラグが立っている場合はフラグを戻して再起動する
log.info(
"Post engine kill process done. Now restarting app because of willRestart flag"
);
appState.willRestart = false;
appState.willQuit = false;
start();
} else {
log.info("Post engine kill process done. Now quit app");
}
return;
}
// すべてのエンジンプロセスのキルを開始
// 同期的にbefore-quitイベントをキャンセル
log.info("Interrupt app quit to kill ENGINE processes");
event.preventDefault();
let numEngineProcessKilled = 0;
// 非同期的にすべてのエンジンプロセスをキル
const waitingKilledPromises: Array<Promise<void>> = Object.entries(
killingProcessPromises
).map(([engineId, promise]) => {
return promise
.catch((error) => {
// TODO: 各エンジンプロセスキルの失敗をUIに通知する
log.error(`ENGINE ${engineId}: Error during killing process: ${error}`);
// エディタを終了するため、エラーが起きてもエンジンプロセスをキルできたとみなす
})
.finally(() => {
numEngineProcessKilled++;
log.info(
`ENGINE ${engineId}: Process killed. ${numEngineProcessKilled} / ${numLivingEngineProcess} processes killed`
);
});
});
// すべてのエンジンプロセスキル処理が完了するまで待機
await Promise.all(waitingKilledPromises);
// アプリケーションの終了を再試行する
log.info(
"All ENGINE process kill operations done. 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 () => {
if (isDevelopment) {
try {
await installExtension(VUEJS3_DEVTOOLS);
} catch (e: unknown) {
if (e instanceof Error) {
log.error("Vue Devtools failed to install:", e.toString());
}
}
}