Skip to content

Commit

Permalink
EngineIdをユニークな型にする (#1172)
Browse files Browse the repository at this point in the history
  • Loading branch information
Hiroshiba authored Feb 9, 2023
1 parent 7203309 commit b6a0d11
Show file tree
Hide file tree
Showing 17 changed files with 188 additions and 132 deletions.
20 changes: 12 additions & 8 deletions src/background.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@ import {
defaultHotkeySettings,
isMac,
defaultToolbarButtonSetting,
engineSetting,
engineSettingSchema,
EngineId,
} from "./type/preload";

import log from "electron-log";
Expand Down Expand Up @@ -133,15 +134,18 @@ const store = new Store<ElectronStoreType>({
},
">=0.14": (store) => {
// FIXME: できるならEngineManagerからEnginIDを取得したい
const engineId = JSON.parse(process.env.DEFAULT_ENGINE_INFOS ?? "[]")[0]
.uuid;
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: engineId,
engineId,
speakerUuid: defaultStyle.speakerUuid,
defaultStyleId: defaultStyle.defaultStyleId,
}))
Expand Down Expand Up @@ -178,7 +182,7 @@ const engineManager = new EngineManager({
const vvppManager = new VvppManager({ vvppEngineDir });

// エンジンのフォルダを開く
function openEngineDirectory(engineId: string) {
function openEngineDirectory(engineId: EngineId) {
const engineDirectory = engineManager.fetchEngineDirectory(engineId);

// Windows環境だとスラッシュ区切りのパスが動かない。
Expand Down Expand Up @@ -270,7 +274,7 @@ function checkMultiEngineEnabled(): boolean {
* VVPPエンジンをアンインストールする。
* 関数を呼んだタイミングでアンインストール処理を途中まで行い、アプリ終了時に完遂する。
*/
async function uninstallVvppEngine(engineId: string) {
async function uninstallVvppEngine(engineId: EngineId) {
let engineInfo: EngineInfo | undefined = undefined;
try {
engineInfo = engineManager.fetchEngineInfo(engineId);
Expand Down Expand Up @@ -492,7 +496,7 @@ async function start() {
for (const engineInfo of engineInfos) {
if (!engineSettings[engineInfo.uuid]) {
// 空オブジェクトをパースさせることで、デフォルト値を取得する
engineSettings[engineInfo.uuid] = engineSetting.parse({});
engineSettings[engineInfo.uuid] = engineSettingSchema.parse({});
}
}
store.set("engineSettings", engineSettings);
Expand Down Expand Up @@ -817,7 +821,7 @@ ipcMainHandle("INSTALL_VVPP_ENGINE", async (_, path: string) => {
return await installVvppEngine(path);
});

ipcMainHandle("UNINSTALL_VVPP_ENGINE", async (_, engineId: string) => {
ipcMainHandle("UNINSTALL_VVPP_ENGINE", async (_, engineId: EngineId) => {
return await uninstallVvppEngine(engineId);
});

Expand Down
30 changes: 19 additions & 11 deletions src/background/engineManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ import {
ElectronStoreType,
EngineDirValidationResult,
MinimumEngineManifest,
EngineId,
engineIdSchema,
} from "@/type/preload";

import log from "electron-log";
Expand All @@ -33,7 +35,7 @@ function createDefaultEngineInfos(defaultEngineDir: string): EngineInfo[] {

const envSchema = z
.object({
uuid: z.string().uuid(),
uuid: engineIdSchema,
host: z.string(),
name: z.string(),
executionEnabled: z.boolean(),
Expand Down Expand Up @@ -62,7 +64,7 @@ export class EngineManager {
vvppEngineDir: string;

defaultEngineInfos: EngineInfo[];
engineProcessContainers: Record<string, EngineProcessContainer>;
engineProcessContainers: Record<EngineId, EngineProcessContainer>;

constructor({
store,
Expand Down Expand Up @@ -160,7 +162,7 @@ export class EngineManager {
/**
* エンジンの情報を取得する。存在しない場合はエラーを返す。
*/
fetchEngineInfo(engineId: string): EngineInfo {
fetchEngineInfo(engineId: EngineId): EngineInfo {
const engineInfos = this.fetchEngineInfos();
const engineInfo = engineInfos.find(
(engineInfo) => engineInfo.uuid === engineId
Expand All @@ -174,7 +176,7 @@ export class EngineManager {
/**
* エンジンのディレクトリを取得する。存在しない場合はエラーを返す。
*/
fetchEngineDirectory(engineId: string): string {
fetchEngineDirectory(engineId: EngineId): string {
const engineInfo = this.fetchEngineInfo(engineId);
const engineDirectory = engineInfo.path;
if (engineDirectory == null) {
Expand Down Expand Up @@ -202,7 +204,7 @@ export class EngineManager {
* エンジンを起動する。
* FIXME: winを受け取らなくても良いようにする
*/
async runEngine(engineId: string, win: BrowserWindow) {
async runEngine(engineId: EngineId, win: BrowserWindow) {
const engineInfos = this.fetchEngineInfos();
const engineInfo = engineInfos.find(
(engineInfo) => engineInfo.uuid === engineId
Expand Down Expand Up @@ -233,7 +235,11 @@ export class EngineManager {
const engineProcessContainer = this.engineProcessContainers[engineId];
engineProcessContainer.willQuitEngine = false;

const useGpu = this.store.get("engineSettings")[engineId].useGpu;
const engineSetting = this.store.get("engineSettings")[engineId];
if (engineSetting == undefined)
throw new Error(`No such engineSetting: engineId == ${engineId}`);

const useGpu = engineSetting.useGpu;
log.info(`ENGINE ${engineId} mode: ${useGpu ? "GPU" : "CPU"}`);

// エンジンプロセスの起動
Expand Down Expand Up @@ -286,10 +292,12 @@ export class EngineManager {
/**
* 全てのエンジンに対し、各エンジンを終了するPromiseを返す。
*/
killEngineAll(): Record<string, Promise<void>> {
const killingProcessPromises: Record<string, Promise<void>> = {};
killEngineAll(): Record<EngineId, Promise<void>> {
const killingProcessPromises: Record<EngineId, Promise<void>> = {};

for (const engineId of Object.keys(this.engineProcessContainers)) {
// FIXME: engineProcessContainersをMapにする
for (const engineIdStr of Object.keys(this.engineProcessContainers)) {
const engineId = EngineId(engineIdStr);
const promise = this.killEngine(engineId);
if (promise === undefined) continue;

Expand All @@ -307,7 +315,7 @@ export class EngineManager {
* Promise.reject: エンジンプロセスのキルに失敗した(非同期)
* undefined: エンジンプロセスのキルが開始されなかった=エンジンプロセスがすでに停止している(同期)
*/
killEngine(engineId: string): Promise<void> | undefined {
killEngine(engineId: EngineId): Promise<void> | undefined {
const engineProcessContainer = this.engineProcessContainers[engineId];
if (!engineProcessContainer) {
log.error(`No such engineProcessContainer: engineId == ${engineId}`);
Expand Down Expand Up @@ -364,7 +372,7 @@ export class EngineManager {
* エンジンを再起動する。
* FIXME: winを受け取らなくても良いようにする
*/
async restartEngine(engineId: string, win: BrowserWindow) {
async restartEngine(engineId: EngineId, win: BrowserWindow) {
// FIXME: killEngine関数を使い回すようにする
await new Promise<void>((resolve, reject) => {
const engineProcessContainer: EngineProcessContainer | undefined =
Expand Down
6 changes: 3 additions & 3 deletions src/background/vvppManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import log from "electron-log";
import { moveFile } from "move-file";
import { Extract } from "unzipper";
import { dialog } from "electron";
import { EngineInfo, MinimumEngineManifest } from "@/type/preload";
import { EngineId, EngineInfo, MinimumEngineManifest } from "@/type/preload";
import MultiStream from "multistream";
import glob, { glob as callbackGlob } from "glob";

Expand Down Expand Up @@ -57,7 +57,7 @@ export const isVvppFile = (filePath: string) => {
export class VvppManager {
vvppEngineDir: string;

willDeleteEngineIds: Set<string>;
willDeleteEngineIds: Set<EngineId>;
willReplaceEngineDirs: Array<{ from: string; to: string }>;

constructor({ vvppEngineDir }: { vvppEngineDir: string }) {
Expand All @@ -73,7 +73,7 @@ export class VvppManager {
});
}

markWillDelete(engineId: string) {
markWillDelete(engineId: EngineId) {
this.willDeleteEngineIds.add(engineId);
}

Expand Down
29 changes: 22 additions & 7 deletions src/components/EngineManageDialog.vue
Original file line number Diff line number Diff line change
Expand Up @@ -333,7 +333,7 @@ import { computed, defineComponent, ref, watch } from "vue";
import { useStore } from "@/store";
import { useQuasar } from "quasar";
import { base64ImageToUri } from "@/helpers/imageHelper";
import type { EngineDirValidationResult } from "@/type/preload";
import { EngineDirValidationResult, EngineId } from "@/type/preload";
import type { SupportedFeatures } from "@/openapi/models/SupportedFeatures";
type EngineLoaderType = "dir" | "vvpp";
Expand Down Expand Up @@ -395,12 +395,14 @@ export default defineComponent({
])
)
);
const engineVersions = ref<Record<string, string>>({});
const engineVersions = ref<Record<EngineId, string>>({});
watch(
[engineInfos, engineStates, engineManifests],
async () => {
for (const id of Object.keys(engineInfos.value)) {
// FIXME: engineInfosをMapにする
for (const idStr of Object.keys(engineInfos.value)) {
const id = EngineId(idStr);
if (engineStates.value[id] !== "READY") continue;
if (engineVersions.value[id]) continue;
const version = await store
Expand All @@ -418,14 +420,21 @@ export default defineComponent({
{ immediate: true }
);
const selectedId = ref("");
const selectedId = ref<EngineId | undefined>(undefined);
const isDeletable = computed(() => {
// FIXME: いたるところにエンジンが選択済みかを検証するコードがある。
// 選択後に現れる領域は別ComponentにしてselectedIdをpropで渡せばこれは不要になる
if (selectedId.value == undefined)
throw new Error("engine is not selected");
return (
engineInfos.value[selectedId.value] &&
engineInfos.value[selectedId.value].type === "path"
);
});
const engineDir = computed(() => {
if (selectedId.value == undefined)
throw new Error("engine is not selected");
return engineInfos.value[selectedId.value]?.path || "(組み込み)";
});
Expand Down Expand Up @@ -522,6 +531,8 @@ export default defineComponent({
textColor: "warning",
},
}).onOk(async () => {
if (selectedId.value == undefined)
throw new Error("engine is not selected");
switch (engineInfos.value[selectedId.value].type) {
case "path": {
const engineDir = store.state.engineInfos[selectedId.value].path;
Expand Down Expand Up @@ -556,15 +567,19 @@ export default defineComponent({
});
};
const selectEngine = (id: string) => {
const selectEngine = (id: EngineId) => {
selectedId.value = id;
};
const openSelectedEngineDirectory = () => {
if (selectedId.value == undefined)
throw new Error("assert selectedId.value != undefined");
store.dispatch("OPEN_ENGINE_DIRECTORY", { engineId: selectedId.value });
};
const restartSelectedEngine = () => {
if (selectedId.value == undefined)
throw new Error("assert selectedId.value != undefined");
store.dispatch("RESTART_ENGINES", {
engineIds: [selectedId.value],
});
Expand Down Expand Up @@ -644,13 +659,13 @@ export default defineComponent({
// ステートの移動
// 初期状態
const toInitialState = () => {
selectedId.value = "";
selectedId.value = undefined;
isAddingEngine.value = false;
};
// エンジン追加状態
const toAddEngineState = () => {
isAddingEngine.value = true;
selectedId.value = "";
selectedId.value = undefined;
newEngineDirValidationState.value = null;
newEngineDir.value = "";
vvppFilePath.value = "";
Expand Down
24 changes: 14 additions & 10 deletions src/components/LibraryPolicy.vue
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,9 @@
import { useStore } from "@/store";
import { computed, ref } from "vue";
import { useMarkdownIt } from "@/plugins/markdownItPlugin";
import { EngineId } from "@/type/preload";
type DetailKey = { engine: string; character: string };
type DetailKey = { engine: EngineId; character: string };
const store = useStore();
const md = useMarkdownIt();
Expand All @@ -88,16 +89,19 @@ const engineInfos = computed(
() =>
new Map(
Object.entries(store.state.characterInfos).map(
([engineId, characterInfos]) => [
engineId,
{
([engineIdStr, characterInfos]) => {
const engineId = EngineId(engineIdStr);
return [
engineId,
name: store.state.engineManifests[engineId].name,
characterInfos: new Map(
characterInfos.map((ci) => [ci.metas.speakerUuid, ci])
),
},
]
{
engineId,
name: store.state.engineManifests[engineId].name,
characterInfos: new Map(
characterInfos.map((ci) => [ci.metas.speakerUuid, ci])
),
},
];
}
)
)
);
Expand Down
9 changes: 5 additions & 4 deletions src/components/SettingDialog.vue
Original file line number Diff line number Diff line change
Expand Up @@ -730,6 +730,7 @@ import {
ActivePointScrollMode,
SplitTextWhenPasteType,
EditorFontType,
EngineId,
} from "@/type/preload";
import FileNamePatternDialog from "./FileNamePatternDialog.vue";
Expand Down Expand Up @@ -921,7 +922,7 @@ export default defineComponent({
{ label: "GPU", value: true },
];
const gpuSwitchEnabled = (engineId: string) => {
const gpuSwitchEnabled = (engineId: EngineId) => {
// CPU版でもGPUモードからCPUモードに変更できるようにする
return store.getters.ENGINE_CAN_USE_GPU(engineId) || engineUseGpu.value;
};
Expand Down Expand Up @@ -1023,16 +1024,16 @@ export default defineComponent({
const showsFilePatternEditDialog = ref(false);
const selectedEngineIdRaw = ref("");
const selectedEngineIdRaw = ref<EngineId | undefined>(undefined);
const selectedEngineId = computed({
get: () => {
return selectedEngineIdRaw.value || engineIds.value[0];
},
set: (engineId: string) => {
set: (engineId: EngineId) => {
selectedEngineIdRaw.value = engineId;
},
});
const renderEngineNameLabel = (engineId: string) => {
const renderEngineNameLabel = (engineId: EngineId) => {
return engineInfos.value[engineId].name;
};
Expand Down
6 changes: 3 additions & 3 deletions src/electron/preload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {
IpcRendererEvent,
} from "electron";

import { Sandbox, ElectronStoreType } from "@/type/preload";
import { Sandbox, ElectronStoreType, EngineId } from "@/type/preload";
import { IpcIHData, IpcSOData } from "@/type/ipc";

function ipcRendererInvoke<T extends keyof IpcIHData>(
Expand Down Expand Up @@ -192,11 +192,11 @@ const api: Sandbox = {
return ipcRendererInvoke("ENGINE_INFOS");
},

restartEngine: (engineId: string) => {
restartEngine: (engineId: EngineId) => {
return ipcRendererInvoke("RESTART_ENGINE", { engineId });
},

openEngineDirectory: (engineId: string) => {
openEngineDirectory: (engineId: EngineId) => {
return ipcRendererInvoke("OPEN_ENGINE_DIRECTORY", { engineId });
},

Expand Down
Loading

0 comments on commit b6a0d11

Please sign in to comment.