refactor: refactoring store

This commit is contained in:
AkiChase 2025-03-11 00:11:15 +08:00
parent 1bc0ba313a
commit 940d1699f8
16 changed files with 293 additions and 266 deletions

View File

@ -10,7 +10,6 @@ use std::{fs::read_to_string, sync::Arc};
use tauri::{Emitter, Listener, Manager};
use tauri_plugin_store::StoreExt;
// TODO move to command.rs
#[tauri::command]
/// get devices info list
pub fn adb_devices() -> Result<Vec<Device>, String> {

View File

@ -32,32 +32,54 @@ async fn main() {
Some(value) => {
// TODO check position and size validity
let pos_x = value["posX"].as_i64();
let pos_y = value["posY"].as_i64();
let size_w = value["sizeW"].as_i64().unwrap_or(800);
let size_h = value["sizeH"].as_i64().unwrap_or(600);
let pos_x = value["posX"].as_f64();
let pos_y = value["posY"].as_f64();
let mut size_w = value["sizeW"].as_i64().unwrap_or(800) as f64;
let mut size_h = value["sizeH"].as_i64().unwrap_or(600) as f64;
let main_window: tauri::WebviewWindow = app.get_webview_window("main").unwrap();
main_window.set_zoom(1.).unwrap_or(());
if pos_x.is_none() || pos_y.is_none() {
main_window.center().unwrap_or(());
} else {
main_window
.set_position(tauri::Position::Logical(tauri::LogicalPosition {
x: (pos_x.unwrap() - 70) as f64,
y: (pos_y.unwrap() - 30) as f64,
}))
.unwrap();
// check size validity
if size_w < 100.0 {
size_w = 100.0;
}
if size_h < 100.0 {
size_h = 100.0;
}
if let Some(monitor) = main_window.primary_monitor().ok().flatten() {
let size = monitor.size().to_logical::<f64>(monitor.scale_factor());
let (max_w, max_h) = (size.width - 70.0, size.height - 30.0);
if size_w > max_w {
size_w = max_w;
}
if size_h > max_h {
size_h = max_h;
}
}
main_window
.set_size(tauri::Size::Logical(tauri::LogicalSize {
width: (size_w + 70) as f64,
height: (size_h + 30) as f64,
width: size_w + 70.0,
height: size_h + 30.0,
}))
.unwrap();
// check position validity
if pos_x.is_none() || pos_y.is_none() {
main_window.center().unwrap_or(());
} else {
let pos_x = pos_x.unwrap();
let pos_y = pos_y.unwrap();
main_window
.set_position(tauri::Position::Logical(tauri::LogicalPosition {
x: pos_x - 70.0,
y: pos_y - 30.0,
}))
.unwrap();
}
}
None => {
let main_window: tauri::WebviewWindow = app.get_webview_window("main").unwrap();

View File

@ -9,10 +9,12 @@ import {
} from "naive-ui";
import { onMounted } from "vue";
import { useRouter } from "vue-router";
import { LocalStore } from "./store/localStore";
const router = useRouter();
onMounted(async () => {
await LocalStore.init();
await router.replace({ name: "mask" });
});
</script>

View File

@ -362,7 +362,7 @@ function closeWS() {
<div class="container">
<NScrollbar>
<div class="device">
<NSpin :show="store.showLoadingRef">
<NSpin :show="store.showLoadingFlag">
<NH4 prefix="bar">{{ $t("pages.Device.localPort") }}</NH4>
<NInputNumber
v-model:value="port"

View File

@ -18,7 +18,6 @@ import { open } from "@tauri-apps/plugin-shell";
import { getCurrentWindow, PhysicalSize } from "@tauri-apps/api/window";
import { useI18n } from "vue-i18n";
import { checkAdbAvailable } from "../invoke";
import { loadPersistentStorage } from "../storeLoader";
const { t } = useI18n();
const store = useGlobalStore();
@ -59,7 +58,6 @@ onActivated(async () => {
onMounted(async () => {
store.screenStreamClientId = genClientId();
loadPersistentStorage(store, t);
store.checkUpdate = checkUpdate;
if (store.checkUpdateAtStart) checkUpdate();
store.checkAdb = checkAdb;
@ -176,7 +174,7 @@ async function checkUpdate() {
<template>
<div class="content-container">
<div v-show="!store.controledDevice" class="notice">
<div v-show="store.controledDevice === null" class="notice">
<div class="content">
<NDialog
:closable="false"
@ -197,8 +195,8 @@ async function checkUpdate() {
"
/>
<div
v-if="store.maskButton.show"
:style="'--transparency: ' + store.maskButton.transparency"
v-if="store.maskKeyTip.show"
:style="'--transparency: ' + store.maskKeyTip.transparency"
class="button-layer"
>
<!-- <div style="position: absolute;height: 100%;width: 1px;background-color: red;left: 50%;"></div>

View File

@ -20,6 +20,7 @@ import { useKeyboardStore } from "../../store/keyboard";
import { useI18n } from "vue-i18n";
import { writeText } from "@tauri-apps/plugin-clipboard-manager";
import { LocalStore } from "../../store/localStore";
import { NonReactiveStore } from "../../store/noneReactiveStore";
const { t } = useI18n();
const store = useGlobalStore();
@ -47,26 +48,26 @@ const curRelativeSize = computed(() => {
return store.keyMappingConfigList[store.curKeyMappingIndex].relativeSize;
});
const keySettingPos = ref({ x: 100, y: 100 });
onMounted(async () => {
// loading keySettingPos from local store
let storedPos = await LocalStore.get<{ x: number; y: number }>(
"keySettingPos"
);
if (storedPos === undefined) {
await LocalStore.set("keySettingPos", keySettingPos.value);
storedPos = { x: 100, y: 100 };
}
// apply keySettingPos
const keyboardElement = document.getElementById(
"keyboardElement"
) as HTMLElement;
const maxWidth = keyboardElement.clientWidth - 40;
const maxHeight = keyboardElement.clientHeight - 40;
keySettingPos.value.x = Math.max(0, Math.min(storedPos.x, maxWidth));
keySettingPos.value.y = Math.max(0, Math.min(storedPos.y, maxHeight));
NonReactiveStore.setLocal("keySettingPos", {
x: Math.max(0, Math.min(NonReactiveStore.local.keySettingPos.x, maxWidth)),
y: Math.max(0, Math.min(NonReactiveStore.local.keySettingPos.y, maxHeight)),
});
const target = document.getElementById("keySettingBtn") as HTMLElement;
target.style.setProperty(
"left",
`${NonReactiveStore.local.keySettingPos.x}px`
);
target.style.setProperty(
"top",
`${NonReactiveStore.local.keySettingPos.y}px`
);
});
onActivated(() => {
@ -92,24 +93,26 @@ function dragHandler(downEvent: MouseEvent) {
const maxWidth = keyboardElement.clientWidth - 40;
const maxHeight = keyboardElement.clientHeight - 40;
const oldX = keySettingPos.value.x;
const oldY = keySettingPos.value.y;
const oldX = NonReactiveStore.local.keySettingPos.x;
const oldY = NonReactiveStore.local.keySettingPos.y;
const x = downEvent.clientX;
const y = downEvent.clientY;
let moveFlag = false;
let newX = oldX;
let newY = oldY;
const moveHandler = (moveEvent: MouseEvent) => {
const newX = oldX + moveEvent.clientX - x;
const newY = oldY + moveEvent.clientY - y;
keySettingPos.value.x = Math.max(0, Math.min(newX, maxWidth));
keySettingPos.value.y = Math.max(0, Math.min(newY, maxHeight));
newX = Math.max(0, Math.min(oldX + moveEvent.clientX - x, maxWidth));
newY = Math.max(0, Math.min(oldY + moveEvent.clientY - y, maxHeight));
target.style.setProperty("left", `${newX}px`);
target.style.setProperty("top", `${newY}px`);
};
const timer = setTimeout(() => {
moveFlag = true;
target.style.setProperty("cursor", "grabbing");
window.addEventListener("mousemove", moveHandler);
}, 1000);
}, 500);
const upHandler = () => {
clearTimeout(timer);
@ -118,7 +121,10 @@ function dragHandler(downEvent: MouseEvent) {
if (moveFlag) {
// move up
target.style.setProperty("cursor", "pointer");
LocalStore.set("keySettingPos", keySettingPos.value);
NonReactiveStore.setLocal("keySettingPos", {
x: newX,
y: newY,
});
} else {
// click up
if (keyboardStore.editSwipePointsFlag) {
@ -149,7 +155,7 @@ function importKeyMappingConfig() {
return;
}
store.keyMappingConfigList.push(keyMappingConfig);
store.setKeyMappingIndex(store.keyMappingConfigList.length - 1);
store.setCurKeyMappingIndex(store.keyMappingConfigList.length - 1);
showImportModal.value = false;
LocalStore.set("keyMappingConfigList", store.keyMappingConfigList);
message.success(t("pages.KeyBoard.KeySetting.importSuccess"));
@ -193,7 +199,7 @@ function createKeyMappingConfig() {
list: [],
};
store.keyMappingConfigList.push(newConfig);
store.setKeyMappingIndex(store.keyMappingConfigList.length - 1);
store.setCurKeyMappingIndex(store.keyMappingConfigList.length - 1);
LocalStore.set("keyMappingConfigList", store.keyMappingConfigList);
message.success(t("pages.KeyBoard.KeySetting.newConfigSuccess"));
}
@ -216,7 +222,7 @@ function copyCurKeyMappingConfig() {
store.keyMappingConfigList.push(newConfig);
keyboardStore.activeButtonIndex = -1;
keyboardStore.activeSteeringWheelButtonKeyIndex = -1;
store.setKeyMappingIndex(store.keyMappingConfigList.length - 1);
store.setCurKeyMappingIndex(store.keyMappingConfigList.length - 1);
LocalStore.set("keyMappingConfigList", store.keyMappingConfigList);
message.success(t("pages.KeyBoard.KeySetting.copyConfigSuccess", [newTitle]));
}
@ -233,7 +239,7 @@ function delCurKeyMappingConfig() {
keyboardStore.activeButtonIndex = -1;
keyboardStore.activeSteeringWheelButtonKeyIndex = -1;
keyboardStore.edited = false;
store.setKeyMappingIndex(
store.setCurKeyMappingIndex(
store.curKeyMappingIndex > 0 ? store.curKeyMappingIndex - 1 : 0
);
LocalStore.set("keyMappingConfigList", store.keyMappingConfigList);
@ -337,7 +343,7 @@ function migrateKeyMappingConfig() {
);
keyboardStore.activeButtonIndex = -1;
keyboardStore.activeSteeringWheelButtonKeyIndex = -1;
store.setKeyMappingIndex(store.curKeyMappingIndex + 1);
store.setCurKeyMappingIndex(store.curKeyMappingIndex + 1);
} else {
message.info(t("pages.KeyBoard.KeySetting.migrateConfigNeedless"));
}
@ -351,7 +357,7 @@ function selectKeyMappingConfig(index: number) {
keyboardStore.activeButtonIndex = -1;
keyboardStore.activeSteeringWheelButtonKeyIndex = -1;
store.setKeyMappingIndex(index);
store.setCurKeyMappingIndex(index);
}
function resetKeyMappingConfig() {
@ -371,10 +377,6 @@ function resetKeyMappingConfig() {
id="keySettingBtn"
:title="$t('pages.KeyBoard.KeySetting.buttonDrag')"
@mousedown="dragHandler"
:style="{
left: keySettingPos.x + 'px',
top: keySettingPos.y + 'px',
}"
>
<template #icon>
<NIcon>

View File

@ -11,9 +11,8 @@ import {
NTooltip,
} from "naive-ui";
import { onMounted, ref } from "vue";
import i18n, { allLanguage } from "../../i18n";
import { allLanguage } from "../../i18n";
import { useI18n } from "vue-i18n";
import { setAdbPath } from "../../invoke";
import { useGlobalStore } from "../../store/global";
import { LocalStore } from "../../store/localStore";
@ -28,28 +27,17 @@ const languageOptions = Object.entries(allLanguage).map(([key, value]) => {
};
});
const curLanguage = ref("en-US");
const adbPath = ref("");
const curAdbPath = ref("");
onMounted(async () => {
curLanguage.value = (await LocalStore.get<string>("language")) ?? "en-US";
adbPath.value = (await LocalStore.get<string>("adbPath")) ?? "";
curAdbPath.value = store.adbPath;
});
function changeLanguage(language: "zh-CN" | "en-US") {
if (language === curLanguage.value) return;
curLanguage.value = language;
LocalStore.set("language", language);
i18n.global.locale = language;
}
async function adjustAdbPath() {
store.showLoading();
await setAdbPath(adbPath.value);
store.changeAbdPath(curAdbPath.value);
message.success(t("pages.Setting.Basic.adbPath.setSuccess"));
await store.checkAdb();
adbPath.value = (await LocalStore.get<string>("adbPath")) ?? "";
store.hideLoading();
}
@ -62,15 +50,15 @@ function changeClipboardSync() {
<div class="setting-page">
<NH4 prefix="bar">{{ $t("pages.Setting.Basic.language") }}</NH4>
<NSelect
:value="curLanguage"
@update:value="changeLanguage"
:value="store.language"
@update:value="store.setLanguage"
:options="languageOptions"
style="max-width: 300px; margin: 20px 0"
/>
<NH4 prefix="bar">{{ $t("pages.Setting.Basic.adbPath.title") }}</NH4>
<NInputGroup style="max-width: 300px; margin-bottom: 20px">
<NInput
v-model:value="adbPath"
v-model:value="curAdbPath"
clearable
:placeholder="$t('pages.Setting.Basic.adbPath.placeholder')"
/>

View File

@ -29,6 +29,7 @@ import { UnlistenFn } from "@tauri-apps/api/event";
import { useGlobalStore } from "../../store/global";
import { useI18n } from "vue-i18n";
import { LocalStore } from "../../store/localStore";
import { NonReactiveStore } from "../../store/noneReactiveStore";
let unlistenResize: UnlistenFn = () => {};
let unlistenMove: UnlistenFn = () => {};
@ -40,13 +41,7 @@ const message = useMessage();
const formRef = ref<FormInst | null>(null);
// logical pos and size of the mask area
interface MaskArea {
posX: number;
posY: number;
sizeW: number;
sizeH: number;
}
const areaModel = ref({
const curMaskArea = ref({
posX: 0,
posY: 0,
sizeW: 0,
@ -80,7 +75,7 @@ const areaFormRules: FormRules = {
},
};
async function refreshAreaModel(size?: PhysicalSize, pos?: PhysicalPosition) {
async function refreshCurMaskArea(size?: PhysicalSize, pos?: PhysicalPosition) {
const lSize = size?.toLogical(factor);
const lPos = pos?.toLogical(factor);
@ -90,12 +85,12 @@ async function refreshAreaModel(size?: PhysicalSize, pos?: PhysicalPosition) {
// use logical position and size
if (lSize !== undefined) {
areaModel.value.sizeW = Math.round(lSize.width) - ml;
areaModel.value.sizeH = Math.round(lSize.height) - mt;
curMaskArea.value.sizeW = Math.round(lSize.width) - ml;
curMaskArea.value.sizeH = Math.round(lSize.height) - mt;
}
if (lPos !== undefined) {
areaModel.value.posX = Math.round(lPos.x) + ml;
areaModel.value.posY = Math.round(lPos.y) + mt;
curMaskArea.value.posX = Math.round(lPos.x) + ml;
curMaskArea.value.posY = Math.round(lPos.y) + mt;
}
}
@ -103,8 +98,9 @@ function handleAdjustClick(e: MouseEvent) {
e.preventDefault();
formRef.value?.validate((errors) => {
if (!errors) {
// save the mask area
adjustMaskArea().then(() => {
LocalStore.set("maskArea", areaModel.value);
NonReactiveStore.setLocal("maskArea", curMaskArea.value);
message.success(t("pages.Setting.Mask.areaSaved"));
});
} else {
@ -113,7 +109,6 @@ function handleAdjustClick(e: MouseEvent) {
});
}
// move and resize window to the selected window (control) area
async function adjustMaskArea() {
// header size and sidebar size
const mt = 30;
@ -122,13 +117,13 @@ async function adjustMaskArea() {
const appWindow = getCurrentWindow();
const pos = new LogicalPosition(
areaModel.value.posX - ml,
areaModel.value.posY - mt
curMaskArea.value.posX - ml,
curMaskArea.value.posY - mt
);
const size = new LogicalSize(
areaModel.value.sizeW + ml,
areaModel.value.sizeH + mt
curMaskArea.value.sizeW + ml,
curMaskArea.value.sizeH + mt
);
await appWindow.setPosition(pos);
@ -139,18 +134,13 @@ onMounted(async () => {
const appWindow = getCurrentWindow();
factor = await appWindow.scaleFactor();
let maskArea = await LocalStore.get<MaskArea>("maskArea");
if (maskArea !== undefined) {
areaModel.value = maskArea;
}
unlistenResize = await appWindow.onResized(({ payload: size }) => {
refreshAreaModel(size, undefined);
refreshCurMaskArea(size, undefined);
});
unlistenMove = await appWindow.onMoved(({ payload: position }) => {
refreshAreaModel(undefined, position);
refreshCurMaskArea(undefined, position);
});
refreshAreaModel(
refreshCurMaskArea(
await appWindow.outerSize(),
await appWindow.outerPosition()
);
@ -170,14 +160,14 @@ onUnmounted(() => {
label-placement="left"
>
<NCheckbox
v-model:checked="store.maskButton.show"
@update:checked="LocalStore.set('maskButton', store.maskButton)"
v-model:checked="store.maskKeyTip.show"
@update:checked="LocalStore.set('maskKeyTip', store.maskKeyTip)"
/>
</NFormItem>
<NFormItem :label="$t('pages.Setting.Mask.opacity')" label-placement="left">
<NSlider
v-model:value="store.maskButton.transparency"
@update:value="LocalStore.set('maskButton', store.maskButton)"
v-model:value="store.maskKeyTip.transparency"
@update:value="LocalStore.set('maskKeyTip', store.maskKeyTip)"
:min="0"
:max="1"
:step="0.01"
@ -187,7 +177,7 @@ onUnmounted(() => {
<NForm
ref="formRef"
:model="areaModel"
:model="curMaskArea"
:rules="areaFormRules"
label-placement="left"
label-width="auto"
@ -210,25 +200,25 @@ onUnmounted(() => {
<NGrid :cols="2" :x-gap="24">
<NFormItemGi label="X" path="posX">
<NInputNumber
v-model:value="areaModel.posX"
v-model:value="curMaskArea.posX"
:placeholder="$t('pages.Setting.Mask.areaPlaceholder.x')"
/>
</NFormItemGi>
<NFormItemGi label="Y" path="posY">
<NInputNumber
v-model:value="areaModel.posY"
v-model:value="curMaskArea.posY"
:placeholder="$t('pages.Setting.Mask.areaFormPlaceholder.y')"
/>
</NFormItemGi>
<NFormItemGi label="W" path="sizeW">
<NInputNumber
v-model:value="areaModel.sizeW"
v-model:value="curMaskArea.sizeW"
:placeholder="$t('pages.Setting.Mask.areaFormPlaceholder.w')"
/>
</NFormItemGi>
<NFormItemGi label="H" path="sizeH">
<NInputNumber
v-model:value="areaModel.sizeH"
v-model:value="curMaskArea.sizeH"
:placeholder="$t('pages.Setting.Mask.areaFormPlaceholder.h')"
/>
</NFormItemGi>

View File

@ -11,7 +11,7 @@ const store = useGlobalStore();
<template>
<div class="setting">
<NSpin :show="store.showLoadingRef">
<NSpin :show="store.showLoadingFlag">
<NTabs type="line" animated placement="left" default-value="basic">
<NTabPane :tab="$t('pages.Setting.tabs.basic')" name="basic">
<NScrollbar>

View File

@ -40,7 +40,6 @@
},
"Mask": {
"keyconfigException": "The key mapping config is abnormal, please delete this config",
"blankConfig": "Blank config",
"checkUpdate": {
"failed": "Check for updates failed",
"isLatest": "Latest version: {0}, currently the latest version: {1}",

View File

@ -1,6 +1,4 @@
import { createI18n } from "vue-i18n";
import { load } from "@tauri-apps/plugin-store";
import { locale } from "@tauri-apps/plugin-os";
import enUS from "./en-US.json";
import zhCN from "./zh-CN.json";
@ -17,24 +15,4 @@ const i18n = createI18n({
),
});
load("store.json").then((localStore) => {
localStore.get<"en-US" | "zh-CN">("language").then((language) => {
if (language === undefined) {
locale().then((lang) => {
if (lang === null) i18n.global.locale = "en-US";
else if (lang in allLanguage) {
i18n.global.locale = lang;
} else {
if (lang.startsWith("zh")) i18n.global.locale = "zh-CN";
else if (lang.startsWith("en")) i18n.global.locale = "en-US";
else i18n.global.locale = "en-US";
}
});
// "en-US"
} else {
i18n.global.locale = language;
}
});
});
export default i18n;

View File

@ -40,7 +40,6 @@
},
"Mask": {
"keyconfigException": "按键方案异常,请删除此方案",
"blankConfig": "空白方案",
"checkUpdate": {
"failed": "检查更新失败",
"isLatest": "最新版本: {0},当前已是最新版本: {1}",

View File

@ -6,14 +6,16 @@ import {
KeySteeringWheel,
} from "../keyMappingConfig";
import { LocalStore } from "./localStore";
import { setAdbPath } from "../invoke";
import i18n, { allLanguage } from "../i18n";
export const useGlobalStore = defineStore("global", () => {
const showLoadingRef = ref(false);
const showLoadingFlag = ref(false);
function showLoading() {
showLoadingRef.value = true;
showLoadingFlag.value = true;
}
function hideLoading() {
showLoadingRef.value = false;
showLoadingFlag.value = false;
}
interface ControledDevice {
@ -58,7 +60,7 @@ export const useGlobalStore = defineStore("global", () => {
}
// change key mapping scheme
function setKeyMappingIndex(index: number) {
function setCurKeyMappingIndex(index: number) {
curKeyMappingIndex.value = index;
resetEditKeyMappingList();
LocalStore.set("curKeyMappingIndex", index);
@ -79,7 +81,7 @@ export const useGlobalStore = defineStore("global", () => {
// persistent storage
const keyMappingConfigList: Ref<KeyMappingConfig[]> = ref([]);
const curKeyMappingIndex = ref(0);
const maskButton = ref({
const maskKeyTip = ref({
transparency: 0.5,
show: true,
});
@ -101,31 +103,52 @@ export const useGlobalStore = defineStore("global", () => {
pasteFromPC: true,
});
const adbPath = ref("adb");
function changeAbdPath(path: string) {
adbPath.value = path;
setAdbPath(path);
LocalStore.set("adbPath", path);
}
const language = ref<keyof typeof allLanguage>("en-US");
function setLanguage(lang: keyof typeof allLanguage) {
if (lang === language.value) return;
language.value = lang;
i18n.global.locale = lang;
LocalStore.set("language", lang);
}
return {
// persistent storage
keyMappingConfigList,
curKeyMappingIndex,
maskButton,
maskKeyTip,
checkUpdateAtStart,
externalControlled,
screenStream,
rotation,
clipboardSync,
adbPath,
language,
// in-memory storage
screenStreamClientId,
screenStreamClientId, // TODO none reactive
maskSizeW,
maskSizeH,
screenSizeW,
screenSizeH,
keyInputFlag,
showLoading,
hideLoading,
showLoadingRef,
keyInputFlag, // TODO none reactive
showLoadingFlag,
controledDevice,
editKeyMappingList,
// action
showLoading,
hideLoading,
applyEditKeyMappingList,
resetEditKeyMappingList,
setKeyMappingIndex,
setCurKeyMappingIndex,
changeAbdPath,
setLanguage,
// TODO move to NonReactive Store
checkUpdate,
checkAdb,
};

View File

@ -1,10 +1,55 @@
import { load, Store } from "@tauri-apps/plugin-store";
import { KeyMappingConfig } from "../keyMappingConfig";
import { useGlobalStore } from "./global";
import { setAdbPath } from "../invoke";
import { allLanguage } from "../i18n";
import { locale } from "@tauri-apps/plugin-os";
import { NonReactiveStore } from "./noneReactiveStore";
export class LocalStore {
public static store: Store;
public static vueStore: ReturnType<typeof useGlobalStore>;
static async init() {
this.store = await load("store.json");
this.store = await load("store.json", { autoSave: true });
this.vueStore = useGlobalStore();
await initAdbPath();
await initMaskArea();
await initKeyMappingConfigList();
await initCurKeyMappingIndex();
await initLanugage();
await this._load("maskKeyTip", {
show: true,
transparency: 0.5,
});
await this._load("checkUpdateAtStart", true);
await this._load("rotation", {
enable: true,
verticalLength: 600,
horizontalLength: 800,
});
await this._load("screenStream", {
enable: false,
address: "",
});
await this._load("clipboardSync", {
syncFromDevice: true,
pasteFromPC: true,
});
await this._load("keySettingPos", { x: 100, y: 100 });
}
static async _load(key: string, defaultValue: any) {
const value = (await this.get(key)) ?? defaultValue;
if (key in this.vueStore.$state) {
this.vueStore.$patch({ [key]: value });
} else if (key in NonReactiveStore.local) {
NonReactiveStore.local[key as keyof typeof NonReactiveStore.local] =
value;
}
}
static async get<T>(key: string): Promise<T | undefined> {
@ -23,7 +68,78 @@ export class LocalStore {
return this.store.clear();
}
static async entries(){
static async entries() {
return this.store.entries();
}
}
// init adbPath
async function initAdbPath() {
const adbPath = (await LocalStore.get<string>("adbPath")) ?? "adb";
await setAdbPath(adbPath);
LocalStore.vueStore.adbPath = adbPath;
}
async function initMaskArea() {
const maskArea = (await LocalStore.get<{
posX: number;
posY: number;
sizeW: number;
sizeH: number;
}>("maskArea")) ?? { posX: 100, posY: 100, sizeW: 800, sizeH: 600 };
// TODO check mask area valid and remove related code in rust
NonReactiveStore.setLocal("maskArea", maskArea);
}
// init keyMappingConfigList from local store
async function initKeyMappingConfigList() {
let keyMappingConfigList = await LocalStore.get<KeyMappingConfig[]>(
"keyMappingConfigList"
);
if (keyMappingConfigList === undefined || keyMappingConfigList.length === 0) {
// add empty key mapping config
const maskArea = NonReactiveStore.local.maskArea;
keyMappingConfigList = [
{
relativeSize: { w: maskArea.sizeW, h: maskArea.sizeH },
title: "Default",
list: [],
},
];
await LocalStore.set("keyMappingConfigList", keyMappingConfigList);
}
LocalStore.vueStore.keyMappingConfigList = keyMappingConfigList;
}
// init curKeyMappingIndex from local store
async function initCurKeyMappingIndex() {
let curKeyMappingIndex = await LocalStore.get<number>("curKeyMappingIndex");
if (
curKeyMappingIndex === undefined ||
curKeyMappingIndex >= LocalStore.vueStore.keyMappingConfigList.length
) {
curKeyMappingIndex = 0;
LocalStore.set("curKeyMappingIndex", curKeyMappingIndex);
}
LocalStore.vueStore.curKeyMappingIndex = curKeyMappingIndex;
}
async function initLanugage() {
let language = await LocalStore.get<keyof typeof allLanguage>("language");
if (language === undefined) {
const lang = await locale();
if (lang === null) language = "en-US";
else if (lang in allLanguage) {
language = lang as keyof typeof allLanguage;
} else {
if (lang.startsWith("zh")) language = "zh-CN";
else if (lang.startsWith("en")) language = "en-US";
else language = "en-US";
}
}
LocalStore.vueStore.setLanguage(language);
}

View File

@ -0,0 +1,31 @@
import { LocalStore } from "./localStore";
interface MemType {}
interface LocalType {
keySettingPos: { x: number; y: number };
maskArea: {
posX: number;
posY: number;
sizeW: number;
sizeH: number;
};
}
export class NonReactiveStore {
static mem: MemType = {};
static local: LocalType = {
keySettingPos: { x: 100, y: 100 },
maskArea: { posX: 0, posY: 0, sizeW: 0, sizeH: 0 },
};
// local setter
static async setLocal<K extends keyof LocalType>(
key: K,
value: LocalType[K]
) {
await LocalStore.set(key, value);
NonReactiveStore.local[key] = value;
}
}

View File

@ -1,120 +0,0 @@
import { KeyMappingConfig } from "./keyMappingConfig";
import { useGlobalStore } from "./store/global";
import { useI18n } from "vue-i18n";
import { LocalStore } from "./store/localStore";
let store: ReturnType<typeof useGlobalStore>;
let t: ReturnType<typeof useI18n>["t"];
async function loadKeyMappingConfigList() {
// loading keyMappingConfigList from local store
let keyMappingConfigList = await LocalStore.get<KeyMappingConfig[]>(
"keyMappingConfigList"
);
if (keyMappingConfigList === undefined || keyMappingConfigList.length === 0) {
// add empty key mapping config
// unable to get mask element when app is not ready
// so we use the stored mask area to get relative size
const maskArea = await LocalStore.get<{
posX: number;
posY: number;
sizeW: number;
sizeH: number;
}>("maskArea");
let relativeSize = { w: 800, h: 600 };
if (maskArea !== undefined) {
relativeSize = {
w: maskArea.sizeW,
h: maskArea.sizeH,
};
}
keyMappingConfigList = [
{
relativeSize,
title: t("pages.Mask.blankConfig"),
list: [],
},
];
await LocalStore.set("keyMappingConfigList", keyMappingConfigList);
}
store.keyMappingConfigList = keyMappingConfigList;
}
async function loadCurKeyMappingIndex() {
// loading curKeyMappingIndex from local store
let curKeyMappingIndex = await LocalStore.get<number>("curKeyMappingIndex");
if (
curKeyMappingIndex === undefined ||
curKeyMappingIndex >= store.keyMappingConfigList.length
) {
curKeyMappingIndex = 0;
LocalStore.set("curKeyMappingIndex", curKeyMappingIndex);
}
store.curKeyMappingIndex = curKeyMappingIndex;
}
async function loadMaskButton() {
// loading maskButton from local store
const maskButton = await LocalStore.get<{
show: boolean;
transparency: number;
}>("maskButton");
store.maskButton = maskButton ?? {
show: true,
transparency: 0.5,
};
}
async function loadCheckUpdateAtStart() {
// loading checkUpdateAtStart from local store
const checkUpdateAtStart = await LocalStore.get<boolean>(
"checkUpdateAtStart"
);
store.checkUpdateAtStart = checkUpdateAtStart ?? true;
}
async function loadRotation() {
// loading rotation from local store
const rotation = await LocalStore.get<{
enable: boolean;
verticalLength: number;
horizontalLength: number;
}>("rotation");
if (rotation) store.rotation = rotation;
}
async function loadScreenStream() {
// loading screenStream from local store
const screenStream = await LocalStore.get<{
enable: boolean;
address: string;
}>("screenStream");
if (screenStream) store.screenStream = screenStream;
}
async function loadClipboardSync() {
// loading clipboardSync from local store
const clipboardSync = await LocalStore.get<{
syncFromDevice: boolean;
pasteFromPC: boolean;
}>("clipboardSync");
if (clipboardSync) store.clipboardSync = clipboardSync;
}
export async function loadPersistentStorage(
theStore: ReturnType<typeof useGlobalStore>,
theT: ReturnType<typeof useI18n>["t"]
) {
await LocalStore.init();
store = theStore;
t = theT;
await loadKeyMappingConfigList();
await loadCurKeyMappingIndex();
await loadMaskButton();
await loadCheckUpdateAtStart();
await loadRotation();
await loadScreenStream();
await loadClipboardSync();
}