refactor: 升级 tauri 到 2.x

This commit is contained in:
jeasonnow
2024-07-30 10:53:06 +08:00
parent 1d0628ed19
commit 8c07aaae3c
17 changed files with 6475 additions and 1673 deletions

2575
src-tauri/Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -9,17 +9,25 @@ default-run = "app"
edition = "2021"
rust-version = "1.78.0"
[lib]
name = "app_lib"
crate-type = ["staticlib", "cdylib", "lib"]
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[build-dependencies]
tauri-build = { version = "1.5.2", features = [] }
tauri-build = { version = "2.0.0-beta", features = [] }
[dependencies]
serde_json = "1.0.116"
serde = { version = "1.0.200", features = ["derive"] }
tauri = { version = "1.6.3", features = ["api-all", "system-tray"] }
tauri-plugin-window-state = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v1" }
tauri-plugin-oauth = { git = "https://github.com/FabianLars/tauri-plugin-oauth", branch = "main" }
tauri = { version = "2.0.0-beta", features = ["tray-icon"] }
tauri-plugin-window-state = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v2" }
tauri-plugin-oauth = { git = "https://github.com/FabianLars/tauri-plugin-oauth", branch = "v2" }
tauri-plugin-clipboard-manager = "2.1.0-beta.6"
tauri-plugin-http = { version = "2.0.0-beta.12" }
[target."cfg(not(any(target_os = \"android\", target_os = \"ios\")))".dependencies]
tauri-plugin-global-shortcut = { version = "2.0.0-beta.8" }
[dev-dependencies]
cargo-bloat = "0.11.1"

View File

@@ -0,0 +1,17 @@
{
"identifier": "migrated",
"description": "permissions that were migrated from v1",
"local": true,
"windows": [
"pake"
],
"permissions": [
"path:default",
"event:default",
"window:default",
"app:default",
"resources:default",
"menu:default",
"tray:default"
]
}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
{"migrated":{"identifier":"migrated","description":"permissions that were migrated from v1","local":true,"windows":["pake"],"permissions":["path:default","event:default","window:default","app:default","resources:default","menu:default","tray:default"]}}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

BIN
src-tauri/icons/icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 71 KiB

View File

