Skip to content
This repository has been archived by the owner on May 20, 2023. It is now read-only.

Commit

Permalink
feat: config read and write
Browse files Browse the repository at this point in the history
  • Loading branch information
fzdwx committed Mar 14, 2023
1 parent 26719fd commit c2b7e3e
Show file tree
Hide file tree
Showing 10 changed files with 201 additions and 75 deletions.
1 change: 1 addition & 0 deletions src-tauri/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ log = "0.4.17"
tauri-plugin-log = { git = "https://github.com/lencx/tauri-plugins-workspace", branch = "dev", features = [
"colored",
] }
anyhow = "1.0.69"

[features]
# this feature is used for production builds or when `devPath` points to the filesystem
Expand Down
17 changes: 15 additions & 2 deletions src-tauri/src/command.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,21 @@
use crate::clip;
use crate::{clip, setting::Config};

// remember to call `.manage(MyState::default())`
#[tauri::command]
#[allow(dead_code)]
pub async fn get_selection_text() -> Result<String, String> {
clip::read_text()
}

#[tauri::command]
#[allow(dead_code)]
pub async fn write_config(data: String) -> Result<(), String> {
println!("data:{:?}", data);
Config::cover(data);
Ok(())
}

#[tauri::command]
#[allow(dead_code)]
pub async fn read_config() -> Result<Config, String> {
Ok(Config::read())
}
41 changes: 7 additions & 34 deletions src-tauri/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,45 +3,18 @@

mod clip;
mod command;
mod setting;
mod setup;

use std::path::PathBuf;

use tauri_plugin_log::{
fern::colors::{Color, ColoredLevelConfig},
LogTarget,
};

pub fn app_root() -> PathBuf {
tauri::api::path::home_dir()
.unwrap()
.join(".popup-translation")
}

fn log() -> tauri_plugin_log::Builder {
tauri_plugin_log::Builder::default()
.targets([
// LogTarget::LogDir,
// LOG PATH: ~/.popup-translation
LogTarget::Folder(app_root()),
LogTarget::Stdout,
LogTarget::Webview,
])
.level(log::LevelFilter::Debug)
.with_colors(ColoredLevelConfig {
error: Color::Red,
warn: Color::Yellow,
debug: Color::Blue,
info: Color::BrightGreen,
trace: Color::Cyan,
})
}

fn main() {
tauri::Builder::default()
.plugin(log().build())
.plugin(setting::log_builder().build())
.setup(setup::init)
.invoke_handler(tauri::generate_handler![command::get_selection_text])
.invoke_handler(tauri::generate_handler![
command::get_selection_text,
command::write_config,
command::read_config
])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
114 changes: 114 additions & 0 deletions src-tauri/src/setting.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
use std::path::{Path, PathBuf};

use anyhow::Result;

use tauri_plugin_log::{
fern::colors::{Color, ColoredLevelConfig},
LogTarget,
};

// ~/.popup-translation
pub fn app_root() -> PathBuf {
tauri::api::path::home_dir()
.unwrap()
.join(".popup-translation")
}

pub fn exists(path: &Path) -> bool {
Path::new(path).exists()
}

pub fn create_file(path: &Path) -> Result<std::fs::File> {
if let Some(p) = path.parent() {
std::fs::create_dir_all(p)?
}
std::fs::File::create(path).map_err(Into::into)
}

fn config_path() -> PathBuf {
app_root().join("config.json")
}

#[derive(Default, serde::Deserialize, serde::Serialize, Debug)]
pub struct Config {
pub keys: KeyInfo,
}

#[derive(Default, serde::Deserialize, serde::Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct KeyInfo {
pub chat_gpt: String,
pub youdao: String,
pub google: String,
}

impl Config {
pub fn read() -> Self {
if !exists(&config_path()) {
log::info!("config.json not found");
Self::default().write();
}

match std::fs::read_to_string(config_path()) {
Ok(v) => serde_json::from_str(&v).unwrap_or_else(|err| {
log::error!("[read] config parse error: {}", err);
Self::default()
}),
Err(err) => {
log::error!("config.json read error: {}", err);
Self::default()
}
}
}

pub fn write(self) -> Self {
let path = &config_path();
if !exists(path) {
create_file(path).unwrap();
log::info!("confg.json created");
}
if let Ok(v) = serde_json::to_string_pretty(&self) {
std::fs::write(path, v).unwrap_or_else(|err| {
log::error!("config.json write error: {}", err);
Self::default().write();
});
} else {
log::error!("config.json serialize error");
}

self
}

pub fn cover(data: String) -> Self {
log::debug!("config.json cover new config: {}", data);
log::debug!(
"config.json cover old config: {}",
serde_json::to_string_pretty(&Self::read()).unwrap()
);
serde_json::from_str(&data)
.unwrap_or_else(|err| {
log::error!("[cover] config parse error: {}", err);
Self::default()
})
.write()
}
}

