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

View file

@ -7,8 +7,8 @@ use yazi_fs::Xdg;
#[derive(Clone, Default)]
pub(crate) struct Dependency {
pub(crate) use_: String, // owner/repo:child
pub(crate) name: String, // child.yazi
pub(crate) r#use: String, // owner/repo:child
pub(crate) name: String, // child.yazi
pub(crate) parent: String, // owner/repo
pub(crate) child: String, // child.yazi
@ -81,7 +81,7 @@ impl FromStr for Dependency {
}
Ok(Self {
use_: s.to_owned(),
r#use: s.to_owned(),
name: format!("{name}.yazi"),
parent: format!("{parent}{}", if child.is_empty() { ".yazi" } else { "" }),
child: if child.is_empty() { String::new() } else { format!("{child}.yazi") },
@ -97,19 +97,18 @@ impl<'de> Deserialize<'de> for Dependency {
{
#[derive(Deserialize)]
struct Shadow {
#[serde(rename = "use")]
use_: String,
r#use: String,
#[serde(default)]
rev: String,
rev: String,
#[serde(default)]
hash: String,
hash: String,
}
let outer = Shadow::deserialize(deserializer)?;
Ok(Self {
rev: outer.rev,
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)]
struct Shadow<'a> {
#[serde(rename = "use")]
use_: &'a str,
rev: &'a str,
hash: &'a str,
r#use: &'a str,
rev: &'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:")?;
for d in &self.plugins {
if d.rev.is_empty() {
outln!("\t{}", d.use_)?;
outln!("\t{}", d.r#use)?;
} else {
outln!("\t{} ({})", d.use_, d.rev)?;
outln!("\t{} ({})", d.r#use, d.rev)?;
}
}
outln!("Flavors:")?;
for d in &self.flavors {
if d.rev.is_empty() {
outln!("\t{}", d.use_)?;
outln!("\t{}", d.r#use)?;
} else {
outln!("\t{} ({})", d.use_, d.rev)?;
outln!("\t{} ({})", d.r#use, d.rev)?;
}
}
Ok(())
}
async fn add(&mut self, use_: &str) -> Result<()> {
let mut dep = Dependency::from_str(use_)?;
async fn add(&mut self, r#use: &str) -> Result<()> {
let mut dep = Dependency::from_str(r#use)?;
if let Some(d) = self.identical(&dep) {
bail!(
"{} `{}` already exists in package.toml",
@ -98,9 +98,9 @@ impl Package {
Ok(())
}
async fn delete(&mut self, use_: &str) -> Result<()> {
let Some(dep) = self.identical(&Dependency::from_str(use_)?).cloned() else {
bail!("`{}` was not found in package.toml", use_)
async fn delete(&mut self, r#use: &str) -> Result<()> {
let Some(dep) = self.identical(&Dependency::from_str(r#use)?).cloned() else {
bail!("`{}` was not found in package.toml", r#use)
};
dep.delete().await?;

View file

@ -1,6 +1,6 @@
use proc_macro::TokenStream;
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]
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
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;
// Collect the rest of the arguments

View file

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

View file

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

View file

@ -38,7 +38,7 @@ impl Open {
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))
})
.flat_map(|r| &r.use_)
.flat_map(|r| &r.r#use)
.map(String::as_str)
}

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -38,7 +38,7 @@ impl Help {
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 {
return false;
};
@ -56,7 +56,7 @@ impl Help {
input.backspace(false);
}
_ => {
input.type_(key);
input.r#type(key);
}
}

View file

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

View file

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

View file

@ -6,7 +6,7 @@ use yazi_shared::event::CmdCow;
use crate::tab::Tab;
struct Opt {
type_: Cow<'static, str>,
r#type: Cow<'static, str>,
separator: Separator,
hovered: bool,
}
@ -14,7 +14,7 @@ struct Opt {
impl From<CmdCow> for Opt {
fn from(mut c: CmdCow) -> 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(),
hovered: c.bool("hovered"),
}
@ -37,7 +37,7 @@ impl Tab {
.peekable();
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),
"dirname" => opt.separator.transform(u.parent().unwrap_or(Path::new(""))),
"filename" => opt.separator.transform(u.name()),
@ -50,7 +50,7 @@ impl Tab {
}
// 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());
}

View file

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

View file

@ -12,7 +12,7 @@ pub struct 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.times += 1;

View file

@ -1,5 +1,5 @@
#![allow(clippy::module_inception)]
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()
}
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>) {
if receiver == *ID {
return Self::pub_(body);
return Self::r#pub(body);
}
let kind = body.kind();
@ -87,7 +87,7 @@ impl Pubsub {
pub fn pub_from_tab(idx: Id) {
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")) {
Client::push(BodyTab::owned(idx));
@ -99,7 +99,7 @@ impl Pubsub {
pub fn pub_from_cd(tab: Id, url: &Url) {
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")) {
Client::push(BodyCd::borrowed(tab, url));
@ -111,7 +111,7 @@ impl Pubsub {
pub fn pub_from_load(tab: Id, url: &Url, stage: FolderStage) {
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")) {
Client::push(BodyLoad::borrowed(tab, url, stage));
@ -123,7 +123,7 @@ impl Pubsub {
pub fn pub_from_hover(tab: Id, url: Option<&Url>) {
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")) {
Client::push(BodyHover::borrowed(tab, url));
@ -135,7 +135,7 @@ impl Pubsub {
pub fn pub_from_rename(tab: Id, from: &Url, to: &Url) {
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")) {
Client::push(BodyRename::borrowed(tab, from, to));
@ -147,7 +147,7 @@ impl Pubsub {
pub fn pub_from_bulk(changes: HashMap<&Url, &Url>) {
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")) {
Client::push(BodyBulk::borrowed(&changes));
@ -159,7 +159,7 @@ impl Pubsub {
pub fn pub_from_yank(cut: bool, urls: &HashSet<Url>) {
if LOCAL.read().contains_key("@yank") {
Self::pub_(BodyYank::dummy());
Self::r#pub(BodyYank::dummy());
}
if Self::any_remote_own("@yank") {
Client::push(BodyYank::borrowed(cut, urls));
@ -177,7 +177,7 @@ impl Pubsub {
BodyMove::borrowed(&items).with_receiver(*ID).flush();
}
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();
}
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();
}
if LOCAL.read().contains_key("delete") {
Self::pub_(BodyDelete::owned(urls));
Self::r#pub(BodyDelete::owned(urls));
}
}
pub fn pub_from_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")) {
Client::push(BodyMount::owned());

View file

@ -16,14 +16,14 @@ unsafe extern "C" {
pub fn DARegisterDiskAppearedCallback(
session: *const c_void,
match_: CFDictionaryRef,
r#match: CFDictionaryRef,
callback: extern "C" fn(disk: *const c_void, context: *mut c_void),
context: *mut c_void,
);
pub fn DARegisterDiskDescriptionChangedCallback(
session: *const c_void,
match_: CFDictionaryRef,
r#match: CFDictionaryRef,
watch: CFArrayRef,
callback: extern "C" fn(disk: *const c_void, keys: CFArrayRef, context: *mut c_void),
context: *mut c_void,
@ -31,7 +31,7 @@ unsafe extern "C" {
pub fn DARegisterDiskDisappearedCallback(
session: *const c_void,
match_: CFDictionaryRef,
r#match: CFDictionaryRef,
callback: extern "C" fn(disk: *const 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 layer = cx.layer();
if cx.help.visible && cx.help.type_(&key) {
if cx.help.visible && cx.help.r#type(&key) {
return true;
}
if cx.input.visible && cx.input.type_(&key) {
if cx.input.visible && cx.input.r#type(&key) {
return true;
}
@ -31,7 +31,7 @@ impl<'a> Router<'a> {
self.matches(layer, 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) 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) titles: Vec<(ratatui::widgets::block::Position, ratatui::text::Line<'static>)>,
@ -60,7 +60,7 @@ impl Border {
) {
let mut block = ratatui::widgets::Block::default()
.borders(self.position)
.border_type(self.type_)
.border_type(self.r#type)
.border_style(self.style);
for title in self.titles {
@ -80,7 +80,7 @@ impl UserData for Border {
crate::impl_style_method!(methods, style);
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,
DOUBLE => ratatui::widgets::BorderType::Double,
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> {
lua.create_async_function(|lua, (type_, url): (mlua::String, UrlRef)| async move {
let result = match type_.as_bytes().as_ref() {
lua.create_async_function(|lua, (r#type, url): (mlua::String, UrlRef)| async move {
let result = match r#type.as_bytes().as_ref() {
b"dir" => fs::create_dir(&*url).await,
b"dir_all" => fs::create_dir_all(&*url).await,
_ => 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> {
lua.create_async_function(|lua, (type_, url): (mlua::String, UrlRef)| async move {
let result = match type_.as_bytes().as_ref() {
lua.create_async_function(|lua, (r#type, url): (mlua::String, UrlRef)| async move {
let result = match r#type.as_bytes().as_ref() {
b"file" => fs::remove_file(&*url).await,
b"dir" => fs::remove_dir(&*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 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));
Ok(ts)
}
@ -72,9 +72,9 @@ impl Require {
if sync {
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);
let result = mod_.call_function::<MultiValue>(&f, args);
let result = r#mod.call_function::<MultiValue>(&f, args);
lua.named_registry_value::<RtRefMut>("ir")?.pop();
result
})
@ -82,9 +82,9 @@ impl Require {
lua.create_async_function(move |lua, args: MultiValue| {
let (id, f) = (id.clone(), f.clone());
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);
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();
result
}
@ -104,9 +104,9 @@ impl Require {
args.push_front(front);
return Ok((LOADER.try_load(lua, id)?, args));
};
Ok(if let Ok(mod_) = tbl.raw_get::<Table>("__mod") {
args.push_front(Value::Table(mod_.clone()));
(mod_, args)
Ok(if let Ok(r#mod) = tbl.raw_get::<Table>("__mod") {
args.push_front(Value::Table(r#mod.clone()));
(r#mod, args)
} else {
args.push_front(Value::Table(tbl));
(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> {
Composer::make(lua, 10, |lua, key| {
match key {
b"pub" => Pubsub::pub_(lua)?,
b"pub" => Pubsub::r#pub(lua)?,
b"pub_to" => Pubsub::pub_to(lua)?,
b"sub" => Pubsub::sub(lua)?,
b"sub_remote" => Pubsub::sub_remote(lua)?,

View file

@ -7,9 +7,9 @@ use crate::runtime::RtRef;
pub struct 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)| {
yazi_dds::Pubsub::pub_(Body::from_lua(&kind.to_str()?, value)?);
yazi_dds::Pubsub::r#pub(Body::from_lua(&kind.to_str()?, value)?);
Ok(())
})
}

View file

@ -7,8 +7,8 @@ use crate::bindings::{Permit, PermitRef};
impl Utils {
pub(super) fn id(lua: &Lua) -> mlua::Result<Function> {
lua.create_function(|_, type_: mlua::String| {
Ok(Id(match type_.as_bytes().as_ref() {
lua.create_function(|_, r#type: mlua::String| {
Ok(Id(match r#type.as_bytes().as_ref() {
b"app" => *yazi_dds::ID,
b"ft" => yazi_fs::FILES_TICKET.next(),
_ => 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() {
let cand = cand?;
cands.push(Chord {
on: Self::parse_keys(cand.raw_get("on")?)?,
run: vec![Cmd::args("which:callback", &[i]).with_any("tx", tx.clone())],
desc: cand.raw_get("desc").ok(),
for_: None,
on: Self::parse_keys(cand.raw_get("on")?)?,
run: vec![Cmd::args("which:callback", &[i]).with_any("tx", tx.clone())],
desc: cand.raw_get("desc").ok(),
r#for: None,
});
}

View file

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

View file

@ -40,8 +40,8 @@ impl Utils {
}
pub(super) fn chan(lua: &Lua) -> mlua::Result<Function> {
lua.create_function(|lua, (type_, buffer): (mlua::String, Option<usize>)| {
match (&*type_.as_bytes(), buffer) {
lua.create_function(|lua, (r#type, buffer): (mlua::String, Option<usize>)| {
match (&*r#type.as_bytes(), buffer) {
(b"mpsc", Some(buffer)) if buffer < 1 => {
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 callback: PluginCallback = {
let id_ = id.clone();
let id = id.clone();
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());
};

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_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};
pub struct File {
macro_: async_priority_channel::Sender<TaskOp, u8>,
prog: mpsc::UnboundedSender<TaskProg>,
r#macro: async_priority_channel::Sender<TaskOp, u8>,
prog: mpsc::UnboundedSender<TaskProg>,
}
impl File {
pub fn new(
macro_: async_priority_channel::Sender<TaskOp, u8>,
r#macro: async_priority_channel::Sender<TaskOp, u8>,
prog: mpsc::UnboundedSender<TaskProg>,
) -> Self {
Self { macro_, prog }
Self { r#macro, prog }
}
pub async fn work(&self, op: FileOp) -> Result<()> {
match op {
FileOp::Paste(mut task) => {
pub async fn work(&self, r#in: FileIn) -> Result<()> {
match r#in {
FileIn::Paste(mut task) => {
ok_or_not_found(fs::remove_file(&task.to).await)?;
let mut it = copy_with_progress(&task.from, &task.to, task.cha.unwrap());
@ -50,7 +50,7 @@ impl File {
{
task.retry += 1;
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(());
}
Err(e) => Err(e)?,
@ -58,7 +58,7 @@ impl File {
}
self.prog.send(TaskProg::Adv(task.id, 1, 0))?;
}
FileOp::Link(task) => {
FileIn::Link(task) => {
let cha = task.cha.unwrap();
let src = if task.resolve {
@ -99,7 +99,7 @@ impl File {
}
self.prog.send(TaskProg::Adv(task.id, 1, cha.len))?;
}
FileOp::Hardlink(task) => {
FileIn::Hardlink(task) => {
let cha = task.cha.unwrap();
let src = if !task.follow {
Cow::Borrowed(task.from.as_path())
@ -119,7 +119,7 @@ impl File {
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 e.kind() != NotFound && maybe_exists(&task.target).await {
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))?
}
FileOp::Trash(task) => {
FileIn::Trash(task) => {
tokio::task::spawn_blocking(move || {
#[cfg(target_os = "macos")]
{
@ -150,7 +150,7 @@ impl File {
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() {
return self.succ(task.id);
}
@ -165,9 +165,9 @@ impl File {
self.prog.send(TaskProg::New(id, cha.len))?;
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 {
self.queue(FileOp::Paste(task), LOW).await?;
self.queue(FileIn::Paste(task), LOW).await?;
}
return self.succ(id);
}
@ -210,27 +210,27 @@ impl File {
self.prog.send(TaskProg::New(task.id, cha.len))?;
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 {
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)
}
pub async fn link(&self, mut task: FileOpLink) -> Result<()> {
pub async fn link(&self, mut task: FileInLink) -> Result<()> {
let id = task.id;
if task.cha.is_none() {
task.cha = Some(Self::cha(&task.from, false).await?);
}
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)
}
pub async fn hardlink(&self, mut task: FileOpHardlink) -> Result<()> {
pub async fn hardlink(&self, mut task: FileInHardlink) -> Result<()> {
if task.cha.is_none() {
task.cha = Some(Self::cha(&task.from, task.follow).await?);
}
@ -239,7 +239,7 @@ impl File {
if !cha.is_dir() {
let id = task.id;
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);
}
@ -279,19 +279,19 @@ impl File {
let to = dest.join(from.file_name().unwrap());
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)
}
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?;
if !meta.is_dir() {
let id = task.id;
task.length = 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);
}
@ -310,18 +310,18 @@ impl File {
task.target = Url::from(entry.path());
task.length = 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)
}
pub async fn trash(&self, mut task: FileOpTrash) -> Result<()> {
pub async fn trash(&self, mut task: FileInTrash) -> Result<()> {
let id = task.id;
task.length = SizeCalculator::total(&task.target).await?;
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)
}
@ -356,7 +356,7 @@ impl File {
}
#[inline]
async fn queue(&self, op: impl Into<TaskOp>, priority: u8) -> Result<()> {
self.macro_.send(op.into(), priority).await.map_err(|_| anyhow!("Failed to send task"))
async fn queue(&self, r#in: impl Into<TaskOp>, priority: u8) -> Result<()> {
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;
#[derive(Debug)]
pub enum FileOp {
Paste(FileOpPaste),
Link(FileOpLink),
Hardlink(FileOpHardlink),
Delete(FileOpDelete),
Trash(FileOpTrash),
pub enum FileIn {
Paste(FileInPaste),
Link(FileInLink),
Hardlink(FileInHardlink),
Delete(FileInDelete),
Trash(FileInTrash),
}
impl FileOp {
impl FileIn {
pub fn id(&self) -> usize {
match self {
Self::Paste(op) => op.id,
Self::Link(op) => op.id,
Self::Hardlink(op) => op.id,
Self::Delete(op) => op.id,
Self::Trash(op) => op.id,
Self::Paste(r#in) => r#in.id,
Self::Link(r#in) => r#in.id,
Self::Hardlink(r#in) => r#in.id,
Self::Delete(r#in) => r#in.id,
Self::Trash(r#in) => r#in.id,
}
}
}
// --- Paste
#[derive(Clone, Debug)]
pub struct FileOpPaste {
pub struct FileInPaste {
pub id: usize,
pub from: Url,
pub to: Url,
@ -34,7 +34,7 @@ pub struct FileOpPaste {
pub retry: u8,
}
impl FileOpPaste {
impl FileInPaste {
pub(super) fn spawn(&self, from: Url, to: Url, cha: Cha) -> Self {
Self {
id: self.id,
@ -50,7 +50,7 @@ impl FileOpPaste {
// --- Link
#[derive(Clone, Debug)]
pub struct FileOpLink {
pub struct FileInLink {
pub id: usize,
pub from: Url,
pub to: Url,
@ -60,8 +60,8 @@ pub struct FileOpLink {
pub delete: bool,
}
impl From<FileOpPaste> for FileOpLink {
fn from(value: FileOpPaste) -> Self {
impl From<FileInPaste> for FileInLink {
fn from(value: FileInPaste) -> Self {
Self {
id: value.id,
from: value.from,
@ -76,7 +76,7 @@ impl From<FileOpPaste> for FileOpLink {
// --- Hardlink
#[derive(Clone, Debug)]
pub struct FileOpHardlink {
pub struct FileInHardlink {
pub id: usize,
pub from: Url,
pub to: Url,
@ -84,7 +84,7 @@ pub struct FileOpHardlink {
pub follow: bool,
}
impl FileOpHardlink {
impl FileInHardlink {
pub(super) fn spawn(&self, from: Url, to: Url, cha: Cha) -> Self {
Self { id: self.id, from, to, cha: Some(cha), follow: self.follow }
}
@ -92,7 +92,7 @@ impl FileOpHardlink {
// --- Delete
#[derive(Clone, Debug)]
pub struct FileOpDelete {
pub struct FileInDelete {
pub id: usize,
pub target: Url,
pub length: u64,
@ -100,7 +100,7 @@ pub struct FileOpDelete {
// --- Trash
#[derive(Clone, Debug)]
pub struct FileOpTrash {
pub struct FileInTrash {
pub id: usize,
pub target: Url,
pub length: u64,

View file

@ -1,3 +1,3 @@
#![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_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 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;
#[derive(Debug)]
pub enum PluginOp {
Entry(PluginOpEntry),
pub enum PluginIn {
Entry(PluginInEntry),
}
impl PluginOp {
impl PluginIn {
pub fn id(&self) -> usize {
match self {
Self::Entry(op) => op.id,
Self::Entry(r#in) => r#in.id,
}
}
}
#[derive(Debug)]
pub struct PluginOpEntry {
pub struct PluginInEntry {
pub id: usize,
pub opt: PluginOpt,
}

View file

@ -1,3 +1,3 @@
#![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 yazi_plugin::isolate;
use super::{PluginOp, PluginOpEntry};
use super::{PluginIn, PluginInEntry};
use crate::{HIGH, TaskOp, TaskProg};
pub struct Plugin {
macro_: async_priority_channel::Sender<TaskOp, u8>,
prog: mpsc::UnboundedSender<TaskProg>,
r#macro: async_priority_channel::Sender<TaskOp, u8>,
prog: mpsc::UnboundedSender<TaskProg>,
}
impl Plugin {
pub fn new(
macro_: async_priority_channel::Sender<TaskOp, u8>,
r#macro: async_priority_channel::Sender<TaskOp, u8>,
prog: mpsc::UnboundedSender<TaskProg>,
) -> Self {
Self { macro_, prog }
Self { r#macro, prog }
}
pub async fn work(&self, op: PluginOp) -> Result<()> {
match op {
PluginOp::Entry(task) => {
pub async fn work(&self, r#in: PluginIn) -> Result<()> {
match r#in {
PluginIn::Entry(task) => {
isolate::entry(task.opt).await?;
}
}
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))?;
if let Err(e) = isolate::entry(task.opt).await {
@ -39,11 +39,11 @@ impl Plugin {
self.succ(task.id)
}
pub fn macro_(&self, task: PluginOpEntry) -> Result<()> {
pub fn r#macro(&self, task: PluginInEntry) -> Result<()> {
let id = task.id;
self.prog.send(TaskProg::New(id, 0))?;
self.queue(PluginOp::Entry(task), HIGH)?;
self.queue(PluginIn::Entry(task), HIGH)?;
self.succ(id)
}
}
@ -58,7 +58,7 @@ impl Plugin {
}
#[inline]
fn queue(&self, op: impl Into<TaskOp>, priority: u8) -> Result<()> {
self.macro_.try_send(op.into(), priority).map_err(|_| anyhow!("Failed to send task"))
fn queue(&self, r#in: impl Into<TaskOp>, priority: u8) -> Result<()> {
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};
#[derive(Debug)]
pub enum PreworkOp {
Fetch(PreworkOpFetch),
Load(PreworkOpLoad),
Size(PreworkOpSize),
pub enum PreworkIn {
Fetch(PreworkInFetch),
Load(PreworkInLoad),
Size(PreworkInSize),
}
impl PreworkOp {
impl PreworkIn {
pub fn id(&self) -> usize {
match self {
Self::Fetch(op) => op.id,
Self::Load(op) => op.id,
Self::Size(op) => op.id,
Self::Fetch(r#in) => r#in.id,
Self::Load(r#in) => r#in.id,
Self::Size(r#in) => r#in.id,
}
}
}
#[derive(Debug)]
pub struct PreworkOpFetch {
pub struct PreworkInFetch {
pub id: usize,
pub plugin: &'static Fetcher,
pub targets: Vec<yazi_fs::File>,
}
#[derive(Clone, Debug)]
pub struct PreworkOpLoad {
pub struct PreworkInLoad {
pub id: usize,
pub plugin: &'static Preloader,
pub target: yazi_fs::File,
}
#[derive(Debug)]
pub struct PreworkOpSize {
pub struct PreworkInSize {
pub id: usize,
pub target: Url,
pub throttle: Arc<Throttle<(Url, u64)>>,

View file

@ -1,3 +1,3 @@
#![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_shared::{event::CmdCow, url::Url};
use super::{PreworkOp, PreworkOpFetch, PreworkOpLoad, PreworkOpSize};
use super::{PreworkIn, PreworkInFetch, PreworkInLoad, PreworkInSize};
use crate::{HIGH, NORMAL, TaskOp, TaskProg};
pub struct Prework {
macro_: async_priority_channel::Sender<TaskOp, u8>,
prog: mpsc::UnboundedSender<TaskProg>,
r#macro: async_priority_channel::Sender<TaskOp, u8>,
prog: mpsc::UnboundedSender<TaskProg>,
pub loaded: Mutex<LruCache<u64, u32>>,
pub size_loading: RwLock<HashSet<Url>>,
@ -23,20 +23,20 @@ pub struct Prework {
impl Prework {
pub fn new(
macro_: async_priority_channel::Sender<TaskOp, u8>,
r#macro: async_priority_channel::Sender<TaskOp, u8>,
prog: mpsc::UnboundedSender<TaskProg>,
) -> Self {
Self {
macro_,
r#macro,
prog,
loaded: Mutex::new(LruCache::new(NonZeroUsize::new(4096).unwrap())),
size_loading: Default::default(),
}
}
pub async fn work(&self, op: PreworkOp) -> Result<()> {
match op {
PreworkOp::Fetch(task) => {
pub async fn work(&self, r#in: PreworkIn) -> Result<()> {
match r#in {
PreworkIn::Fetch(task) => {
let hashes: Vec<_> = task.targets.iter().map(|f| f.hash()).collect();
let result = isolate::fetch(CmdCow::from(&task.plugin.run), task.targets).await;
if let Err(e) = result {
@ -54,7 +54,7 @@ impl Prework {
}
self.prog.send(TaskProg::Adv(task.id, 1, 0))?;
}
PreworkOp::Load(task) => {
PreworkIn::Load(task) => {
let hash = task.target.hash();
let result = isolate::preload(&task.plugin.run, task.target).await;
if let Err(e) = result {
@ -72,7 +72,7 @@ impl Prework {
}
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);
task.throttle.done((task.target, length), |buf| {
{
@ -95,35 +95,35 @@ impl Prework {
Ok(())
}
pub async fn fetch(&self, task: PreworkOpFetch) -> Result<()> {
pub async fn fetch(&self, task: PreworkInFetch) -> Result<()> {
let id = task.id;
self.prog.send(TaskProg::New(id, 0))?;
match task.plugin.prio {
Priority::Low => self.queue(PreworkOp::Fetch(task), NORMAL).await?,
Priority::Normal => self.queue(PreworkOp::Fetch(task), HIGH).await?,
Priority::High => self.work(PreworkOp::Fetch(task)).await?,
Priority::Low => self.queue(PreworkIn::Fetch(task), NORMAL).await?,
Priority::Normal => self.queue(PreworkIn::Fetch(task), HIGH).await?,
Priority::High => self.work(PreworkIn::Fetch(task)).await?,
}
self.succ(id)
}
pub async fn load(&self, task: PreworkOpLoad) -> Result<()> {
pub async fn load(&self, task: PreworkInLoad) -> Result<()> {
let id = task.id;
self.prog.send(TaskProg::New(id, 0))?;
match task.plugin.prio {
Priority::Low => self.queue(PreworkOp::Load(task), NORMAL).await?,
Priority::Normal => self.queue(PreworkOp::Load(task), HIGH).await?,
Priority::High => self.work(PreworkOp::Load(task)).await?,
Priority::Low => self.queue(PreworkIn::Load(task), NORMAL).await?,
Priority::Normal => self.queue(PreworkIn::Load(task), HIGH).await?,
Priority::High => self.work(PreworkIn::Load(task)).await?,
}
self.succ(id)
}
pub async fn size(&self, task: PreworkOpSize) -> Result<()> {
pub async fn size(&self, task: PreworkInSize) -> Result<()> {
let id = task.id;
self.prog.send(TaskProg::New(id, 0))?;
self.work(PreworkOp::Size(task)).await?;
self.work(PreworkIn::Size(task)).await?;
self.succ(id)
}
}
@ -138,7 +138,7 @@ impl Prework {
}
#[inline]
async fn queue(&self, op: impl Into<TaskOp>, priority: u8) -> Result<()> {
self.macro_.send(op.into(), priority).await.map_err(|_| anyhow!("Failed to send task"))
async fn queue(&self, r#in: impl Into<TaskOp>, priority: u8) -> Result<()> {
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)]
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 yazi_proxy::{AppProxy, HIDER};
use super::{ProcessOpBg, ProcessOpBlock, ProcessOpOrphan, ShellOpt};
use super::{ProcessInBg, ProcessInBlock, ProcessInOrphan, ShellOpt};
use crate::TaskProg;
pub struct Process {
@ -13,7 +13,7 @@ pub struct Process {
impl Process {
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();
defer!(AppProxy::resume());
AppProxy::stop().await;
@ -38,7 +38,7 @@ impl Process {
self.succ(id)
}
pub async fn orphan(&self, task: ProcessOpOrphan) -> Result<()> {
pub async fn orphan(&self, task: ProcessInOrphan) -> Result<()> {
let id = task.id;
match super::shell(task.into()) {
Ok(_) => self.succ(id)?,
@ -51,7 +51,7 @@ impl Process {
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))?;
let mut child = super::shell(ShellOpt {
cwd: task.cwd,

View file

@ -11,7 +11,7 @@ use yazi_proxy::{MgrProxy, options::{PluginOpt, ProcessExecOpt}};
use yazi_shared::{Throttle, url::Url};
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 file: Arc<File>,
@ -102,7 +102,7 @@ impl Scheduler {
if !force {
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 {
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?;
}
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
});
}
@ -150,7 +150,7 @@ impl Scheduler {
if !force {
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(
id,
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();
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 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) {
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>) {
@ -230,7 +230,7 @@ impl Scheduler {
let prework = self.prework.clone();
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 prework = self.prework.clone();
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();
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();
self.send_micro(id, NORMAL, async move {
if opener.block {
process.block(ProcessOpBlock { id, cwd, cmd, args }).await
process.block(ProcessInBlock { id, cwd, cmd, args }).await
} else if opener.orphan {
process.orphan(ProcessOpOrphan { id, cwd, cmd, args }).await
process.orphan(ProcessInOrphan { id, cwd, cmd, args }).await
} 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(
&self,
micro: async_priority_channel::Receiver<BoxFuture<'static, ()>, u8>,
macro_: async_priority_channel::Receiver<TaskOp, u8>,
r#macro: async_priority_channel::Receiver<TaskOp, u8>,
) -> JoinHandle<()> {
let file = self.file.clone();
let plugin = self.plugin.clone();
@ -336,16 +336,16 @@ impl Scheduler {
Ok((fut, _)) = micro.recv() => {
fut.await;
}
Ok((op, _)) = macro_.recv() => {
let id = op.id();
Ok((r#in, _)) = r#macro.recv() => {
let id = r#in.id();
if !ongoing.lock().exists(id) {
continue;
}
let result = match op {
TaskOp::File(op) => file.work(*op).await,
TaskOp::Plugin(op) => plugin.work(*op).await,
TaskOp::Prework(op) => prework.work(*op).await,
let result = match r#in {
TaskOp::File(r#in) => file.work(*r#in).await,
TaskOp::Plugin(r#in) => plugin.work(*r#in).await,
TaskOp::Prework(r#in) => prework.work(*r#in).await,
};
if let Err(e) = result {
@ -362,8 +362,8 @@ impl Scheduler {
let ongoing = self.ongoing.clone();
tokio::spawn(async move {
while let Some(op) = rx.recv().await {
match op {
while let Some(r#in) = rx.recv().await {
match r#in {
TaskProg::New(id, size) => {
if let Some(task) = ongoing.lock().get_mut(id) {
task.total += 1;

View file

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

View file

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

View file

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

View file

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

View file

@ -22,11 +22,11 @@ impl Input {
InputOp::Select(start) => {
self.snap_mut().op = InputOp::Delete(opt.cut, opt.insert, start);
render!(self.handle_op(self.snap().cursor, true));
self.move_(0);
self.r#move(0);
}
InputOp::Delete(..) => {
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 => {
snap.mode = InputMode::Normal;
self.move_(-1);
self.r#move(-1);
}
InputMode::Replace => {
snap.mode = InputMode::Normal;

View file

@ -18,7 +18,7 @@ impl Input {
let mut it = snap.value.chars().skip(snap.cursor).enumerate();
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 {
@ -29,13 +29,13 @@ impl Input {
k != CharKind::Space && k.vary(prev, opt.far)
};
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 {
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;
}
self.move_(snap.len() as isize)
self.r#move(snap.len() as isize)
}
}

View file

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

View file

@ -52,7 +52,7 @@ impl Input {
return;
}
self.move_(0);
self.r#move(0);
self.flush_value();
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 {
#[yazi_codegen::command]
pub fn move_(&mut self, opt: Opt) {
pub fn r#move(&mut self, opt: Opt) {
let snap = self.snap();
if opt.in_operating && snap.op == InputOp::None {
return;

View file

@ -11,7 +11,7 @@ impl From<CmdCow> for Opt {
}
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 };
if self.mode() == InputMode::Insert {
@ -33,7 +33,7 @@ impl Input {
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();
render!();
}

View file

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