-
Notifications
You must be signed in to change notification settings - Fork 309
/
background.ts
1343 lines (1185 loc) · 36.4 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 { spawn, ChildProcess } from "child_process";
import dotenv from "dotenv";
import treeKill from "tree-kill";
import Store from "electron-store";
import {
app,
protocol,
BrowserWindow,
dialog,
Menu,
shell,
nativeTheme,
} from "electron";
import { createProtocol } from "vue-cli-plugin-electron-builder/lib";
import installExtension, { VUEJS3_DEVTOOLS } from "electron-devtools-installer";
import path from "path";
import { textEditContextMenu } from "./electron/contextMenu";
import { hasSupportedGpu } from "./electron/device";
import { ipcMainHandle, ipcMainSend } from "@/electron/ipc";
import fs from "fs";
import {
HotkeySetting,
ThemeConf,
AcceptTermsStatus,
ToolbarSetting,
EngineInfo,
ElectronStoreType,
} from "./type/preload";
import log from "electron-log";
import dayjs from "dayjs";
import windowStateKeeper from "electron-window-state";
type EngineManifest = {
name: string;
uuid: string;
command: string;
port: string;
icon: string;
};
// 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`;
const isDevelopment = process.env.NODE_ENV !== "production";
if (isDevelopment) {
app.setPath(
"userData",
path.join(app.getPath("appData"), `${app.getName()}-dev`)
);
}
let win: BrowserWindow;
// 多重起動防止
if (!isDevelopment && !app.requestSingleInstanceLock()) {
log.info("VOICEVOX already running. Cancelling launch");
app.quit();
}
process.on("uncaughtException", (error) => {
log.error(error);
});
process.on("unhandledRejection", (reason) => {
log.error(reason);
});
// .envから設定をprocess.envに読み込み
const appDirPath = path.dirname(app.getPath("exe"));
// NOTE: 開発版では、カレントディレクトリにある .env ファイルを読み込む。
// 一方、配布パッケージ版では .env ファイルが実行ファイルと同じディレクトリに配置されているが、
// Linux・macOS ではそのディレクトリはカレントディレクトリとはならないため、.env ファイルの
// パスを明示的に指定する必要がある。Windows の配布パッケージ版でもこの設定で起動できるため、
// 全 OS で共通の条件分岐とした。
if (isDevelopment) {
dotenv.config({ override: true });
} else {
const envPath = path.join(appDirPath, ".env");
dotenv.config({ path: envPath });
}
protocol.registerSchemesAsPrivileged([
{ scheme: "app", privileges: { secure: true, standard: true, stream: true } },
]);
const isMac = process.platform === "darwin";
function detectImageTypeFromBase64(data: string): string {
switch (data[0]) {
case "/":
return "image/svg+xml";
case "R":
return "image/gif";
case "i":
return "image/png";
case "D":
return "image/jpeg";
default:
return "";
}
}
// EngineInfoからアイコンを読み込む
function replaceEngineInfoIconData(engineInfo: EngineInfo): EngineInfo {
if (!engineInfo.iconPath) return engineInfo;
let b64icon;
try {
b64icon = fs.readFileSync(path.resolve(appDirPath, engineInfo.iconPath), {
encoding: "base64",
});
} catch (e) {
log.error("Failed to read icon file: " + engineInfo.iconPath);
return engineInfo;
}
return {
...engineInfo,
iconData: `data:${detectImageTypeFromBase64(b64icon)};base64,${b64icon}`,
};
}
const defaultEngineInfos: EngineInfo[] = (() => {
// TODO: envから直接ではなく、envに書いたengine_manifest.jsonから情報を得るようにする
const defaultEngineInfosEnv = process.env.DEFAULT_ENGINE_INFOS;
let engines: EngineInfo[] = [];
if (defaultEngineInfosEnv) {
engines = JSON.parse(defaultEngineInfosEnv) as EngineInfo[];
}
return engines.map(replaceEngineInfoIconData).map((engineInfo) => {
return {
...engineInfo,
path:
engineInfo.path === undefined
? undefined
: path.resolve(appDirPath, engineInfo.path),
};
});
})();
// ユーザーディレクトリにあるエンジンを取得する
function fetchEngineInfosFromUserDirectory(): EngineInfo[] {
const userEngineDir = path.join(app.getPath("userData"), "engines");
if (!fs.existsSync(userEngineDir)) {
fs.mkdirSync(userEngineDir);
}
const engines: EngineInfo[] = [];
for (const dirName of fs.readdirSync(userEngineDir)) {
const engineDir = path.join(userEngineDir, dirName);
if (!fs.statSync(engineDir).isDirectory()) {
console.log(`${engineDir} is not directory`);
continue;
}
const manifestPath = path.join(engineDir, "engine_manifest.json");
if (!fs.existsSync(manifestPath)) {
console.log(`${manifestPath} is not found`);
continue;
}
const manifest: EngineManifest = JSON.parse(
fs.readFileSync(manifestPath, { encoding: "utf8" })
);
engines.push({
uuid: manifest.uuid,
host: `http://127.0.0.1:${manifest.port}`,
name: manifest.name,
iconPath: path.join(engineDir, manifest.icon),
path: engineDir,
executionEnabled: true,
executionFilePath: path.join(engineDir, manifest.command),
});
}
return engines.map(replaceEngineInfoIconData);
}
function fetchEngineInfos(): EngineInfo[] {
const userEngineInfos = fetchEngineInfosFromUserDirectory();
return [...defaultEngineInfos, ...userEngineInfos];
}
const defaultHotkeySettings: HotkeySetting[] = [
{
action: "音声書き出し",
combination: !isMac ? "Ctrl E" : "Meta E",
},
{
action: "一つだけ書き出し",
combination: "E",
},
{
action: "音声を繋げて書き出し",
combination: "",
},
{
action: "再生/停止",
combination: "Space",
},
{
action: "連続再生/停止",
combination: "Shift Space",
},
{
action: "アクセント欄を表示",
combination: "1",
},
{
action: "イントネーション欄を表示",
combination: "2",
},
{
action: "長さ欄を表示",
combination: "3",
},
{
action: "テキスト欄を追加",
combination: "Shift Enter",
},
{
action: "テキスト欄を削除",
combination: "Shift Delete",
},
{
action: "テキスト欄からフォーカスを外す",
combination: "Escape",
},
{
action: "テキスト欄にフォーカスを戻す",
combination: "Enter",
},
{
action: "元に戻す",
combination: !isMac ? "Ctrl Z" : "Meta Z",
},
{
action: "やり直す",
combination: !isMac ? "Ctrl Y" : "Shift Meta Z",
},
{
action: "新規プロジェクト",
combination: !isMac ? "Ctrl N" : "Meta N",
},
{
action: "プロジェクトを名前を付けて保存",
combination: !isMac ? "Ctrl Shift S" : "Shift Meta S",
},
{
action: "プロジェクトを上書き保存",
combination: !isMac ? "Ctrl S" : "Meta S",
},
{
action: "プロジェクト読み込み",
combination: !isMac ? "Ctrl O" : "Meta O",
},
{
action: "テキスト読み込む",
combination: "",
},
{
action: "全体のイントネーションをリセット",
combination: !isMac ? "Ctrl G" : "Meta G",
},
{
action: "選択中のアクセント句のイントネーションをリセット",
combination: "R",
},
];
const defaultToolbarButtonSetting: ToolbarSetting = [
"PLAY_CONTINUOUSLY",
"STOP",
"EXPORT_AUDIO_ONE",
"EMPTY",
"UNDO",
"REDO",
];
// 設定ファイル
const store = new Store<ElectronStoreType>({
schema: {
useGpu: {
type: "boolean",
default: false,
},
inheritAudioInfo: {
type: "boolean",
default: true,
},
activePointScrollMode: {
type: "string",
enum: ["CONTINUOUSLY", "PAGE", "OFF"],
default: "OFF",
},
savingSetting: {
type: "object",
properties: {
fileEncoding: {
type: "string",
enum: ["UTF-8", "Shift_JIS"],
default: "UTF-8",
},
fileNamePattern: {
type: "string",
default: "",
},
fixedExportEnabled: { type: "boolean", default: false },
avoidOverwrite: { type: "boolean", default: false },
fixedExportDir: { type: "string", default: "" },
exportLab: { type: "boolean", default: false },
exportText: { type: "boolean", default: false },
outputStereo: { type: "boolean", default: false },
outputSamplingRate: { type: "number", default: 24000 },
audioOutputDevice: { type: "string", default: "default" },
},
default: {
fileEncoding: "UTF-8",
fileNamePattern: "",
fixedExportEnabled: false,
avoidOverwrite: false,
fixedExportDir: "",
exportLab: false,
exportText: false,
outputStereo: false,
outputSamplingRate: 24000,
audioOutputDevice: "default",
splitTextWhenPaste: "PERIOD_AND_NEW_LINE",
},
},
// To future developers: if you are to modify the store schema with array type,
// for example, the hotkeySettings below,
// please remember to add a corresponding migration
// Learn more: https://github.com/sindresorhus/electron-store#migrations
hotkeySettings: {
type: "array",
items: {
type: "object",
properties: {
action: { type: "string" },
combination: { type: "string" },
},
},
default: defaultHotkeySettings,
},
toolbarSetting: {
type: "array",
items: {
type: "string",
},
default: defaultToolbarButtonSetting,
},
userCharacterOrder: {
type: "array",
items: {
type: "string",
},
default: [],
},
defaultStyleIds: {
type: "array",
items: {
type: "object",
properties: {
speakerUuid: { type: "string" },
defaultStyleId: { type: "number" },
},
},
default: [],
},
presets: {
type: "object",
properties: {
items: {
type: "object",
patternProperties: {
// uuid
"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}": {
type: "object",
properties: {
name: { type: "string" },
speedScale: { type: "number" },
pitchScale: { type: "number" },
intonationScale: { type: "number" },
volumeScale: { type: "number" },
prePhonemeLength: { type: "number" },
postPhonemeLength: { type: "number" },
},
},
},
additionalProperties: false,
},
keys: {
type: "array",
items: {
type: "string",
pattern:
"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",
},
},
},
default: { items: {}, keys: [] },
},
currentTheme: {
type: "string",
default: "Default",
},
experimentalSetting: {
type: "object",
properties: {
enablePreset: { type: "boolean", default: false },
enableInterrogativeUpspeak: {
type: "boolean",
default: false,
},
},
default: {
enablePreset: false,
enableInterrogativeUpspeak: false,
},
},
acceptRetrieveTelemetry: {
type: "string",
enum: ["Unconfirmed", "Accepted", "Refused"],
default: "Unconfirmed",
},
acceptTerms: {
type: "string",
enum: ["Unconfirmed", "Accepted", "Rejected"],
default: "Unconfirmed",
},
splitTextWhenPaste: {
type: "string",
enum: ["PERIOD_AND_NEW_LINE", "NEW_LINE", "OFF"],
default: "PERIOD_AND_NEW_LINE",
},
splitterPosition: {
type: "object",
properties: {
portraitPaneWidth: { type: "number" },
audioInfoPaneWidth: { type: "number" },
audioDetailPaneHeight: { type: "number" },
},
default: {},
},
confirmedTips: {
type: "object",
properties: {
tweakableSliderByScroll: { type: "boolean", default: false },
},
default: {
tweakableSliderByScroll: false,
},
},
},
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);
}
},
},
});
// engine
type EngineProcessContainer = {
willQuitEngine: boolean;
engineProcess?: ChildProcess;
};
const engineProcessContainers: Record<string, EngineProcessContainer> = {};
async function runEngineAll() {
const engineInfos = fetchEngineInfos();
log.info(`Starting ${engineInfos.length} engine/s...`);
for (const engineInfo of engineInfos) {
log.info(`ENGINE ${engineInfo.uuid}: Start launching`);
await runEngine(engineInfo.uuid);
}
}
async function runEngine(engineId: string) {
const engineInfos = fetchEngineInfos();
const engineInfo = engineInfos.find(
(engineInfo) => engineInfo.uuid === engineId
);
if (!engineInfo)
throw new Error(`No such engineInfo registered: engineId == ${engineId}`);
if (!engineInfo.executionEnabled) {
log.info(`ENGINE ${engineId}: Skipped engineInfo execution: disabled`);
return;
}
if (!engineInfo.executionFilePath) {
log.info(
`ENGINE ${engineId}: Skipped engineInfo execution: empty executionFilePath`
);
return;
}
log.info(`ENGINE ${engineId}: Starting process`);
if (!(engineId in engineProcessContainers)) {
engineProcessContainers[engineId] = {
willQuitEngine: false,
};
}
const engineProcessContainer = engineProcessContainers[engineId];
engineProcessContainer.willQuitEngine = false;
// 最初のエンジンモード
if (!store.has("useGpu")) {
const hasGpu = await hasSupportedGpu(process.platform);
store.set("useGpu", hasGpu);
dialog.showMessageBox(win, {
message: `音声合成エンジンを${
hasGpu ? "GPU" : "CPU"
}モードで起動しました`,
detail:
"エンジンの起動モードは、画面上部の「エンジン」メニューから変更できます。",
title: "エンジンの起動モード",
type: "info",
});
}
if (!store.has("inheritAudioInfo")) {
store.set("inheritAudioInfo", true);
}
const useGpu = store.get("useGpu");
log.info(`ENGINE ${engineId} mode: ${useGpu ? "GPU" : "CPU"}`);
// エンジンプロセスの起動
const enginePath = path.resolve(
appDirPath,
engineInfo.executionFilePath ?? "run.exe"
);
const args = useGpu ? ["--use_gpu"] : [];
log.info(`ENGINE ${engineId} path: ${enginePath}`);
log.info(`ENGINE ${engineId} args: ${JSON.stringify(args)}`);
const engineProcess = spawn(enginePath, args, {
cwd: path.dirname(enginePath),
});
engineProcessContainer.engineProcess = engineProcess;
engineProcess.stdout?.on("data", (data) => {
log.info(`ENGINE ${engineId} STDOUT: ${data.toString("utf-8")}`);
});
engineProcess.stderr?.on("data", (data) => {
log.error(`ENGINE ${engineId} STDERR: ${data.toString("utf-8")}`);
});
engineProcess.on("close", (code, signal) => {
log.info(
`ENGINE ${engineId}: Process terminated due to receipt of signal ${signal}`
);
log.info(`ENGINE ${engineId}: Process exited with code ${code}`);
if (!engineProcessContainer.willQuitEngine) {
ipcMainSend(win, "DETECTED_ENGINE_ERROR", { engineId });
dialog.showErrorBox(
"音声合成エンジンエラー",
"音声合成エンジンが異常終了しました。エンジンを再起動してください。"
);
}
});
}
function killEngineAll(): Record<string, Promise<void>> {
const killingProcessPromises: Record<string, Promise<void>> = {};
for (const engineId of Object.keys(engineProcessContainers)) {
const promise = killEngine(engineId);
if (promise === undefined) continue;
killingProcessPromises[engineId] = promise;
}
return killingProcessPromises;
}
// Promise<void> | undefined
// Promise.resolve: エンジンプロセスのキルに成功した(非同期)
// Promise.reject: エンジンプロセスのキルに失敗した(非同期)
// undefined: エンジンプロセスのキルが開始されなかった=エンジンプロセスがすでに停止している(同期)
function killEngine(engineId: string): Promise<void> | undefined {
const engineProcessContainer = engineProcessContainers[engineId];
if (!engineProcessContainer) {
log.error(`No such engineProcessContainer: engineId == ${engineId}`);
return undefined;
}
const engineProcess = engineProcessContainer.engineProcess;
if (engineProcess === undefined) {
// nop if no process started (already killed or not started yet)
log.info(`ENGINE ${engineId}: Process not started`);
return undefined;
}
const engineNotExited = engineProcess.exitCode === null;
const engineNotKilled = engineProcess.signalCode === null;
log.info(
`ENGINE ${engineId}: last exit code: ${engineProcess.exitCode}, signal: ${engineProcess.signalCode}`
);
const isAlive = engineNotExited && engineNotKilled;
if (!isAlive) {
log.info(`ENGINE ${engineId}: Process already closed`);
return undefined;
}
return new Promise<void>((resolve, reject) => {
log.info(`ENGINE ${engineId}: Killing process (PID=${engineProcess.pid})`);
// エラーダイアログを抑制
engineProcessContainer.willQuitEngine = true;
// プロセス終了時のイベントハンドラ
engineProcess.once("close", () => {
log.info(`ENGINE ${engineId}: Process closed`);
resolve();
});
try {
engineProcess.pid != undefined && treeKill(engineProcess.pid);
} catch (error: unknown) {
log.error(`ENGINE ${engineId}: Error during killing process`);
reject(error);
}
});
}
async function restartEngineAll() {
const engineInfos = fetchEngineInfos();
for (const engineInfo of engineInfos) {
await restartEngine(engineInfo.uuid);
}
}
async function restartEngine(engineId: string) {
await new Promise<void>((resolve, reject) => {
const engineProcessContainer: EngineProcessContainer | undefined =
engineProcessContainers[engineId];
const engineProcess = engineProcessContainer?.engineProcess;
log.info(
`ENGINE ${engineId}: Restarting process (last exit code: ${engineProcess?.exitCode}, signal: ${engineProcess?.signalCode})`
);
// エンジンのプロセスがすでに終了している、またはkillされている場合
const engineExited = engineProcess?.exitCode !== null;
const engineKilled = engineProcess?.signalCode !== null;
// engineProcess === undefinedの場合true
if (engineExited || engineKilled) {
log.info(
`ENGINE ${engineId}: Process is not started yet or already killed. Starting process...`
);
runEngine(engineId);
resolve();
return;
}
// エンジンエラー時のエラーウィンドウ抑制用。
engineProcessContainer.willQuitEngine = true;
// 「killに使用するコマンドが終了するタイミング」と「OSがプロセスをkillするタイミング」が違うので単純にtreeKillのコールバック関数でrunEngine()を実行すると失敗します。
// closeイベントはexitイベントよりも後に発火します。
const restartEngineOnProcessClosedCallback = () => {
log.info(`ENGINE ${engineId}: Process killed. Restarting process...`);
runEngine(engineId);
resolve();
};
engineProcess.once("close", restartEngineOnProcessClosedCallback);
// treeKillのコールバック関数はコマンドが終了した時に呼ばれます。
log.info(
`ENGINE ${engineId}: Killing current process (PID=${engineProcess.pid})...`
);
treeKill(engineProcess.pid, (error) => {
// error変数の値がundefined以外であればkillコマンドが失敗したことを意味します。
if (error != null) {
log.error(`ENGINE ${engineId}: Failed to kill process`);
log.error(error);
// killに失敗したとき、closeイベントが発生せず、once listenerが消費されない
// listenerを削除してENGINEの意図しない再起動を防止
engineProcess.removeListener(
"close",
restartEngineOnProcessClosedCallback
);
reject();
}
});
});
}
// エンジンのフォルダを開く
function openEngineDirectory(engineId: string) {
const engineInfos = fetchEngineInfos();
const engineInfo = engineInfos.find(
(engineInfo) => engineInfo.uuid === engineId
);
if (!engineInfo) {
throw new Error(`No such engineInfo registered: engineId == ${engineId}`);
}
const engineDirectory = engineInfo.path;
if (engineDirectory == null) {
return;
}
// Windows環境だとスラッシュ区切りのパスが動かない。
// path.resolveはWindowsだけバックスラッシュ区切りにしてくれるため、path.resolveを挟む。
shell.openPath(path.resolve(engineDirectory));
}
// temp dir
const tempDir = path.join(app.getPath("temp"), "VOICEVOX");
if (!fs.existsSync(tempDir)) {
fs.mkdirSync(tempDir);
}
// 使い方テキストの読み込み
declare let __static: string;
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();
let willQuit = false;
let filePathOnMac: string | null = null;
// 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: true,
contextIsolation: true,
},
icon: path.join(__static, "icon.png"),
});
if (process.env.WEBPACK_DEV_SERVER_URL) {
await win.loadURL(
(process.env.WEBPACK_DEV_SERVER_URL as string) + "#/home"
);
} else {
createProtocol("app");
win.loadURL("app://./index.html#/home");
}
if (isDevelopment) win.webContents.openDevTools();
// Macではdarkモードかつウィンドウが非アクティブのときに閉じるボタンなどが見えなくなるので、lightテーマに固定
if (isMac) nativeTheme.themeSource = "light";
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 (!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],
});
});
win.webContents.once("did-finish-load", () => {
if (isMac) {
if (filePathOnMac != null) {
ipcMainSend(win, "LOAD_PROJECT_FILE", {
filePath: filePathOnMac,
confirm: false,
});
filePathOnMac = null;
}
} else {
if (process.argv.length >= 2) {
const filePath = process.argv[1];
ipcMainSend(win, "LOAD_PROJECT_FILE", { filePath, confirm: false });
}
}
});
mainWindowState.manage(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("SHOW_AUDIO_SAVE_DIALOG", async (_, { title, defaultPath }) => {
const result = await dialog.showSaveDialog(win, {