@@ -1,8 +1,11 @@
use crate::util::{check_file_or_append, get_download_message, show_toast, MessageType};
use std::fs::{self, File};
use std::io::Write;
use tauri::api::http::{ClientBuilder, HttpRequestBuilder, ResponseType};
use tauri::{api, command, AppHandle, Manager, Window};
use std::str::FromStr;
use tauri::http::Method;
use tauri_plugin_http::reqwest::{ClientBuilder, Request};
// use tauri::http::{ClientBuilder, HttpRequestBuilder, ResponseType};
use tauri::{command, AppHandle, Manager, Url, WebviewWindow};
#[derive(serde::Deserialize)]
pub struct DownloadFileParams {
@@ -18,24 +21,22 @@ pub struct BinaryDownloadParams {
#[command]
pub async fn download_file(app: AppHandle, params: DownloadFileParams) -> Result<(), String> {
let window: Window = app.get_window("pake").unwrap();
let window: WebviewWindow = app.get_webview_window("pake").unwrap();
show_toast(&window, &get_download_message(MessageType::Start));
let output_path = api::path::download_dir().unwrap().join(params.filename);
let output_path = app.path().download_dir().unwrap().join(params.filename);
let file_path = check_file_or_append(output_path.to_str().unwrap());
let client = ClientBuilder::new().build().unwrap();
let response = client
.send(
HttpRequestBuilder::new("GET", &params.url)
.unwrap()
.response_type(ResponseType::Binary),
.execute(
Request::new(Method::GET, Url::from_str(&params.url).unwrap())
)
.await;
match response {
Ok(res) => {
let bytes = res.bytes().await.unwrap().data;
let bytes = res.bytes().await.unwrap();
let mut file = File::create(file_path).unwrap();
file.write_all(&bytes).unwrap();
@@ -54,9 +55,9 @@ pub async fn download_file_by_binary(
app: AppHandle,
params: BinaryDownloadParams,
) -> Result<(), String> {
let window: Window = app.get_window("pake").unwrap();
let window: WebviewWindow = app.get_webview_window("pake").unwrap();
show_toast(&window, &get_download_message(MessageType::Start));
let output_path = api::path::download_dir().unwrap().join(params.filename);
let output_path = app.path().download_dir().unwrap().join(params.filename);
let file_path = check_file_or_append(output_path.to_str().unwrap());
let download_file_result = fs::write(file_path, &params.binary);
match download_file_result {

View File

@@ -1,31 +1,30 @@
use tauri::{CustomMenuItem, Manager, SystemTray, SystemTrayEvent, SystemTrayMenu};
use tauri::{
menu::{MenuBuilder, MenuItemBuilder}, tray::TrayIconBuilder, AppHandle, Manager
};
use tauri_plugin_window_state::{AppHandleExt, StateFlags};
pub fn get_system_tray() -> SystemTray {
let hide_app = CustomMenuItem::new("hide_app".to_string(), "Hide");
let show_app = CustomMenuItem::new("show_app".to_string(), "Show");
let quit = CustomMenuItem::new("quit".to_string(), "Quit");
let tray_menu = SystemTrayMenu::new()
.add_item(show_app)
.add_item(hide_app)
.add_item(quit);
SystemTray::new().with_menu(tray_menu)
}
pub fn set_system_tray(app: &AppHandle) -> tauri::Result<()> {
let hide_app = MenuItemBuilder::with_id("hide_app", "Hide").build(app)?;
let show_app = MenuItemBuilder::with_id("show_app", "Show").build(app)?;
let quit = MenuItemBuilder::with_id("quit", "Quit").build(app)?;
let menu = MenuBuilder::new(app).items(&[&hide_app, &show_app, &quit]).build()?;
pub fn system_tray_handle(app: &tauri::AppHandle, event: SystemTrayEvent) {
if let SystemTrayEvent::MenuItemClick { tray_id: _, id, .. } = event {
match id.as_str() {
TrayIconBuilder::new()
.menu(&menu)
.on_menu_event(move |app, event| match event.id().as_ref() {
"hide_app" => {
app.get_window("pake").unwrap().minimize().unwrap();
app.get_webview_window("pake").unwrap().minimize().unwrap();
}
"show_app" => {
app.get_window("pake").unwrap().show().unwrap();
app.get_webview_window("pake").unwrap().show().unwrap();
}
"quit" => {
let _res = app.save_window_state(StateFlags::all());
std::process::exit(0);
}
_ => {}
}
};
_ => (),
})
.build(app)?;
Ok(())
}

View File

@@ -1,11 +1,11 @@
use crate::app::config::PakeConfig;
use std::path::PathBuf;
use tauri::{App, Window, WindowBuilder, WindowUrl};
use tauri::{App, WebviewUrl, WebviewWindow, WebviewWindowBuilder};
#[cfg(target_os = "macos")]
use tauri::TitleBarStyle;
pub fn get_window(app: &mut App, config: PakeConfig, _data_dir: PathBuf) -> Window {
pub fn get_window(app: &mut App, config: PakeConfig, _data_dir: PathBuf) -> WebviewWindow {
let window_config = config
.windows
.first()
@@ -14,8 +14,8 @@ pub fn get_window(app: &mut App, config: PakeConfig, _data_dir: PathBuf) -> Wind
let user_agent = config.user_agent.get();
let url = match window_config.url_type.as_str() {
"web" => WindowUrl::App(window_config.url.parse().unwrap()),
"local" => WindowUrl::App(PathBuf::from(&window_config.url)),
"web" => WebviewUrl::App(window_config.url.parse().unwrap()),
"local" => WebviewUrl::App(PathBuf::from(&window_config.url)),
_ => panic!("url type can only be web or local"),
};
@@ -24,14 +24,14 @@ pub fn get_window(app: &mut App, config: PakeConfig, _data_dir: PathBuf) -> Wind
serde_json::to_string(&window_config).unwrap()
);
let mut window_builder = WindowBuilder::new(app, "pake", url)
let mut window_builder = WebviewWindowBuilder::new(app, "pake", url)
.title("")
.user_agent(user_agent)
.visible(false) // Prevent initial shaking
.resizable(window_config.resizable)
.fullscreen(window_config.fullscreen)
.inner_size(window_config.width, window_config.height)
.disable_file_drop_handler()
.disable_drag_drop_handler()
.always_on_top(window_config.always_on_top)
.initialization_script(&config_script)
.initialization_script(include_str!("../inject/component.js"))

90
src-tauri/src/lib.rs Normal file
View File

@@ -0,0 +1,90 @@
#[cfg_attr(mobile, tauri::mobile_entry_point)]
mod app;
mod util;
use std::str::FromStr;
use app::{invoke, menu::set_system_tray, window};
use invoke::{download_file, download_file_by_binary};
use tauri::Manager;
use tauri_plugin_window_state::Builder as windowStatePlugin;
use tauri_plugin_global_shortcut::Shortcut;
use util::{get_data_dir, get_pake_config};
use window::get_window;
pub fn run_app() {
let (pake_config, tauri_config) = get_pake_config();
let mut tauri_app = tauri::Builder::default();
let show_system_tray = pake_config.show_system_tray();
// Save the value of toggle_app_shortcut before pake_config is moved
let activation_shortcut = pake_config.windows[0].activation_shortcut.clone();
tauri_app
.plugin(windowStatePlugin::default().build())
.plugin(tauri_plugin_oauth::init())
.plugin(tauri_plugin_http::init())
.invoke_handler(tauri::generate_handler![
download_file,
download_file_by_binary
])
.setup(move |app| {
let data_dir = get_data_dir(&app.app_handle(), tauri_config);
let _window = get_window(app, pake_config, data_dir);
// Prevent initial shaking
_window.show().unwrap();
if show_system_tray {
let _ = set_system_tray(&app.app_handle());
}
if !activation_shortcut.is_empty() {
let app_handle = app.app_handle().clone();
app_handle
.plugin(
tauri_plugin_global_shortcut::Builder::new()
.with_shortcut(activation_shortcut.as_str())
?.with_handler(move |app, event, _shortcut| {
let shortcut_hotkey = Shortcut::from_str(&activation_shortcut.as_str()).unwrap();
if shortcut_hotkey.eq(event) {
let window = app.get_webview_window("pake").unwrap();
match window.is_visible().unwrap() {
true => window.hide().unwrap(),
false => {
window.show().unwrap();
window.set_focus().unwrap();
}
}
}
}
).build())
.expect("Error registering global evoke shortcuts!");
}
Ok(())
})
.on_window_event(|window, event| {
if let tauri::WindowEvent::CloseRequested { api, .. } = event {
#[cfg(target_os = "macos")]
{
window.minimize().unwrap();
window.hide().unwrap();
}
#[cfg(not(target_os = "macos"))]
event.window().close().unwrap();
api.prevent_close();
}
})
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
pub fn run() {
run_app()
}

View File

@@ -3,84 +3,6 @@
windows_subsystem = "windows"
)]
mod app;
mod util;
use app::{invoke, menu, window};
use invoke::{download_file, download_file_by_binary};
use menu::{get_system_tray, system_tray_handle};
use tauri::{GlobalShortcutManager, Manager};
use tauri_plugin_window_state::Builder as windowStatePlugin;
use util::{get_data_dir, get_pake_config};
use window::get_window;
pub fn run_app() {
let (pake_config, tauri_config) = get_pake_config();
let data_dir = get_data_dir(tauri_config);
let mut tauri_app = tauri::Builder::default();
let show_system_tray = pake_config.show_system_tray();
let system_tray = get_system_tray();
if show_system_tray {
tauri_app = tauri_app
.system_tray(system_tray)
.on_system_tray_event(system_tray_handle);
}
// Save the value of toggle_app_shortcut before pake_config is moved
let activation_shortcut = pake_config.windows[0].activation_shortcut.clone();
tauri_app
.plugin(windowStatePlugin::default().build())
.plugin(tauri_plugin_oauth::init())
.invoke_handler(tauri::generate_handler![
download_file,
download_file_by_binary
])
.setup(move |app| {
let _window = get_window(app, pake_config, data_dir);
// Prevent initial shaking
_window.show().unwrap();
if !activation_shortcut.is_empty() {
let app_handle = app.app_handle().clone();
app_handle
.global_shortcut_manager()
.register(activation_shortcut.as_str(), move || {
let window = app_handle.get_window("pake").unwrap();
match window.is_visible().unwrap() {
true => window.hide().unwrap(),
false => {
window.show().unwrap();
window.set_focus().unwrap();
}
}
})
.expect("Error registering global evoke shortcuts!");
}
Ok(())
})
.on_window_event(|event| {
if let tauri::WindowEvent::CloseRequested { api, .. } = event.event() {
#[cfg(target_os = "macos")]
{
event.window().minimize().unwrap();
event.window().hide().unwrap();
}
#[cfg(not(target_os = "macos"))]
event.window().close().unwrap();
api.prevent_close();
}
})
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
fn main() {
run_app()
app_lib::run()
}

View File

@@ -1,7 +1,8 @@
use crate::app::config::PakeConfig;
use std::env;
use std::path::PathBuf;
use tauri::{api, Config, Window};
use tauri::{App, AppHandle, Config, Manager, WebviewWindow};
pub fn get_pake_config() -> (PakeConfig, Config) {
#[cfg(feature = "cli-build")]
@@ -23,10 +24,10 @@ pub fn get_pake_config() -> (PakeConfig, Config) {
(pake_config, tauri_config)
}
pub fn get_data_dir(_tauri_config: Config) -> PathBuf {
pub fn get_data_dir(app: &AppHandle, _tauri_config: Config, ) -> PathBuf {
{
let package_name = _tauri_config.package.product_name.unwrap();
let data_dir = api::path::config_dir()
let package_name = _tauri_config.product_name.unwrap();
let data_dir = app.path().config_dir()
.expect("Failed to get data dirname")
.join(package_name);
@@ -38,7 +39,7 @@ pub fn get_data_dir(_tauri_config: Config) -> PathBuf {
}
}
pub fn show_toast(window: &Window, message: &str) {
pub fn show_toast(window: &WebviewWindow, message: &str) {
let script = format!(r#"pakeToast("{}");"#, message);
window.eval(&script).unwrap();
}

View File

@@ -1,39 +1,20 @@
{
"package": {
"productName": "WeRead",
"version": "1.0.0"
"build": {
"beforeBuildCommand": "",
"frontendDist": "../dist",
"beforeDevCommand": ""
},
"tauri": {
"plugins": {},
"productName": "WeRead",
"version": "1.0.0",
"app": {
"security": {
"csp": null,
"dangerousRemoteDomainIpcAccess": [
{
"domain": "weread.qq.com",
"windows": ["pake"],
"enableTauriAPI": true
}
]
"csp": null
},
"updater": {
"active": false
},
"systemTray": {
"trayIcon": {
"iconPath": "png/icon_512.png",
"iconAsTemplate": false
},
"allowlist": {
"all": true,
"fs": {
"all": true,
"scope": ["$DOWNLOAD/*"]
}
}
},
"build": {
"withGlobalTauri": true,
"devPath": "../dist",
"distDir": "../dist",
"beforeBuildCommand": "",
"beforeDevCommand": ""
"withGlobalTauri": true
}
}

View File

@@ -1,23 +1,21 @@
{
"tauri": {
"bundle": {
"icon": ["icons/weread.icns"],
"identifier": "com.pake.weread",
"active": true,
"category": "DeveloperTool",
"copyright": "",
"externalBin": [],
"longDescription": "",
"macOS": {
"entitlements": null,
"exceptionDomain": "",
"frameworks": [],
"providerShortName": null,
"signingIdentity": null
},
"resources": [],
"shortDescription": "",
"targets": ["dmg"]
}
"identifier": "com.pake.weread",
"bundle": {
"icon": ["icons/weread.icns"],
"active": true,
"category": "DeveloperTool",
"copyright": "",
"externalBin": [],
"longDescription": "",
"macOS": {
"entitlements": null,
"exceptionDomain": null,
"frameworks": [],
"providerShortName": null,
"signingIdentity": null
},
"resources": [],
"shortDescription": "",
"targets": ["dmg"]
}
}