pub fn log_builder() -> tauri_plugin_log::Builder {
tauri_plugin_log::Builder::default()
.targets([
// LogTarget::LogDir,
// LOG PATH: ~/.popup-translation/log
LogTarget::Folder(app_root().join("log")),
LogTarget::Stdout,
LogTarget::Webview,
])
.level(log::LevelFilter::Debug)
.with_colors(ColoredLevelConfig {
error: Color::Red,
warn: Color::Yellow,
debug: Color::Blue,
info: Color::BrightGreen,
trace: Color::Cyan,
})
}
23 changes: 15 additions & 8 deletions src/App.vue
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import Set from "./components/Set.vue";
import Model1Nav from "./components/nav/Model1Nav.vue";
import { KeyInfo, Model, Platform } from "./types/type";
import { readKeys } from "./utils/file";
import { readConfig } from "./command/core";
const plat = reactive({
current: Platform.Google,
Expand All @@ -18,7 +18,7 @@ const takes = reactive({
});
const keyList = reactive<KeyInfo>({
chatgpt: {
chatGpt: {
platform: "ChatGPT Key",
key: "",
},
Expand All @@ -42,12 +42,13 @@ const showSetPage = reactive({
// console.log(takes.isTakes);
// });
// read keys
// read config
onBeforeMount(() => {
readKeys().then(({ chatgpt, google, youdao }) => {
keyList.chatgpt = chatgpt;
keyList.google = google;
keyList.youdao = youdao;
readConfig().then((config) => {
const keys = config.keys;
keyList.chatGpt.key = keys.chatGpt;
keyList.google.key = keys.google;
keyList.youdao.key = keys.youdao;
});
});
Expand All @@ -65,7 +66,13 @@ provide("showSetPage", showSetPage);
<div class="header">
<Nav :plat="plat" :takes="takes" :showSetPage="showSetPage">
<template #platform_link>
<button type="button" v-if="model.currentModel === Model.ModelOne" @click="reload">读取选中文本/粘贴板</button>
<button
type="button"
v-if="model.currentModel === Model.ModelOne"
@click="reload"
>
读取选中文本/粘贴板
</button>
<Model1Nav v-else :plat="plat"></Model1Nav>
</template>
</Nav>
Expand Down
21 changes: 19 additions & 2 deletions src/command/core.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { invoke } from "@tauri-apps/api/tauri";
import { appWindow, WebviewWindow } from '@tauri-apps/api/window'
import { Config } from "../types/type";

/**
* 获取光标选择的文本/粘贴板内容
Expand All @@ -9,4 +9,21 @@ async function getSelectionText(): Promise<String> {
return invoke<String>("get_selection_text")
}

export { getSelectionText }
/**
* 写入配置
* @param config string
* @returns
*/
async function writeConfig(config: any): Promise<void> {
return invoke("write_config", { "data": config })
}

/**
* 读取配置
* @returns Config
*/
async function readConfig(): Promise<Config> {
return invoke("read_config")
}

export { getSelectionText, writeConfig, readConfig }
29 changes: 19 additions & 10 deletions src/components/Set.vue
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
<script lang="ts" setup>
import { inject } from "vue";
import { KeyInfo, Model } from "../types/type";
import { KeyInfo, Model, Config } from "../types/type";
import Input from "./common/Input.vue";
import Button from "./common/Button.vue";
import { saveKey2Json } from "../utils/file";
import { writeConfig } from "../command/core";
const props = defineProps<{
keyList: KeyInfo;
model: {
Expand All @@ -17,18 +17,23 @@ const showClick = () => {
};
const save = async () => {
await saveKey2Json(props.keyList);
const config: Config = {
keys: {
chatGpt: props.keyList.chatGpt.key,
youdao: props.keyList.youdao.key,
google: props.keyList.google.key,
},
};
const configJson = JSON.stringify(config);
await writeConfig(configJson);
};
</script>

<template>
<div class="set">
<div class="close-set">
<span>翻译设置:</span>
<span class="close-btn" @click="showClick">
X
</span>
<span class="close-btn" @click="showClick"> X </span>
</div>
<div class="model">
选择模式:
Expand All @@ -37,7 +42,11 @@ const save = async () => {
<option :value="Model.ModelTwo">模式二</option>
</select>
</div>
<Input v-for="item in props.keyList" :platform="item.platform" v-model="item.key"></Input>
<Input
v-for="item in props.keyList"
:platform="item.platform"
v-model="item.key"
></Input>
<div>
<Button :style="{ border: '1px solid #fff' }" @click="save">保存</Button>
</div>
Expand Down Expand Up @@ -78,12 +87,12 @@ const save = async () => {
margin: 8px;
}
.model>select {
.model > select {
width: 100px;
height: 30px;
margin: 8px;
font-size: 16px;
background-color: #1d1d1d;
color: #fff;
}
</style>
</style>
11 changes: 10 additions & 1 deletion src/types/type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ interface KeyItem {
}

interface KeyInfo {
chatgpt: KeyItem;
chatGpt: KeyItem;
google: KeyItem;
youdao: KeyItem;
}
Expand All @@ -39,10 +39,19 @@ interface TranslationInfo {
source: TranslationItem;
}

interface Config {
keys: {
chatGpt: string,
youdao: string,
google: string,
}
}

export { Platform, Model };
export type {
KeyInfo,
TranslationItem,
TranslationInfo,
AggregateTranslationInfo,
Config
};
Loading

0 comments on commit c2b7e3e

Please sign in to comment.