diff --git a/Cargo.lock b/Cargo.lock index 0b8cc07a..dd3c6ad5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2747,6 +2747,7 @@ dependencies = [ "parking_lot", "ratatui", "regex", + "scopeguard", "serde", "tokio", "tokio-stream", @@ -2793,6 +2794,7 @@ dependencies = [ "libc", "mlua", "ratatui", + "scopeguard", "signal-hook-tokio", "syntect", "tikv-jemallocator", @@ -2874,6 +2876,7 @@ dependencies = [ "libc", "parking_lot", "regex", + "scopeguard", "tokio", "tokio-stream", "tracing", diff --git a/cspell.json b/cspell.json index 3469e3d8..2ee0789c 100644 --- a/cspell.json +++ b/cspell.json @@ -1 +1 @@ -{"version":"0.2","words":["Punct","KEYMAP","splitn","crossterm","YAZI","unar","peekable","ratatui","syntect","pbpaste","pbcopy","ffmpegthumbnailer","oneshot","Posix","Lsar","XADDOS","zoxide","cands","Deque","precache","imageops","IFBLK","IFCHR","IFDIR","IFIFO","IFLNK","IFMT","IFSOCK","IRGRP","IROTH","IRUSR","ISGID","ISUID","ISVTX","IWGRP","IWOTH","IWUSR","IXGRP","IXOTH","IXUSR","libc","winsize","TIOCGWINSZ","xpixel","ypixel","ioerr","appender","Catppuccin","macchiato","gitmodules","Dotfiles","bashprofile","vimrc","flac","webp","exiftool","mediainfo","ripgrep","nvim","indexmap","indexmap","unwatch","canonicalize","serde","fsevent","Ueberzug","iterm","wezterm","sixel","chafa","ueberzugpp","️ Überzug","️ Überzug","Konsole","Alacritty","Überzug","pkgs","paru","unarchiver","pdftoppm","poppler","prebuild","singlefile","jpegopt","EXIF","rustfmt","mktemp","nanos","xclip","xsel","natord","Mintty","nixos","nixpkgs","SIGTSTP","SIGCONT","SIGCONT","mlua","nonstatic","userdata","metatable","natsort","backstack","luajit","Succ","Succ","cand","fileencoding","foldmethod","lightgreen","darkgray","lightred","lightyellow","lightcyan","nushell","msvc","aarch","linemode","sxyazi","rsplit","ZELLIJ","bitflags","bitflags","USERPROFILE","Neovim","vergen","gitcl","Renderable","preloaders","prec","imagesize","Upserting","prio","Ghostty","Catmull","Lanczos","cmds","unyank","scrolloff","headsup","unsub","uzers"],"language":"en","flagWords":[]} \ No newline at end of file +{"language":"en","flagWords":[],"words":["Punct","KEYMAP","splitn","crossterm","YAZI","unar","peekable","ratatui","syntect","pbpaste","pbcopy","ffmpegthumbnailer","oneshot","Posix","Lsar","XADDOS","zoxide","cands","Deque","precache","imageops","IFBLK","IFCHR","IFDIR","IFIFO","IFLNK","IFMT","IFSOCK","IRGRP","IROTH","IRUSR","ISGID","ISUID","ISVTX","IWGRP","IWOTH","IWUSR","IXGRP","IXOTH","IXUSR","libc","winsize","TIOCGWINSZ","xpixel","ypixel","ioerr","appender","Catppuccin","macchiato","gitmodules","Dotfiles","bashprofile","vimrc","flac","webp","exiftool","mediainfo","ripgrep","nvim","indexmap","indexmap","unwatch","canonicalize","serde","fsevent","Ueberzug","iterm","wezterm","sixel","chafa","ueberzugpp","️ Überzug","️ Überzug","Konsole","Alacritty","Überzug","pkgs","paru","unarchiver","pdftoppm","poppler","prebuild","singlefile","jpegopt","EXIF","rustfmt","mktemp","nanos","xclip","xsel","natord","Mintty","nixos","nixpkgs","SIGTSTP","SIGCONT","SIGCONT","mlua","nonstatic","userdata","metatable","natsort","backstack","luajit","Succ","Succ","cand","fileencoding","foldmethod","lightgreen","darkgray","lightred","lightyellow","lightcyan","nushell","msvc","aarch","linemode","sxyazi","rsplit","ZELLIJ","bitflags","bitflags","USERPROFILE","Neovim","vergen","gitcl","Renderable","preloaders","prec","imagesize","Upserting","prio","Ghostty","Catmull","Lanczos","cmds","unyank","scrolloff","headsup","unsub","uzers","scopeguard","SPDLOG"],"version":"0.2"} \ No newline at end of file diff --git a/yazi-adaptor/src/ueberzug.rs b/yazi-adaptor/src/ueberzug.rs index 3bcd905c..1e3a0106 100644 --- a/yazi-adaptor/src/ueberzug.rs +++ b/yazi-adaptor/src/ueberzug.rs @@ -74,6 +74,7 @@ impl Ueberzug { // TODO: demon let result = Command::new("ueberzugpp") .args(["layer", "-so", &adaptor.to_string()]) + .env("SPDLOG_LEVEL", if cfg!(debug_assertions) { "debug" } else { "" }) .kill_on_drop(true) .stdin(Stdio::piped()) .stderr(Stdio::null()) diff --git a/yazi-core/Cargo.toml b/yazi-core/Cargo.toml index 8e43304a..38a344b9 100644 --- a/yazi-core/Cargo.toml +++ b/yazi-core/Cargo.toml @@ -29,6 +29,7 @@ notify = { version = "6.1.1", default-features = false, features = [ "mac parking_lot = "0.12.1" ratatui = "0.26.1" regex = "1.10.4" +scopeguard = "1.2.0" serde = "1.0.197" tokio = { version = "1.37.0", features = [ "full" ] } tokio-stream = "0.1.15" diff --git a/yazi-core/src/manager/commands/bulk_rename.rs b/yazi-core/src/manager/commands/bulk_rename.rs index 79425ca3..e3b65244 100644 --- a/yazi-core/src/manager/commands/bulk_rename.rs +++ b/yazi-core/src/manager/commands/bulk_rename.rs @@ -1,10 +1,11 @@ use std::{borrow::Cow, collections::HashMap, ffi::{OsStr, OsString}, io::{stderr, BufWriter, Write}, path::PathBuf}; use anyhow::{anyhow, Result}; +use scopeguard::defer; use tokio::{fs::{self, OpenOptions}, io::{stdin, AsyncReadExt, AsyncWriteExt}}; use yazi_config::{OPEN, PREVIEW}; use yazi_proxy::{AppProxy, TasksProxy, HIDER, WATCHER}; -use yazi_shared::{fs::{accessible, max_common_root, File, FilesOp, Url}, term::Term, Defer}; +use yazi_shared::{fs::{accessible, max_common_root, File, FilesOp, Url}, term::Term}; use crate::manager::Manager; @@ -31,12 +32,12 @@ impl Manager { .write_all(s.as_encoded_bytes()) .await?; - let _defer1 = Defer::new(|| tokio::spawn(fs::remove_file(tmp.clone()))); + defer! { tokio::spawn(fs::remove_file(tmp.clone())); } TasksProxy::process_exec(vec![OsString::new(), tmp.to_owned().into()], Cow::Borrowed(opener)) .await; let _permit = HIDER.acquire().await.unwrap(); - let _defer2 = Defer::new(AppProxy::resume); + defer!(AppProxy::resume()); AppProxy::stop().await; let new: Vec<_> = fs::read_to_string(&tmp).await?.lines().map(PathBuf::from).collect(); diff --git a/yazi-core/src/tasks/commands/inspect.rs b/yazi-core/src/tasks/commands/inspect.rs index 4910a79b..b17f3cce 100644 --- a/yazi-core/src/tasks/commands/inspect.rs +++ b/yazi-core/src/tasks/commands/inspect.rs @@ -1,9 +1,10 @@ use std::{io::{stderr, BufWriter, LineWriter, Write}, mem}; use crossterm::terminal::{disable_raw_mode, enable_raw_mode}; +use scopeguard::defer; use tokio::{io::{stdin, AsyncReadExt}, select, sync::mpsc, time}; use yazi_proxy::{AppProxy, HIDER}; -use yazi_shared::{event::Cmd, term::Term, Defer}; +use yazi_shared::{event::Cmd, term::Term}; use crate::tasks::Tasks; @@ -26,14 +27,13 @@ impl Tasks { task.logs.clone() }; + defer!(AppProxy::resume()); AppProxy::stop().await; - let _defer = Defer::new(|| { - disable_raw_mode().ok(); - AppProxy::resume(); - }); Term::clear(&mut stderr()).ok(); BufWriter::new(stderr().lock()).write_all(mem::take(&mut buffered).as_bytes()).ok(); + + defer! { disable_raw_mode().ok(); } enable_raw_mode().ok(); let mut stdin = stdin(); diff --git a/yazi-dds/src/body/body.rs b/yazi-dds/src/body/body.rs index c6b9f76e..31fd75bd 100644 --- a/yazi-dds/src/body/body.rs +++ b/yazi-dds/src/body/body.rs @@ -40,7 +40,7 @@ impl<'a> Body<'a> { pub fn from_lua(kind: &str, value: Value) -> Result { Ok(match kind { - "hi" | "hey" | "cd" | "hover" | "rename" | "bulk" | "yank" => { + "hi" | "hey" | "cd" | "hover" | "rename" | "bulk" | "yank" | "move" | "trash" | "delete" => { Err("Cannot construct system event from Lua").into_lua_err()? } _ if !kind.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-') => { diff --git a/yazi-dds/src/body/delete.rs b/yazi-dds/src/body/delete.rs index 5397cacb..47ae9e79 100644 --- a/yazi-dds/src/body/delete.rs +++ b/yazi-dds/src/body/delete.rs @@ -27,10 +27,10 @@ impl<'a> From> for Body<'a> { impl IntoLua<'_> for BodyDelete<'static> { fn into_lua(self, lua: &Lua) -> mlua::Result> { - let t = lua.create_table_with_capacity(self.urls.len(), 0)?; + let urls = lua.create_table_with_capacity(self.urls.len(), 0)?; for (i, url) in self.urls.into_owned().into_iter().enumerate() { - t.raw_set(i + 1, lua.create_any_userdata(url)?)?; + urls.raw_set(i + 1, lua.create_any_userdata(url)?)?; } - t.into_lua(lua) + lua.create_table_from([("urls", urls)])?.into_lua(lua) } } diff --git a/yazi-dds/src/body/move_.rs b/yazi-dds/src/body/move_.rs index a38cc776..26aea7af 100644 --- a/yazi-dds/src/body/move_.rs +++ b/yazi-dds/src/body/move_.rs @@ -30,7 +30,9 @@ impl<'a> From> for Body<'a> { } impl IntoLua<'_> for BodyMove<'static> { - fn into_lua(self, lua: &Lua) -> mlua::Result { self.items.into_owned().into_lua(lua) } + fn into_lua(self, lua: &Lua) -> mlua::Result { + lua.create_table_from([("items", self.items.into_owned())])?.into_lua(lua) + } } // --- Item diff --git a/yazi-dds/src/body/trash.rs b/yazi-dds/src/body/trash.rs index 88a2242b..91e42a5b 100644 --- a/yazi-dds/src/body/trash.rs +++ b/yazi-dds/src/body/trash.rs @@ -27,10 +27,10 @@ impl<'a> From> for Body<'a> { impl IntoLua<'_> for BodyTrash<'static> { fn into_lua(self, lua: &Lua) -> mlua::Result> { - let t = lua.create_table_with_capacity(self.urls.len(), 0)?; + let urls = lua.create_table_with_capacity(self.urls.len(), 0)?; for (i, url) in self.urls.into_owned().into_iter().enumerate() { - t.raw_set(i + 1, lua.create_any_userdata(url)?)?; + urls.raw_set(i + 1, lua.create_any_userdata(url)?)?; } - t.into_lua(lua) + lua.create_table_from([("urls", urls)])?.into_lua(lua) } } diff --git a/yazi-dds/src/lib.rs b/yazi-dds/src/lib.rs index 14f7f4e9..e923dc36 100644 --- a/yazi-dds/src/lib.rs +++ b/yazi-dds/src/lib.rs @@ -32,6 +32,13 @@ pub fn serve() { LOCAL.with(Default::default); REMOTE.with(Default::default); + // Env + std::env::set_var("YAZI_ID", ID.to_string()); + std::env::set_var( + "YAZI_LEVEL", + (std::env::var("YAZI_LEVEL").unwrap_or_default().parse().unwrap_or(0u16) + 1).to_string(), + ); + Pump::serve(); Client::serve(rx); } diff --git a/yazi-fm/Cargo.toml b/yazi-fm/Cargo.toml index 8c9c76e1..16cec860 100644 --- a/yazi-fm/Cargo.toml +++ b/yazi-fm/Cargo.toml @@ -27,6 +27,7 @@ fdlimit = "0.3.0" futures = "0.3.30" mlua = { version = "0.9.6", features = [ "lua54", "vendored" ] } ratatui = "0.26.1" +scopeguard = "1.2.0" syntect = { version = "5.2.0", default-features = false, features = [ "parsing", "plist-load", "regex-onig" ] } tokio = { version = "1.37.0", features = [ "full" ] } tokio-util = "0.7.10" diff --git a/yazi-fm/src/app/commands/plugin.rs b/yazi-fm/src/app/commands/plugin.rs index a71e08e4..ba71f5e0 100644 --- a/yazi-fm/src/app/commands/plugin.rs +++ b/yazi-fm/src/app/commands/plugin.rs @@ -1,9 +1,10 @@ use std::fmt::Display; use mlua::TableExt; +use scopeguard::defer; use tracing::warn; use yazi_plugin::{loader::LOADER, OptData, RtRef, LUA}; -use yazi_shared::{emit, event::Cmd, Defer, Layer}; +use yazi_shared::{emit, event::Cmd, Layer}; use crate::{app::App, lives::Lives}; @@ -45,7 +46,7 @@ impl App { Err(e) => return warn!("{e}"), } - let _defer = Defer::new(|| LUA.named_registry_value::("rt").map(|mut r| r.reset())); + defer! { LUA.named_registry_value::("rt").map(|mut r| r.reset()).ok(); }; let plugin = match LOADER.load(&opt.name) { Ok(plugin) => plugin, Err(e) => return warn!("{e}"), diff --git a/yazi-fm/src/lives/lives.rs b/yazi-fm/src/lives/lives.rs index 03e12cad..ee0ada44 100644 --- a/yazi-fm/src/lives/lives.rs +++ b/yazi-fm/src/lives/lives.rs @@ -1,10 +1,11 @@ use std::{mem, sync::Arc}; use mlua::{Scope, Table}; +use scopeguard::defer; use tracing::error; use yazi_config::LAYOUT; use yazi_plugin::{elements::RectRef, LUA}; -use yazi_shared::{Defer, RoCell}; +use yazi_shared::RoCell; use crate::Ctx; @@ -34,7 +35,7 @@ impl Lives { f: impl FnOnce(&Scope<'a, 'a>) -> mlua::Result, ) -> mlua::Result { let result = LUA.scope(|scope| { - let _defer = Defer::new(|| SCOPE.drop()); + defer! { SCOPE.drop(); }; SCOPE.init(unsafe { mem::transmute(scope) }); LUA.set_named_registry_value("cx", scope.create_any_userdata_ref(cx)?)?; diff --git a/yazi-scheduler/Cargo.toml b/yazi-scheduler/Cargo.toml index 6c407e42..d3e0e704 100644 --- a/yazi-scheduler/Cargo.toml +++ b/yazi-scheduler/Cargo.toml @@ -24,6 +24,7 @@ crossterm = "0.27.0" futures = "0.3.30" parking_lot = "0.12.1" regex = "1.10.4" +scopeguard = "1.2.0" tokio = { version = "1.37.0", features = [ "full" ] } tokio-stream = "0.1.15" diff --git a/yazi-scheduler/src/process/process.rs b/yazi-scheduler/src/process/process.rs index e8a27cb8..13b745b4 100644 --- a/yazi-scheduler/src/process/process.rs +++ b/yazi-scheduler/src/process/process.rs @@ -1,7 +1,7 @@ use anyhow::Result; +use scopeguard::defer; use tokio::{io::{AsyncBufReadExt, BufReader}, select, sync::mpsc}; use yazi_proxy::{AppProxy, HIDER}; -use yazi_shared::Defer; use super::{ProcessOpBg, ProcessOpBlock, ProcessOpOrphan, ShellOpt}; use crate::TaskProg; @@ -15,7 +15,7 @@ impl Process { pub async fn block(&self, task: ProcessOpBlock) -> Result<()> { let _permit = HIDER.acquire().await.unwrap(); - let _defer = Defer::new(AppProxy::resume); + defer!(AppProxy::resume()); AppProxy::stop().await; let (id, cmd) = (task.id, task.cmd.clone()); diff --git a/yazi-scheduler/src/process/shell.rs b/yazi-scheduler/src/process/shell.rs index 2be7f2fc..8f5f8195 100644 --- a/yazi-scheduler/src/process/shell.rs +++ b/yazi-scheduler/src/process/shell.rs @@ -1,4 +1,4 @@ -use std::{env, ffi::OsString, process::Stdio}; +use std::{ffi::OsString, process::Stdio}; use anyhow::Result; use tokio::process::{Child, Command}; @@ -25,12 +25,9 @@ impl ShellOpt { } pub fn shell(opt: ShellOpt) -> Result { - let level = env::var("YAZI_LEVEL").ok().and_then(|s| s.parse::().ok()).unwrap_or(0); - #[cfg(unix)] return Ok(unsafe { Command::new("sh") - .env("YAZI_LEVEL", (level + 1).to_string()) .arg("-c") .stdin(opt.stdio()) .stdout(opt.stdio()) @@ -54,7 +51,6 @@ pub fn shell(opt: ShellOpt) -> Result { let expanded = parser::parse(opt.cmd.to_string_lossy().as_ref(), &args_); Ok( Command::new("cmd") - .env("YAZI_LEVEL", (level + 1).to_string()) .arg("/C") .args(&expanded) .stdin(opt.stdio()) diff --git a/yazi-shared/src/defer.rs b/yazi-shared/src/defer.rs deleted file mode 100644 index ff86a57a..00000000 --- a/yazi-shared/src/defer.rs +++ /dev/null @@ -1,13 +0,0 @@ -pub struct Defer T, T>(Option); - -impl T, T> Defer { - pub fn new(f: F) -> Self { Defer(Some(f)) } -} - -impl T, T> Drop for Defer { - fn drop(&mut self) { - if let Some(f) = self.0.take() { - _ = f(); - } - } -} diff --git a/yazi-shared/src/lib.rs b/yazi-shared/src/lib.rs index f3838584..76494181 100644 --- a/yazi-shared/src/lib.rs +++ b/yazi-shared/src/lib.rs @@ -3,7 +3,6 @@ mod chars; mod condition; mod debounce; -mod defer; mod env; mod errors; pub mod event; @@ -21,7 +20,6 @@ mod xdg; pub use chars::*; pub use condition::*; pub use debounce::*; -pub use defer::*; pub use env::*; pub use errors::*; pub use layer::*;