refactor: use raw identifiers (#2783)

This commit is contained in:
三咲雅 misaki masa 2025-05-21 17:19:05 +08:00 committed by sxyazi
parent c6fcb4f799
commit 622ba09a80
No known key found for this signature in database
68 changed files with 404 additions and 357 deletions

20
Cargo.lock generated
View file

@ -177,9 +177,9 @@ checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26"
[[package]] [[package]]
name = "av1-grain" name = "av1-grain"
version = "0.2.3" version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6678909d8c5d46a42abcf571271e15fdbc0a225e3646cf23762cd415046c78bf" checksum = "4f3efb2ca85bc610acfa917b5aaa36f3fcbebed5b3182d7f877b02531c4b80c8"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"arrayvec", "arrayvec",
@ -1085,7 +1085,7 @@ dependencies = [
"js-sys", "js-sys",
"log", "log",
"wasm-bindgen", "wasm-bindgen",
"windows-core 0.61.1", "windows-core 0.61.2",
] ]
[[package]] [[package]]
@ -3087,14 +3087,14 @@ dependencies = [
[[package]] [[package]]
name = "windows-core" name = "windows-core"
version = "0.61.1" version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "46ec44dc15085cea82cf9c78f85a9114c463a369786585ad2882d1ff0b0acf40" checksum = "c0fdd3ddb90610c7638aa2b3a3ab2904fb9e5cdbecc643ddb3647212781c4ae3"
dependencies = [ dependencies = [
"windows-implement 0.60.0", "windows-implement 0.60.0",
"windows-interface 0.59.1", "windows-interface 0.59.1",
"windows-link", "windows-link",
"windows-result 0.3.3", "windows-result 0.3.4",
"windows-strings", "windows-strings",
] ]
@ -3159,18 +3159,18 @@ dependencies = [
[[package]] [[package]]
name = "windows-result" name = "windows-result"
version = "0.3.3" version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4b895b5356fc36103d0f64dd1e94dfa7ac5633f1c9dd6e80fe9ec4adef69e09d" checksum = "56f42bd332cc6c8eac5af113fc0c1fd6a8fd2aa08a0119358686e5160d0586c6"
dependencies = [ dependencies = [
"windows-link", "windows-link",
] ]
[[package]] [[package]]
name = "windows-strings" name = "windows-strings"
version = "0.4.1" version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2a7ab927b2637c19b3dbe0965e75d8f2d30bdd697a1516191cad2ec4df8fb28a" checksum = "56e6c93f3a0c3b36176cb1327a4958a0353d5d166c2a35cb268ace15e91d3b57"
dependencies = [ dependencies = [
"windows-link", "windows-link",
] ]

View file

@ -7,8 +7,8 @@ use yazi_fs::Xdg;
#[derive(Clone, Default)] #[derive(Clone, Default)]
pub(crate) struct Dependency { pub(crate) struct Dependency {
pub(crate) use_: String, // owner/repo:child pub(crate) r#use: String, // owner/repo:child
pub(crate) name: String, // child.yazi pub(crate) name: String, // child.yazi
pub(crate) parent: String, // owner/repo pub(crate) parent: String, // owner/repo
pub(crate) child: String, // child.yazi pub(crate) child: String, // child.yazi
@ -81,7 +81,7 @@ impl FromStr for Dependency {
} }
Ok(Self { Ok(Self {
use_: s.to_owned(), r#use: s.to_owned(),
name: format!("{name}.yazi"), name: format!("{name}.yazi"),
parent: format!("{parent}{}", if child.is_empty() { ".yazi" } else { "" }), parent: format!("{parent}{}", if child.is_empty() { ".yazi" } else { "" }),
child: if child.is_empty() { String::new() } else { format!("{child}.yazi") }, child: if child.is_empty() { String::new() } else { format!("{child}.yazi") },
@ -97,19 +97,18 @@ impl<'de> Deserialize<'de> for Dependency {
{ {
#[derive(Deserialize)] #[derive(Deserialize)]
struct Shadow { struct Shadow {
#[serde(rename = "use")] r#use: String,
use_: String,
#[serde(default)] #[serde(default)]
rev: String, rev: String,
#[serde(default)] #[serde(default)]
hash: String, hash: String,
} }
let outer = Shadow::deserialize(deserializer)?; let outer = Shadow::deserialize(deserializer)?;
Ok(Self { Ok(Self {
rev: outer.rev, rev: outer.rev,
hash: outer.hash, hash: outer.hash,
..Self::from_str(&outer.use_).map_err(serde::de::Error::custom)? ..Self::from_str(&outer.r#use).map_err(serde::de::Error::custom)?
}) })
} }
} }
@ -121,12 +120,11 @@ impl Serialize for Dependency {
{ {
#[derive(Serialize)] #[derive(Serialize)]
struct Shadow<'a> { struct Shadow<'a> {
#[serde(rename = "use")] r#use: &'a str,
use_: &'a str, rev: &'a str,
rev: &'a str, hash: &'a str,
hash: &'a str,
} }
Shadow { use_: &self.use_, rev: &self.rev, hash: &self.hash }.serialize(serializer) Shadow { r#use: &self.r#use, rev: &self.rev, hash: &self.hash }.serialize(serializer)
} }
} }

View file

@ -61,26 +61,26 @@ impl Package {
outln!("Plugins:")?; outln!("Plugins:")?;
for d in &self.plugins { for d in &self.plugins {
if d.rev.is_empty() { if d.rev.is_empty() {
outln!("\t{}", d.use_)?; outln!("\t{}", d.r#use)?;
} else { } else {
outln!("\t{} ({})", d.use_, d.rev)?; outln!("\t{} ({})", d.r#use, d.rev)?;
} }
} }
outln!("Flavors:")?; outln!("Flavors:")?;
for d in &self.flavors { for d in &self.flavors {
if d.rev.is_empty() { if d.rev.is_empty() {
outln!("\t{}", d.use_)?; outln!("\t{}", d.r#use)?;
} else { } else {
outln!("\t{} ({})", d.use_, d.rev)?; outln!("\t{} ({})", d.r#use, d.rev)?;
} }
} }
Ok(()) Ok(())
} }
async fn add(&mut self, use_: &str) -> Result<()> { async fn add(&mut self, r#use: &str) -> Result<()> {
let mut dep = Dependency::from_str(use_)?; let mut dep = Dependency::from_str(r#use)?;
if let Some(d) = self.identical(&dep) { if let Some(d) = self.identical(&dep) {
bail!( bail!(
"{} `{}` already exists in package.toml", "{} `{}` already exists in package.toml",
@ -98,9 +98,9 @@ impl Package {
Ok(()) Ok(())
} }
async fn delete(&mut self, use_: &str) -> Result<()> { async fn delete(&mut self, r#use: &str) -> Result<()> {
let Some(dep) = self.identical(&Dependency::from_str(use_)?).cloned() else { let Some(dep) = self.identical(&Dependency::from_str(r#use)?).cloned() else {
bail!("`{}` was not found in package.toml", use_) bail!("`{}` was not found in package.toml", r#use)
}; };
dep.delete().await?; dep.delete().await?;

View file

@ -1,6 +1,6 @@
use proc_macro::TokenStream; use proc_macro::TokenStream;
use quote::{format_ident, quote}; use quote::{format_ident, quote};
use syn::{Attribute, Data, DeriveInput, Fields, FnArg, ItemFn, parse_macro_input}; use syn::{Attribute, Data, DeriveInput, Fields, FnArg, ItemFn, ext::IdentExt, parse_macro_input};
#[proc_macro_attribute] #[proc_macro_attribute]
pub fn command(_: TokenStream, item: TokenStream) -> TokenStream { pub fn command(_: TokenStream, item: TokenStream) -> TokenStream {
@ -23,7 +23,7 @@ pub fn command(_: TokenStream, item: TokenStream) -> TokenStream {
// Add `__` prefix to the original function name // Add `__` prefix to the original function name
let name_ori = f.sig.ident; let name_ori = f.sig.ident;
f.sig.ident = format_ident!("__{name_ori}"); f.sig.ident = format_ident!("__{}", name_ori.unraw());
let name_new = &f.sig.ident; let name_new = &f.sig.ident;
// Collect the rest of the arguments // Collect the rest of the arguments

View file

@ -12,12 +12,11 @@ static RE: OnceLock<Regex> = OnceLock::new();
#[derive(Debug, Default, Deserialize)] #[derive(Debug, Default, Deserialize)]
pub struct Chord { pub struct Chord {
#[serde(deserialize_with = "super::deserialize_on")] #[serde(deserialize_with = "super::deserialize_on")]
pub on: Vec<Key>, pub on: Vec<Key>,
#[serde(deserialize_with = "super::deserialize_run")] #[serde(deserialize_with = "super::deserialize_run")]
pub run: Vec<Cmd>, pub run: Vec<Cmd>,
pub desc: Option<String>, pub desc: Option<String>,
#[serde(rename = "for")] pub r#for: Option<String>,
pub for_: Option<String>,
} }
impl PartialEq for Chord { impl PartialEq for Chord {

View file

@ -38,8 +38,8 @@ impl KeymapRules {
self.keymap.into_iter().filter(|v| !a_seen.contains(&on(v))), self.keymap.into_iter().filter(|v| !a_seen.contains(&on(v))),
self.append_keymap.into_iter().filter(|v| !b_seen.contains(&on(v))), self.append_keymap.into_iter().filter(|v| !b_seen.contains(&on(v))),
) )
.map(|mut chord| (chord.for_.take(), chord)) .map(|mut chord| (chord.r#for.take(), chord))
.filter(|(for_, chord)| !chord.noop() && check_for(for_.as_deref())) .filter(|(r#for, chord)| !chord.noop() && check_for(r#for.as_deref()))
.map(|(_, chord)| chord.reshape(layer)) .map(|(_, chord)| chord.reshape(layer))
.collect::<Result<_>>()?; .collect::<Result<_>>()?;

View file

@ -38,7 +38,7 @@ impl Open {
r.mime.as_ref().is_some_and(|p| p.match_mime(&mime)) r.mime.as_ref().is_some_and(|p| p.match_mime(&mime))
|| r.name.as_ref().is_some_and(|p| p.match_path(&path, is_dir)) || r.name.as_ref().is_some_and(|p| p.match_path(&path, is_dir))
}) })
.flat_map(|r| &r.use_) .flat_map(|r| &r.r#use)
.map(String::as_str) .map(String::as_str)
} }

View file

@ -6,11 +6,10 @@ use crate::pattern::Pattern;
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
pub struct OpenRule { pub struct OpenRule {
pub name: Option<Pattern>, pub name: Option<Pattern>,
pub mime: Option<Pattern>, pub mime: Option<Pattern>,
#[serde(rename = "use")]
#[serde(deserialize_with = "OpenRule::deserialize")] #[serde(deserialize_with = "OpenRule::deserialize")]
pub use_: Vec<String>, pub r#use: Vec<String>,
} }
impl OpenRule { impl OpenRule {

View file

@ -44,8 +44,8 @@ impl Opener {
for rules in self.0.values_mut() { for rules in self.0.values_mut() {
*rules = mem::take(rules) *rules = mem::take(rules)
.into_iter() .into_iter()
.map(|mut r| (r.for_.take(), r)) .map(|mut r| (r.r#for.take(), r))
.filter(|(for_, _)| check_for(for_.as_deref())) .filter(|(r#for, _)| check_for(r#for.as_deref()))
.map(|(_, r)| r.reshape()) .map(|(_, r)| r.reshape())
.collect::<Result<IndexSet<_>>>()? .collect::<Result<IndexSet<_>>>()?
.into_iter() .into_iter()

View file

@ -10,8 +10,7 @@ pub struct OpenerRule {
pub orphan: bool, pub orphan: bool,
#[serde(default)] #[serde(default)]
pub desc: String, pub desc: String,
#[serde(rename = "for")] pub r#for: Option<String>,
pub for_: Option<String>,
#[serde(skip)] #[serde(skip)]
pub spread: bool, pub spread: bool,
} }

View file

@ -1,6 +1,6 @@
#[inline] #[inline]
pub(crate) fn check_for(for_: Option<&str>) -> bool { pub(crate) fn check_for(r#for: Option<&str>) -> bool {
match for_.as_ref().map(|s| s.as_ref()) { match r#for.as_ref().map(|s| s.as_ref()) {
Some("unix") if cfg!(unix) => true, Some("unix") if cfg!(unix) => true,
Some(os) if os == std::env::consts::OS => true, Some(os) if os == std::env::consts::OS => true,
Some(_) => false, Some(_) => false,

View file

@ -193,8 +193,7 @@ impl<'de> Deserialize<'de> for CondIcons {
{ {
#[derive(Deserialize)] #[derive(Deserialize)]
struct Shadow { struct Shadow {
#[serde(rename = "if")] r#if: Condition,
if_: Condition,
text: String, text: String,
fg: Option<Color>, fg: Option<Color>,
} }
@ -202,7 +201,7 @@ impl<'de> Deserialize<'de> for CondIcons {
Ok(Self( Ok(Self(
<Vec<Shadow>>::deserialize(deserializer)? <Vec<Shadow>>::deserialize(deserializer)?
.into_iter() .into_iter()
.map(|s| (s.if_, I { text: s.text, style: Style { fg: s.fg, ..Default::default() } })) .map(|s| (s.r#if, I { text: s.text, style: Style { fg: s.fg, ..Default::default() } }))
.collect(), .collect(),
)) ))
} }

View file

@ -38,7 +38,7 @@ impl Help {
render!(); render!();
} }
pub fn type_(&mut self, key: &Key) -> bool { pub fn r#type(&mut self, key: &Key) -> bool {
let Some(input) = &mut self.in_filter else { let Some(input) = &mut self.in_filter else {
return false; return false;
}; };
@ -56,7 +56,7 @@ impl Help {
input.backspace(false); input.backspace(false);
} }
_ => { _ => {
input.type_(key); input.r#type(key);
} }
} }

View file

@ -51,7 +51,7 @@ impl Input {
// TODO: remove this // TODO: remove this
if let Some(cursor) = opt.cfg.cursor { if let Some(cursor) = opt.cfg.cursor {
self.snap_mut().cursor = cursor; self.snap_mut().cursor = cursor;
self.move_(0); self.r#move(0);
} }
render!(); render!();

View file

@ -6,11 +6,11 @@ use yazi_shared::event::CmdCow;
use crate::spot::Spot; use crate::spot::Spot;
struct Opt { struct Opt {
type_: Cow<'static, str>, r#type: Cow<'static, str>,
} }
impl From<CmdCow> for Opt { impl From<CmdCow> for Opt {
fn from(mut c: CmdCow) -> Self { Self { type_: c.take_first_str().unwrap_or_default() } } fn from(mut c: CmdCow) -> Self { Self { r#type: c.take_first_str().unwrap_or_default() } }
} }
impl Spot { impl Spot {
@ -20,7 +20,7 @@ impl Spot {
let Some(table) = lock.table() else { return }; let Some(table) = lock.table() else { return };
let mut s = String::new(); let mut s = String::new();
match opt.type_.as_ref() { match opt.r#type.as_ref() {
"cell" => { "cell" => {
let Some(cell) = table.selected_cell() else { return }; let Some(cell) = table.selected_cell() else { return };
s = cell.to_string(); s = cell.to_string();

View file

@ -6,7 +6,7 @@ use yazi_shared::event::CmdCow;
use crate::tab::Tab; use crate::tab::Tab;
struct Opt { struct Opt {
type_: Cow<'static, str>, r#type: Cow<'static, str>,
separator: Separator, separator: Separator,
hovered: bool, hovered: bool,
} }
@ -14,7 +14,7 @@ struct Opt {
impl From<CmdCow> for Opt { impl From<CmdCow> for Opt {
fn from(mut c: CmdCow) -> Self { fn from(mut c: CmdCow) -> Self {
Self { Self {
type_: c.take_first_str().unwrap_or_default(), r#type: c.take_first_str().unwrap_or_default(),
separator: c.str("separator").unwrap_or_default().into(), separator: c.str("separator").unwrap_or_default().into(),
hovered: c.bool("hovered"), hovered: c.bool("hovered"),
} }
@ -37,7 +37,7 @@ impl Tab {
.peekable(); .peekable();
while let Some(u) = it.next() { while let Some(u) = it.next() {
s.push(match opt.type_.as_ref() { s.push(match opt.r#type.as_ref() {
"path" => opt.separator.transform(u), "path" => opt.separator.transform(u),
"dirname" => opt.separator.transform(u.parent().unwrap_or(Path::new(""))), "dirname" => opt.separator.transform(u.parent().unwrap_or(Path::new(""))),
"filename" => opt.separator.transform(u.name()), "filename" => opt.separator.transform(u.name()),
@ -50,7 +50,7 @@ impl Tab {
} }
// Copy the CWD path regardless even if the directory is empty // Copy the CWD path regardless even if the directory is empty
if s.is_empty() && opt.type_ == "dirname" { if s.is_empty() && opt.r#type == "dirname" {
s.push(self.cwd()); s.push(self.cwd());
} }

View file

@ -76,7 +76,7 @@ impl Tab {
block: opt.block, block: opt.block,
orphan: opt.orphan, orphan: opt.orphan,
desc: Default::default(), desc: Default::default(),
for_: None, r#for: None,
spread: true, spread: true,
}), }),
cwd, cwd,

View file

@ -12,7 +12,7 @@ pub struct Which {
} }
impl Which { impl Which {
pub fn type_(&mut self, key: Key) -> bool { pub fn r#type(&mut self, key: Key) -> bool {
self.cands.retain(|c| c.on.len() > self.times && c.on[self.times] == key); self.cands.retain(|c| c.on.len() > self.times && c.on[self.times] == key);
self.times += 1; self.times += 1;

View file

@ -1,5 +1,5 @@
#![allow(clippy::module_inception)] #![allow(clippy::module_inception)]
yazi_macro::mod_flat!( yazi_macro::mod_flat!(
body bulk bye cd custom delete hey hi hover load mount move_ rename tab trash yank body bulk bye cd custom delete hey hi hover load mount r#move rename tab trash yank
); );

View file

@ -62,11 +62,11 @@ impl Pubsub {
unsub!(REMOTE)(plugin, kind) && Self::pub_from_hi() unsub!(REMOTE)(plugin, kind) && Self::pub_from_hi()
} }
pub fn pub_(body: Body<'static>) { body.with_receiver(*ID).emit(); } pub fn r#pub(body: Body<'static>) { body.with_receiver(*ID).emit(); }
pub fn pub_to(receiver: Id, body: Body<'static>) { pub fn pub_to(receiver: Id, body: Body<'static>) {
if receiver == *ID { if receiver == *ID {
return Self::pub_(body); return Self::r#pub(body);
} }
let kind = body.kind(); let kind = body.kind();
@ -87,7 +87,7 @@ impl Pubsub {
pub fn pub_from_tab(idx: Id) { pub fn pub_from_tab(idx: Id) {
if LOCAL.read().contains_key("tab") { if LOCAL.read().contains_key("tab") {
Self::pub_(BodyTab::owned(idx)); Self::r#pub(BodyTab::owned(idx));
} }
if PEERS.read().values().any(|p| p.able("tab")) { if PEERS.read().values().any(|p| p.able("tab")) {
Client::push(BodyTab::owned(idx)); Client::push(BodyTab::owned(idx));
@ -99,7 +99,7 @@ impl Pubsub {
pub fn pub_from_cd(tab: Id, url: &Url) { pub fn pub_from_cd(tab: Id, url: &Url) {
if LOCAL.read().contains_key("cd") { if LOCAL.read().contains_key("cd") {
Self::pub_(BodyCd::dummy(tab)); Self::r#pub(BodyCd::dummy(tab));
} }
if PEERS.read().values().any(|p| p.able("cd")) { if PEERS.read().values().any(|p| p.able("cd")) {
Client::push(BodyCd::borrowed(tab, url)); Client::push(BodyCd::borrowed(tab, url));
@ -111,7 +111,7 @@ impl Pubsub {
pub fn pub_from_load(tab: Id, url: &Url, stage: FolderStage) { pub fn pub_from_load(tab: Id, url: &Url, stage: FolderStage) {
if LOCAL.read().contains_key("load") { if LOCAL.read().contains_key("load") {
Self::pub_(BodyLoad::dummy(tab, url, stage)); Self::r#pub(BodyLoad::dummy(tab, url, stage));
} }
if PEERS.read().values().any(|p| p.able("load")) { if PEERS.read().values().any(|p| p.able("load")) {
Client::push(BodyLoad::borrowed(tab, url, stage)); Client::push(BodyLoad::borrowed(tab, url, stage));
@ -123,7 +123,7 @@ impl Pubsub {
pub fn pub_from_hover(tab: Id, url: Option<&Url>) { pub fn pub_from_hover(tab: Id, url: Option<&Url>) {
if LOCAL.read().contains_key("hover") { if LOCAL.read().contains_key("hover") {
Self::pub_(BodyHover::dummy(tab)); Self::r#pub(BodyHover::dummy(tab));
} }
if PEERS.read().values().any(|p| p.able("hover")) { if PEERS.read().values().any(|p| p.able("hover")) {
Client::push(BodyHover::borrowed(tab, url)); Client::push(BodyHover::borrowed(tab, url));
@ -135,7 +135,7 @@ impl Pubsub {
pub fn pub_from_rename(tab: Id, from: &Url, to: &Url) { pub fn pub_from_rename(tab: Id, from: &Url, to: &Url) {
if LOCAL.read().contains_key("rename") { if LOCAL.read().contains_key("rename") {
Self::pub_(BodyRename::dummy(tab, from, to)); Self::r#pub(BodyRename::dummy(tab, from, to));
} }
if PEERS.read().values().any(|p| p.able("rename")) { if PEERS.read().values().any(|p| p.able("rename")) {
Client::push(BodyRename::borrowed(tab, from, to)); Client::push(BodyRename::borrowed(tab, from, to));
@ -147,7 +147,7 @@ impl Pubsub {
pub fn pub_from_bulk(changes: HashMap<&Url, &Url>) { pub fn pub_from_bulk(changes: HashMap<&Url, &Url>) {
if LOCAL.read().contains_key("bulk") { if LOCAL.read().contains_key("bulk") {
Self::pub_(BodyBulk::owned(&changes)); Self::r#pub(BodyBulk::owned(&changes));
} }
if PEERS.read().values().any(|p| p.able("bulk")) { if PEERS.read().values().any(|p| p.able("bulk")) {
Client::push(BodyBulk::borrowed(&changes)); Client::push(BodyBulk::borrowed(&changes));
@ -159,7 +159,7 @@ impl Pubsub {
pub fn pub_from_yank(cut: bool, urls: &HashSet<Url>) { pub fn pub_from_yank(cut: bool, urls: &HashSet<Url>) {
if LOCAL.read().contains_key("@yank") { if LOCAL.read().contains_key("@yank") {
Self::pub_(BodyYank::dummy()); Self::r#pub(BodyYank::dummy());
} }
if Self::any_remote_own("@yank") { if Self::any_remote_own("@yank") {
Client::push(BodyYank::borrowed(cut, urls)); Client::push(BodyYank::borrowed(cut, urls));
@ -177,7 +177,7 @@ impl Pubsub {
BodyMove::borrowed(&items).with_receiver(*ID).flush(); BodyMove::borrowed(&items).with_receiver(*ID).flush();
} }
if LOCAL.read().contains_key("move") { if LOCAL.read().contains_key("move") {
Self::pub_(BodyMove::owned(items)); Self::r#pub(BodyMove::owned(items));
} }
} }
@ -189,7 +189,7 @@ impl Pubsub {
BodyTrash::borrowed(&urls).with_receiver(*ID).flush(); BodyTrash::borrowed(&urls).with_receiver(*ID).flush();
} }
if LOCAL.read().contains_key("trash") { if LOCAL.read().contains_key("trash") {
Self::pub_(BodyTrash::owned(urls)); Self::r#pub(BodyTrash::owned(urls));
} }
} }
@ -201,13 +201,13 @@ impl Pubsub {
BodyDelete::borrowed(&urls).with_receiver(*ID).flush(); BodyDelete::borrowed(&urls).with_receiver(*ID).flush();
} }
if LOCAL.read().contains_key("delete") { if LOCAL.read().contains_key("delete") {
Self::pub_(BodyDelete::owned(urls)); Self::r#pub(BodyDelete::owned(urls));
} }
} }
pub fn pub_from_mount() { pub fn pub_from_mount() {
if LOCAL.read().contains_key("mount") { if LOCAL.read().contains_key("mount") {
Self::pub_(BodyMount::owned()); Self::r#pub(BodyMount::owned());
} }
if PEERS.read().values().any(|p| p.able("mount")) { if PEERS.read().values().any(|p| p.able("mount")) {
Client::push(BodyMount::owned()); Client::push(BodyMount::owned());

View file

@ -16,14 +16,14 @@ unsafe extern "C" {
pub fn DARegisterDiskAppearedCallback( pub fn DARegisterDiskAppearedCallback(
session: *const c_void, session: *const c_void,
match_: CFDictionaryRef, r#match: CFDictionaryRef,
callback: extern "C" fn(disk: *const c_void, context: *mut c_void), callback: extern "C" fn(disk: *const c_void, context: *mut c_void),
context: *mut c_void, context: *mut c_void,
); );
pub fn DARegisterDiskDescriptionChangedCallback( pub fn DARegisterDiskDescriptionChangedCallback(
session: *const c_void, session: *const c_void,
match_: CFDictionaryRef, r#match: CFDictionaryRef,
watch: CFArrayRef, watch: CFArrayRef,
callback: extern "C" fn(disk: *const c_void, keys: CFArrayRef, context: *mut c_void), callback: extern "C" fn(disk: *const c_void, keys: CFArrayRef, context: *mut c_void),
context: *mut c_void, context: *mut c_void,
@ -31,7 +31,7 @@ unsafe extern "C" {
pub fn DARegisterDiskDisappearedCallback( pub fn DARegisterDiskDisappearedCallback(
session: *const c_void, session: *const c_void,
match_: CFDictionaryRef, r#match: CFDictionaryRef,
callback: extern "C" fn(disk: *const c_void, context: *mut c_void), callback: extern "C" fn(disk: *const c_void, context: *mut c_void),
context: *mut c_void, context: *mut c_void,
); );

View file

@ -17,10 +17,10 @@ impl<'a> Router<'a> {
let cx = &mut self.app.cx; let cx = &mut self.app.cx;
let layer = cx.layer(); let layer = cx.layer();
if cx.help.visible && cx.help.type_(&key) { if cx.help.visible && cx.help.r#type(&key) {
return true; return true;
} }
if cx.input.visible && cx.input.type_(&key) { if cx.input.visible && cx.input.r#type(&key) {
return true; return true;
} }
@ -31,7 +31,7 @@ impl<'a> Router<'a> {
self.matches(layer, key) self.matches(layer, key)
} }
L::Cmp => self.matches(L::Cmp, key) || self.matches(L::Input, key), L::Cmp => self.matches(L::Cmp, key) || self.matches(L::Input, key),
L::Which => cx.which.type_(key), L::Which => cx.which.r#type(key),
} }
} }

View file

@ -17,7 +17,7 @@ pub struct Border {
pub(crate) area: Area, pub(crate) area: Area,
pub(crate) position: ratatui::widgets::Borders, pub(crate) position: ratatui::widgets::Borders,
pub(crate) type_: ratatui::widgets::BorderType, pub(crate) r#type: ratatui::widgets::BorderType,
pub(crate) style: ratatui::style::Style, pub(crate) style: ratatui::style::Style,
pub(crate) titles: Vec<(ratatui::widgets::block::Position, ratatui::text::Line<'static>)>, pub(crate) titles: Vec<(ratatui::widgets::block::Position, ratatui::text::Line<'static>)>,
@ -60,7 +60,7 @@ impl Border {
) { ) {
let mut block = ratatui::widgets::Block::default() let mut block = ratatui::widgets::Block::default()
.borders(self.position) .borders(self.position)
.border_type(self.type_) .border_type(self.r#type)
.border_style(self.style); .border_style(self.style);
for title in self.titles { for title in self.titles {
@ -80,7 +80,7 @@ impl UserData for Border {
crate::impl_style_method!(methods, style); crate::impl_style_method!(methods, style);
methods.add_function_mut("type", |_, (ud, value): (AnyUserData, u8)| { methods.add_function_mut("type", |_, (ud, value): (AnyUserData, u8)| {
ud.borrow_mut::<Self>()?.type_ = match value { ud.borrow_mut::<Self>()?.r#type = match value {
ROUNDED => ratatui::widgets::BorderType::Rounded, ROUNDED => ratatui::widgets::BorderType::Rounded,
DOUBLE => ratatui::widgets::BorderType::Double, DOUBLE => ratatui::widgets::BorderType::Double,
THICK => ratatui::widgets::BorderType::Thick, THICK => ratatui::widgets::BorderType::Thick,

View file

@ -67,8 +67,8 @@ fn write(lua: &Lua) -> mlua::Result<Function> {
} }
fn create(lua: &Lua) -> mlua::Result<Function> { fn create(lua: &Lua) -> mlua::Result<Function> {
lua.create_async_function(|lua, (type_, url): (mlua::String, UrlRef)| async move { lua.create_async_function(|lua, (r#type, url): (mlua::String, UrlRef)| async move {
let result = match type_.as_bytes().as_ref() { let result = match r#type.as_bytes().as_ref() {
b"dir" => fs::create_dir(&*url).await, b"dir" => fs::create_dir(&*url).await,
b"dir_all" => fs::create_dir_all(&*url).await, b"dir_all" => fs::create_dir_all(&*url).await,
_ => Err("Creation type must be 'dir' or 'dir_all'".into_lua_err())?, _ => Err("Creation type must be 'dir' or 'dir_all'".into_lua_err())?,
@ -82,8 +82,8 @@ fn create(lua: &Lua) -> mlua::Result<Function> {
} }
fn remove(lua: &Lua) -> mlua::Result<Function> { fn remove(lua: &Lua) -> mlua::Result<Function> {
lua.create_async_function(|lua, (type_, url): (mlua::String, UrlRef)| async move { lua.create_async_function(|lua, (r#type, url): (mlua::String, UrlRef)| async move {
let result = match type_.as_bytes().as_ref() { let result = match r#type.as_bytes().as_ref() {
b"file" => fs::remove_file(&*url).await, b"file" => fs::remove_file(&*url).await,
b"dir" => fs::remove_dir(&*url).await, b"dir" => fs::remove_dir(&*url).await,
b"dir_all" => fs::remove_dir_all(&*url).await, b"dir_all" => fs::remove_dir_all(&*url).await,

View file

@ -40,7 +40,7 @@ impl Require {
) )
} }
fn create_mt(lua: &Lua, id: &str, mod_: Table, sync: bool) -> mlua::Result<Table> { fn create_mt(lua: &Lua, id: &str, r#mod: Table, sync: bool) -> mlua::Result<Table> {
let id: Arc<str> = Arc::from(id); let id: Arc<str> = Arc::from(id);
let mt = lua.create_table_from([ let mt = lua.create_table_from([
( (
@ -62,7 +62,7 @@ impl Require {
), ),
])?; ])?;
let ts = lua.create_table_from([("__mod", mod_)])?; let ts = lua.create_table_from([("__mod", r#mod)])?;
ts.set_metatable(Some(mt)); ts.set_metatable(Some(mt));
Ok(ts) Ok(ts)
} }
@ -72,9 +72,9 @@ impl Require {
if sync { if sync {
lua.create_function(move |lua, args: MultiValue| { lua.create_function(move |lua, args: MultiValue| {
let (mod_, args) = Self::split_mod_and_args(lua, &id, args)?; let (r#mod, args) = Self::split_mod_and_args(lua, &id, args)?;
lua.named_registry_value::<RtRefMut>("ir")?.push(&id); lua.named_registry_value::<RtRefMut>("ir")?.push(&id);
let result = mod_.call_function::<MultiValue>(&f, args); let result = r#mod.call_function::<MultiValue>(&f, args);
lua.named_registry_value::<RtRefMut>("ir")?.pop(); lua.named_registry_value::<RtRefMut>("ir")?.pop();
result result
}) })
@ -82,9 +82,9 @@ impl Require {
lua.create_async_function(move |lua, args: MultiValue| { lua.create_async_function(move |lua, args: MultiValue| {
let (id, f) = (id.clone(), f.clone()); let (id, f) = (id.clone(), f.clone());
async move { async move {
let (mod_, args) = Self::split_mod_and_args(&lua, &id, args)?; let (r#mod, args) = Self::split_mod_and_args(&lua, &id, args)?;
lua.named_registry_value::<RtRefMut>("ir")?.push(&id); lua.named_registry_value::<RtRefMut>("ir")?.push(&id);
let result = mod_.call_async_function::<MultiValue>(&f, args).await; let result = r#mod.call_async_function::<MultiValue>(&f, args).await;
lua.named_registry_value::<RtRefMut>("ir")?.pop(); lua.named_registry_value::<RtRefMut>("ir")?.pop();
result result
} }
@ -104,9 +104,9 @@ impl Require {
args.push_front(front); args.push_front(front);
return Ok((LOADER.try_load(lua, id)?, args)); return Ok((LOADER.try_load(lua, id)?, args));
}; };
Ok(if let Ok(mod_) = tbl.raw_get::<Table>("__mod") { Ok(if let Ok(r#mod) = tbl.raw_get::<Table>("__mod") {
args.push_front(Value::Table(mod_.clone())); args.push_front(Value::Table(r#mod.clone()));
(mod_, args) (r#mod, args)
} else { } else {
args.push_front(Value::Table(tbl)); args.push_front(Value::Table(tbl));
(LOADER.try_load(lua, id)?, args) (LOADER.try_load(lua, id)?, args)

View file

@ -9,7 +9,7 @@ yazi_macro::mod_flat!(pubsub);
pub(super) fn compose(lua: &Lua) -> mlua::Result<Value> { pub(super) fn compose(lua: &Lua) -> mlua::Result<Value> {
Composer::make(lua, 10, |lua, key| { Composer::make(lua, 10, |lua, key| {
match key { match key {
b"pub" => Pubsub::pub_(lua)?, b"pub" => Pubsub::r#pub(lua)?,
b"pub_to" => Pubsub::pub_to(lua)?, b"pub_to" => Pubsub::pub_to(lua)?,
b"sub" => Pubsub::sub(lua)?, b"sub" => Pubsub::sub(lua)?,
b"sub_remote" => Pubsub::sub_remote(lua)?, b"sub_remote" => Pubsub::sub_remote(lua)?,

View file

@ -7,9 +7,9 @@ use crate::runtime::RtRef;
pub struct Pubsub; pub struct Pubsub;
impl Pubsub { impl Pubsub {
pub(super) fn pub_(lua: &Lua) -> mlua::Result<Function> { pub(super) fn r#pub(lua: &Lua) -> mlua::Result<Function> {
lua.create_function(|_, (kind, value): (mlua::String, Value)| { lua.create_function(|_, (kind, value): (mlua::String, Value)| {
yazi_dds::Pubsub::pub_(Body::from_lua(&kind.to_str()?, value)?); yazi_dds::Pubsub::r#pub(Body::from_lua(&kind.to_str()?, value)?);
Ok(()) Ok(())
}) })
} }

View file

@ -7,8 +7,8 @@ use crate::bindings::{Permit, PermitRef};
impl Utils { impl Utils {
pub(super) fn id(lua: &Lua) -> mlua::Result<Function> { pub(super) fn id(lua: &Lua) -> mlua::Result<Function> {
lua.create_function(|_, type_: mlua::String| { lua.create_function(|_, r#type: mlua::String| {
Ok(Id(match type_.as_bytes().as_ref() { Ok(Id(match r#type.as_bytes().as_ref() {
b"app" => *yazi_dds::ID, b"app" => *yazi_dds::ID,
b"ft" => yazi_fs::FILES_TICKET.next(), b"ft" => yazi_fs::FILES_TICKET.next(),
_ => Err("Invalid id type".into_lua_err())?, _ => Err("Invalid id type".into_lua_err())?,

View file

@ -20,10 +20,10 @@ impl Utils {
for (i, cand) in t.raw_get::<Table>("cands")?.sequence_values::<Table>().enumerate() { for (i, cand) in t.raw_get::<Table>("cands")?.sequence_values::<Table>().enumerate() {
let cand = cand?; let cand = cand?;
cands.push(Chord { cands.push(Chord {
on: Self::parse_keys(cand.raw_get("on")?)?, on: Self::parse_keys(cand.raw_get("on")?)?,
run: vec![Cmd::args("which:callback", &[i]).with_any("tx", tx.clone())], run: vec![Cmd::args("which:callback", &[i]).with_any("tx", tx.clone())],
desc: cand.raw_get("desc").ok(), desc: cand.raw_get("desc").ok(),
for_: None, r#for: None,
}); });
} }

View file

@ -74,7 +74,7 @@ impl Utils {
Renderable::Border(crate::elements::Border { Renderable::Border(crate::elements::Border {
area, area,
position: ratatui::widgets::Borders::ALL, position: ratatui::widgets::Borders::ALL,
type_: ratatui::widgets::BorderType::Rounded, r#type: ratatui::widgets::BorderType::Rounded,
style: THEME.spot.border.into(), style: THEME.spot.border.into(),
titles: vec![( titles: vec![(
ratatui::widgets::block::Position::Top, ratatui::widgets::block::Position::Top,

View file

@ -40,8 +40,8 @@ impl Utils {
} }
pub(super) fn chan(lua: &Lua) -> mlua::Result<Function> { pub(super) fn chan(lua: &Lua) -> mlua::Result<Function> {
lua.create_function(|lua, (type_, buffer): (mlua::String, Option<usize>)| { lua.create_function(|lua, (r#type, buffer): (mlua::String, Option<usize>)| {
match (&*type_.as_bytes(), buffer) { match (&*r#type.as_bytes(), buffer) {
(b"mpsc", Some(buffer)) if buffer < 1 => { (b"mpsc", Some(buffer)) if buffer < 1 => {
Err("Buffer size must be greater than 0".into_lua_err()) Err("Buffer size must be greater than 0".into_lua_err())
} }
@ -82,9 +82,9 @@ impl Utils {
let (tx, rx) = oneshot::channel::<Vec<Data>>(); let (tx, rx) = oneshot::channel::<Vec<Data>>();
let callback: PluginCallback = { let callback: PluginCallback = {
let id_ = id.clone(); let id = id.clone();
Box::new(move |lua, plugin| { Box::new(move |lua, plugin| {
let Some(block) = lua.named_registry_value::<RtRef>("ir")?.get_block(&id_, calls) else { let Some(block) = lua.named_registry_value::<RtRef>("ir")?.get_block(&id, calls) else {
return Err("sync block not found".into_lua_err()); return Err("sync block not found".into_lua_err());
}; };

View file

@ -7,25 +7,25 @@ use yazi_config::YAZI;
use yazi_fs::{SizeCalculator, cha::Cha, copy_with_progress, maybe_exists, ok_or_not_found, path_relative_to, skip_path}; use yazi_fs::{SizeCalculator, cha::Cha, copy_with_progress, maybe_exists, ok_or_not_found, path_relative_to, skip_path};
use yazi_shared::url::Url; use yazi_shared::url::Url;
use super::{FileOp, FileOpDelete, FileOpHardlink, FileOpLink, FileOpPaste, FileOpTrash}; use super::{FileIn, FileInDelete, FileInHardlink, FileInLink, FileInPaste, FileInTrash};
use crate::{LOW, NORMAL, TaskOp, TaskProg}; use crate::{LOW, NORMAL, TaskOp, TaskProg};
pub struct File { pub struct File {
macro_: async_priority_channel::Sender<TaskOp, u8>, r#macro: async_priority_channel::Sender<TaskOp, u8>,
prog: mpsc::UnboundedSender<TaskProg>, prog: mpsc::UnboundedSender<TaskProg>,
} }
impl File { impl File {
pub fn new( pub fn new(
macro_: async_priority_channel::Sender<TaskOp, u8>, r#macro: async_priority_channel::Sender<TaskOp, u8>,
prog: mpsc::UnboundedSender<TaskProg>, prog: mpsc::UnboundedSender<TaskProg>,
) -> Self { ) -> Self {
Self { macro_, prog } Self { r#macro, prog }
} }
pub async fn work(&self, op: FileOp) -> Result<()> { pub async fn work(&self, r#in: FileIn) -> Result<()> {
match op { match r#in {
FileOp::Paste(mut task) => { FileIn::Paste(mut task) => {
ok_or_not_found(fs::remove_file(&task.to).await)?; ok_or_not_found(fs::remove_file(&task.to).await)?;
let mut it = copy_with_progress(&task.from, &task.to, task.cha.unwrap()); let mut it = copy_with_progress(&task.from, &task.to, task.cha.unwrap());
@ -50,7 +50,7 @@ impl File {
{ {
task.retry += 1; task.retry += 1;
self.log(task.id, format!("Paste task retry: {task:?}"))?; self.log(task.id, format!("Paste task retry: {task:?}"))?;
self.queue(FileOp::Paste(task), LOW).await?; self.queue(FileIn::Paste(task), LOW).await?;
return Ok(()); return Ok(());
} }
Err(e) => Err(e)?, Err(e) => Err(e)?,
@ -58,7 +58,7 @@ impl File {
} }
self.prog.send(TaskProg::Adv(task.id, 1, 0))?; self.prog.send(TaskProg::Adv(task.id, 1, 0))?;
} }
FileOp::Link(task) => { FileIn::Link(task) => {
let cha = task.cha.unwrap(); let cha = task.cha.unwrap();
let src = if task.resolve { let src = if task.resolve {
@ -99,7 +99,7 @@ impl File {
} }
self.prog.send(TaskProg::Adv(task.id, 1, cha.len))?; self.prog.send(TaskProg::Adv(task.id, 1, cha.len))?;
} }
FileOp::Hardlink(task) => { FileIn::Hardlink(task) => {
let cha = task.cha.unwrap(); let cha = task.cha.unwrap();
let src = if !task.follow { let src = if !task.follow {
Cow::Borrowed(task.from.as_path()) Cow::Borrowed(task.from.as_path())
@ -119,7 +119,7 @@ impl File {
self.prog.send(TaskProg::Adv(task.id, 1, cha.len))?; self.prog.send(TaskProg::Adv(task.id, 1, cha.len))?;
} }
FileOp::Delete(task) => { FileIn::Delete(task) => {
if let Err(e) = fs::remove_file(&task.target).await { if let Err(e) = fs::remove_file(&task.target).await {
if e.kind() != NotFound && maybe_exists(&task.target).await { if e.kind() != NotFound && maybe_exists(&task.target).await {
self.fail(task.id, format!("Delete task failed: {task:?}, {e}"))?; self.fail(task.id, format!("Delete task failed: {task:?}, {e}"))?;
@ -128,7 +128,7 @@ impl File {
} }
self.prog.send(TaskProg::Adv(task.id, 1, task.length))? self.prog.send(TaskProg::Adv(task.id, 1, task.length))?
} }
FileOp::Trash(task) => { FileIn::Trash(task) => {
tokio::task::spawn_blocking(move || { tokio::task::spawn_blocking(move || {
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
{ {
@ -150,7 +150,7 @@ impl File {
Ok(()) Ok(())
} }
pub async fn paste(&self, mut task: FileOpPaste) -> Result<()> { pub async fn paste(&self, mut task: FileInPaste) -> Result<()> {
if task.cut && ok_or_not_found(fs::rename(&task.from, &task.to).await).is_ok() { if task.cut && ok_or_not_found(fs::rename(&task.from, &task.to).await).is_ok() {
return self.succ(task.id); return self.succ(task.id);
} }
@ -165,9 +165,9 @@ impl File {
self.prog.send(TaskProg::New(id, cha.len))?; self.prog.send(TaskProg::New(id, cha.len))?;
if cha.is_orphan() || (cha.is_link() && !task.follow) { if cha.is_orphan() || (cha.is_link() && !task.follow) {
self.queue(FileOp::Link(task.into()), NORMAL).await?; self.queue(FileIn::Link(task.into()), NORMAL).await?;
} else { } else {
self.queue(FileOp::Paste(task), LOW).await?; self.queue(FileIn::Paste(task), LOW).await?;
} }
return self.succ(id); return self.succ(id);
} }
@ -210,27 +210,27 @@ impl File {
self.prog.send(TaskProg::New(task.id, cha.len))?; self.prog.send(TaskProg::New(task.id, cha.len))?;
if cha.is_orphan() || (cha.is_link() && !task.follow) { if cha.is_orphan() || (cha.is_link() && !task.follow) {
self.queue(FileOp::Link(task.spawn(from, to, cha).into()), NORMAL).await?; self.queue(FileIn::Link(task.spawn(from, to, cha).into()), NORMAL).await?;
} else { } else {
self.queue(FileOp::Paste(task.spawn(from, to, cha)), LOW).await?; self.queue(FileIn::Paste(task.spawn(from, to, cha)), LOW).await?;
} }
} }
} }
self.succ(task.id) self.succ(task.id)
} }
pub async fn link(&self, mut task: FileOpLink) -> Result<()> { pub async fn link(&self, mut task: FileInLink) -> Result<()> {
let id = task.id; let id = task.id;
if task.cha.is_none() { if task.cha.is_none() {
task.cha = Some(Self::cha(&task.from, false).await?); task.cha = Some(Self::cha(&task.from, false).await?);
} }
self.prog.send(TaskProg::New(id, task.cha.unwrap().len))?; self.prog.send(TaskProg::New(id, task.cha.unwrap().len))?;
self.queue(FileOp::Link(task), NORMAL).await?; self.queue(FileIn::Link(task), NORMAL).await?;
self.succ(id) self.succ(id)
} }
pub async fn hardlink(&self, mut task: FileOpHardlink) -> Result<()> { pub async fn hardlink(&self, mut task: FileInHardlink) -> Result<()> {
if task.cha.is_none() { if task.cha.is_none() {
task.cha = Some(Self::cha(&task.from, task.follow).await?); task.cha = Some(Self::cha(&task.from, task.follow).await?);
} }
@ -239,7 +239,7 @@ impl File {
if !cha.is_dir() { if !cha.is_dir() {
let id = task.id; let id = task.id;
self.prog.send(TaskProg::New(id, cha.len))?; self.prog.send(TaskProg::New(id, cha.len))?;
self.queue(FileOp::Hardlink(task), NORMAL).await?; self.queue(FileIn::Hardlink(task), NORMAL).await?;
return self.succ(id); return self.succ(id);
} }
@ -279,19 +279,19 @@ impl File {
let to = dest.join(from.file_name().unwrap()); let to = dest.join(from.file_name().unwrap());
self.prog.send(TaskProg::New(task.id, cha.len))?; self.prog.send(TaskProg::New(task.id, cha.len))?;
self.queue(FileOp::Hardlink(task.spawn(from, to, cha)), NORMAL).await?; self.queue(FileIn::Hardlink(task.spawn(from, to, cha)), NORMAL).await?;
} }
} }
self.succ(task.id) self.succ(task.id)
} }
pub async fn delete(&self, mut task: FileOpDelete) -> Result<()> { pub async fn delete(&self, mut task: FileInDelete) -> Result<()> {
let meta = fs::symlink_metadata(&task.target).await?; let meta = fs::symlink_metadata(&task.target).await?;
if !meta.is_dir() { if !meta.is_dir() {
let id = task.id; let id = task.id;
task.length = meta.len(); task.length = meta.len();
self.prog.send(TaskProg::New(id, meta.len()))?; self.prog.send(TaskProg::New(id, meta.len()))?;
self.queue(FileOp::Delete(task), NORMAL).await?; self.queue(FileIn::Delete(task), NORMAL).await?;
return self.succ(id); return self.succ(id);
} }
@ -310,18 +310,18 @@ impl File {
task.target = Url::from(entry.path()); task.target = Url::from(entry.path());
task.length = meta.len(); task.length = meta.len();
self.prog.send(TaskProg::New(task.id, meta.len()))?; self.prog.send(TaskProg::New(task.id, meta.len()))?;
self.queue(FileOp::Delete(task.clone()), NORMAL).await?; self.queue(FileIn::Delete(task.clone()), NORMAL).await?;
} }
} }
self.succ(task.id) self.succ(task.id)
} }
pub async fn trash(&self, mut task: FileOpTrash) -> Result<()> { pub async fn trash(&self, mut task: FileInTrash) -> Result<()> {
let id = task.id; let id = task.id;
task.length = SizeCalculator::total(&task.target).await?; task.length = SizeCalculator::total(&task.target).await?;
self.prog.send(TaskProg::New(id, task.length))?; self.prog.send(TaskProg::New(id, task.length))?;
self.queue(FileOp::Trash(task), LOW).await?; self.queue(FileIn::Trash(task), LOW).await?;
self.succ(id) self.succ(id)
} }
@ -356,7 +356,7 @@ impl File {
} }
#[inline] #[inline]
async fn queue(&self, op: impl Into<TaskOp>, priority: u8) -> Result<()> { async fn queue(&self, r#in: impl Into<TaskOp>, priority: u8) -> Result<()> {
self.macro_.send(op.into(), priority).await.map_err(|_| anyhow!("Failed to send task")) self.r#macro.send(r#in.into(), priority).await.map_err(|_| anyhow!("Failed to send task"))
} }
} }

View file

@ -2,29 +2,29 @@ use yazi_fs::cha::Cha;
use yazi_shared::url::Url; use yazi_shared::url::Url;
#[derive(Debug)] #[derive(Debug)]
pub enum FileOp { pub enum FileIn {
Paste(FileOpPaste), Paste(FileInPaste),
Link(FileOpLink), Link(FileInLink),
Hardlink(FileOpHardlink), Hardlink(FileInHardlink),
Delete(FileOpDelete), Delete(FileInDelete),
Trash(FileOpTrash), Trash(FileInTrash),
} }
impl FileOp { impl FileIn {
pub fn id(&self) -> usize { pub fn id(&self) -> usize {
match self { match self {
Self::Paste(op) => op.id, Self::Paste(r#in) => r#in.id,
Self::Link(op) => op.id, Self::Link(r#in) => r#in.id,
Self::Hardlink(op) => op.id, Self::Hardlink(r#in) => r#in.id,
Self::Delete(op) => op.id, Self::Delete(r#in) => r#in.id,
Self::Trash(op) => op.id, Self::Trash(r#in) => r#in.id,
} }
} }
} }
// --- Paste // --- Paste
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct FileOpPaste { pub struct FileInPaste {
pub id: usize, pub id: usize,
pub from: Url, pub from: Url,
pub to: Url, pub to: Url,
@ -34,7 +34,7 @@ pub struct FileOpPaste {
pub retry: u8, pub retry: u8,
} }
impl FileOpPaste { impl FileInPaste {
pub(super) fn spawn(&self, from: Url, to: Url, cha: Cha) -> Self { pub(super) fn spawn(&self, from: Url, to: Url, cha: Cha) -> Self {
Self { Self {
id: self.id, id: self.id,
@ -50,7 +50,7 @@ impl FileOpPaste {
// --- Link // --- Link
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct FileOpLink { pub struct FileInLink {
pub id: usize, pub id: usize,
pub from: Url, pub from: Url,
pub to: Url, pub to: Url,
@ -60,8 +60,8 @@ pub struct FileOpLink {
pub delete: bool, pub delete: bool,
} }
impl From<FileOpPaste> for FileOpLink { impl From<FileInPaste> for FileInLink {
fn from(value: FileOpPaste) -> Self { fn from(value: FileInPaste) -> Self {
Self { Self {
id: value.id, id: value.id,
from: value.from, from: value.from,
@ -76,7 +76,7 @@ impl From<FileOpPaste> for FileOpLink {
// --- Hardlink // --- Hardlink
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct FileOpHardlink { pub struct FileInHardlink {
pub id: usize, pub id: usize,
pub from: Url, pub from: Url,
pub to: Url, pub to: Url,
@ -84,7 +84,7 @@ pub struct FileOpHardlink {
pub follow: bool, pub follow: bool,
} }
impl FileOpHardlink { impl FileInHardlink {
pub(super) fn spawn(&self, from: Url, to: Url, cha: Cha) -> Self { pub(super) fn spawn(&self, from: Url, to: Url, cha: Cha) -> Self {
Self { id: self.id, from, to, cha: Some(cha), follow: self.follow } Self { id: self.id, from, to, cha: Some(cha), follow: self.follow }
} }
@ -92,7 +92,7 @@ impl FileOpHardlink {
// --- Delete // --- Delete
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct FileOpDelete { pub struct FileInDelete {
pub id: usize, pub id: usize,
pub target: Url, pub target: Url,
pub length: u64, pub length: u64,
@ -100,7 +100,7 @@ pub struct FileOpDelete {
// --- Trash // --- Trash
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct FileOpTrash { pub struct FileInTrash {
pub id: usize, pub id: usize,
pub target: Url, pub target: Url,
pub length: u64, pub length: u64,

View file

@ -1,3 +1,3 @@
#![allow(clippy::module_inception)] #![allow(clippy::module_inception)]
yazi_macro::mod_flat!(file op); yazi_macro::mod_flat!(file out r#in);

View file

@ -0,0 +1,23 @@
#[derive(Debug)]
pub enum FileOut {
Paste(FileOutPaste),
Link(FileOutLink),
Hardlink(FileOutHardlink),
Delete(FileOutDelete),
Trash(FileOutTrash),
}
#[derive(Debug)]
pub struct FileOutPaste;
#[derive(Debug)]
pub struct FileOutLink;
#[derive(Debug)]
pub struct FileOutHardlink;
#[derive(Debug)]
pub struct FileOutDelete;
#[derive(Debug)]
pub struct FileOutTrash;

30
yazi-scheduler/src/in.rs Normal file
View file

@ -0,0 +1,30 @@
use crate::{file::FileIn, plugin::PluginIn, prework::PreworkIn};
#[derive(Debug)]
pub enum TaskOp {
File(Box<FileIn>),
Plugin(Box<PluginIn>),
Prework(Box<PreworkIn>),
}
impl TaskOp {
pub fn id(&self) -> usize {
match self {
TaskOp::File(r#in) => r#in.id(),
TaskOp::Plugin(r#in) => r#in.id(),
TaskOp::Prework(r#in) => r#in.id(),
}
}
}
impl From<FileIn> for TaskOp {
fn from(r#in: FileIn) -> Self { Self::File(Box::new(r#in)) }
}
impl From<PluginIn> for TaskOp {
fn from(r#in: PluginIn) -> Self { Self::Plugin(Box::new(r#in)) }
}
impl From<PreworkIn> for TaskOp {
fn from(r#in: PreworkIn) -> Self { Self::Prework(Box::new(r#in)) }
}

View file

@ -2,7 +2,7 @@
yazi_macro::mod_pub!(file plugin prework process); yazi_macro::mod_pub!(file plugin prework process);
yazi_macro::mod_flat!(ongoing op scheduler task); yazi_macro::mod_flat!(ongoing out r#in scheduler task);
const LOW: u8 = yazi_config::Priority::Low as u8; const LOW: u8 = yazi_config::Priority::Low as u8;
const NORMAL: u8 = yazi_config::Priority::Normal as u8; const NORMAL: u8 = yazi_config::Priority::Normal as u8;

View file

@ -1,30 +0,0 @@
use crate::{file::FileOp, plugin::PluginOp, prework::PreworkOp};
#[derive(Debug)]
pub enum TaskOp {
File(Box<FileOp>),
Plugin(Box<PluginOp>),
Prework(Box<PreworkOp>),
}
impl TaskOp {
pub fn id(&self) -> usize {
match self {
TaskOp::File(op) => op.id(),
TaskOp::Plugin(op) => op.id(),
TaskOp::Prework(op) => op.id(),
}
}
}
impl From<FileOp> for TaskOp {
fn from(op: FileOp) -> Self { Self::File(Box::new(op)) }
}
impl From<PluginOp> for TaskOp {
fn from(op: PluginOp) -> Self { Self::Plugin(Box::new(op)) }
}
impl From<PreworkOp> for TaskOp {
fn from(op: PreworkOp) -> Self { Self::Prework(Box::new(op)) }
}

View file

@ -0,0 +1,8 @@
use crate::{file::FileOut, plugin::PluginOut, prework::PreworkOut};
#[derive(Debug)]
pub enum TaskOut {
File(FileOut),
Plugin(PluginOut),
Prework(PreworkOut),
}

View file

@ -1,20 +1,20 @@
use yazi_proxy::options::PluginOpt; use yazi_proxy::options::PluginOpt;
#[derive(Debug)] #[derive(Debug)]
pub enum PluginOp { pub enum PluginIn {
Entry(PluginOpEntry), Entry(PluginInEntry),
} }
impl PluginOp { impl PluginIn {
pub fn id(&self) -> usize { pub fn id(&self) -> usize {
match self { match self {
Self::Entry(op) => op.id, Self::Entry(r#in) => r#in.id,
} }
} }
} }
#[derive(Debug)] #[derive(Debug)]
pub struct PluginOpEntry { pub struct PluginInEntry {
pub id: usize, pub id: usize,
pub opt: PluginOpt, pub opt: PluginOpt,
} }

View file

@ -1,3 +1,3 @@
#![allow(clippy::module_inception)] #![allow(clippy::module_inception)]
yazi_macro::mod_flat!(op plugin); yazi_macro::mod_flat!(out plugin r#in);

View file

@ -0,0 +1,7 @@
#[derive(Debug)]
pub enum PluginOut {
Entry(PluginOutEntry),
}
#[derive(Debug)]
pub struct PluginOutEntry;

View file

@ -2,32 +2,32 @@ use anyhow::{Result, anyhow};
use tokio::sync::mpsc; use tokio::sync::mpsc;
use yazi_plugin::isolate; use yazi_plugin::isolate;
use super::{PluginOp, PluginOpEntry}; use super::{PluginIn, PluginInEntry};
use crate::{HIGH, TaskOp, TaskProg}; use crate::{HIGH, TaskOp, TaskProg};
pub struct Plugin { pub struct Plugin {
macro_: async_priority_channel::Sender<TaskOp, u8>, r#macro: async_priority_channel::Sender<TaskOp, u8>,
prog: mpsc::UnboundedSender<TaskProg>, prog: mpsc::UnboundedSender<TaskProg>,
} }
impl Plugin { impl Plugin {
pub fn new( pub fn new(
macro_: async_priority_channel::Sender<TaskOp, u8>, r#macro: async_priority_channel::Sender<TaskOp, u8>,
prog: mpsc::UnboundedSender<TaskProg>, prog: mpsc::UnboundedSender<TaskProg>,
) -> Self { ) -> Self {
Self { macro_, prog } Self { r#macro, prog }
} }
pub async fn work(&self, op: PluginOp) -> Result<()> { pub async fn work(&self, r#in: PluginIn) -> Result<()> {
match op { match r#in {
PluginOp::Entry(task) => { PluginIn::Entry(task) => {
isolate::entry(task.opt).await?; isolate::entry(task.opt).await?;
} }
} }
Ok(()) Ok(())
} }
pub async fn micro(&self, task: PluginOpEntry) -> Result<()> { pub async fn micro(&self, task: PluginInEntry) -> Result<()> {
self.prog.send(TaskProg::New(task.id, 0))?; self.prog.send(TaskProg::New(task.id, 0))?;
if let Err(e) = isolate::entry(task.opt).await { if let Err(e) = isolate::entry(task.opt).await {
@ -39,11 +39,11 @@ impl Plugin {
self.succ(task.id) self.succ(task.id)
} }
pub fn macro_(&self, task: PluginOpEntry) -> Result<()> { pub fn r#macro(&self, task: PluginInEntry) -> Result<()> {
let id = task.id; let id = task.id;
self.prog.send(TaskProg::New(id, 0))?; self.prog.send(TaskProg::New(id, 0))?;
self.queue(PluginOp::Entry(task), HIGH)?; self.queue(PluginIn::Entry(task), HIGH)?;
self.succ(id) self.succ(id)
} }
} }
@ -58,7 +58,7 @@ impl Plugin {
} }
#[inline] #[inline]
fn queue(&self, op: impl Into<TaskOp>, priority: u8) -> Result<()> { fn queue(&self, r#in: impl Into<TaskOp>, priority: u8) -> Result<()> {
self.macro_.try_send(op.into(), priority).map_err(|_| anyhow!("Failed to send task")) self.r#macro.try_send(r#in.into(), priority).map_err(|_| anyhow!("Failed to send task"))
} }
} }

View file

@ -4,38 +4,38 @@ use yazi_config::plugin::{Fetcher, Preloader};
use yazi_shared::{Throttle, url::Url}; use yazi_shared::{Throttle, url::Url};
#[derive(Debug)] #[derive(Debug)]
pub enum PreworkOp { pub enum PreworkIn {
Fetch(PreworkOpFetch), Fetch(PreworkInFetch),
Load(PreworkOpLoad), Load(PreworkInLoad),
Size(PreworkOpSize), Size(PreworkInSize),
} }
impl PreworkOp { impl PreworkIn {
pub fn id(&self) -> usize { pub fn id(&self) -> usize {
match self { match self {
Self::Fetch(op) => op.id, Self::Fetch(r#in) => r#in.id,
Self::Load(op) => op.id, Self::Load(r#in) => r#in.id,
Self::Size(op) => op.id, Self::Size(r#in) => r#in.id,
} }
} }
} }
#[derive(Debug)] #[derive(Debug)]
pub struct PreworkOpFetch { pub struct PreworkInFetch {
pub id: usize, pub id: usize,
pub plugin: &'static Fetcher, pub plugin: &'static Fetcher,
pub targets: Vec<yazi_fs::File>, pub targets: Vec<yazi_fs::File>,
} }
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct PreworkOpLoad { pub struct PreworkInLoad {
pub id: usize, pub id: usize,
pub plugin: &'static Preloader, pub plugin: &'static Preloader,
pub target: yazi_fs::File, pub target: yazi_fs::File,
} }
#[derive(Debug)] #[derive(Debug)]
pub struct PreworkOpSize { pub struct PreworkInSize {
pub id: usize, pub id: usize,
pub target: Url, pub target: Url,
pub throttle: Arc<Throttle<(Url, u64)>>, pub throttle: Arc<Throttle<(Url, u64)>>,

View file

@ -1,3 +1,3 @@
#![allow(clippy::module_inception)] #![allow(clippy::module_inception)]
yazi_macro::mod_flat!(op prework); yazi_macro::mod_flat!(out prework r#in);

View file

@ -0,0 +1,15 @@
#[derive(Debug)]
pub enum PreworkOut {
Fetch(PreworkOutFetch),
Load(PreworkOutLoad),
Size(PreworkOutSize),
}
#[derive(Debug)]
pub struct PreworkOutFetch;
#[derive(Debug)]
pub struct PreworkOutLoad;
#[derive(Debug)]
pub struct PreworkOutSize;

View file

@ -10,12 +10,12 @@ use yazi_fs::{FilesOp, SizeCalculator};
use yazi_plugin::isolate; use yazi_plugin::isolate;
use yazi_shared::{event::CmdCow, url::Url}; use yazi_shared::{event::CmdCow, url::Url};
use super::{PreworkOp, PreworkOpFetch, PreworkOpLoad, PreworkOpSize}; use super::{PreworkIn, PreworkInFetch, PreworkInLoad, PreworkInSize};
use crate::{HIGH, NORMAL, TaskOp, TaskProg}; use crate::{HIGH, NORMAL, TaskOp, TaskProg};
pub struct Prework { pub struct Prework {
macro_: async_priority_channel::Sender<TaskOp, u8>, r#macro: async_priority_channel::Sender<TaskOp, u8>,
prog: mpsc::UnboundedSender<TaskProg>, prog: mpsc::UnboundedSender<TaskProg>,
pub loaded: Mutex<LruCache<u64, u32>>, pub loaded: Mutex<LruCache<u64, u32>>,
pub size_loading: RwLock<HashSet<Url>>, pub size_loading: RwLock<HashSet<Url>>,
@ -23,20 +23,20 @@ pub struct Prework {
impl Prework { impl Prework {
pub fn new( pub fn new(
macro_: async_priority_channel::Sender<TaskOp, u8>, r#macro: async_priority_channel::Sender<TaskOp, u8>,
prog: mpsc::UnboundedSender<TaskProg>, prog: mpsc::UnboundedSender<TaskProg>,
) -> Self { ) -> Self {
Self { Self {
macro_, r#macro,
prog, prog,
loaded: Mutex::new(LruCache::new(NonZeroUsize::new(4096).unwrap())), loaded: Mutex::new(LruCache::new(NonZeroUsize::new(4096).unwrap())),
size_loading: Default::default(), size_loading: Default::default(),
} }
} }
pub async fn work(&self, op: PreworkOp) -> Result<()> { pub async fn work(&self, r#in: PreworkIn) -> Result<()> {
match op { match r#in {
PreworkOp::Fetch(task) => { PreworkIn::Fetch(task) => {
let hashes: Vec<_> = task.targets.iter().map(|f| f.hash()).collect(); let hashes: Vec<_> = task.targets.iter().map(|f| f.hash()).collect();
let result = isolate::fetch(CmdCow::from(&task.plugin.run), task.targets).await; let result = isolate::fetch(CmdCow::from(&task.plugin.run), task.targets).await;
if let Err(e) = result { if let Err(e) = result {
@ -54,7 +54,7 @@ impl Prework {
} }
self.prog.send(TaskProg::Adv(task.id, 1, 0))?; self.prog.send(TaskProg::Adv(task.id, 1, 0))?;
} }
PreworkOp::Load(task) => { PreworkIn::Load(task) => {
let hash = task.target.hash(); let hash = task.target.hash();
let result = isolate::preload(&task.plugin.run, task.target).await; let result = isolate::preload(&task.plugin.run, task.target).await;
if let Err(e) = result { if let Err(e) = result {
@ -72,7 +72,7 @@ impl Prework {
} }
self.prog.send(TaskProg::Adv(task.id, 1, 0))?; self.prog.send(TaskProg::Adv(task.id, 1, 0))?;
} }
PreworkOp::Size(task) => { PreworkIn::Size(task) => {
let length = SizeCalculator::total(&task.target).await.unwrap_or(0); let length = SizeCalculator::total(&task.target).await.unwrap_or(0);
task.throttle.done((task.target, length), |buf| { task.throttle.done((task.target, length), |buf| {
{ {
@ -95,35 +95,35 @@ impl Prework {
Ok(()) Ok(())
} }
pub async fn fetch(&self, task: PreworkOpFetch) -> Result<()> { pub async fn fetch(&self, task: PreworkInFetch) -> Result<()> {
let id = task.id; let id = task.id;
self.prog.send(TaskProg::New(id, 0))?; self.prog.send(TaskProg::New(id, 0))?;
match task.plugin.prio { match task.plugin.prio {
Priority::Low => self.queue(PreworkOp::Fetch(task), NORMAL).await?, Priority::Low => self.queue(PreworkIn::Fetch(task), NORMAL).await?,
Priority::Normal => self.queue(PreworkOp::Fetch(task), HIGH).await?, Priority::Normal => self.queue(PreworkIn::Fetch(task), HIGH).await?,
Priority::High => self.work(PreworkOp::Fetch(task)).await?, Priority::High => self.work(PreworkIn::Fetch(task)).await?,
} }
self.succ(id) self.succ(id)
} }
pub async fn load(&self, task: PreworkOpLoad) -> Result<()> { pub async fn load(&self, task: PreworkInLoad) -> Result<()> {
let id = task.id; let id = task.id;
self.prog.send(TaskProg::New(id, 0))?; self.prog.send(TaskProg::New(id, 0))?;
match task.plugin.prio { match task.plugin.prio {
Priority::Low => self.queue(PreworkOp::Load(task), NORMAL).await?, Priority::Low => self.queue(PreworkIn::Load(task), NORMAL).await?,
Priority::Normal => self.queue(PreworkOp::Load(task), HIGH).await?, Priority::Normal => self.queue(PreworkIn::Load(task), HIGH).await?,
Priority::High => self.work(PreworkOp::Load(task)).await?, Priority::High => self.work(PreworkIn::Load(task)).await?,
} }
self.succ(id) self.succ(id)
} }
pub async fn size(&self, task: PreworkOpSize) -> Result<()> { pub async fn size(&self, task: PreworkInSize) -> Result<()> {
let id = task.id; let id = task.id;
self.prog.send(TaskProg::New(id, 0))?; self.prog.send(TaskProg::New(id, 0))?;
self.work(PreworkOp::Size(task)).await?; self.work(PreworkIn::Size(task)).await?;
self.succ(id) self.succ(id)
} }
} }
@ -138,7 +138,7 @@ impl Prework {
} }
#[inline] #[inline]
async fn queue(&self, op: impl Into<TaskOp>, priority: u8) -> Result<()> { async fn queue(&self, r#in: impl Into<TaskOp>, priority: u8) -> Result<()> {
self.macro_.send(op.into(), priority).await.map_err(|_| anyhow!("Failed to send task")) self.r#macro.send(r#in.into(), priority).await.map_err(|_| anyhow!("Failed to send task"))
} }
} }

View file

@ -0,0 +1,52 @@
use std::ffi::OsString;
use tokio::sync::mpsc;
use yazi_shared::url::Url;
use super::ShellOpt;
// --- Block
#[derive(Debug)]
pub struct ProcessInBlock {
pub id: usize,
pub cwd: Url,
pub cmd: OsString,
pub args: Vec<OsString>,
}
impl From<ProcessInBlock> for ShellOpt {
fn from(r#in: ProcessInBlock) -> Self {
Self { cwd: r#in.cwd, cmd: r#in.cmd, args: r#in.args, piped: false, orphan: false }
}
}
// --- Orphan
#[derive(Debug)]
pub struct ProcessInOrphan {
pub id: usize,
pub cwd: Url,
pub cmd: OsString,
pub args: Vec<OsString>,
}
impl From<ProcessInOrphan> for ShellOpt {
fn from(r#in: ProcessInOrphan) -> Self {
Self { cwd: r#in.cwd, cmd: r#in.cmd, args: r#in.args, piped: false, orphan: true }
}
}
// --- Bg
#[derive(Debug)]
pub struct ProcessInBg {
pub id: usize,
pub cwd: Url,
pub cmd: OsString,
pub args: Vec<OsString>,
pub cancel: mpsc::Receiver<()>,
}
impl From<ProcessInBg> for ShellOpt {
fn from(r#in: ProcessInBg) -> Self {
Self { cwd: r#in.cwd, cmd: r#in.cmd, args: r#in.args, piped: true, orphan: false }
}
}

View file

@ -1,3 +1,3 @@
#![allow(clippy::module_inception)] #![allow(clippy::module_inception)]
yazi_macro::mod_flat!(op process shell); yazi_macro::mod_flat!(process r#in shell);

View file

@ -1,52 +0,0 @@
use std::ffi::OsString;
use tokio::sync::mpsc;
use yazi_shared::url::Url;
use super::ShellOpt;
// --- Block
#[derive(Debug)]
pub struct ProcessOpBlock {
pub id: usize,
pub cwd: Url,
pub cmd: OsString,
pub args: Vec<OsString>,
}
impl From<ProcessOpBlock> for ShellOpt {
fn from(op: ProcessOpBlock) -> Self {
Self { cwd: op.cwd, cmd: op.cmd, args: op.args, piped: false, orphan: false }
}
}
// --- Orphan
#[derive(Debug)]
pub struct ProcessOpOrphan {
pub id: usize,
pub cwd: Url,
pub cmd: OsString,
pub args: Vec<OsString>,
}
impl From<ProcessOpOrphan> for ShellOpt {
fn from(op: ProcessOpOrphan) -> Self {
Self { cwd: op.cwd, cmd: op.cmd, args: op.args, piped: false, orphan: true }
}
}
// --- Bg
#[derive(Debug)]
pub struct ProcessOpBg {
pub id: usize,
pub cwd: Url,
pub cmd: OsString,
pub args: Vec<OsString>,
pub cancel: mpsc::Receiver<()>,
}
impl From<ProcessOpBg> for ShellOpt {
fn from(op: ProcessOpBg) -> Self {
Self { cwd: op.cwd, cmd: op.cmd, args: op.args, piped: true, orphan: false }
}
}

View file

@ -3,7 +3,7 @@ use scopeguard::defer;
use tokio::{io::{AsyncBufReadExt, BufReader}, select, sync::mpsc}; use tokio::{io::{AsyncBufReadExt, BufReader}, select, sync::mpsc};
use yazi_proxy::{AppProxy, HIDER}; use yazi_proxy::{AppProxy, HIDER};
use super::{ProcessOpBg, ProcessOpBlock, ProcessOpOrphan, ShellOpt}; use super::{ProcessInBg, ProcessInBlock, ProcessInOrphan, ShellOpt};
use crate::TaskProg; use crate::TaskProg;
pub struct Process { pub struct Process {
@ -13,7 +13,7 @@ pub struct Process {
impl Process { impl Process {
pub fn new(prog: mpsc::UnboundedSender<TaskProg>) -> Self { Self { prog } } pub fn new(prog: mpsc::UnboundedSender<TaskProg>) -> Self { Self { prog } }
pub async fn block(&self, task: ProcessOpBlock) -> Result<()> { pub async fn block(&self, task: ProcessInBlock) -> Result<()> {
let _permit = HIDER.acquire().await.unwrap(); let _permit = HIDER.acquire().await.unwrap();
defer!(AppProxy::resume()); defer!(AppProxy::resume());
AppProxy::stop().await; AppProxy::stop().await;
@ -38,7 +38,7 @@ impl Process {
self.succ(id) self.succ(id)
} }
pub async fn orphan(&self, task: ProcessOpOrphan) -> Result<()> { pub async fn orphan(&self, task: ProcessInOrphan) -> Result<()> {
let id = task.id; let id = task.id;
match super::shell(task.into()) { match super::shell(task.into()) {
Ok(_) => self.succ(id)?, Ok(_) => self.succ(id)?,
@ -51,7 +51,7 @@ impl Process {
Ok(()) Ok(())
} }
pub async fn bg(&self, task: ProcessOpBg) -> Result<()> { pub async fn bg(&self, task: ProcessInBg) -> Result<()> {
self.prog.send(TaskProg::New(task.id, 0))?; self.prog.send(TaskProg::New(task.id, 0))?;
let mut child = super::shell(ShellOpt { let mut child = super::shell(ShellOpt {
cwd: task.cwd, cwd: task.cwd,

View file

@ -11,7 +11,7 @@ use yazi_proxy::{MgrProxy, options::{PluginOpt, ProcessExecOpt}};
use yazi_shared::{Throttle, url::Url}; use yazi_shared::{Throttle, url::Url};
use super::{Ongoing, TaskProg, TaskStage}; use super::{Ongoing, TaskProg, TaskStage};
use crate::{HIGH, LOW, NORMAL, TaskKind, TaskOp, file::{File, FileOpDelete, FileOpHardlink, FileOpLink, FileOpPaste, FileOpTrash}, plugin::{Plugin, PluginOpEntry}, prework::{Prework, PreworkOpFetch, PreworkOpLoad, PreworkOpSize}, process::{Process, ProcessOpBg, ProcessOpBlock, ProcessOpOrphan}}; use crate::{HIGH, LOW, NORMAL, TaskKind, TaskOp, file::{File, FileInDelete, FileInHardlink, FileInLink, FileInPaste, FileInTrash}, plugin::{Plugin, PluginInEntry}, prework::{Prework, PreworkInFetch, PreworkInLoad, PreworkInSize}, process::{Process, ProcessInBg, ProcessInBlock, ProcessInOrphan}};
pub struct Scheduler { pub struct Scheduler {
pub file: Arc<File>, pub file: Arc<File>,
@ -102,7 +102,7 @@ impl Scheduler {
if !force { if !force {
to = unique_name(to, must_be_dir(&from)).await?; to = unique_name(to, must_be_dir(&from)).await?;
} }
file.paste(FileOpPaste { id, from, to, cha: None, cut: true, follow: false, retry: 0 }).await file.paste(FileInPaste { id, from, to, cha: None, cut: true, follow: false, retry: 0 }).await
}); });
} }
@ -119,7 +119,7 @@ impl Scheduler {
if !force { if !force {
to = unique_name(to, must_be_dir(&from)).await?; to = unique_name(to, must_be_dir(&from)).await?;
} }
file.paste(FileOpPaste { id, from, to, cha: None, cut: false, follow, retry: 0 }).await file.paste(FileInPaste { id, from, to, cha: None, cut: false, follow, retry: 0 }).await
}); });
} }
@ -132,7 +132,7 @@ impl Scheduler {
to = unique_name(to, must_be_dir(&from)).await?; to = unique_name(to, must_be_dir(&from)).await?;
} }
file file
.link(FileOpLink { id, from, to, cha: None, resolve: false, relative, delete: false }) .link(FileInLink { id, from, to, cha: None, resolve: false, relative, delete: false })
.await .await
}); });
} }
@ -150,7 +150,7 @@ impl Scheduler {
if !force { if !force {
to = unique_name(to, must_be_dir(&from)).await?; to = unique_name(to, must_be_dir(&from)).await?;
} }
file.hardlink(FileOpHardlink { id, from, to, cha: None, follow }).await file.hardlink(FileInHardlink { id, from, to, cha: None, follow }).await
}); });
} }
@ -179,7 +179,7 @@ impl Scheduler {
self.send_micro( self.send_micro(
id, id,
LOW, LOW,
async move { file.delete(FileOpDelete { id, target, length: 0 }).await }, async move { file.delete(FileInDelete { id, target, length: 0 }).await },
); );
} }
@ -205,7 +205,7 @@ impl Scheduler {
let file = self.file.clone(); let file = self.file.clone();
self.send_micro(id, LOW, async move { self.send_micro(id, LOW, async move {
file.trash(FileOpTrash { id, target: target.clone(), length: 0 }).await file.trash(FileInTrash { id, target: target.clone(), length: 0 }).await
}) })
} }
@ -213,13 +213,13 @@ impl Scheduler {
let id = self.ongoing.lock().add(TaskKind::User, format!("Run micro plugin `{}`", opt.id)); let id = self.ongoing.lock().add(TaskKind::User, format!("Run micro plugin `{}`", opt.id));
let plugin = self.plugin.clone(); let plugin = self.plugin.clone();
self.send_micro(id, NORMAL, async move { plugin.micro(PluginOpEntry { id, opt }).await }); self.send_micro(id, NORMAL, async move { plugin.micro(PluginInEntry { id, opt }).await });
} }
pub fn plugin_macro(&self, opt: PluginOpt) { pub fn plugin_macro(&self, opt: PluginOpt) {
let id = self.ongoing.lock().add(TaskKind::User, format!("Run macro plugin `{}`", opt.id)); let id = self.ongoing.lock().add(TaskKind::User, format!("Run macro plugin `{}`", opt.id));
self.plugin.macro_(PluginOpEntry { id, opt }).ok(); self.plugin.r#macro(PluginInEntry { id, opt }).ok();
} }
pub fn fetch_paged(&self, fetcher: &'static Fetcher, targets: Vec<yazi_fs::File>) { pub fn fetch_paged(&self, fetcher: &'static Fetcher, targets: Vec<yazi_fs::File>) {
@ -230,7 +230,7 @@ impl Scheduler {
let prework = self.prework.clone(); let prework = self.prework.clone();
self.send_micro(id, NORMAL, async move { self.send_micro(id, NORMAL, async move {
prework.fetch(PreworkOpFetch { id, plugin: fetcher, targets }).await prework.fetch(PreworkInFetch { id, plugin: fetcher, targets }).await
}); });
} }
@ -241,7 +241,7 @@ impl Scheduler {
let target = target.clone(); let target = target.clone();
let prework = self.prework.clone(); let prework = self.prework.clone();
self.send_micro(id, NORMAL, async move { self.send_micro(id, NORMAL, async move {
prework.load(PreworkOpLoad { id, plugin: preloader, target }).await prework.load(PreworkInLoad { id, plugin: preloader, target }).await
}); });
} }
@ -256,7 +256,7 @@ impl Scheduler {
let prework = self.prework.clone(); let prework = self.prework.clone();
self.send_micro(id, NORMAL, async move { self.send_micro(id, NORMAL, async move {
prework.size(PreworkOpSize { id, target, throttle }).await prework.size(PreworkInSize { id, target, throttle }).await
}); });
} }
} }
@ -296,11 +296,11 @@ impl Scheduler {
let process = self.process.clone(); let process = self.process.clone();
self.send_micro(id, NORMAL, async move { self.send_micro(id, NORMAL, async move {
if opener.block { if opener.block {
process.block(ProcessOpBlock { id, cwd, cmd, args }).await process.block(ProcessInBlock { id, cwd, cmd, args }).await
} else if opener.orphan { } else if opener.orphan {
process.orphan(ProcessOpOrphan { id, cwd, cmd, args }).await process.orphan(ProcessInOrphan { id, cwd, cmd, args }).await
} else { } else {
process.bg(ProcessOpBg { id, cwd, cmd, args, cancel: cancel_rx }).await process.bg(ProcessInBg { id, cwd, cmd, args, cancel: cancel_rx }).await
} }
}); });
} }
@ -321,7 +321,7 @@ impl Scheduler {
fn schedule_macro( fn schedule_macro(
&self, &self,
micro: async_priority_channel::Receiver<BoxFuture<'static, ()>, u8>, micro: async_priority_channel::Receiver<BoxFuture<'static, ()>, u8>,
macro_: async_priority_channel::Receiver<TaskOp, u8>, r#macro: async_priority_channel::Receiver<TaskOp, u8>,
) -> JoinHandle<()> { ) -> JoinHandle<()> {
let file = self.file.clone(); let file = self.file.clone();
let plugin = self.plugin.clone(); let plugin = self.plugin.clone();
@ -336,16 +336,16 @@ impl Scheduler {
Ok((fut, _)) = micro.recv() => { Ok((fut, _)) = micro.recv() => {
fut.await; fut.await;
} }
Ok((op, _)) = macro_.recv() => { Ok((r#in, _)) = r#macro.recv() => {
let id = op.id(); let id = r#in.id();
if !ongoing.lock().exists(id) { if !ongoing.lock().exists(id) {
continue; continue;
} }
let result = match op { let result = match r#in {
TaskOp::File(op) => file.work(*op).await, TaskOp::File(r#in) => file.work(*r#in).await,
TaskOp::Plugin(op) => plugin.work(*op).await, TaskOp::Plugin(r#in) => plugin.work(*r#in).await,
TaskOp::Prework(op) => prework.work(*op).await, TaskOp::Prework(r#in) => prework.work(*r#in).await,
}; };
if let Err(e) = result { if let Err(e) = result {
@ -362,8 +362,8 @@ impl Scheduler {
let ongoing = self.ongoing.clone(); let ongoing = self.ongoing.clone();
tokio::spawn(async move { tokio::spawn(async move {
while let Some(op) = rx.recv().await { while let Some(r#in) = rx.recv().await {
match op { match r#in {
TaskProg::New(id, size) => { TaskProg::New(id, size) => {
if let Some(task) = ongoing.lock().get_mut(id) { if let Some(task) = ongoing.lock().get_mut(id) {
task.total += 1; task.total += 1;

View file

@ -2,6 +2,6 @@
yazi_macro::mod_pub!(tty); yazi_macro::mod_pub!(tty);
yazi_macro::mod_flat!(cursor if_); yazi_macro::mod_flat!(cursor r#if);
pub fn init() { tty::init(); } pub fn init() { tty::init(); }

View file

@ -26,10 +26,10 @@ impl Input {
if opt.under { if opt.under {
snap.value.remove(snap.idx(snap.cursor).unwrap()); snap.value.remove(snap.idx(snap.cursor).unwrap());
self.move_(0); self.r#move(0);
} else { } else {
snap.value.remove(snap.idx(snap.cursor - 1).unwrap()); snap.value.remove(snap.idx(snap.cursor - 1).unwrap());
self.move_(-1); self.r#move(-1);
} }
self.flush_value(); self.flush_value();

View file

@ -15,7 +15,7 @@ impl Input {
pub fn backward(&mut self, opt: Opt) { pub fn backward(&mut self, opt: Opt) {
let snap = self.snap(); let snap = self.snap();
if snap.cursor == 0 { if snap.cursor == 0 {
return self.move_(0); return self.r#move(0);
} }
let idx = snap.idx(snap.cursor).unwrap_or(snap.len()); let idx = snap.idx(snap.cursor).unwrap_or(snap.len());
@ -24,13 +24,13 @@ impl Input {
for (i, c) in it { for (i, c) in it {
let k = CharKind::new(c); let k = CharKind::new(c);
if prev != CharKind::Space && prev.vary(k, opt.far) { if prev != CharKind::Space && prev.vary(k, opt.far) {
return self.move_(-(i as isize)); return self.r#move(-(i as isize));
} }
prev = k; prev = k;
} }
if prev != CharKind::Space { if prev != CharKind::Space {
self.move_(-(snap.len() as isize)); self.r#move(-(snap.len() as isize));
} }
} }
} }

View file

@ -17,7 +17,7 @@ impl Input {
}; };
} }
on!(move_, "move"); on!(r#move, "move");
on!(backward); on!(backward);
on!(forward); on!(forward);

View file

@ -47,7 +47,7 @@ impl Input {
let delta = new.chars().count() as isize - snap.count() as isize; let delta = new.chars().count() as isize - snap.count() as isize;
snap.value = new; snap.value = new;
self.move_(delta); self.r#move(delta);
self.flush_value(); self.flush_value();
render!(); render!();
} }

View file

@ -22,11 +22,11 @@ impl Input {
InputOp::Select(start) => { InputOp::Select(start) => {
self.snap_mut().op = InputOp::Delete(opt.cut, opt.insert, start); self.snap_mut().op = InputOp::Delete(opt.cut, opt.insert, start);
render!(self.handle_op(self.snap().cursor, true)); render!(self.handle_op(self.snap().cursor, true));
self.move_(0); self.r#move(0);
} }
InputOp::Delete(..) => { InputOp::Delete(..) => {
self.snap_mut().op = InputOp::Delete(opt.cut, opt.insert, 0); self.snap_mut().op = InputOp::Delete(opt.cut, opt.insert, 0);
self.move_(self.snap().len() as isize); self.r#move(self.snap().len() as isize);
} }
_ => {} _ => {}
} }

View file

@ -16,7 +16,7 @@ impl Input {
} }
InputMode::Insert => { InputMode::Insert => {
snap.mode = InputMode::Normal; snap.mode = InputMode::Normal;
self.move_(-1); self.r#move(-1);
} }
InputMode::Replace => { InputMode::Replace => {
snap.mode = InputMode::Normal; snap.mode = InputMode::Normal;

View file

@ -18,7 +18,7 @@ impl Input {
let mut it = snap.value.chars().skip(snap.cursor).enumerate(); let mut it = snap.value.chars().skip(snap.cursor).enumerate();
let Some(mut prev) = it.next().map(|(_, c)| CharKind::new(c)) else { let Some(mut prev) = it.next().map(|(_, c)| CharKind::new(c)) else {
return self.move_(0); return self.r#move(0);
}; };
for (i, c) in it { for (i, c) in it {
@ -29,13 +29,13 @@ impl Input {
k != CharKind::Space && k.vary(prev, opt.far) k != CharKind::Space && k.vary(prev, opt.far)
}; };
if b && !matches!(snap.op, InputOp::None | InputOp::Select(_)) { if b && !matches!(snap.op, InputOp::None | InputOp::Select(_)) {
return self.move_(i as isize); return self.r#move(i as isize);
} else if b { } else if b {
return self.move_(if opt.end_of_word { i - 1 } else { i } as isize); return self.r#move(if opt.end_of_word { i - 1 } else { i } as isize);
} }
prev = k; prev = k;
} }
self.move_(snap.len() as isize) self.r#move(snap.len() as isize)
} }
} }

View file

@ -26,7 +26,7 @@ impl Input {
} }
if opt.append { if opt.append {
self.move_(1); self.r#move(1);
} }
render!(); render!();

View file

@ -52,7 +52,7 @@ impl Input {
return; return;
} }
self.move_(0); self.r#move(0);
self.flush_value(); self.flush_value();
render!(); render!();
} }

View file

@ -1 +1 @@
yazi_macro::mod_flat!(backspace backward commands complete delete escape forward insert kill move_ paste redo replace type_ undo visual yank); yazi_macro::mod_flat!(backspace backward commands complete delete escape forward insert kill paste r#move r#type redo replace undo visual yank);

View file

@ -24,7 +24,7 @@ impl From<isize> for Opt {
impl Input { impl Input {
#[yazi_codegen::command] #[yazi_codegen::command]
pub fn move_(&mut self, opt: Opt) { pub fn r#move(&mut self, opt: Opt) {
let snap = self.snap(); let snap = self.snap();
if opt.in_operating && snap.op == InputOp::None { if opt.in_operating && snap.op == InputOp::None {
return; return;

View file

@ -11,7 +11,7 @@ impl From<CmdCow> for Opt {
} }
impl Input { impl Input {
pub fn type_(&mut self, key: &Key) -> bool { pub fn r#type(&mut self, key: &Key) -> bool {
let Some(c) = key.plain() else { return false }; let Some(c) = key.plain() else { return false };
if self.mode() == InputMode::Insert { if self.mode() == InputMode::Insert {
@ -33,7 +33,7 @@ impl Input {
snap.value.insert_str(snap.idx(snap.cursor).unwrap(), s); snap.value.insert_str(snap.idx(snap.cursor).unwrap(), s);
} }
self.move_(s.chars().count() as isize); self.r#move(s.chars().count() as isize);
self.flush_value(); self.flush_value();
render!(); render!();
} }

View file

@ -12,11 +12,11 @@ impl Input {
InputOp::Select(start) => { InputOp::Select(start) => {
self.snap_mut().op = InputOp::Yank(start); self.snap_mut().op = InputOp::Yank(start);
render!(self.handle_op(self.snap().cursor, true)); render!(self.handle_op(self.snap().cursor, true));
self.move_(0); self.r#move(0);
} }
InputOp::Yank(_) => { InputOp::Yank(_) => {
self.snap_mut().op = InputOp::Yank(0); self.snap_mut().op = InputOp::Yank(0);
self.move_(self.snap().len() as isize); self.r#move(self.snap().len() as isize);
} }
_ => {} _ => {}
} }