Compare commits

..

7 Commits

Author SHA1 Message Date
amrbashir bc53cf11db use ShellExecuteExW 2024-10-30 01:55:03 +03:00
amrbashir 539d41ace7 use dunce 2024-10-30 01:38:01 +03:00
amrbashir 1ec8844b0e lock file 2024-10-30 00:37:30 +03:00
amrbashir b5c55d4ba2 Merge branch 'v2' into feat/shell-show-item-in-dir 2024-10-30 00:37:20 +03:00
阿良仔 4341d7f500 fix(sql): replace Mutex with RwLock to enable concurrent SQL execution (#1972) 2024-10-26 13:19:59 +02:00
Amr Bashir 77149dc432 fix(fs): fix writeFile converting UTF-8 characters in path into replacement character (#1965) 2024-10-22 08:17:37 +03:00
amrbashir 5092683f97 feat(shell): add show_item_in_dir api 2024-02-28 03:25:18 +02:00
13 changed files with 174 additions and 15 deletions
+5
View File
@@ -0,0 +1,5 @@
---
sql: patch
---
Replace `Mutex` with `RwLock` to enable concurrent SQL execution.
+5
View File
@@ -0,0 +1,5 @@
---
"fs-js": "patch"
---
Fix `writeTextFile` converting UTF-8 characters (for example `äöü`) in the given path into replacement character (``)
Generated
+22
View File
@@ -7042,6 +7042,7 @@ dependencies = [
name = "tauri-plugin-shell"
version = "2.0.2"
dependencies = [
"dunce",
"encoding_rs",
"log",
"open",
@@ -7055,6 +7056,7 @@ dependencies = [
"tauri-plugin",
"thiserror",
"tokio",
"windows 0.54.0",
]
[[package]]
@@ -8344,6 +8346,16 @@ dependencies = [
"windows_x86_64_msvc 0.36.1",
]
[[package]]
name = "windows"
version = "0.54.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9252e5725dbed82865af151df558e754e4a3c2c30818359eb17465f1346a1b49"
dependencies = [
"windows-core 0.54.0",
"windows-targets 0.52.6",
]
[[package]]
name = "windows"
version = "0.56.0"
@@ -8373,6 +8385,16 @@ dependencies = [
"windows-targets 0.52.6",
]
[[package]]
name = "windows-core"
version = "0.54.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "12661b9c89351d684a50a8a643ce5f608e20243b9fb84687800163429f161d65"
dependencies = [
"windows-result 0.1.2",
"windows-targets 0.52.6",
]
[[package]]
name = "windows-core"
version = "0.56.0"
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -1072,7 +1072,7 @@ async function writeTextFile(
await invoke('plugin:fs|write_text_file', encoder.encode(data), {
headers: {
path: path instanceof URL ? path.toString() : path,
path: encodeURIComponent(path instanceof URL ? path.toString() : path),
options: JSON.stringify(options)
}
})
+11
View File
@@ -37,6 +37,17 @@ regex = "1"
open = { version = "5", features = ["shellexecute-on-windows"] }
encoding_rs = "0.8"
os_pipe = "1"
dunce = { workspace = true }
[target."cfg(windows)".dependencies.windows]
version = "0.54"
features = [
"Win32_Foundation",
"Win32_UI_Shell_Common",
"Win32_UI_WindowsAndMessaging",
"Win32_System_Com",
"Win32_System_Registry",
]
[target.'cfg(target_os = "ios")'.dependencies]
tauri = { workspace = true, features = ["wry"] }
+9
View File
@@ -30,6 +30,15 @@ pub enum Error {
/// JSON error.
#[error(transparent)]
Json(#[from] serde_json::Error),
/// API not supported on the current platform
#[error("API not supported on the current platform")]
UnsupportedPlatform,
#[error(transparent)]
#[cfg(windows)]
Win32Error(#[from] windows::core::Error),
/// Path doesn't have a parent.
#[error("Path doesn't have a parent: {0}")]
NoParent(PathBuf),
/// Utf8 error.
#[error(transparent)]
Utf8(#[from] std::string::FromUtf8Error),
+4
View File
@@ -85,6 +85,10 @@ impl<R: Runtime> Shell<R> {
.run_mobile_plugin("open", path.into())
.map_err(Into::into)
}
pub fn show_item_in_directory<P: AsRef<Path>>(&self, p: P) -> Result<()> {
open::show_item_in_directory(p)
}
}
pub trait ShellExt<R: Runtime> {
+3
View File
@@ -0,0 +1,3 @@
use std::path::Path;
pub fn show_item_in_directory(file: &Path) -> crate::Result<()> {}
@@ -9,6 +9,22 @@ use serde::{Deserialize, Deserializer};
use crate::scope::OpenScope;
use std::str::FromStr;
#[cfg(windows)]
#[path = "windows.rs"]
mod platform;
#[cfg(target_os = "macos")]
#[path = "macos.rs"]
mod platform;
#[cfg(any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
#[path = "linux.rs"]
mod platform;
/// Program to use on the [`open()`] call.
pub enum Program {
/// Use the `open` program.
@@ -120,3 +136,30 @@ impl Program {
pub fn open<P: AsRef<str>>(scope: &OpenScope, path: P, with: Option<Program>) -> crate::Result<()> {
scope.open(path.as_ref(), with).map_err(Into::into)
}
pub fn show_item_in_directory<P: AsRef<std::path::Path>>(p: P) -> crate::Result<()> {
let p = p.as_ref().canonicalize()?;
let p = dunce::simplified(&p);
#[cfg(any(
windows,
target_os = "macos",
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
return platform::show_item_in_directory(p);
#[cfg(not(any(
windows,
target_os = "macos",
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
)))]
Err(crate::Error::UnsupportedPlatform)
}
+59
View File
@@ -0,0 +1,59 @@
use std::path::Path;
use windows::{
core::{w, HSTRING, PCWSTR},
Win32::{
Foundation::ERROR_FILE_NOT_FOUND,
System::Com::CoInitialize,
UI::{
Shell::{
ILCreateFromPathW, ILFree, SHOpenFolderAndSelectItems, ShellExecuteExW,
SHELLEXECUTEINFOW,
},
WindowsAndMessaging::SW_SHOWNORMAL,
},
},
};
pub fn show_item_in_directory(file: &Path) -> crate::Result<()> {
let _ = unsafe { CoInitialize(None) };
let dir = file
.parent()
.ok_or_else(|| crate::Error::NoParent(file.to_path_buf()))?;
let dir = HSTRING::from(dir);
let dir_item = unsafe { ILCreateFromPathW(PCWSTR::from_raw(dir.as_ptr())) };
let file_h = HSTRING::from(file);
let file_item = unsafe { ILCreateFromPathW(PCWSTR::from_raw(file_h.as_ptr())) };
unsafe {
if let Err(e) = SHOpenFolderAndSelectItems(dir_item, Some(&[file_item]), 0) {
if e.code().0 == ERROR_FILE_NOT_FOUND.0 as i32 {
let is_dir = std::fs::metadata(file).map(|f| f.is_dir()).unwrap_or(false);
let mut info = SHELLEXECUTEINFOW {
cbSize: std::mem::size_of::<SHELLEXECUTEINFOW>() as _,
nShow: SW_SHOWNORMAL.0,
lpVerb: if is_dir {
w!("explore")
} else {
PCWSTR::null()
},
lpClass: if is_dir { w!("folder") } else { PCWSTR::null() },
lpFile: PCWSTR(file_h.as_ptr()),
..std::mem::zeroed()
};
ShellExecuteExW(&mut info)?;
}
}
}
unsafe {
ILFree(Some(dir_item));
ILFree(Some(file_item));
}
Ok(())
}
+7 -9
View File
@@ -23,7 +23,7 @@ pub(crate) async fn load<R: Runtime>(
pool.migrate(&migrator).await?;
}
db_instances.0.lock().await.insert(db.clone(), pool);
db_instances.0.write().await.insert(db.clone(), pool);
Ok(db)
}
@@ -36,7 +36,7 @@ pub(crate) async fn close(
db_instances: State<'_, DbInstances>,
db: Option<String>,
) -> Result<bool, crate::Error> {
let mut instances = db_instances.0.lock().await;
let instances = db_instances.0.read().await;
let pools = if let Some(db) = db {
vec![db]
@@ -45,9 +45,7 @@ pub(crate) async fn close(
};
for pool in pools {
let db = instances
.get_mut(&pool)
.ok_or(Error::DatabaseNotLoaded(pool))?;
let db = instances.get(&pool).ok_or(Error::DatabaseNotLoaded(pool))?;
db.close().await;
}
@@ -62,9 +60,9 @@ pub(crate) async fn execute(
query: String,
values: Vec<JsonValue>,
) -> Result<(u64, LastInsertId), crate::Error> {
let mut instances = db_instances.0.lock().await;
let instances = db_instances.0.read().await;
let db = instances.get_mut(&db).ok_or(Error::DatabaseNotLoaded(db))?;
let db = instances.get(&db).ok_or(Error::DatabaseNotLoaded(db))?;
db.execute(query, values).await
}
@@ -75,8 +73,8 @@ pub(crate) async fn select(
query: String,
values: Vec<JsonValue>,
) -> Result<Vec<IndexMap<String, JsonValue>>, crate::Error> {
let mut instances = db_instances.0.lock().await;
let instances = db_instances.0.read().await;
let db = instances.get_mut(&db).ok_or(Error::DatabaseNotLoaded(db))?;
let db = instances.get(&db).ok_or(Error::DatabaseNotLoaded(db))?;
db.select(query, values).await
}
+4 -4
View File
@@ -29,12 +29,12 @@ use tauri::{
plugin::{Builder as PluginBuilder, TauriPlugin},
Manager, RunEvent, Runtime,
};
use tokio::sync::Mutex;
use tokio::sync::{Mutex, RwLock};
use std::collections::HashMap;
#[derive(Default)]
pub struct DbInstances(pub Mutex<HashMap<String, DbPool>>);
pub struct DbInstances(pub RwLock<HashMap<String, DbPool>>);
#[derive(Serialize)]
#[serde(untagged)]
@@ -140,7 +140,7 @@ impl Builder {
tauri::async_runtime::block_on(async move {
let instances = DbInstances::default();
let mut lock = instances.0.lock().await;
let mut lock = instances.0.write().await;
for db in config.preload {
let pool = DbPool::connect(&db, app).await?;
@@ -168,7 +168,7 @@ impl Builder {
if let RunEvent::Exit = event {
tauri::async_runtime::block_on(async move {
let instances = &*app.state::<DbInstances>();
let instances = instances.0.lock().await;
let instances = instances.0.read().await;
for value in instances.values() {
value.close().await;
}